]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/mcp2221/mcp2221.py
619c70e7da879d1b4eec0858e65f7c8701db92d4
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / mcp2221 / mcp2221.py
1 """Chip Definition for MCP2221"""
2
3 import os
4 import time
5 import hid
6
7 # Here if you need it
8 MCP2221_HID_DELAY = float(os.environ.get("BLINKA_MCP2221_HID_DELAY", 0))
9 # Use to set delay between reset and device reopen
10 MCP2221_RESET_DELAY = float(os.environ.get("BLINKA_MCP2221_RESET_DELAY", 0.5))
11
12 # from the C driver
13 # http://ww1.microchip.com/downloads/en/DeviceDoc/mcp2221_0_1.tar.gz
14 # others (???) determined during driver developement
15 # pylint: disable=bad-whitespace
16 RESP_ERR_NOERR = 0x00
17 RESP_ADDR_NACK = 0x25
18 RESP_READ_ERR = 0x7F
19 RESP_READ_COMPL = 0x55
20 RESP_READ_PARTIAL = 0x54  # ???
21 RESP_I2C_IDLE = 0x00
22 RESP_I2C_START_TOUT = 0x12
23 RESP_I2C_RSTART_TOUT = 0x17
24 RESP_I2C_WRADDRL_TOUT = 0x23
25 RESP_I2C_WRADDRL_WSEND = 0x21
26 RESP_I2C_WRADDRL_NACK = 0x25
27 RESP_I2C_WRDATA_TOUT = 0x44
28 RESP_I2C_RDDATA_TOUT = 0x52
29 RESP_I2C_STOP_TOUT = 0x62
30
31 RESP_I2C_MOREDATA = 0x43  # ???
32 RESP_I2C_PARTIALDATA = 0x41  # ???
33 RESP_I2C_WRITINGNOSTOP = 0x45  # ???
34
35 MCP2221_RETRY_MAX = 50
36 MCP2221_MAX_I2C_DATA_LEN = 60
37 MASK_ADDR_NACK = 0x40
38 # pylint: enable=bad-whitespace
39
40
41 class MCP2221:
42     """MCP2221 Device Class Definition"""
43
44     VID = 0x04D8
45     PID = 0x00DD
46
47     GP_GPIO = 0b000
48     GP_DEDICATED = 0b001
49     GP_ALT0 = 0b010
50     GP_ALT1 = 0b011
51     GP_ALT2 = 0b100
52
53     def __init__(self):
54         self._hid = hid.device()
55         self._hid.open(MCP2221.VID, MCP2221.PID)
56         self._reset()
57         self._gp_config = [0x07] * 4  # "don't care" initial value
58         for pin in range(4):
59             self.gp_set_mode(pin, self.GP_GPIO)  # set to GPIO mode
60             self.gpio_set_direction(pin, 1)  # set to INPUT
61
62     def _hid_xfer(self, report, response=True):
63         """Perform HID Transfer"""
64         # first byte is report ID, which =0 for MCP2221
65         # remaing bytes = 64 byte report data
66         # https://github.com/libusb/hidapi/blob/083223e77952e1ef57e6b77796536a3359c1b2a3/hidapi/hidapi.h#L185
67         self._hid.write(b"\0" + report + b"\0" * (64 - len(report)))
68         time.sleep(MCP2221_HID_DELAY)
69         if response:
70             # return is 64 byte response report
71             return self._hid.read(64)
72         return None
73
74     # ----------------------------------------------------------------
75     # MISC
76     # ----------------------------------------------------------------
77     def gp_get_mode(self, pin):
78         """Get Current Pin Mode"""
79         val = self._hid_xfer(b"\x61")[22 + pin]
80         print("0b{:08b}".format(val))
81         return self._hid_xfer(b"\x61")[22 + pin] & 0x07
82
83     def gp_set_mode(self, pin, mode):
84         """Set Current Pin Mode"""
85         # already set to that mode?
86         mode &= 0x07
87         if mode == (self._gp_config[pin] & 0x07):
88             return
89         # update GP mode for pin
90         self._gp_config[pin] = mode
91         # empty report, this is safe since 0's = no change
92         report = bytearray(b"\x60" + b"\x00" * 63)
93         # set the alter GP flag byte
94         report[7] = 0xFF
95         # add GP setttings
96         report[8] = self._gp_config[0]
97         report[9] = self._gp_config[1]
98         report[10] = self._gp_config[2]
99         report[11] = self._gp_config[3]
100         # and make it so
101         self._hid_xfer(report)
102
103     def _pretty_report(self, register):
104         report = self._hid_xfer(register)
105         print("     0  1  2  3  4  5  6  7  8  9")
106         index = 0
107         for row in range(7):
108             print("{} : ".format(row), end="")
109             for _ in range(10):
110                 print("{:02x} ".format(report[index]), end="")
111                 index += 1
112                 if index > 63:
113                     break
114             print()
115
116     def _status_dump(self):
117         self._pretty_report(b"\x10")
118
119     def _sram_dump(self):
120         self._pretty_report(b"\x61")
121
122     def _reset(self):
123         self._hid_xfer(b"\x70\xAB\xCD\xEF", response=False)
124         time.sleep(MCP2221_RESET_DELAY)
125         start = time.monotonic()
126         while time.monotonic() - start < 5:
127             try:
128                 self._hid.open(MCP2221.VID, MCP2221.PID)
129             except OSError:
130                 # try again
131                 time.sleep(0.1)
132                 continue
133             return
134         raise OSError("open failed")
135
136     # ----------------------------------------------------------------
137     # GPIO
138     # ----------------------------------------------------------------
139     def gpio_set_direction(self, pin, mode):
140         """Set Current GPIO Pin Direction"""
141         if mode:
142             # set bit 3 for INPUT
143             self._gp_config[pin] |= 1 << 3
144         else:
145             # clear bit 3 for OUTPUT
146             self._gp_config[pin] &= ~(1 << 3)
147         report = bytearray(b"\x50" + b"\x00" * 63)  # empty set GPIO report
148         offset = 4 * (pin + 1)
149         report[offset] = 0x01  # set pin direction
150         report[offset + 1] = mode  # to this
151         self._hid_xfer(report)
152
153     def gpio_set_pin(self, pin, value):
154         """Set Current GPIO Pin Value"""
155         if value:
156             # set bit 4
157             self._gp_config[pin] |= 1 << 4
158         else:
159             # clear bit 4
160             self._gp_config[pin] &= ~(1 << 4)
161         report = bytearray(b"\x50" + b"\x00" * 63)  # empty set GPIO report
162         offset = 2 + 4 * pin
163         report[offset] = 0x01  # set pin value
164         report[offset + 1] = value  # to this
165         self._hid_xfer(report)
166
167     def gpio_get_pin(self, pin):
168         """Get Current GPIO Pin Value"""
169         resp = self._hid_xfer(b"\x51")
170         offset = 2 + 2 * pin
171         if resp[offset] == 0xEE:
172             raise RuntimeError("Pin is not set for GPIO operation.")
173         return resp[offset]
174
175     # ----------------------------------------------------------------
176     # I2C
177     # ----------------------------------------------------------------
178     def _i2c_status(self):
179         resp = self._hid_xfer(b"\x10")
180         if resp[1] != 0:
181             raise RuntimeError("Couldn't get I2C status")
182         return resp
183
184     def _i2c_state(self):
185         return self._i2c_status()[8]
186
187     def _i2c_cancel(self):
188         resp = self._hid_xfer(b"\x10\x00\x10")
189         if resp[1] != 0x00:
190             raise RuntimeError("Couldn't cancel I2C")
191         if resp[2] == 0x10:
192             # bus release will need "a few hundred microseconds"
193             time.sleep(0.001)
194
195     # pylint: disable=too-many-arguments
196     def _i2c_write(self, cmd, address, buffer, start=0, end=None):
197         if self._i2c_state() != 0x00:
198             self._i2c_cancel()
199
200         end = end if end else len(buffer)
201         length = end - start
202         retries = 0
203
204         while (end - start) > 0:
205             chunk = min(end - start, MCP2221_MAX_I2C_DATA_LEN)
206             # write out current chunk
207             resp = self._hid_xfer(
208                 bytes([cmd, length & 0xFF, (length >> 8) & 0xFF, address << 1])
209                 + buffer[start : (start + chunk)]
210             )
211             # check for success
212             if resp[1] != 0x00:
213                 if resp[2] in (
214                     RESP_I2C_START_TOUT,
215                     RESP_I2C_WRADDRL_TOUT,
216                     RESP_I2C_WRADDRL_NACK,
217                     RESP_I2C_WRDATA_TOUT,
218                     RESP_I2C_STOP_TOUT,
219                 ):
220                     raise RuntimeError("Unrecoverable I2C state failure")
221                 retries += 1
222                 if retries >= MCP2221_RETRY_MAX:
223                     raise RuntimeError("I2C write error, max retries reached.")
224                 time.sleep(0.001)
225                 continue  # try again
226             # yay chunk sent!
227             while self._i2c_state() == RESP_I2C_PARTIALDATA:
228                 time.sleep(0.001)
229             start += chunk
230             retries = 0
231
232         # check status in another loop
233         for _ in range(MCP2221_RETRY_MAX):
234             status = self._i2c_status()
235             if status[20] & MASK_ADDR_NACK:
236                 raise RuntimeError("I2C slave address was NACK'd")
237             usb_cmd_status = status[8]
238             if usb_cmd_status == 0:
239                 break
240             if usb_cmd_status == RESP_I2C_WRITINGNOSTOP and cmd == 0x94:
241                 break  # this is OK too!
242             if usb_cmd_status in (
243                 RESP_I2C_START_TOUT,
244                 RESP_I2C_WRADDRL_TOUT,
245                 RESP_I2C_WRADDRL_NACK,
246                 RESP_I2C_WRDATA_TOUT,
247                 RESP_I2C_STOP_TOUT,
248             ):
249                 raise RuntimeError("Unrecoverable I2C state failure")
250             time.sleep(0.001)
251         else:
252             raise RuntimeError("I2C write error: max retries reached.")
253         # whew success!
254
255     def _i2c_read(self, cmd, address, buffer, start=0, end=None):
256         if self._i2c_state() not in (RESP_I2C_WRITINGNOSTOP, 0):
257             self._i2c_cancel()
258
259         end = end if end else len(buffer)
260         length = end - start
261
262         # tell it we want to read
263         resp = self._hid_xfer(
264             bytes([cmd, length & 0xFF, (length >> 8) & 0xFF, (address << 1) | 0x01])
265         )
266
267         # check for success
268         if resp[1] != 0x00:
269             raise RuntimeError("Unrecoverable I2C read failure")
270
271         # and now the read part
272         while (end - start) > 0:
273             for retry in range(MCP2221_RETRY_MAX):
274                 # the actual read
275                 resp = self._hid_xfer(b"\x40")
276                 # check for success
277                 if resp[1] == RESP_I2C_PARTIALDATA:
278                     time.sleep(0.001)
279                     continue
280                 if resp[1] != 0x00:
281                     raise RuntimeError("Unrecoverable I2C read failure")
282                 if resp[2] == RESP_ADDR_NACK:
283                     raise RuntimeError("I2C NACK")
284                 if resp[3] == 0x00 and resp[2] == 0x00:
285                     break
286                 if resp[3] == RESP_READ_ERR:
287                     time.sleep(0.001)
288                     continue
289                 if resp[2] in (RESP_READ_COMPL, RESP_READ_PARTIAL):
290                     break
291
292             # move data into buffer
293             chunk = min(end - start, 60)
294             for i, k in enumerate(range(start, start + chunk)):
295                 buffer[k] = resp[4 + i]
296             start += chunk
297
298     # pylint: enable=too-many-arguments
299
300     def i2c_configure(self, baudrate=100000):
301         """Configure I2C"""
302         self._hid_xfer(
303             bytes(
304                 [
305                     0x10,  # set parameters
306                     0x00,  # don't care
307                     0x00,  # no effect
308                     0x20,  # next byte is clock divider
309                     12000000 // baudrate - 3,
310                 ]
311             )
312         )
313
314     def i2c_writeto(self, address, buffer, *, start=0, end=None):
315         """Write data from the buffer to an address"""
316         self._i2c_write(0x90, address, buffer, start, end)
317
318     def i2c_readfrom_into(self, address, buffer, *, start=0, end=None):
319         """Read data from an address and into the buffer"""
320         self._i2c_read(0x91, address, buffer, start, end)
321
322     def i2c_writeto_then_readfrom(
323         self,
324         address,
325         out_buffer,
326         in_buffer,
327         *,
328         out_start=0,
329         out_end=None,
330         in_start=0,
331         in_end=None
332     ):
333         """Write data from buffer_out to an address and then
334         read data from an address and into buffer_in
335         """
336         self._i2c_write(0x94, address, out_buffer, out_start, out_end)
337         self._i2c_read(0x93, address, in_buffer, in_start, in_end)
338
339     def i2c_scan(self, *, start=0, end=0x79):
340         """Perform an I2C Device Scan"""
341         found = []
342         for addr in range(start, end + 1):
343             # try a write
344             try:
345                 self.i2c_writeto(addr, b"\x00")
346             except RuntimeError:  # no reply!
347                 continue
348             # store if success
349             found.append(addr)
350         return found
351
352     # ----------------------------------------------------------------
353     # ADC
354     # ----------------------------------------------------------------
355     def adc_configure(self, vref=0):
356         """Configure the Analog-to-Digital Converter"""
357         report = bytearray(b"\x60" + b"\x00" * 63)
358         report[5] = 1 << 7 | (vref & 0b111)
359         self._hid_xfer(report)
360
361     def adc_read(self, pin):
362         """Read from the Analog-to-Digital Converter"""
363         resp = self._hid_xfer(b"\x10")
364         return resp[49 + 2 * pin] << 8 | resp[48 + 2 * pin]
365
366     # ----------------------------------------------------------------
367     # DAC
368     # ----------------------------------------------------------------
369     def dac_configure(self, vref=0):
370         """Configure the Digital-to-Analog Converter"""
371         report = bytearray(b"\x60" + b"\x00" * 63)
372         report[3] = 1 << 7 | (vref & 0b111)
373         self._hid_xfer(report)
374
375     # pylint: disable=unused-argument
376     def dac_write(self, pin, value):
377         """Write to the Digital-to-Analog Converter"""
378         report = bytearray(b"\x60" + b"\x00" * 63)
379         report[4] = 1 << 7 | (value & 0b11111)
380         self._hid_xfer(report)
381
382     # pylint: enable=unused-argument
383
384
385 mcp2221 = MCP2221()