# -*- 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()
