. -, main , yield from, . ,
if __name__ == "__main__":
main()
main ; main() -, ( ). - main . main loop.run_until_complete.
queue, . queue.get(), , , asyncio , , . asyncio.Queue.
put_io_to_port. q2, , , put_io_to_port , process_queue queue. , , if not q2.empty() put_io_to_port .
, , asyncio.async, . , # do these tasks, in this order, , asyncio.async. , . , , :
yield from get_io_from_port(reader,q1)
yield from process_queue(q1, q2)
yield from put_io_to_port(writer, q2)
. ; , , , , .
(q1.Get(), q2.put =(...) ..).
, , :
import queue
import asyncio
@asyncio.coroutine
def process_queue(q1, q2):
while True:
tmp = yield from q1.get()
if tmp == 'ABCDEF':
yield from q2.put('12345')
elif tmp == 'GHIJKL':
yield from q2.put('67890')
else:
print('There is a data error')
@asyncio.coroutine
def put_io_to_port(writer, q2):
while True:
try:
data = yield from q2.get()
writer.write(data)
except IOError as e:
print('OUT Port issue: ', e)
@asyncio.coroutine
def get_io_from_port(reader, q1):
while True:
try:
data_i = yield from reader.read(1200)
yield from q1.put(data_i)
except IOError as e:
print('IN Port issue: ', e)
@asyncio.coroutine
def main():
q1 = asyncio.Queue()
q2 = asyncio.Queue()
reader, writer = yield from asyncio.open_connection('192.168.1.103', 5555)
print('Start')
tasks = [
asyncio.async(get_io_from_port(reader,q1)),
asyncio.async(process_queue(q1, q2)),
asyncio.async(put_io_to_port(writer, q2)),]
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())