Skip to content

Commit

Permalink
keypad structured communication
Browse files Browse the repository at this point in the history
  • Loading branch information
georgeharker committed Nov 5, 2023
1 parent 7e39d6f commit 4d22046
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
42 changes: 38 additions & 4 deletions adafruit_seesaw/keypad.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@
====================================================
"""

import struct
from enum import IntEnum
from typing import NamedTuple

try:
from micropython import const
except ImportError:
Expand All @@ -48,6 +52,30 @@ def const(x):
_KEYPAD_COUNT = const(0x04)
_KEYPAD_FIFO = const(0x10)


class ResponseType(IntEnum):
# Types for the repsonse
TYPE_KEY = 0
TYPE_COUNT = 1
TYPE_STATUS = 2
TYPE_INVALID = 0xff


class SeesawKeyResponse(NamedTuple):
response_type: ResponseType
data: int

unpacker: struct.Struct = struct.Struct('<BB')

@classmethod
def unpack(cls, buf: bytearray):
return SeesawKeyResponse(*cls.unpacker.unpack(buf))

@classmethod
def unpack_from(cls, buf: bytearray, frm: int):
return SeesawKeyResponse(*cls.unpacker.unpack_from(buf, frm))


# pylint: disable=too-few-public-methods
class KeyEvent:
"""Holds information about a key event in its properties
Expand Down Expand Up @@ -103,7 +131,11 @@ def interrupt_enabled(self, value):
@property
def count(self):
"""Retrieve or set the number of keys"""
return self.read8(_KEYPAD_BASE, _KEYPAD_COUNT)
buf = self.readn(_KEYPAD_BASE, _KEYPAD_COUNT, 2)
d = SeesawKeyResponse.unpack(buf)
if d.response_type != self.TYPE_COUNT:
return 0
return d.data

# pylint: disable=unused-argument, no-self-use
@count.setter
Expand Down Expand Up @@ -134,6 +166,8 @@ def read_keypad(self, num):
"""Read data from the keypad
:param int num: The number of bytes to read"""
ret = bytearray(num)
self.read(_KEYPAD_BASE, _KEYPAD_FIFO, ret)
return ret
buf = bytearray(num * 2)
self.read(_KEYPAD_BASE, _KEYPAD_FIFO, buf)

return [SeesawKeyResponse.unpack_from(buf, i)
for i in range(0, num)]
6 changes: 6 additions & 0 deletions adafruit_seesaw/seesaw.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,12 @@ def read8(self, reg_base, reg):
self.read(reg_base, reg, ret)
return ret[0]

def readn(self, reg_base, reg, n):
"""Read an arbitrary I2C byte register on the device"""
ret = bytearray(n)
self.read(reg_base, reg, ret)
return ret

def read(self, reg_base, reg, buf, delay=0.0006):
"""Read an arbitrary I2C register range on the device"""
self.write(reg_base, reg)
Expand Down

0 comments on commit 4d22046

Please sign in to comment.