]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/nova/uart.py
Black formatted
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / nova / uart.py
1 """UART Class for Binho Nova"""
2
3 from adafruit_blinka.microcontroller.nova import Connection
4
5
6 class UART:
7     """Custom UART Class for Binho Nova"""
8
9     ESCAPE_SEQUENCE = "+++UART0"
10
11     # pylint: disable=too-many-arguments
12     def __init__(
13         self,
14         portid,
15         baudrate=9600,
16         bits=8,
17         parity=None,
18         stop=1,
19         timeout=1000,
20         read_buf_len=None,
21         flow=None,
22     ):
23         self._nova = Connection.getInstance()
24
25         self._id = portid
26         self._baudrate = baudrate
27         self._parity = parity
28         self._bits = bits
29         self._stop = stop
30         self._timeout = timeout
31
32         if flow is not None:  # default 0
33             raise NotImplementedError(
34                 "Parameter '{}' unsupported on Binho Nova".format("flow")
35             )
36
37         self._nova.setOperationMode(self._id, "UART")
38         self._nova.setBaudRateUART(self._id, baudrate)
39         self._nova.setDataBitsUART(self._id, bits)
40         self._nova.setParityUART(self._id, parity)
41         self._nova.setStopBitsUART(self._id, stop)
42         self._nova.setEscapeSequenceUART(self._id, UART.ESCAPE_SEQUENCE)
43         self._nova.beginBridgeUART(self._id)
44
45     # pylint: enable=too-many-arguments
46
47     def deinit(self):
48         """Deinitialize"""
49         self._nova.writeBridgeUART(UART.ESCAPE_SEQUENCE)
50         self._nova.stopBridgeUART(UART.ESCAPE_SEQUENCE)
51
52     def read(self, nbytes=None):
53         """Read data from UART and return it"""
54         if nbytes is None:
55             return None
56         data = bytearray()
57         for _ in range(nbytes):
58             data.append(ord(self._nova.readBridgeUART()))
59         return data
60
61     def readinto(self, buf, nbytes=None):
62         """Read data from UART and into the buffer"""
63         if nbytes is None:
64             return None
65         for _ in range(nbytes):
66             buf.append(ord(self._nova.readBridgeUART()))
67         return buf
68
69     def readline(self):
70         """Read a single line of data from UART"""
71         out = self._nova.readBridgeUART()
72         line = out
73         while out != "\r":
74             out = self._nova.readBridgeUART()
75             line += out
76         return line
77
78     def write(self, buf):
79         """Write data from the buffer to UART"""
80         return self._nova.writeBridgeUART(buf)