# SPDX-License-Identifier: MIT
# Copyright (c) 2026 Dreiym Engineering PLLC
#
# Dreiym bench firmware for the BBC micro:bit V2 (MicroPython for micro:bit, version 2), protocol dzhw/1.
# Load it with the micro:bit Python Editor (python.microbit.org): open this file, then send it to the board.
#
# Pins (3.3 V logic; never more than 3.3 V on any pin):
#   P0 / P1 / P2 = inputs IN0..IN2, 0 to 3.3 V (the three large ring pads; crocodile clips are fine)
#   P8 = PWM output, filtered by 10 kohm + 10 uF to a DC level 0 to 3.3 V (output "PWM", DC only; needs an edge breakout)
#   P12 / P16 = relay module inputs K1 / K2 (low voltage relay boards only; edge breakout)
#   Self test loop: a jumper from the filtered PWM output to P0.
# Hold button A while the board starts to skip this program (the display shows a dash and the board waits).
# The micro:bit V1 has too little memory for this file; use a V2 (it has a speaker and a touch logo).
import utime
from microbit import pin0, pin1, pin2, pin8, pin12, pin16, uart, button_a, display
try:
    import json
except ImportError:
    json = None
try:
    import ubinascii as binascii
except ImportError:
    try:
        import binascii
    except ImportError:
        binascii = None
try:
    import machine
except ImportError:
    machine = None

FW = 'microbit-mpy 1.0.0'
VREF = 3.3
WATCHDOG_MS = 3000
CAP_RATE = 4000        # samples per second in total across the inputs of one capture (declared; the test plan records it)
CAP_N = 1000           # samples per input per capture
MAX_LINE = 4096
PWM_PERIOD_US = 256    # about 3.9 kHz; the 10 kohm + 10 uF filter leaves a few mV of ripple

_T = []
for _i in range(256):
    _c = _i << 8
    for _j in range(8):
        _c = ((_c << 1) ^ 0x1021) & 0xffff if _c & 0x8000 else (_c << 1) & 0xffff
    _T.append(_c)


def crc16(b):
    c = 0xffff
    t = _T
    for x in b:
        c = ((c << 8) & 0xffff) ^ t[((c >> 8) ^ x) & 0xff]
    return c


# ---- small JSON reader and writer, used when the MicroPython build has no json module
def _jw(o, out):
    if o is None:
        out.append('null')
    elif o is True:
        out.append('true')
    elif o is False:
        out.append('false')
    elif isinstance(o, int):
        out.append(str(o))
    elif isinstance(o, float):
        if o != o or o in (float('inf'), float('-inf')):
            out.append('null')
        else:
            out.append(repr(o))
    elif isinstance(o, str):
        s = ['"']
        for ch in o:
            k = ord(ch)
            if ch == '"' or ch == '\\':
                s.append('\\' + ch)
            elif k < 32:
                s.append('\\u%04x' % k)
            else:
                s.append(ch)
        s.append('"')
        out.append(''.join(s))
    elif isinstance(o, (list, tuple)):
        out.append('[')
        for i, v in enumerate(o):
            if i:
                out.append(',')
            _jw(v, out)
        out.append(']')
    elif isinstance(o, dict):
        out.append('{')
        i = 0
        for k in o:
            if i:
                out.append(',')
            _jw(str(k), out)
            out.append(':')
            _jw(o[k], out)
            i += 1
        out.append('}')
    else:
        _jw(str(o), out)


def dumps(o):
    if json:
        return json.dumps(o)
    out = []
    _jw(o, out)
    return ''.join(out)


