Advertisement
DeaD_EyE

read_serial

May 25th, 2016
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. # main.py -- put your code here!
  2. import machine
  3. import utime
  4. import wipy
  5. import utime
  6. import ustruct
  7. import usocket
  8. import ujson
  9. import gc
  10.  
  11.  
  12. SYNC = bytes([0x24, 0x02, 0xa2, 0xe1, 0x5a, 0xd6, 0x19, 0x73])
  13. SYNC_LEN = 8
  14. FRAME_LEN = 1032
  15. SERVER = ('192.168.1.2', 5000)
  16.  
  17. wipy.heartbeat(False)
  18. uart = machine.UART(0, 921600, timeout=5000)
  19. led = machine.Pin('GP25', mode=machine.Pin.OUT)
  20.  
  21. def reader():
  22.     while True:
  23.         gc.collect()
  24.         #utime.sleep_ms(10)
  25.         #print('Seeking SYNC')
  26.         buffer = uart.read(FRAME_LEN)
  27.         idx = buffer.find(SYNC)
  28.         if idx != -1:
  29.             buffer = buffer[idx:]
  30.             while len(buffer) != FRAME_LEN:
  31.                 rest = FRAME_LEN - len(buffer)
  32.                 buffer = b''.join([buffer, uart.read(rest)])
  33.             else:
  34.                 #print('{}'.format(len(buffer)))
  35.                 yield buffer
  36.                 buffer = b''
  37.                 #utime.sleep_ms(5)
  38.  
  39.  
  40. def unpack(data):
  41.     try:
  42.         return ujson.dumps(ustruct.unpack('!8x512h', data))[SYNC_LEN:]
  43.     except:
  44.         return b''
  45.  
  46. def test():
  47.     for data in reader():
  48.         print('Got Data')
  49.         print('Free:', gc.mem_free())
  50.  
  51. def worker(conn):
  52.     for data in reader():
  53.         try:
  54.             conn.send(unpack(data))
  55.         except OSError:
  56.             break
  57.  
  58. def server():
  59.     sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
  60.     while True:
  61.         try:
  62.             sock.connect(SERVER)
  63.         except:
  64.             utime.sleep(1)
  65.             continue
  66.         print('Connected to Server {}:{}'.format(*SERVER))
  67.         worker(sock)
  68.         sock.close()
  69.  
  70. #server()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement