# SPDX-License-Identifier: MIT
# Copyright (c) 2026 Dreiym Engineering PLLC
# Dreiym bench firmware for Raspberry Pi Pico / Pico W / Pico 2 / Pico 2 W (MicroPython), protocol dzhw/1.
# Copy this file to the board as main.py (Thonny, or: mpremote cp main.py :main.py).
#
# Pins (3.3 V logic; NOT 5 V tolerant):
#   GP26 / GP27 / GP28 = ADC0..ADC2 inputs, 0 to 3.3 V   (use a divider for more; see the setup guide)
#   GP15 = PWM output, filtered by 10 kohm + 10 uF to a DC level 0 to 3.3 V (output "PWM", DC only)
#   GP16 / GP17 = relay module inputs K1 / K2 (low voltage relay boards only)
#   GP4 (SDA) / GP5 (SCL) = I2C for optional ADS1115 (0x48), MCP4725 (0x60), INA219 (0x40)
#   Self test loop: a jumper from the filtered PWM output to GP26.
# Hold GP14 to GND while plugging in to skip this program and get the normal MicroPython prompt.
import sys, json, time
try:
    import micropython
    native = micropython.native
except Exception:  # CPython tests
    def native(f):
        return f
try:
    import ubinascii as binascii
except ImportError:
    import binascii
try:
    import uselect as select
except ImportError:
    import select
import machine

FW = 'pico-mpy 1.0.0'
VREF = 3.3
WATCHDOG_MS = 3000
CAP_RATE = 20000       # samples per second in total across the inputs of one capture (MicroPython loop; see test plan)
CAP_N = 2000           # samples per input per capture
MAX_LINE = 8192

_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