class _JR:
    def __init__(self, s):
        self.s = s
        self.i = 0

    def ws(self):
        s = self.s
        while self.i < len(s) and s[self.i] in ' \t\r\n':
            self.i += 1

    def val(self, depth=0):
        if depth > 8:
            raise ValueError('deep')
        self.ws()
        s = self.s
        if self.i >= len(s):
            raise ValueError('end')
        ch = s[self.i]
        if ch == '{':
            self.i += 1
            d = {}
            self.ws()
            if s[self.i:self.i + 1] == '}':
                self.i += 1
                return d
            while True:
                self.ws()
                if s[self.i:self.i + 1] != '"':
                    raise ValueError('key')
                k = self.str_()
                self.ws()
                if s[self.i:self.i + 1] != ':':
                    raise ValueError(':')
                self.i += 1
                d[k] = self.val(depth + 1)
                self.ws()
                c = s[self.i:self.i + 1]
                self.i += 1
                if c == '}':
                    return d
                if c != ',':
                    raise ValueError(',')
        if ch == '[':
            self.i += 1
            a = []
            self.ws()
            if s[self.i:self.i + 1] == ']':
                self.i += 1
                return a
            while True:
                a.append(self.val(depth + 1))
                self.ws()
                c = s[self.i:self.i + 1]
                self.i += 1
                if c == ']':
                    return a
                if c != ',':
                    raise ValueError(',')
        if ch == '"':
            return self.str_()
        for word, v in (('true', True), ('false', False), ('null', None)):
            if s[self.i:self.i + len(word)] == word:
                self.i += len(word)
                return v
        j = self.i
        while j < len(s) and s[j] in '+-0123456789.eE':
            j += 1
        t = s[self.i:j]
        if not t:
            raise ValueError('value')
        self.i = j
        if '.' in t or 'e' in t or 'E' in t:
            return float(t)
        return int(t)

    def str_(self):
        s = self.s
        self.i += 1
        out = []
        while True:
            if self.i >= len(s):
                raise ValueError('string')
            ch = s[self.i]
            self.i += 1
            if ch == '"':
                return ''.join(out)
            if ch == '\\':
                e = s[self.i:self.i + 1]
                self.i += 1
                if e == 'u':
                    out.append(chr(int(s[self.i:self.i + 4], 16)))
                    self.i += 4
                else:
                    out.append({'n': '\n', 't': '\t', 'r': '\r', 'b': '\b', 'f': '\f'}.get(e, e))
            else:
                out.append(ch)


def loads(b):
    if json:
        return json.loads(b)
    s = b.decode() if isinstance(b, (bytes, bytearray)) else b
    r = _JR(s)
    v = r.val()
    r.ws()
    if r.i != len(s):
        raise ValueError('trailing')
    return v


_B64 = b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'


def b64(data):
    if binascii:
        return binascii.b2a_base64(data).decode().strip()
    out = bytearray()
    n = len(data)
    for i in range(0, n - n % 3, 3):
        v = (data[i] << 16) | (data[i + 1] << 8) | data[i + 2]
        out += bytes([_B64[v >> 18], _B64[(v >> 12) & 63], _B64[(v >> 6) & 63], _B64[v & 63]])
    r = n % 3
    if r == 1:
        v = data[n - 1] << 16
        out += bytes([_B64[v >> 18], _B64[(v >> 12) & 63]]) + b'=='
    elif r == 2:
        v = (data[n - 2] << 16) | (data[n - 1] << 8)
        out += bytes([_B64[v >> 18], _B64[(v >> 12) & 63], _B64[(v >> 6) & 63]]) + b'='
    return out.decode()


def frame(obj):
    jb = dumps(obj).encode()
    return jb + b'~' + ('%04X' % crc16(jb)).encode() + b'\n'


def unframe(line):
    line = line.strip()
    k = line.rfind(b'~')
    if k < 0 or len(line) - k != 5:
        return None
    try:
        want = int(line[k + 1:], 16)
    except ValueError:
        return None
    body = line[:k]
    if crc16(body) != want:
        return None
    try:
        o = loads(body)
    except Exception:
        return None
    return o if isinstance(o, dict) else None


class Err(Exception):
    def __init__(self, code, msg=''):
        Exception.__init__(self, msg)
        self.code = code
        self.msg = msg


class Hardware:
    """Pins of the micro:bit. Everything the host may touch is listed here; nothing else."""
    def __init__(self):
        self.ins = [pin0, pin1, pin2]
        self.pwm = pin8
        self.pwm.write_digital(0)
        self.relays = [pin12, pin16]
        for r in self.relays:
            r.write_digital(0)

    def set_pwm(self, code):
        if code <= 0:
            self.pwm.write_digital(0)
        else:
            self.pwm.write_analog(min(1023, code))
            try:
                self.pwm.set_analog_period_microseconds(PWM_PERIOD_US)
            except Exception:
                pass


class Bench:
    def __init__(self, hw, write):
        self.hw = hw
        self.write = write
        self.buf = b''
        self.last = utime.ticks_ms()
        self.outs_on = False
        self.bench = self._load('bench.txt', '')
        self.cal = self._loadj('cal.json', {})
        self.t0 = utime.ticks_ms()
        self.ain = [{'ch': k, 'name': 'IN' + str(k), 'min': 0, 'max': VREF, 'bits': 10, 'rate': CAP_RATE} for k in range(3)]
        self.aout = [{'ch': 0, 'name': 'PWM', 'min': 0, 'max': VREF, 'bits': 10, 'shapes': ['dc'], 'fmax': 0}]
        self.valid_in = [0, 1, 2]

    def _load(self, fn, d):
        try:
            with open(fn) as f:
                return f.read().strip()[:24]
        except Exception:
            return d

    def _loadj(self, fn, d):
        try:
            with open(fn) as f:
                return loads(f.read())
        except Exception:
            return d

    def _raw(self, ch):
        return self.hw.ins[ch].read_analog() * VREF / 1023

    def _chs(self, a):
        if not isinstance(a, list) or not a or len(a) > 3:
            raise Err('badarg', 'ch')
        out = []
        for c in a:
            if not isinstance(c, int) or isinstance(c, bool) or c not in self.valid_in:
                raise Err('badarg', 'ch %s' % c)
            out.append(c)
        return out

    def safe(self):
        self.hw.set_pwm(0)
        for r in self.hw.relays:
            r.write_digital(0)
        self.outs_on = False

    def out(self, m):
        ch = m.get('ch')
        if ch != 0 or isinstance(ch, bool):
            raise Err('badarg', 'ch')
        if m.get('off') is True:
            v = 0.0
        elif 'dc' in m:
            v = m['dc']
            if isinstance(v, bool) or not isinstance(v, (int, float)) or v < 0 or v > VREF:
                raise Err('range', 'dc 0 to 3.3 V')
        elif 'wave' in m:
            raise Err('nocap', 'this output is DC only')
        else:
            raise Err('badarg', 'out')
        self.hw.set_pwm(int(round(v / VREF * 1023)))
        self.outs_on = self.outs_on or v > 0
        return {'set': {'dc': v} if m.get('off') is not True else {'off': True}}

    def hello(self, m):
        uid = ''
        try:
            u = machine.unique_id()
            uid = ''.join('%02x' % x for x in u)
        except Exception:
            pass
        return {'proto': 1,
                'dev': {'vendor': 'micro:bit', 'model': 'micro:bit bench', 'fw': FW, 'serial': uid, 'bench': self.bench, 'transport': 'usb-cdc'},
                'caps': {'ain': self.ain, 'aout': self.aout, 'dout': [],
                         'relay': [{'ch': 0, 'name': 'K1', 'maxV': 12, 'maxA': 1}, {'ch': 1, 'name': 'K2', 'maxV': 12, 'maxA': 1}],
                         'capture': {'rate': CAP_RATE, 'n': CAP_N, 'trig': True, 'shared': True}, 'stream': None, 'calStore': True, 'selftest': True},
                'safety': {'maxIn': VREF, 'outMax': VREF, 'note': '3.3 V pins, not 5 V tolerant'}}

    def read(self, m):
        chs = self._chs(m.get('ch'))
        n = m.get('n', 64)
        n = 1 if not isinstance(n, int) or n < 1 else min(n, 512)
        win = m.get('win', 0) or 0
        dt_us = int(win * 1e6 / n) if isinstance(win, (int, float)) and 0 < win <= 1 else 0
        acc = [[0.0, 0.0, 1e9, -1e9] for _ in chs]
        t_next = utime.ticks_us()
        for _ in range(n):
            if dt_us:
                while utime.ticks_diff(utime.ticks_us(), t_next) < 0:
                    pass
                t_next = utime.ticks_add(t_next, dt_us)
            for k, c in enumerate(chs):
                v = self._raw(c)
                a = acc[k]
                a[0] += v
                a[1] += v * v
                if v < a[2]:
                    a[2] = v
                if v > a[3]:
                    a[3] = v
        return {'mean': [a[0] / n for a in acc], 'rms': [(a[1] / n) ** 0.5 for a in acc], 'min': [a[2] for a in acc],
                'max': [a[3] for a in acc], 'n': n, 'rate': (n / win) if dt_us else 0}

    def capture(self, m):
        chs = self._chs(m.get('ch'))
        n = m.get('n', 500)
        n = max(16, min(int(n), CAP_N)) if isinstance(n, (int, float)) and not isinstance(n, bool) else 500
        rate = m.get('rate', 2000)
        if isinstance(rate, bool) or not isinstance(rate, (int, float)) or rate <= 0 or rate * len(chs) > CAP_RATE:
            raise Err('range', 'rate times inputs must be at most %d' % CAP_RATE)
        tr = m.get('trig') or None
        if tr is not None and not isinstance(tr, dict):
            raise Err('badarg', 'trig')
        pre = 0
        if tr:
            pre = int(max(0.0, min(0.9, float(tr.get('pre', 0.1)))) * n)
        data, real_rate = self._sample(chs, 2 * n if tr else n, rate)
        start = 0
        trig = 'none'
        nc = len(chs)
        if tr:
            trig = 'auto'
            tch = tr.get('ch')
            if tch in chs:
                lvl = int(float(tr.get('level', 0)) / VREF * 1023)
                col = chs.index(tch)
                rise = tr.get('edge', 'rise') != 'fall'
                for i in range(max(1, pre), 2 * n - (n - pre)):
                    a = data[(i - 1) * nc + col]
                    b = data[i * nc + col]
                    if (rise and a < lvl <= b) or ((not rise) and a > lvl >= b):
                        start = i - pre
                        trig = 'ok'
                        break
        out = {'rate': real_rate, 'n': n, 'pre': pre if trig == 'ok' else 0, 'trig': trig if tr else 'none', 'enc': 'i16b64', 'd': [], 'scale': [], 'off': []}
        for k in range(nc):
            seg = bytearray(2 * n)
            for i in range(n):
                x = data[(start + i) * nc + k]
                seg[2 * i] = x & 0xff
                seg[2 * i + 1] = (x >> 8) & 0xff
            out['d'].append(b64(seg))
            out['scale'].append(VREF / 1023)
            out['off'].append(0)
        return out

    def _sample(self, chs, total, rate):
        import array
        nc = len(chs)
        buf = array.array('H', [0] * (total * nc))
        ins = [self.hw.ins[c] for c in chs]
        dt = int(1000000 / rate)
        t_next = utime.ticks_us()
        t_start = t_next
        j = 0
        for i in range(total):
            while utime.ticks_diff(utime.ticks_us(), t_next) < 0:
                pass
            t_next = utime.ticks_add(t_next, dt)
            for p in ins:
                buf[j] = p.read_analog()
                j += 1
        el = utime.ticks_diff(utime.ticks_us(), t_start)
        real = (total * 1e6 / el) if el > 0 else rate
        return buf, real

    def selftest(self, m):
        tests = []
        for want in (1.0, 2.0):
            self.hw.set_pwm(int(round(want / VREF * 1023)))
            utime.sleep_ms(600)  # 10 kohm x 10 uF filter settles in about 5 tau
            s = 0.0
            for _ in range(64):
                s += self._raw(0)
            v = s / 64
            tests.append({'name': 'PWM to IN0 at %.1f V (needs the loop jumper)' % want, 'ok': abs(v - want) < 0.15, 'v': v, 'want': want})
        self.hw.set_pwm(0)
        return {'tests': tests}

    def handle(self, m):
        op = m.get('op')
        if op == 'hello':
            return self.hello(m)
        if op == 'ping':
            return {'t': utime.ticks_diff(utime.ticks_ms(), self.t0)}
        if op == 'read':
            return self.read(m)
        if op == 'capture':
            return self.capture(m)
        if op == 'out':
            return self.out(m)
        if op == 'dout':
            ch = m.get('ch')
            if ch not in (0, 1) or isinstance(ch, bool):
                raise Err('badarg', 'ch')
            self.hw.relays[ch].write_digital(1 if m.get('v') else 0)
            self.outs_on = self.outs_on or bool(m.get('v'))
            return {}
        if op == 'safe':
            self.safe()
            return {}
        if op == 'stop':
            return {}
        if op == 'selftest':
            return self.selftest(m)
        if op == 'name':
            b = ''.join(ch for ch in str(m.get('bench', ''))[:24] if ch.isalpha() or ch.isdigit() or ch in ' _.')
            with open('bench.txt', 'w') as f:
                f.write(b)
            self.bench = b
            return {}
        if op == 'cal':
            ch = m.get('ch')
            g = m.get('gain')
            o = m.get('off')
            if ch not in self.valid_in or isinstance(g, bool) or isinstance(o, bool) or not isinstance(g, (int, float)) or not isinstance(o, (int, float)) or not (0.8 < g < 1.25) or abs(o) > 0.5:
                raise Err('badarg', 'cal')
            self.cal[str(ch)] = [g, o]
            with open('cal.json', 'w') as f:
                f.write(dumps(self.cal))
            return {}
        raise Err('badop', str(op))

    def feed(self, data):
        self.buf += data
        if len(self.buf) > MAX_LINE and b'\n' not in self.buf:
            self.buf = b''
        while b'\n' in self.buf:
            line, self.buf = self.buf.split(b'\n', 1)
            if not line.strip():
                continue
            self.last = utime.ticks_ms()
            m = unframe(line)
            if m is None:
                continue
            try:
                r = self.handle(m)
                r['ok'] = True
            except Err as e:
                r = {'ok': False, 'err': e.code, 'msg': e.msg}
            except Exception as e:
                r = {'ok': False, 'err': 'internal', 'msg': str(e)[:80]}
            if 'id' in m:
                r['id'] = m['id']
                self.write(frame(r))

    def tick(self):
        if self.outs_on and utime.ticks_diff(utime.ticks_ms(), self.last) > WATCHDOG_MS:
            self.safe()


def run():
    uart.init(baudrate=115200)

    def write(b):
        for i in range(0, len(b), 256):
            uart.write(b[i:i + 256])
    bench = Bench(Hardware(), write)
    display.show('D')
    while True:
        if uart.any():
            ch = uart.read(256)
            if ch:
                bench.feed(ch)
        else:
            utime.sleep_ms(2)
        bench.tick()


if __name__ == '__main__':
    if button_a.is_pressed():
        display.show('-')
    else:
        run()
