Q: How to write non-blocking code for twisted 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:


*

*send packet with ID 1 and wait for ACK with same ID

*keep waiting while packet with ID 1 is not available in the received packets queue

*if packet with ID 1 is found, return the result so the callbacks are "called" (sorry about the redundancy)


Thanks!

A: 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. 
