Reputation: 2752
I have a connection which sends and receives data from a custom networking protocol through a serial port (yes, a serial port, an arduino, a rf24 card, etc etc).
I want to be able to do non-blocking code that queries the serial port waiting for response packets. I already know I can use deferToThread when I'm using a 3rd party library I can't modify, but this is not the case, I can modify the code. I just want to know how you can implement your own non-blocking code that returns a Deferred and returns the result later.
for example:
Thanks!
Upvotes: 1
Views: 152
Reputation: 3445
Basic idea is the following:
id_to_deferred_map = {}
def sendPacket(id, ...):
... # write to transport
d = Deferred()
id_to_deferred_map[id] = d
return d
# In protocol:
def packetReceived(id, ...):
d = id_to_deferred_map[id]
del id_to_deferred_map[id]
d.callback()
This should give you an idea. You simply have to maintain the state to remember the id
's and map them to the Deferred
's you've given out. When you've got an packet back, you fetch the Deferred
and trigger it with .callback()
.
You have to fill in the code to write your packet, as well as parse arriving packets, fetch id
and call packetReceived
.
Upvotes: 1