Advertisement
DeaD_EyE

kxc1_serial_reader

Mar 7th, 2019
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.20 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. """
  4. This script reads data from K-XC1 (https://www.rfbeam.ch/product?id=24)
  5. and sends the data as zmq_publisher to connected clients.
  6. The data is sent as bytes and have to be interpreted on the receiver side.
  7. The struct is: '>512h'
  8.  
  9. Subscriber: https://pastebin.com/ueHWgw2a
  10. """
  11.  
  12. import serial
  13. import zmq
  14.  
  15. SYNC_LEN = 8
  16. DATA_LEN = 1024
  17. FRAME_LEN = SYNC_LEN + DATA_LEN
  18.  
  19. buffer = bytearray(FRAME_LEN)
  20. view = memoryview(buffer)
  21. sync = bytearray([0x24, 0x02, 0xa2, 0xe1, 0x5a, 0xd6, 0x19, 0x73])
  22.  
  23. def reader(port):
  24.     with serial.Serial(port, baudrate=921600) as ser:
  25.         while True:
  26.             ser.readinto(buffer)
  27.             idx = buffer.find(sync)
  28.             if idx > 0:
  29.                 ser.read(FRAME_LEN + idx)
  30.             elif idx == 0:
  31.                 yield buffer[SYNC_LEN:]
  32.  
  33.  
  34. def sender(serial_port, publisher_address, topic):
  35.     with zmq.Context() as ctx:
  36.         sock = ctx.socket(zmq.PUB)
  37.         sock.bind(publisher_address)
  38.         for frame in reader(serial_port):
  39.             sock.send_multipart([topic, frame])
  40.  
  41.  
  42. if __name__ == '__main__':
  43.     port = '/dev/ttyAMA0'
  44.     address = 'tcp://192.168.0.254:5050'
  45.     sender(port, address, b'sensor')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement