111 lines
2.9 KiB
Python
111 lines
2.9 KiB
Python
"""Test serial communication with the ATOMS3 MacroPad device."""
|
|
import sys
|
|
import os
|
|
import time
|
|
import json
|
|
|
|
sys.path.insert(0, os.path.dirname(__file__))
|
|
|
|
import serial
|
|
import serial.tools.list_ports
|
|
|
|
ESPRESSIF_VID = 0x303A
|
|
DEVICE_ID = "ATOMS3-MACROPAD"
|
|
|
|
|
|
def find_device():
|
|
ports = serial.tools.list_ports.comports()
|
|
candidates = []
|
|
for port in ports:
|
|
if port.vid == ESPRESSIF_VID:
|
|
candidates.append(port)
|
|
print(f" Found Espressif device: {port.device} "
|
|
f"(VID={hex(port.vid)}, PID={hex(port.pid)}, desc={port.description})")
|
|
return candidates
|
|
|
|
|
|
def test_connection(port_name, attempt=1):
|
|
"""Try to connect and ping the device."""
|
|
print(f"\n--- Attempt {attempt} on {port_name} ---")
|
|
try:
|
|
ser = serial.Serial()
|
|
ser.port = port_name
|
|
ser.baudrate = 115200
|
|
ser.timeout = 2
|
|
ser.dtr = False
|
|
ser.rts = False
|
|
ser.open()
|
|
print(f" Port opened")
|
|
|
|
time.sleep(0.1)
|
|
ser.dtr = True
|
|
time.sleep(0.5)
|
|
ser.reset_input_buffer()
|
|
|
|
cmd = b'{"cmd":"ping"}\n'
|
|
ser.write(cmd)
|
|
print(f" Sent: {cmd.strip()}")
|
|
|
|
line = ser.readline().decode("utf-8", errors="ignore").strip()
|
|
print(f" Received: {repr(line)}")
|
|
|
|
if line:
|
|
try:
|
|
data = json.loads(line)
|
|
if data.get("id") == DEVICE_ID:
|
|
print(f" PING OK - Device identified as {DEVICE_ID}")
|
|
ser.close()
|
|
return True
|
|
else:
|
|
print(f" Wrong device ID: {data}")
|
|
except json.JSONDecodeError:
|
|
print(f" Invalid JSON response")
|
|
else:
|
|
print(f" No response (empty)")
|
|
|
|
ser.close()
|
|
return False
|
|
|
|
except serial.SerialException as e:
|
|
print(f" Serial error: {e}")
|
|
return False
|
|
except OSError as e:
|
|
print(f" OS error: {e}")
|
|
return False
|
|
|
|
|
|
def test_reconnect(port_name):
|
|
print(f"\n=== Testing reconnect cycle on {port_name} ===")
|
|
for i in range(3):
|
|
if not test_connection(port_name, i + 1):
|
|
print(f"\nRECONNECT TEST FAILED on attempt {i + 1}")
|
|
return False
|
|
if i < 2:
|
|
print(" Waiting 1s before reconnect...")
|
|
time.sleep(1)
|
|
print(f"\nRECONNECT TEST PASSED - 3/3 cycles successful")
|
|
return True
|
|
|
|
|
|
def main():
|
|
print("=== ATOMS3 MacroPad Serial Test ===\n")
|
|
print("Scanning for Espressif USB devices...")
|
|
candidates = find_device()
|
|
|
|
if not candidates:
|
|
print("\nNo Espressif USB devices found!")
|
|
print("Make sure the ATOMS3 is connected via USB.")
|
|
return 1
|
|
|
|
for port in candidates:
|
|
if test_reconnect(port.device):
|
|
print(f"\nAll tests PASSED on {port.device}")
|
|
return 0
|
|
|
|
print("\nAll tests FAILED")
|
|
return 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|