Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import asyncio
- # wait until at least one line available and then return all complete lines
- # available in input buffer
- async def readlines( reader, sep = b'\n' ):
- seplen = len(sep)
- # wait for (at least) one line
- lines = [ ( await reader.readuntil( sep ) )[ : -seplen ] ]
- # get any additional lines in input buffer
- # (rudely use internals since the public API is inadequate)
- if sep in reader._buffer:
- lines.extend( bytes( reader._buffer ).split( sep ) )
- remaining = len( lines.pop() )
- if remaining > 0:
- del reader._buffer[ : -remaining ]
- else:
- reader._buffer.clear()
- reader._maybe_resume_transport()
- return lines
- def parse_line( line ):
- ( timestamp_cycles, force, angle ) = line.decode('ascii').split(',')
- timestamp_cycles = int( timestamp_cycles )
- force = int( force )
- angle = float( angle ) # XXX is it int or float?
- return ( timestamp_cycles, force, angle )
- def process_data( data ):
- # update user interface with most recent data:
- ( timestamp_cycles, force, angle ) = data[ -1 ]
- timestamp_ms = timestamp_cycles // 200000
- timestamp_s = ( timestamp_ms % 60000 ) / 1000
- timestamp_m = timestamp_ms // 60000
- timestamp_h = timestamp_m // 60
- timestamp_m = timestamp_m % 60
- timestamp_label = f'{timestamp_h:02d}:{timestamp_m:02d}:{timestamp_s:06.3f}'
- print( f'\rtime={timestamp_label} angle={angle} force={force:08d}', end=' \x1b[K', flush=True )
- async def capture_stream( host, port ):
- reader, writer = await asyncio.open_connection( host, port )
- # loop until server sends EOF (or connection is closed)
- try:
- while not reader.at_eof():
- # read and process a batch of data points
- process_data( list( map( parse_line, await readlines( reader ) ) ) )
- except asyncio.exceptions.IncompleteReadError as e:
- if e.partial != b'':
- raise
- finally:
- print( '' )
- print( 'connection closing' )
- writer.close()
- await writer.wait_closed()
- print( 'connection closed' )
- asyncio.run( capture_stream( 'beaglebone.local', 7778 ) )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement