Blame view
software/common_class/serial_com.py
1.71 KB
14b996da3 First commit |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# -*- coding: utf-8 -*- """ author Benoit Dubois licence GPL v3+ brief Basic protocol communication with stm32 discovery board. """ import pyb import uselect import ustruct class SerialCom(object): def __init__(self, id_=0): self.vcom = pyb.USB_VCP(id_) self.poller = uselect.poll() self.poller.register(self.vcom, uselect.POLLIN) def write_message(self, msg): header = ustruct.pack('<L', len(msg)) self.vcom.write(header + msg.encode('utf-8')) def read_message(self): header = self.vcom.read(4) if header is None: print("Read error: no data readed") return '' if len(header) == 4: msg_len = ustruct.unpack('<L', header)[0] try: data = self.vcom.read(msg_len).decode('utf-8') except: print("Serial read error") return # Check message validity if data is None: print("Read error: data received but no message to read") return if len(data) != msg_len: print("Read error: bad message length") return data def write_message_simple(self, msg): self.vcom.write(msg.encode('utf-8')) def read_message_simple(self): data = self.vcom.readline().decode('utf-8') if data is None: print("Read error: data received but no message to read") return return data def test(): scom = SerialCom() while True: scom.poller.poll(250) if scom.vcom.any(): msg = scom.read_message_simple() if msg is not None: scom.write_simple_message("Read: " + msg) #test() |