Created
May 12, 2019 08:51
-
-
Save fabaff/461bae72a0558f34eee1e405c76a147a to your computer and use it in GitHub Desktop.
Reading one number from a PRG320
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import binascii | |
import json | |
import serial_asyncio | |
class Prg320Output(asyncio.Protocol): | |
"""Get the output of PRG320.""" | |
def connection_made(self, transport): | |
"""Initialize the connection.""" | |
self.transport = transport | |
def data_received(self, data): | |
"""Get one random number.""" | |
output = { | |
'raw': str(repr(data)), | |
'hex': str(binascii.hexlify(bytearray(data))), | |
'int': int(bytearray(data).hex(), 16), | |
} | |
print(json.dumps(output, sort_keys=True, indent=2)) | |
if b'\n' in data: | |
self.transport.close() | |
def connection_lost(self, exc): | |
"""Close the connection.""" | |
self.transport.loop.stop() | |
loop = asyncio.get_event_loop() | |
coro = serial_asyncio.create_serial_connection( | |
loop, Prg320Output, '/dev/ttyUSB0', baudrate=921600) | |
loop.run_until_complete(coro) | |
loop.run_forever() | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment