def _send_command(self, hex_bytes, expected_length):
try:
self.master.flushInput() # Clear the input buffer
self.master.write(hex_bytes) # Send the command
response = self.master.read(expected_length) # Read the expected length of the response
if response and response[-1:] == b'\x03': # Check the last byte of the response
return response
except serial.SerialException as e:
print(f"Serial communication error: {e}")
time.sleep(1) # Wait for a second before trying to reconnect
self.reconnect() # Attempt to reconnect
return False
Key Points Explained
- Clearing Input Buffer:
self.master.flushInput()
: Clears the input buffer before sending a new command to ensure no stale data is read.
- Sending Command:
self.master.write(hex_bytes)
: Sends the command in byte format to the device.
- Reading Response:
response = self.master.read(expected_length)
: Reads the response data of the expected length.
- Response Check:
- Checks if the last byte of the response is
b'\x03'
. This can be adjusted based on your specific protocol.
- Exception Handling:
- Catches
serial.SerialException
to handle communication errors. - When an error occurs, it prints the error message, waits for one second, and then calls
self.reconnect()
to re-establish the connection.
Considerations
- Command Length: Ensure
expected_length
is appropriate to avoid reading beyond the device’s response length. - Reconnecting: Make sure to handle the state after reconnecting (e.g., updating
is_connected
). - Response Processing: You may need to further process the response content, such as parsing data or checking other protocol fields.
With these adjustments, your _send_command
method will be more robust, effectively handling connection interruptions while maintaining communication continuity.