/* C11 host fixture: ADC endpoint mapping and one Modbus RTU transaction */
#include <assert.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

static uint32_t adc_millivolts(uint16_t code, uint16_t reference_mv)
{
    assert(code <= 4095u);
    return ((uint32_t)code * reference_mv + 2047u) / 4095u;
}

static uint16_t modbus_crc(const uint8_t *bytes, size_t length)
{
    uint16_t crc = 0xffffu;
    for (size_t i = 0; i < length; ++i) {
        crc ^= bytes[i];
        for (unsigned bit = 0; bit < 8; ++bit) {
            bool carry = (crc & 1u) != 0;
            crc >>= 1;
            if (carry)
                crc ^= 0xa001u;
        }
    }
    return crc;
}

/* Called only after the line receiver has delimited a complete RTU frame */
static bool decode_register(const uint8_t *frame, size_t length, uint16_t *value)
{
    if (length != 7 || frame[0] != 1 || frame[1] != 3 || frame[2] != 2)
        return false;
    uint16_t crc = modbus_crc(frame, length - 2);
    if (frame[5] != (uint8_t)crc || frame[6] != (uint8_t)(crc >> 8))
        return false;
    *value = (uint16_t)((uint16_t)frame[3] << 8 | frame[4]);
    return true;
}

int main(void)
{
    const uint8_t request[] = {1, 3, 0, 0, 0, 1, 0x84, 0x0a};
    uint8_t response[] = {1, 3, 2, 0, 250, 0, 0};
    const uint16_t crc = modbus_crc(response, 5);
    response[5] = (uint8_t)crc;
    response[6] = (uint8_t)(crc >> 8);
    uint16_t register_value = 0;
    assert(modbus_crc(request, sizeof request) == 0);
    assert(decode_register(response, sizeof response, &register_value));
    assert(register_value == 250);
    assert(!decode_register(response, 5, &register_value));
    response[4] ^= 1;
    assert(!decode_register(response, sizeof response, &register_value));

    const uint32_t delta = UINT32_C(3) - UINT32_C(4294967293);
    assert(delta == 6);
    assert(adc_millivolts(0, 3300) == 0 && adc_millivolts(4095, 3300) == 3300);
    printf("adc(2048)=%" PRIu32 " mV; elapsed=%" PRIu32 " ticks\n",
           adc_millivolts(2048, 3300), delta);
    printf("RTU=01 03 02 00 FA %02X %02X; register=%u; short/bad CRC rejected\n",
           (unsigned)response[5], (unsigned)response[6], (unsigned)register_value);
    return 0;
}
