import serial
import threading

PORT = "COM15"  # AT Mode XBee COM Port
BAUD_RATE = 57600

# Initialize serial connection
ser = serial.Serial(PORT, BAUD_RATE, timeout=1)

# Function to receive messages from the Coordinator
def receive_data():
    while True:
        data = ser.readline().decode("utf-8", errors="ignore").strip()  # Read incoming data
        if data:
            print(f"\nReceived from Coordinator: {data}")
            print("Enter message: ", end="", flush=True)  # Keep input prompt intact

# Function to send messages to the Coordinator
def send_data():
    while True:
        user_input = input("\nEnter message: ")  # User input
        ser.write(user_input.encode() + b'\r')  # Send message in AT Mode
        print("Message sent.")

# Start the receiving thread
receive_thread = threading.Thread(target=receive_data, daemon=True)
receive_thread.start()

# Start the sending thread
send_thread = threading.Thread(target=send_data, daemon=True)
send_thread.start()

print("AT Mode XBee communication started. Type a message and press Enter to send.\n")

# Keep the program running
try:
    while True:
        pass
except KeyboardInterrupt:
    print("\nProgram terminated.")
    ser.close()
