I am trying to connect to a device and send commands while simultaniously receiving answers and working with them. When sending a command, the device can reply in one or more packets, usually size, then command-output. I think its also possible that size and output are send in one, which makes it hard to work with timeouts.
For example:
sending: b'\x00\x00\x00\x0e159>>AAAAAA>>1'
return1: b'\x00\x00\x00m' (size of return2)
return2: b'159>>XXXXXXXXXXXXXXXXX>>XXXXXXXXXXXXXXX>>XXXXXXXXXXXXXXXXXX>>XXXXXXXXX>>XXXXXXXXXXXXXXXXX>>X>>XXXXXX>>X>>X>>X'
Upon receiving the return2, I want to print stuff to the console and send a different command automatically. This needs to be in a thread, because it needs to always do this, while also allowing the user to input their own commands to the terminal. However I am running into problems when trying to close the thread because socket.recv() is blocking.
Current code (class method):
def __threaded_recv(self):
while True:
try:
data = self.socket.recv(1024)
print("Recieved: ", data)
if ">>" in data.decode():
self.__recievedCommandHandler(data)
except Exception as e:
pass
While my code is running in a thread, I am currently trying to grab the userinput like this from the main thread:
socketClass = TCL("192.168.1.7", 10000)
socketClass.startRecvThread()
socketClass.send(b'\x00\x00\x00\x0e159>>AAAAAA>>1')
while True:
input_cmd = input("Command: ")
if not input_cmd == "exit":
socketClass.sendCommandHandler(input_cmd)
else:
socketClass.close()
break
But whenever something gets printed to the console, while input("Command: ") is asking for input, the console will move and display things like this:
Command: <print msg from code>
<actual user command>
Instead of:
<print msg from code>
Command: <actual user command>
I’ve read about thread locking but wasn’t able to implement this, because the userinput is "always running" and it would block the prints from the socket recieving thread. Blocking the other thread wouldnt allow me to let the user make inputs.
TLDR:
- The console needs to handle input while simultaniously printing stuff in a different thread, without scrambling messages.
- Currently thread lock can’t be used for this because it would either block the looping input or prints
- The code needs to be able to handle
socket.recv()non blocking because otherwise thread termination may be blocked - Possible solutions have to work on windows, linux and mac
I know the individual problems are answered on stackoverflow but because of my unique situation, I can’t apply the solutions to my code. This is a unique problem so I hope it won’t get flagged as duplicate. Any help is appreciated!