Advertisement
Guest User

Untitled

a guest
Dec 9th, 2021
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. import asyncio
  2.  
  3. # wait until at least one line available and then return all complete lines
  4. # available in input buffer
  5. async def readlines( reader, sep = b'\n' ):
  6.     seplen = len(sep)
  7.     # wait for (at least) one line
  8.     lines = [ ( await reader.readuntil( sep ) )[ : -seplen ] ]
  9.     # get any additional lines in input buffer
  10.     # (rudely use internals since the public API is inadequate)
  11.     if sep in reader._buffer:
  12.         lines.extend( bytes( reader._buffer ).split( sep ) )
  13.         remaining = len( lines.pop() )
  14.         if remaining > 0:
  15.             del reader._buffer[ : -remaining ]
  16.         else:
  17.             reader._buffer.clear()
  18.         reader._maybe_resume_transport()
  19.     return lines
  20.  
  21.  
  22. def parse_line( line ):
  23.     ( timestamp_cycles, force, angle ) = line.decode('ascii').split(',')
  24.     timestamp_cycles = int( timestamp_cycles )
  25.     force = int( force )
  26.     angle = float( angle )  # XXX is it int or float?
  27.     return ( timestamp_cycles, force, angle )
  28.  
  29.  
  30. def process_data( data ):
  31.     # update user interface with most recent data:
  32.     ( timestamp_cycles, force, angle ) = data[ -1 ]
  33.  
  34.     timestamp_ms = timestamp_cycles // 200000
  35.     timestamp_s = ( timestamp_ms % 60000 ) / 1000
  36.     timestamp_m = timestamp_ms // 60000
  37.     timestamp_h = timestamp_m // 60
  38.     timestamp_m = timestamp_m % 60
  39.     timestamp_label = f'{timestamp_h:02d}:{timestamp_m:02d}:{timestamp_s:06.3f}'
  40.     print( f'\rtime={timestamp_label} angle={angle} force={force:08d}', end=' \x1b[K', flush=True )
  41.  
  42. async def capture_stream( host, port ):
  43.     reader, writer = await asyncio.open_connection( host, port )
  44.  
  45.     # loop until server sends EOF (or connection is closed)
  46.     try:
  47.         while not reader.at_eof():
  48.             # read and process a batch of data points
  49.             process_data( list( map( parse_line, await readlines( reader ) ) ) )
  50.     except asyncio.exceptions.IncompleteReadError as e:
  51.         if e.partial != b'':
  52.             raise
  53.     finally:
  54.         print( '' )
  55.  
  56.     print( 'connection closing' )
  57.     writer.close()
  58.     await writer.wait_closed()
  59.     print( 'connection closed' )
  60.  
  61. asyncio.run( capture_stream( 'beaglebone.local', 7778 ) )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement