Skip to content

← Back to Home

Communication Layer

Device communication for ESP32 and hardware control via PySerial.

Related Components: Game Engine | Hardware Control | Vision System | UI

Overview

The Communication Layer component is responsible for:

  • Serial Communication - Establish connection with microcontroller
  • Protocol Handling - Encode/decode command messages
  • Command Transmission - Send movement and control commands
  • Status Monitoring - Receive and interpret device feedback
  • Error Handling - Manage communication failures gracefully

Module Documentation

Communication Module

The serial communication system for hardware device control.

Communication

Source code in python/Communication.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
class Communication:
    SEND_COMMAND_TIMEOUT = 30  # Timeout for sending commands in seconds
    ser: serial.Serial
    def __init__(self):
        """Initialize serial connection to ESP-32 microcontroller.

        Args:
            None

        Return:
            None
        """
        self._shutdown_event = threading.Event()
        self._serial_lock = threading.RLock()  # Recursive lock for serial port access
        try:
            # Short timeout keeps shutdown responsive when a worker is blocked on read.
            self.ser = serial.Serial("/dev/ttyACM0", 115200, timeout=0.1)
        except Exception as e:
            print("Warning: could not open serial port /dev/ttyACM0:", e)
            self.ser = None
        # time.sleep(2) # attendre reset Arduino

    def _should_stop(self, stop_event=None):
        """Check if shutdown or stop event is set.

        Args:
            stop_event (threading.Event, optional): External stop event to check.

        Return:
            bool: True if shutdown or stop event is set, False otherwise.
        """
        return self._shutdown_event.is_set() or (stop_event is not None and stop_event.is_set())

    def send_command(self, command: Command, stop_event=None):
        """
        Function responsible to send command object to esp-32. Command comes from get_path function that returns 
        chess board square and the magnet state (ex : MOVE 1 2 True)
        """

        if self._should_stop(stop_event):
            return False

        if self.ser is None:
            print("Error: serial port not available")
            return False

        try:
            with self._serial_lock:
                self.ser.write(f"CHESSMOVE|{command.position.x}|{command.position.y}|{int(command.magnet_state)};\n".encode('utf-8'))
        except Exception as e:
            print("Error writing to serial port:", e)
            return False

        if not self.validate_send_command(stop_event=stop_event):
            print("Error: Move command failed.")
            return False
        return True

    def send_path(self, path: list[Command], stop_event=None):
        """
        Function that sends a list of commands to ESP-32 via serial port
        """

        if self._should_stop(stop_event):
            return False

        if self.ser is None:
            print("Error: serial port not available")
            return False

        try:
            with self._serial_lock:
                self.ser.write(f"PATH".encode('utf-8'))
                for command in path:
                    self.ser.write(f"|{command.position.x},{command.position.y},{int(command.magnet_state)}".encode('utf-8'))
                self.ser.write(";\n".encode('utf-8'))
        except Exception as e:
            print("Error writing to serial port:", e)
            return False

        if not self.validate_send_command(stop_event=stop_event):
            print("Error: Move command failed.")
            return False
        return True

    def send_position(self, pos:Position, relative=False, stop_event=None):
        """
        Function that sends a position to ESP-32 via serial port 
        ex: MOVE POSX POSY or JOG POSX POSY for relative movement
        """

        if self._should_stop(stop_event):
            return False

        cmd = "JOG" if relative else "MOVE"

        try:
            with self._serial_lock:
                self.ser.write(f"{cmd}|{pos.x}|{pos.y};\n".encode('utf-8'))
        except Exception as e:
            print("Error writing to serial port:", e)
            return False

        if not self.validate_send_command(expected_responses=("DONE"), stop_event=stop_event):
            print("Error: Move command failed.")
            return False
        return True


    def validate_send_command(self, expected_responses=("DONE", "HOMED"), stop_event=None) -> bool:
        """
        Wait for a line from serial and check whether it matches one of expected_responses.
        Returns True on match, False on timeout or unexpected response.

        Note: This method acquires the serial lock to prevent interleaving with other operations.
        """
        if self.ser is None:
            print("Error: serial port not available for validation")
            return False

        with self._serial_lock:
            expected = set(expected_responses)
            start_time = time()

            while True:
                if self._should_stop(stop_event):
                    return False

                if time() - start_time > self.SEND_COMMAND_TIMEOUT:
                    print("Error: No response from motor controller.")
                    return False

                try:
                    if self.ser.in_waiting == 0:
                        sleep(0.01)
                        continue
                    response = self.ser.readline().decode('utf-8', errors='ignore').strip()
                except Exception as e:
                    print("Error reading response from serial:", e)
                    return False

                if not response:
                    continue
                if response in expected:
                    return True

                # PLAYED can arrive asynchronously while waiting for DONE/HOMED/STOPPED.
                if response == "PLAYED":
                    continue

                print("Error: Unexpected response from motor controller:", response)
                return False

    def go_home(self, stop_event=None):
        if self._should_stop(stop_event):
            return False

        if self.ser is None:
            print("Error: serial port not available")
            return False

        try:
            with self._serial_lock:
                self.ser.write("HOME;\n".encode('utf-8'))
        except Exception as e:
            print("Error writing HOME to serial:", e)
            return False

        # Expect the controller to reply with HOMED
        return self.validate_send_command(expected_responses=("HOMED",), stop_event=stop_event)



    def stop(self, stop_event=None):
        "Send stop command to ESP-32"

        if self._should_stop(stop_event):
            return False

        try:
            with self._serial_lock:
                self.ser.write("STOP;\n".encode('utf-8'))
        except Exception as e:
            print("Error writing STOP to serial:", e)
            return False

        return self.validate_send_command(expected_responses=("STOPPED",), stop_event=stop_event)

    def move_servo(self, state: bool, stop_event=None):
        "Send command to move servo to state (True for up, False for down)"

        if self._should_stop(stop_event):
            return False

        try:
            with self._serial_lock:
                self.ser.write(f"SERVO|{int(state)};\n".encode('utf-8'))
        except Exception as e:
            print("Error writing SERVO to serial:", e)
            return False

        return self.validate_send_command(expected_responses=("SERVO",), stop_event=stop_event)

    def clear_input_buffer(self):
        """Clear pending serial input to avoid re-processing stale messages."""
        if self.ser is None:
            return

        with self._serial_lock:
            try:
                self.ser.reset_input_buffer()
            except Exception:
                # Fallback for drivers/environments where reset_input_buffer can fail.
                try:
                    while self.ser.in_waiting > 0:
                        self.ser.readline()
                except Exception:
                    pass

    def wait_for_button_press(self, stop_event=None, timeout_seconds=600):
        """
        Wait for a button press signal from ESP-32. This is used to detect when the user has placed a piece on the board.
        The ESP-32 should send "PLAYED" when a piece is placed.

        Note: This method periodically releases the serial lock to allow other commands to be sent.
        """
        if self.ser is None:
            print("Error: serial port not available")
            return False

        # Drop stale lines (e.g. an old PLAYED) before waiting for a fresh press.
        self.clear_input_buffer()

        start_time = time()
        while True:
            if self._should_stop(stop_event):
                return False

            if time() - start_time > timeout_seconds:
                print("Error: No button press detected within timeout.")
                return False

            try:
                # Acquire lock, check for data briefly, then release to allow other commands
                with self._serial_lock:
                    if self.ser.in_waiting == 0:
                        # No data waiting, release lock and sleep
                        pass
                    else:
                        response = self.ser.readline().decode('utf-8', errors='ignore').strip()
                        if response:
                            if response == "PLAYED":
                                return True
                            # Ignore other responses while waiting for button press
                # Sleep between lock attempts to give other operations a chance
                sleep(0.01)
            except Exception as e:
                print("Error reading serial in wait_for_button_press:", e)
                return False

    def shutdown(self):
        """Signal all pending operations to stop and close the serial port."""
        self._shutdown_event.set()
        if self.ser is not None:
            try:
                self.ser.close()
            except Exception:
                pass
            self.ser = None

    def close(self):
        self.shutdown()

__init__()

Initialize serial connection to ESP-32 microcontroller.

Return

None

Source code in python/Communication.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def __init__(self):
    """Initialize serial connection to ESP-32 microcontroller.

    Args:
        None

    Return:
        None
    """
    self._shutdown_event = threading.Event()
    self._serial_lock = threading.RLock()  # Recursive lock for serial port access
    try:
        # Short timeout keeps shutdown responsive when a worker is blocked on read.
        self.ser = serial.Serial("/dev/ttyACM0", 115200, timeout=0.1)
    except Exception as e:
        print("Warning: could not open serial port /dev/ttyACM0:", e)
        self.ser = None

clear_input_buffer()

Clear pending serial input to avoid re-processing stale messages.

Source code in python/Communication.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
def clear_input_buffer(self):
    """Clear pending serial input to avoid re-processing stale messages."""
    if self.ser is None:
        return

    with self._serial_lock:
        try:
            self.ser.reset_input_buffer()
        except Exception:
            # Fallback for drivers/environments where reset_input_buffer can fail.
            try:
                while self.ser.in_waiting > 0:
                    self.ser.readline()
            except Exception:
                pass

move_servo(state, stop_event=None)

Send command to move servo to state (True for up, False for down)

Source code in python/Communication.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def move_servo(self, state: bool, stop_event=None):
    "Send command to move servo to state (True for up, False for down)"

    if self._should_stop(stop_event):
        return False

    try:
        with self._serial_lock:
            self.ser.write(f"SERVO|{int(state)};\n".encode('utf-8'))
    except Exception as e:
        print("Error writing SERVO to serial:", e)
        return False

    return self.validate_send_command(expected_responses=("SERVO",), stop_event=stop_event)

send_command(command, stop_event=None)

Function responsible to send command object to esp-32. Command comes from get_path function that returns chess board square and the magnet state (ex : MOVE 1 2 True)

Source code in python/Communication.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def send_command(self, command: Command, stop_event=None):
    """
    Function responsible to send command object to esp-32. Command comes from get_path function that returns 
    chess board square and the magnet state (ex : MOVE 1 2 True)
    """

    if self._should_stop(stop_event):
        return False

    if self.ser is None:
        print("Error: serial port not available")
        return False

    try:
        with self._serial_lock:
            self.ser.write(f"CHESSMOVE|{command.position.x}|{command.position.y}|{int(command.magnet_state)};\n".encode('utf-8'))
    except Exception as e:
        print("Error writing to serial port:", e)
        return False

    if not self.validate_send_command(stop_event=stop_event):
        print("Error: Move command failed.")
        return False
    return True

send_path(path, stop_event=None)

Function that sends a list of commands to ESP-32 via serial port

Source code in python/Communication.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def send_path(self, path: list[Command], stop_event=None):
    """
    Function that sends a list of commands to ESP-32 via serial port
    """

    if self._should_stop(stop_event):
        return False

    if self.ser is None:
        print("Error: serial port not available")
        return False

    try:
        with self._serial_lock:
            self.ser.write(f"PATH".encode('utf-8'))
            for command in path:
                self.ser.write(f"|{command.position.x},{command.position.y},{int(command.magnet_state)}".encode('utf-8'))
            self.ser.write(";\n".encode('utf-8'))
    except Exception as e:
        print("Error writing to serial port:", e)
        return False

    if not self.validate_send_command(stop_event=stop_event):
        print("Error: Move command failed.")
        return False
    return True

send_position(pos, relative=False, stop_event=None)

Function that sends a position to ESP-32 via serial port ex: MOVE POSX POSY or JOG POSX POSY for relative movement

Source code in python/Communication.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def send_position(self, pos:Position, relative=False, stop_event=None):
    """
    Function that sends a position to ESP-32 via serial port 
    ex: MOVE POSX POSY or JOG POSX POSY for relative movement
    """

    if self._should_stop(stop_event):
        return False

    cmd = "JOG" if relative else "MOVE"

    try:
        with self._serial_lock:
            self.ser.write(f"{cmd}|{pos.x}|{pos.y};\n".encode('utf-8'))
    except Exception as e:
        print("Error writing to serial port:", e)
        return False

    if not self.validate_send_command(expected_responses=("DONE"), stop_event=stop_event):
        print("Error: Move command failed.")
        return False
    return True

shutdown()

Signal all pending operations to stop and close the serial port.

Source code in python/Communication.py
270
271
272
273
274
275
276
277
278
def shutdown(self):
    """Signal all pending operations to stop and close the serial port."""
    self._shutdown_event.set()
    if self.ser is not None:
        try:
            self.ser.close()
        except Exception:
            pass
        self.ser = None

stop(stop_event=None)

Send stop command to ESP-32

Source code in python/Communication.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def stop(self, stop_event=None):
    "Send stop command to ESP-32"

    if self._should_stop(stop_event):
        return False

    try:
        with self._serial_lock:
            self.ser.write("STOP;\n".encode('utf-8'))
    except Exception as e:
        print("Error writing STOP to serial:", e)
        return False

    return self.validate_send_command(expected_responses=("STOPPED",), stop_event=stop_event)

validate_send_command(expected_responses=('DONE', 'HOMED'), stop_event=None)

Wait for a line from serial and check whether it matches one of expected_responses. Returns True on match, False on timeout or unexpected response.

Note: This method acquires the serial lock to prevent interleaving with other operations.

Source code in python/Communication.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def validate_send_command(self, expected_responses=("DONE", "HOMED"), stop_event=None) -> bool:
    """
    Wait for a line from serial and check whether it matches one of expected_responses.
    Returns True on match, False on timeout or unexpected response.

    Note: This method acquires the serial lock to prevent interleaving with other operations.
    """
    if self.ser is None:
        print("Error: serial port not available for validation")
        return False

    with self._serial_lock:
        expected = set(expected_responses)
        start_time = time()

        while True:
            if self._should_stop(stop_event):
                return False

            if time() - start_time > self.SEND_COMMAND_TIMEOUT:
                print("Error: No response from motor controller.")
                return False

            try:
                if self.ser.in_waiting == 0:
                    sleep(0.01)
                    continue
                response = self.ser.readline().decode('utf-8', errors='ignore').strip()
            except Exception as e:
                print("Error reading response from serial:", e)
                return False

            if not response:
                continue
            if response in expected:
                return True

            # PLAYED can arrive asynchronously while waiting for DONE/HOMED/STOPPED.
            if response == "PLAYED":
                continue

            print("Error: Unexpected response from motor controller:", response)
            return False

wait_for_button_press(stop_event=None, timeout_seconds=600)

Wait for a button press signal from ESP-32. This is used to detect when the user has placed a piece on the board. The ESP-32 should send "PLAYED" when a piece is placed.

Note: This method periodically releases the serial lock to allow other commands to be sent.

Source code in python/Communication.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
def wait_for_button_press(self, stop_event=None, timeout_seconds=600):
    """
    Wait for a button press signal from ESP-32. This is used to detect when the user has placed a piece on the board.
    The ESP-32 should send "PLAYED" when a piece is placed.

    Note: This method periodically releases the serial lock to allow other commands to be sent.
    """
    if self.ser is None:
        print("Error: serial port not available")
        return False

    # Drop stale lines (e.g. an old PLAYED) before waiting for a fresh press.
    self.clear_input_buffer()

    start_time = time()
    while True:
        if self._should_stop(stop_event):
            return False

        if time() - start_time > timeout_seconds:
            print("Error: No button press detected within timeout.")
            return False

        try:
            # Acquire lock, check for data briefly, then release to allow other commands
            with self._serial_lock:
                if self.ser.in_waiting == 0:
                    # No data waiting, release lock and sleep
                    pass
                else:
                    response = self.ser.readline().decode('utf-8', errors='ignore').strip()
                    if response:
                        if response == "PLAYED":
                            return True
                        # Ignore other responses while waiting for button press
            # Sleep between lock attempts to give other operations a chance
            sleep(0.01)
        except Exception as e:
            print("Error reading serial in wait_for_button_press:", e)
            return False

Key Features

  • Robust Serial Protocol - Reliable communication with error checking
  • Asynchronous Operation - Non-blocking command transmission
  • Auto-reconnection - Handle disconnections gracefully
  • Timeout Management - Prevent hanging on failed commands

Architecture

Communication Layer
├── Serial Port Management
│   ├── Port Detection
│   └── Connection State
├── Command Protocol
│   ├── Command Encoding
│   └── Parameter Packing
├── Response Handling
│   ├── Message Parsing
│   └── Error Detection
└── Device Interface
    ├── Gantry Movement Status
    └── Servo State Feedback

Command Protocol

Message Format

[COMMAND] [PARAMETERS] <>

        1 byte    variable     1 byte    0xFF

Common Commands

  • HOME - Move gantry to home position
  • MOVE - Execute X,Y absolute movement command
  • JOG - Execute X,Y relative movement command
  • SERVO - Control up down of effector to manipulate pieces (magnet)
  • STOP - Stop gantry
  • CHESSMOVE - Send command as grid coordinate with effector state
  • PATH - Send complete sets of command to execute a complete chess move

Communication Flow

  1. Initialization - Detect and connect to device
  2. Handshake - Verify device is responsive
  3. Command Send - Transmit movement commands
  4. Status Check - Wait for completion
  5. Error Handling - Retry or abort as needed
  6. Disconnection - Clean shutdown

Serial Configuration

from Communication import Communication

# Initialize communicator
comm = Communication()

# Send command
comm.send_path(path_commands)

# Wait for button press (human move)
comm.wait_for_button_press()

Dependencies

  • PySerial - Serial port communication
  • Microcontroller firmware (ESP32/Arduino)