main
John Lauer software/: Pico firmware (500 ksps two-channel ADC over DMA, SYNC on GPIO15, framed delta-packed USB stream), smi-dash… e09b832
// SPDX-License-Identifier: MIT
// Framing and block packing for the self-mixing interferometer stream.
// Portable C99: built into the Pico firmware and into the host-side test.
//
// Frame (all fields little-endian):
//   0xA5 0x5A            sync word
//   u8  type             SMI_T_DATA, SMI_T_SYNC, SMI_T_STATUS, SMI_T_INFO
//   u8  flags            reserved, 0
//   u16 payload_len
//   u16 seq              per-frame counter, wraps
//   ... payload ...
//   u16 crc              CRC-16/CCITT-FALSE over type..end of payload
//
// DATA payload:
//   u64 first_pair       index of the first ADC0/ADC1 sample pair in this frame
//   u32 t_us             time_us_32() when the DMA buffer completed
//   u8  n_groups         groups of 64 pairs; each group is a ch0 block then a ch1 block
//   blocks...
// Block (64 samples of one channel):
//   u16 head             bits 0..11 first sample, bits 12..15 width code w
//   payload              w in 0..12: 63 zigzag deltas of w bits each, LSB first
//                        w == 15:    63 raw 12-bit samples, LSB first
//                        padded to a whole byte
#ifndef SMI_FRAME_H
#define SMI_FRAME_H

#include <stdint.h>
#include <stddef.h>

#define SMI_SYNC0 0xA5
#define SMI_SYNC1 0x5A
#define SMI_T_DATA 1
#define SMI_T_SYNC 2
#define SMI_T_STATUS 3
#define SMI_T_INFO 4

#define SMI_BLOCK 64
#define SMI_RAW_CODE 15
#define SMI_HDR_LEN 8
#define SMI_MAX_BLOCK_BYTES (2 + (63 * 12 + 7) / 8)

uint16_t smi_crc16(const uint8_t *p, size_t n, uint16_t crc);

// Pack 64 samples (12-bit values) into dst. Returns bytes written.
size_t smi_pack_block(const uint16_t *s, size_t stride, uint8_t *dst);

// Unpack one block. Returns bytes consumed, or 0 on malformed input.
size_t smi_unpack_block(const uint8_t *src, size_t avail, uint16_t *out);

// Write a frame header at dst[0..8). Fill in the CRC with smi_finish_frame.
void smi_begin_frame(uint8_t *dst, uint8_t type, uint16_t payload_len, uint16_t seq);
// Appends the CRC after the payload; returns the total frame length.
size_t smi_finish_frame(uint8_t *frame, uint16_t payload_len);

static inline void smi_put_u16(uint8_t *p, uint16_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); }
static inline void smi_put_u32(uint8_t *p, uint32_t v) { for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> (8 * i)); }
static inline void smi_put_u64(uint8_t *p, uint64_t v) { for (int i = 0; i < 8; i++) p[i] = (uint8_t)(v >> (8 * i)); }

#endif