import socket
import ollama
import serial
import time
import threading

ip = '127.0.0.1'
port = 5000

usbPort = '/dev/ttyACM0'
baud_rate = 9600
stopFlag = False

instruction = "Ne fait pas de long paragraphe répond simplement"

def send_message(client_socket, message):
    client_socket.send(message.encode())

def connect_arduino():
    count = 0
    
    ser = serial.Serial(usbPort, baud_rate)
    while not ser.isOpen():
        if (count == 5):
            count = 0
            print("Serial port still trying to open...")
        time.sleep(1)
        count += 1
    return (ser)

def arduino_thread(thread_name, ser):
    global stopFlag

    while not stopFlag:
        if ser.in_waiting > 0:
            data = ser.readline().decode('utf-8').strip()
            print("Arduino data:", data)

def start_server():
    global stopFlag

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((ip, port))
    server_socket.listen(1)

    print("Server ready!")

    ser = connect_arduino()
    client_socket, client_address = server_socket.accept()
    thread1 = threading.Thread(target=arduino_thread, args=("Thread1", ser))
    thread1.start()
    while (1):
        message = client_socket.recv(1024).decode()

        if (message == "exit"):
            send_message(client_socket, "exit")
            break
        message = message + instruction
        response = ollama.chat(model='mistral', messages=[
        {
          'role': 'user',
          'content': message,
        },
        ])
        send_message(client_socket, response['message']['content'])
    stopFlag = True
    print("closed server.")
    thread1.join()
    client_socket.close()

start_server()
