'Python TCP socket timing out, can't figure out why
I'm working on an application that's communicating with some hardware. We currently just set up a TCP connection to the hardware, and then read/write data to and from the socket.
This hardware is responsible for moving a group of cameras, and it can do so given absolute pan/tilt positions or coordinates (lat/long, which are then converted to absolute pan/tilt values).
I currently have a weird issue where for any pan/tilt command, it works flawlessly, but for any lat/long command, the socket will time out. But each command is handled in the exact same way, so I have absolutely no idea where or why it's timing out?
Here is an example of basically what is happening:
A working pan/tilt command (I won't bother explaining what the commands actually do since that's not really important):
System receives commands ['B1000,2000,8000,8000', 'A']
TCP handler writes B1000,2000,8000,8000
TCP handler reads B1000,2000,8000,8000 *
TCP handler writes A
TCP handler reads A *
return a CommandResponse object for each command (data object that looks like CommandResponse(command, success, message, _response_raw)
So that all works fine, but for the lat/long type of command, the socket is timing out when it is trying to read the A value from the socket, even though (according to my print statements, the A is being written)
System receives command ['GG-34.8725,137.0007,0.0', 'A']
TCP handler writes GG-34.8725,137.0007,0.0
TCP handler reads GG-34.8725,137.0007,0.0 *
TCP handler writes A
TCP handler attempts to read
Socket times out
The exact error is occuring on the line = self._read.readline().strip() line:
def _read_line(self, delimiter: str = None) -> str:
""" Reads bytes from the TCP socket until delimiter is read. """
if not delimiter:
delimiter = self._delimiter
response: List[str] = []
start_time = time()
while True:
logger.info(f"Reading...")
line = self._read.readline().strip()
logger.info(f"Read: {line}")
response.append(line)
if delimiter in line:
return "\n".join(response)
# Unsure if socket will timeout on its own if we are constantly probing it for incoming bytes.
if time()-start_time > self._TIMEOUT:
raise TimeoutError('Timed out waiting for response from device.')
And the (condensed) stack trace is:
Exception in thread Thread-1:
...
File "/app/pan_tilt_unit/device_handler/tcp_handler.py", line 96, in _read_line
line = self._read.readline().strip()
File "/usr/local/lib/python3.8/socket.py", line 669, in readinto
return self._sock.recv_into(b)
socket.timeout: timedout
I have been stuck on this for some time because I cannot figure out why the A is being written to the socket, but cannot be read? I believe that is the crux of the problem.
Thanks
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
