"""F1 bench ADS1115 reader. Called transiently by capture.py on MicroPython."""

ADC_ADDR = 0x48
LSB_UV = 62.5


def read_raw(bus, clock, origin, channel):
    # OS=start, MUX=single-ended, PGA=2.048 V, single-shot, 128 SPS, comparator off.
    config = 0x8583 | ((4 + channel) << 12)
    before = clock.ticks_us()
    bus.writeto_mem(ADC_ADDR, 1, bytes((config >> 8, config & 255)))
    while True:
        clock.sleep_ms(1)
        high, low = bus.readfrom_mem(ADC_ADDR, 1, 2)
        if ((high << 8 | low) & 0x7fff) != (config & 0x7fff):
            raise RuntimeError("ADS1115 configuration readback disagrees")
        now = clock.ticks_us()
        if clock.ticks_diff(now, before) > 100000:
            raise RuntimeError("ADS1115 conversion timeout")
        if high & 128:
            break
    high, low = bus.readfrom_mem(ADC_ADDR, 0, 2)
    counts = high << 8 | low
    if counts >= 32768:
        counts -= 65536
    return clock.ticks_diff(before, origin), clock.ticks_diff(now, origin), counts


def burst(bus, clock, brackets, emit=print):
    if ADC_ADDR not in bus.scan():
        raise RuntimeError("no device at 0x48")
    origin = clock.ticks_us()
    for sample in range(brackets):
        for slot, channel in enumerate((1, 0, 1)):
            start, ready, counts = read_raw(bus, clock, origin, channel)
            emit("%d,%d,%d,%d,%d,%d" % (sample, slot, channel, start, ready, counts))
    emit("END,%d" % brackets)


def acquire(brackets):
    import machine
    import time
    bus = machine.I2C(0, sda=machine.Pin(0), scl=machine.Pin(1), freq=100000)
    burst(bus, time, brackets)
