import serial
import threading
import sys

def receive_data(ser):
    """Continuously receive and print data from serial port"""
    while True:
        try:
            if ser.in_waiting > 0:
                data = ser.readline().decode('utf-8').strip()
                if data:
                    print(f"\nReceived: {data}")
                    print("Send: ", end='', flush=True)
        except Exception as e:
            print(f"\nError receiving: {e}")
            break

def main():
    # Configure serial port
    #port = input("Enter serial port (e.g., COM3 or /dev/ttyUSB0): ")
    #baudrate = input("Enter baud rate (default 9600): ") or "9600"
    port='COM4'
    baudrate=9600
    try:
        # Open serial port
        ser = serial.Serial(port, int(baudrate), timeout=1)
        print(f"Connected to {port} at {baudrate} baud")
        print("Type your message and press Enter to send. Ctrl+C to quit.\n")
        
        # Start receive thread
        receive_thread = threading.Thread(target=receive_data, args=(ser,), daemon=True)
        receive_thread.start()
        
        # Send loop
        while True:
            try:
                msg = input("Send: ")
                if msg:
                    ser.write((msg + '\n').encode('utf-8'))
            except KeyboardInterrupt:
                print("\n\nClosing connection...")
                break
            except Exception as e:
                print(f"Error sending: {e}")
                break
        
        ser.close()
        print("Connection closed.")
        
    except serial.SerialException as e:
        print(f"Could not open serial port: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()