def frame(obj):
    j = json.dumps(obj)
    if isinstance(j, str):
        jb = j.encode()
    else:
        jb = j
    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 = json.loads(body)
    except ValueError:
        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 and the optional I2C parts. Everything the host may touch is listed here; nothing else."""
    def __init__(self):
        self.adc = [machine.ADC(26), machine.ADC(27), machine.ADC(28)]
        self.pwm = machine.PWM(machine.Pin(15))
        self.pwm.freq(100000)
        self.pwm.duty_u16(0)
        self.relays = [machine.Pin(16, machine.Pin.OUT, value=0), machine.Pin(17, machine.Pin.OUT, value=0)]
        self.i2c = None
        self.ads = self.dac = self.ina = False
        try:
            self.i2c = machine.I2C(0, sda=machine.Pin(4), scl=machine.Pin(5), freq=400000)
            found = self.i2c.scan()
            self.ads = 0x48 in found
            self.dac = 0x60 in found
            self.ina = 0x40 in found
        except Exception:
            self.i2c = None
        if self.ina:
            # 32 V range bit cleared (16 V bus range), PGA /8 (320 mV), 12-bit, continuous; calibration for 0.1 ohm shunt
            self._w16(0x40, 0x00, 0x199F & ~0x2000)
            self._w16(0x40, 0x05, 4096)

    def _w16(self, addr, reg, v):
        self.i2c.writeto_mem(addr, reg, bytes([(v >> 8) & 0xff, v & 0xff]))

    def _r16(self, addr, reg):
        b = self.i2c.readfrom_mem(addr, reg, 2)
        v = (b[0] << 8) | b[1]
        return v - 65536 if v & 0x8000 else v

    def ads_read(self, ch):
        # single shot, AINx to GND, +-4.096 V gain, 860 SPS
        cfg = 0x8000 | ((4 + ch) << 12) | (1 << 9) | (1 << 8) | (7 << 5) | 3
        self._w16(0x48, 0x01, cfg)
        t0 = time.ticks_ms()
        while not (self._r16(0x48, 0x01) & 0x8000):
            if time.ticks_diff(time.ticks_ms(), t0) > 10:
                break
        return self._r16(0x48, 0x00) * 4.096 / 32768

    def ina_amps(self):
        # current register LSB = 0.1 mA with the calibration above (0.1 ohm shunt)
        return self._r16(0x40, 0x04) * 1e-4

    def ina_volts(self):
        return ((self._r16(0x40, 0x02) >> 3) & 0x1fff) * 0.004


class Bench:
    def __init__(self, hw, write):
        self.hw = hw
        self.write = write
        self.buf = b''
        self.last = time.ticks_ms()
        self.outs_on = False
        self.bench = self._load('bench.txt', '')
        self.cal = self._loadj('cal.json', {})
        self.t0 = time.ticks_ms()
        self.ain = [{'ch': 0, 'name': 'ADC0', 'min': 0, 'max': VREF, 'bits': 12, 'rate': CAP_RATE},
                    {'ch': 1, 'name': 'ADC1', 'min': 0, 'max': VREF, 'bits': 12, 'rate': CAP_RATE},
                    {'ch': 2, 'name': 'ADC2', 'min': 0, 'max': VREF, 'bits': 12, 'rate': CAP_RATE}]
        if hw.ads:
            for k in range(4):
                self.ain.append({'ch': 3 + k, 'name': 'ADS' + str(k), 'min': 0, 'max': VREF, 'bits': 16, 'rate': 800})
        if hw.ina:
            self.ain.append({'ch': 7, 'name': 'INA-I', 'min': -3.2, 'max': 3.2, 'bits': 12, 'rate': 500, 'kind': 'i'})
            self.ain.append({'ch': 8, 'name': 'INA-V', 'min': 0, 'max': 12, 'bits': 12, 'rate': 500})
        self.aout = [{'ch': 0, 'name': 'PWM', 'min': 0, 'max': VREF, 'bits': 16, 'shapes': ['dc'], 'fmax': 0}]
        if hw.dac:
            self.aout.append({'ch': 1, 'name': 'DAC', 'min': 0, 'max': VREF, 'bits': 12, 'shapes': ['dc'], 'fmax': 0})
        self.valid_in = [a['ch'] for a in self.ain]

    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 json.loads(f.read())
        except Exception:
            return d

    # ---- inputs
    def _raw(self, ch):
        """volts at the pin, the device's own scale (before host calibration)"""
        if ch < 3:
            return (self.hw.adc[ch].read_u16() >> 4) * VREF / 4095
        if 3 <= ch <= 6:
            return self.hw.ads_read(ch - 3)
        if ch == 7:
            return self.hw.ina_amps()
        if ch == 8:
            return self.hw.ina_volts()
        raise Err('badarg', 'ch')

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

    # ---- outputs (only the declared ones)
    def safe(self):
        self.hw.pwm.duty_u16(0)
        for r in self.hw.relays:
            r.value(0)
        if self.hw.dac:
            try:
                self.hw.i2c.writeto(0x60, bytes([0, 0]))
            except Exception:
                pass
        self.outs_on = False

    def out(self, m):
        ch = m.get('ch')
        if ch not in [a['ch'] for a in self.aout]:
            raise Err('badarg', 'ch')
        if m.get('off') is True:
            v = 0.0
        elif 'dc' in m:
            v = m['dc']
            if 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')
        if ch == 0:
            self.hw.pwm.duty_u16(int(round(v / VREF * 65535)))
        else:
            code = int(round(v / VREF * 4095))
            self.hw.i2c.writeto(0x60, bytes([(code >> 8) & 0x0f, code & 0xff]))
        self.outs_on = self.outs_on or v > 0
        return {'set': {'dc': v} if m.get('off') is not True else {'off': True}}

    # ---- ops
    def hello(self, m):
        try:
            uid = binascii.hexlify(machine.unique_id()).decode()
        except Exception:
            uid = ''
        return {'proto': 1,
                'dev': {'vendor': 'Raspberry Pi', 'model': 'Pico 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, 1024)
        win = m.get('win', 0) or 0
        dt_us = int(win * 1e6 / n) if isinstance(win, (int, float)) and 0 < win <= 1 else 0
        if any(c >= 3 for c in chs):
            n = min(n, 16)  # I2C parts are slow
        acc = [[0.0, 0.0, 1e9, -1e9] for _ in chs]
        t_next = time.ticks_us()
        for _ in range(n):
            if dt_us:
                while time.ticks_diff(time.ticks_us(), t_next) < 0:
                    pass
                t_next = time.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'))
        if any(c >= 3 for c in chs):
            raise Err('nocap', 'capture uses ADC0..ADC2 only')
        n = m.get('n', 1000)
        n = max(16, min(int(n), CAP_N)) if isinstance(n, (int, float)) else 1000
        rate = m.get('rate', 10000)
        if 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
        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'
        if tr:
            trig = 'auto'
            tch = tr.get('ch')
            if tch in chs:
                lvl = int(float(tr.get('level', 0)) / VREF * 4095)
                col = chs.index(tch)
                rise = tr.get('edge', 'rise') != 'fall'
                nc = len(chs)
                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': []}
        nc = len(chs)
        import array
        for k in range(nc):
            seg = array.array('h', [data[(start + i) * nc + k] for i in range(n)])
            out['d'].append(binascii.b2a_base64(bytes(seg)).decode().strip())
            out['scale'].append(VREF / 4095)
            out['off'].append(0)
        return out

    @native
    def _sample(self, chs, total, rate):
        import array
        nc = len(chs)
        buf = array.array('H', bytes(2 * total * nc))
        adcs = [self.hw.adc[c] for c in chs]
        dt = int(1000000 / rate)
        t_next = time.ticks_us()
        t_start = t_next
        j = 0
        for i in range(total):
            while time.ticks_diff(time.ticks_us(), t_next) < 0:
                pass
            t_next = time.ticks_add(t_next, dt)
            for a in adcs:
                buf[j] = a.read_u16() >> 4
                j += 1
        el = time.ticks_diff(time.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.pwm.duty_u16(int(want / VREF * 65535))
            time.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 ADC0 at %.1f V (needs the loop jumper)' % want, 'ok': abs(v - want) < 0.15, 'v': v, 'want': want})
        self.hw.pwm.duty_u16(0)
        tests.append({'name': 'I2C parts found: ADS1115 %s, MCP4725 %s, INA219 %s' % (self.hw.ads, self.hw.dac, self.hw.ina), 'ok': True})
        return {'tests': tests}

    def handle(self, m):
        op = m.get('op')
        if op == 'hello':
            return self.hello(m)
        if op == 'ping':
            return {'t': time.ticks_diff(time.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):
                raise Err('badarg', 'ch')
            self.hw.relays[ch].value(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 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(json.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 = time.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 time.ticks_diff(time.ticks_ms(), self.last) > WATCHDOG_MS:
            self.safe()


def run():
    out = sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout
    inp = sys.stdin.buffer if hasattr(sys.stdin, 'buffer') else sys.stdin

    def write(b):
        out.write(b)
        try:
            out.flush()
        except Exception:
            pass
    bench = Bench(Hardware(), write)
    raw = getattr(inp, 'raw', None)   # CPython test runner: unbuffered reads; MicroPython: one byte at a time
    poll = select.poll()
    poll.register(raw if raw else inp, select.POLLIN)
    while True:
        if poll.poll(50):
            ch = raw.read(4096) if raw else inp.read(1)
            if ch:
                bench.feed(ch)
        bench.tick()


if __name__ == '__main__':
    try:
        skip = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_UP).value() == 0
    except Exception:
        skip = False
    if not skip:
        run()
