"""Module 16: read the Seeed 3x4 capacitive keypad through UART."""

import time
import board
import busio
import adafruit_ssd1306


def show_module(oled, number, title, lines):
    """Draw this lesson's OLED screen without an external helper module."""
    oled.fill(0)
    oled.text("({}) {}".format(number, title)[:21], 0, 0, 1)
    for index, line in enumerate(lines[:4]):
        oled.text(str(line)[:21], 0, 16 + index * 11, 1)
    oled.show()


KEYS = {
    0xE1: "1", 0xE2: "2", 0xE3: "3",
    0xE4: "4", 0xE5: "5", 0xE6: "6",
    0xE7: "7", 0xE8: "8", 0xE9: "9",
    0xEA: "*", 0xEB: "0", 0xEC: "#",
}

i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
uart = busio.UART(
    tx=board.GP20,
    rx=board.GP21,
    baudrate=9600,
    timeout=0.01,
)
history = ""
show_module(oled, 16, "Cap. Keypad", (
    "Pico TX GP20 -> RX",
    "Pico RX GP21 <- TX",
    "Touch a key",
))

try:
    while True:
        data = uart.read(1)
        if data:
            key = KEYS.get(data[0], "?")
            history = (history + key)[-8:]
            show_module(oled, 16, "Cap. Keypad", (
                "TX GP20 / RX GP21",
                "Last key: " + key,
                "Keys: " + history,
            ))
            print("Key:", key, "raw: 0x{:02X}".format(data[0]))
        else:
            time.sleep(0.01)
finally:
    uart.deinit()
    i2c.deinit()
