#!/usr/bin/env python3
"""Control a Lockink BLE locking box (device name AA-A1002, protocol family "OLD").

Protocol source: static analysis of Lockink APK 1.5.7 (package com.lockink.phonelive),
corroborated by a live hardware capture of an AA-A1002 (see skill lockink-lock).

Transport: vendor GATT service 00008ac0, write char 8ac1 (write-with-response),
notify char 8ac2 (CCCD 2902 = 01 00).

Frames (family OLD / AA-A1002):
  battery : AA 03                  -> notify BB 03 <pct>
  unlock  : AA 01 01 <voltage>     (voltage 0 = what the reference app sends)
  lock    : AA 01 00 <voltage>     (EXPERIMENTAL: reference app never sends close
                                    for AA-A1002; the box re-locks itself after a
                                    built-in timeout once unlocked)

The box advertises only in short windows (~minutes). If it does not answer the
scan, it must be re-activated (power cycle / wake via its own app or button).
"""

import argparse
import asyncio
import sys
import time

from bleak import BleakClient, BleakScanner

SERVICE = "00008ac0-0000-1000-8000-00805f9b34fb"
CHAR_WRITE = "00008ac1-0000-1000-8000-00805f9b34fb"
CHAR_NOTIFY = "00008ac2-0000-1000-8000-00805f9b34fb"

FRAME_BATTERY = bytes([0xAA, 0x03])
# AA 01 <open=01/close=00> <voltage>
def frame_lock(close: bool, voltage: int = 0) -> bytes:
    return bytes([0xAA, 0x01, 0x00 if close else 0x01, voltage & 0xFF])


def hexs(data: bytes) -> str:
    return " ".join(f"{b:02X}" for b in data)


async def find_device(name: str, timeout: float) -> str | None:
    print(f"Scanning {timeout:.0f}s for BLE name '{name}' ...")
    dev = await BleakScanner.find_device_by_name(name, timeout=timeout)
    return dev.address if dev else None


class Session:
    """Connected lock with notification logging."""

    def __init__(self, address: str):
        self.address = address
        self.client: BleakClient | None = None
        self.log: list[tuple[float, bytes]] = []

    def _on_notify(self, _char, data: bytearray):
        entry = (time.time(), bytes(data))
        self.log.append(entry)
        print(f"  notify: {hexs(bytes(data))}")

    async def __aenter__(self):
        print(f"Connecting to {self.address} ...")
        self.client = BleakClient(self.address, timeout=20)
        try:
            await self.client.connect()
        except Exception as e:
            raise SystemExit(
                f"ERROR: could not connect to {self.address}: {e}\n"
                "The box advertises only briefly. If it is asleep, "
                "re-activate it (power cycle / wake it) and re-run."
            )
        await self.client.start_notify(CHAR_NOTIFY, self._on_notify)
        print("Connected; notifications on 8ac2 enabled.")
        return self

    async def __aexit__(self, *exc):
        if self.client and self.client.is_connected:
            try:
                await self.client.disconnect()
                print("Disconnected cleanly.")
            except Exception:
                pass

    async def send(self, frame: bytes, wait: float = 2.0):
        print(f"  write  : {hexs(frame)}")
        await self.client.write_gatt_char(CHAR_WRITE, frame, response=True)
        before = len(self.log)
        deadline = time.time() + wait
        while time.time() < deadline and len(self.log) == before:
            await asyncio.sleep(0.1)

    async def battery(self) -> int | None:
        await self.send(FRAME_BATTERY, wait=3.0)
        for _, raw in reversed(self.log):
            # OLD-family handler: response[1]==03 -> battery in response[2]
            if len(raw) >= 3 and raw[1] == 0x03:
                pct = raw[2] & 0xFF
                if pct <= 100:
                    return pct
        return None


async def cmd_scan(args):
    for d in await BleakScanner.discover(timeout=args.timeout):
        if d.name:
            print(f"{d.address}  {d.name}")


async def cmd_connect_run(args, action):
    address = args.address or await find_device(args.name, args.scan_timeout)
    if not address:
        raise SystemExit(
            f"ERROR: no advertising '{args.name}' found. "
            "NOTIFY: the box needs re-activation (it only advertises for a "
            "couple of minutes after waking)."
        )
    async with Session(address) as s:
        # Reference app waits ~3 s after connect before first request.
        await asyncio.sleep(3.0)
        await action(s)


async def action_battery(s: Session):
    pct = await s.battery()
    print(f"BATTERY: {pct}%" if pct is not None else "BATTERY: no parseable reply (see raw log)")


async def action_mech(s: Session, close: bool, voltage: int):
    verb = "LOCK" if close else "UNLOCK"
    print(f"Sending {verb} (mechanical action) ...")
    await s.send(frame_lock(close=close, voltage=voltage), wait=5.0)
    if close:
        print("Lock frame accepted by the GATT layer. "
              "Effect on AA-A1002 is not confirmed by the reference app.")
    else:
        print("Unlock frame accepted by the GATT layer. "
              "Note: the box typically drops the link seconds after unlocking.")


async def action_monitor(s: Session, seconds: float):
    print(f"Monitoring notifications for {seconds:.0f}s "
          "(heartbeat AA 03 every 10s) ...")
    end = time.time() + seconds
    last_hb = 0.0
    while time.time() < end:
        if time.time() - last_hb >= 10.0:
            await s.send(FRAME_BATTERY, wait=0.5)
            last_hb = time.time()
        await asyncio.sleep(0.5)


async def action_raw(s: Session, frame_hex: str):
    await s.send(bytes.fromhex(frame_hex), wait=5.0)


def main():
    p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    p.add_argument("--address", help="BLE address (default: scan by name)")
    p.add_argument("--name", default="AA-A1002", help="BLE name to scan for")
    p.add_argument("--scan-timeout", type=float, default=15.0)
    sub = p.add_subparsers(dest="cmd", required=True)

    sp = sub.add_parser("scan", help="list named BLE devices")
    sp.add_argument("--timeout", type=float, default=12.0)

    sub.add_parser("battery", help="query battery level")
    up = sub.add_parser("unlock", help="mechanically unlock the box")
    up.add_argument("--voltage", type=int, default=0,
                    help="release voltage byte (0 = reference-app default)")
    lp = sub.add_parser("lock", help="mechanically lock (EXPERIMENTAL on A1002)")
    lp.add_argument("--voltage", type=int, default=0)

    mp = sub.add_parser("monitor", help="log all notifications, heartbeating")
    mp.add_argument("--seconds", type=float, default=60.0)

    rp = sub.add_parser("raw", help="send a raw hex frame to 8ac1")
    rp.add_argument("frame", help='hex bytes, e.g. "AA 03"')

    args = p.parse_args()

    async def run():
        if args.cmd == "scan":
            await cmd_scan(args)
        elif args.cmd == "battery":
            await cmd_connect_run(args, action_battery)
        elif args.cmd == "unlock":
            await cmd_connect_run(
                args, lambda s: action_mech(s, close=False, voltage=args.voltage))
        elif args.cmd == "lock":
            await cmd_connect_run(
                args, lambda s: action_mech(s, close=True, voltage=args.voltage))
        elif args.cmd == "monitor":
            await cmd_connect_run(
                args, lambda s: action_monitor(s, args.seconds))
        elif args.cmd == "raw":
            await cmd_connect_run(args, lambda s: action_raw(s, args.frame))

    asyncio.run(run())


if __name__ == "__main__":
    main()
