#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
# Shows the VerityRF web interface's address on a 128x64 SSD1306 OLED (I2C, 0x3C on
# /dev/i2c-1), as fitted to MMDVM hotspot boards. Exits quietly when no screen answers.
# Left: a QR code of the full link (with the token); right: IP, port, token, modem state.
import fcntl, os, socket, subprocess, sys, time, tomllib

BUS, ADDR, I2C_SLAVE = "/dev/i2c-1", 0x3C, 0x0703
CONFIG = "/etc/verityrf/verityrf.toml"
W, H = 128, 64


def open_screen():
    try:
        fd = os.open(BUS, os.O_RDWR)
        fcntl.ioctl(fd, I2C_SLAVE, ADDR)
        os.write(fd, bytes([0x00, 0xE3]))          # a NOP command: fails when nothing is there
        return fd
    except OSError:
        return None


def cmd(fd, *c):
    os.write(fd, bytes([0x00, *c]))


def init(fd):
    for c in ([0xAE], [0xD5, 0x80], [0xA8, 0x3F], [0xD3, 0x00], [0x40], [0x8D, 0x14],
              [0x20, 0x00], [0xA1], [0xC8], [0xDA, 0x12], [0x81, 0x8F], [0xD9, 0xF1],
              [0xDB, 0x40], [0xA4], [0xA6], [0xAF]):
        cmd(fd, *c)


def show(fd, img):
    px = img.convert("1").load()
    buf = bytearray(W * H // 8)
    for page in range(H // 8):
        for x in range(W):
            b = 0
            for bit in range(8):
                if px[x, page * 8 + bit]:
                    b |= 1 << bit
            buf[page * W + x] = b
    cmd(fd, 0x21, 0, W - 1)
    cmd(fd, 0x22, 0, H // 8 - 1)
    for i in range(0, len(buf), 16):
        os.write(fd, bytes([0x40]) + buf[i:i + 16])


def ip_address():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(("192.0.2.1", 9))              # picks the outgoing interface; sends nothing
        return s.getsockname()[0]
    except OSError:
        return None
    finally:
        s.close()


def settings():
    try:
        with open(CONFIG, "rb") as f:
            host = tomllib.load(f).get("host", {})
    except (OSError, ValueError):
        host = {}
    return int(host.get("status_port", 8320)), host.get("status_token", "")


def running():
    r = subprocess.run(["systemctl", "is-active", "--quiet", "verityrf"])
    return r.returncode == 0


def frame(ip, port, token, up):
    from PIL import Image, ImageDraw, ImageFont
    img = Image.new("1", (W, H), 0)
    d = ImageDraw.Draw(img)
    font = ImageFont.load_default()
    if ip:
        link = f"http://{ip}:{port}/" + (f"?token={token}" if token else "")
        try:
            import qrcode
            q = qrcode.QRCode(border=1, box_size=1, error_correction=qrcode.constants.ERROR_CORRECT_L)
            q.add_data(link)
            q.make(fit=True)
            m = q.get_matrix()
            scale = max(1, 64 // len(m))
            off = (64 - len(m) * scale) // 2
            for y, row in enumerate(m):
                for x, dark in enumerate(row):
                    if not dark:                  # light modules lit: dark code on a lit square
                        d.rectangle([off + x * scale, off + y * scale,
                                     off + x * scale + scale - 1, off + y * scale + scale - 1], fill=1)
        except ImportError:
            pass
        a, b = ip.rsplit(".", 2)[0] + ".", ".".join(ip.rsplit(".", 2)[1:])
        lines = ["VerityRF", a, b, f":{port}", token, "running" if up else "stopped"]
    else:
        lines = ["VerityRF", "no network", "", socket.gethostname(), "", "running" if up else "stopped"]
    for i, t in enumerate(lines):
        d.text((67, i * 10 + 1), t[:10], font=font, fill=1)
    return img


def main():
    fd = None
    for _ in range(30):                          # the bus can appear a little after boot
        fd = open_screen()
        if fd is not None:
            break
        time.sleep(2)
    if fd is None:
        print("verityrf-oled: no SSD1306 at 0x3C on", BUS)
        return 0
    init(fd)
    last = None
    while True:
        port, token = settings()
        state = (ip_address(), port, token, running())
        if state != last:
            show(fd, frame(*state))
            last = state
        time.sleep(10)


if __name__ == "__main__":
    sys.exit(main())
