#!/usr/bin/env python """Parse IQ-sampling chunk messages streamed by sensors in IQ mode.""" import struct import zlib import numpy as np __all__ = [ "IQ_CHUNK_SAMPLE_WORDS", "IQ_CHUNK_TYPE_HEADER", "IQ_ACCUM_TYPE_HEADER", "RX_GAIN_TABLE_ENTRIES", "IQAccumPacket", "IQChunkPacket", ] # The receiver gain table has 77 real entries (indices 0..76). The firmware # additionally uses slot 79 as a session-local shadow of the active forced # entry: the DC-offset servo latches its updated DAC codes into the front end # by selecting that bit-identical shadow for ~1 us (sensor-firmware # modem_dcoc_write_entry). Samples captured during the latch pulse are taken # at the unchanged analog gain of the active entry, but the hardware stamps # the shadow's index into their gain field. RX_GAIN_TABLE_ENTRIES = 77 IQ_CHUNK_TYPE_HEADER = 0x32435149 # "IQC2" little-endian (b"IQC2") IQ_ACCUM_TYPE_HEADER = 0x31415149 # "IQA1" little-endian (b"IQA1") IQ_CHUNK_SAMPLE_WORDS = 256 # adc_decimation -> complex sample rate (matches iq_adc_sample_cycles in firmware). DECIM_TO_FS = {1: 80e6, 2: 40e6, 4: 20e6, 6: 10e6, 8: 8e6, 10: 4e6} IQ_SYNC_INFO_SEQ_MASK = 0x0000FFFF IQ_SYNC_INFO_GRID_SYNCED = 1 << 16 IQ_SYNC_INFO_BOOT_SYNCED = 1 << 17 IQ_SYNC_INFO_FIRE_TIME_VALID = 1 << 18 IQ_ACCUM_FLAG_INT16 = 1 << 8 IQ_ACCUM_FLAG_BATCHED = 1 << 9 IQ_CHUNK_FLAG_SIGNAL_CAPTURE = 1 << 8 IQ_CHUNK_FLAG_SIGNAL_FIRST = 1 << 9 IQ_CHUNK_FLAG_SIGNAL_LAST = 1 << 10 IQ_CHUNK_FLAG_REFERENCE = 1 << 11 IQ_CHUNK_FLAG_REFERENCE_READY = 1 << 12 class IQChunkPacket: """One IQ-sampling chunk streamed by a sensor in IQ mode (magic "IQC2"). Timestamps use the local CPU clock, encoded in nanoseconds. Reference snapshots (flag 11) reuse ``fire_time_ns`` for the first snapshot sample and ``producer_wake_write_ptr`` for its onset offset. Four records, indexed by ``capture_chunk_offset``, form one snapshot. Flag 12 acknowledges that the reference detector has observed quiet. Both special record types are excluded from ordinary IQ subscriptions. """ def __init__(self, pktbuf): if len(pktbuf) < 76 + 4 * IQ_CHUNK_SAMPLE_WORDS: raise ValueError("IQ chunk packet too short") self.type_header = int.from_bytes(pktbuf[0:4], byteorder="little") if self.type_header != IQ_CHUNK_TYPE_HEADER: raise ValueError("Unexpected IQ chunk type header") ( self.sequence, self.source_chunk_index, self.chunk_counter, self.adc_decimation, self.sample_rate_hz, self.center_freq_hz, self.rx_gain, self.gain_mode, self.config_generation, self.flags, self.dropped_chunks, self.capture_id, self.capture_chunk_offset, self.producer_wake_write_ptr, fire_lo, fire_hi, self.sync_info, ) = struct.unpack_from("<17I", pktbuf, 4) # Signal mode reuses the old wake-pointer diagnostic word for the # event's explicit total length without changing the IQC2 wire size. self.capture_chunk_count = self.producer_wake_write_ptr if self.flags & IQ_CHUNK_FLAG_SIGNAL_CAPTURE else 0 self.center_freq_mhz = self.center_freq_hz / 1e6 self.fire_time_ns = (fire_hi << 32) | fire_lo self.samples = np.frombuffer(pktbuf, dtype=" bool: return bool(self.flags & IQ_CHUNK_FLAG_SIGNAL_CAPTURE) @property def is_signal_first(self) -> bool: return bool(self.flags & IQ_CHUNK_FLAG_SIGNAL_FIRST) @property def is_signal_last(self) -> bool: return bool(self.flags & IQ_CHUNK_FLAG_SIGNAL_LAST) @property def capture_path(self): """Front end used for this capture.""" return "bluetooth" if self.adc_decimation == 0 else "wifi" def decode_iq(self): """Complex baseband samples. Each 32-bit dump word packs I in bits 0-9 and Q in bits 10-19 (both 10-bit signed two's complement); bits 20-31 carry rx_gain / AGC state.""" words = np.asarray(self.samples, dtype=np.uint32) samples = np.empty(words.shape, dtype=np.complex64) # Move the ten-bit sign bit to bit 31, then shift back with sign # extension. Negate Q to match CSI's baseband orientation. samples.real = (words << 22).view(np.int32) >> 22 samples.imag = -((words << 12).view(np.int32) >> 22) return samples def sample_rx_gain(self): """Effective gain-table index stored alongside every ADC sample. Samples stamped with the DC-offset servo's shadow slot (see :data:`RX_GAIN_TABLE_ENTRIES`) were captured at the analog gain of the active forced entry, which every other sample of the chunk carries — so out-of-table indices are replaced by the chunk's prevailing valid index. Raw fields are available via :attr:`samples` (bits 20-27; bit 27 marks the alternate gain-memory bank, both banks use the same seven-bit gain-table index).""" gains = ((self.samples >> 20) & 0x7F).astype(np.uint8) invalid = gains >= RX_GAIN_TABLE_ENTRIES if invalid.any(): valid = gains[~invalid] if valid.size: gains[invalid] = np.bincount(valid).argmax() return gains class IQAccumPacket: """One 256-sample section of an accumulated IQ vector (magic ``IQA1``). The wire payload keeps exact signed 16-bit or 32-bit I/Q sums. :meth:`decode_iq` returns their count-normalized complex average by default, while :attr:`i_sum` and :attr:`q_sum` expose the lossless integer components. """ HEADER_BYTES = 88 PAYLOAD_BYTES = 8 * IQ_CHUNK_SAMPLE_WORDS WIRE_BYTES = HEADER_BYTES + PAYLOAD_BYTES + 4 def __init__(self, pktbuf): if len(pktbuf) < self.HEADER_BYTES: raise ValueError("IQ accumulation packet too short") self.type_header = int.from_bytes(pktbuf[0:4], byteorder="little") if self.type_header != IQ_ACCUM_TYPE_HEADER: raise ValueError("Unexpected IQ accumulation type header") hdr = np.frombuffer(pktbuf[4 : self.HEADER_BYTES], dtype="= self.vector_chunks: raise ValueError("Invalid accumulation vector section index") window_chunks = (self.source_chunk_end - self.source_chunk_start) & 0xFFFFFFFF if window_chunks == 0 or window_chunks % self.vector_chunks: raise ValueError("Invalid accumulation source window") if not 1 <= self.nominal_chunks <= window_chunks // self.vector_chunks: raise ValueError("Invalid nominal accumulation count") if self.accumulated_chunks > self.nominal_chunks: raise ValueError("Actual accumulation count exceeds nominal count") self.center_freq_mhz = self.center_freq_hz / 1e6 self.fire_time_ns = (fire_hi << 32) | fire_lo dtype = np.dtype(" bool: return bool(self.flags & IQ_ACCUM_FLAG_BATCHED) @property def is_partial(self) -> bool: return bool(self.flags & 1) @property def deadline_aborted(self) -> bool: return bool(self.flags & 2) def decode_iq(self, normalize=True): """Decode using the CSI-compatible ``I - jQ`` phase convention. With ``normalize=True`` (default), divide by the actual number of source chunks included in this vector section. A zero-count section decodes to complex NaNs. ``normalize=False`` returns complex128 sums; use :attr:`i_sum`/:attr:`q_sum` when exact integer values are needed. """ iq = self.i_sum.astype(np.float64) - 1j * self.q_sum.astype(np.float64) if normalize: if self.accumulated_chunks == 0: iq[:] = np.nan + 1j * np.nan else: iq /= self.accumulated_chunks return iq.astype(np.complex64 if normalize else np.complex128) def sample_rx_gain(self): """Manual gain index repeated over the decoded vector section.""" return np.full(IQ_CHUNK_SAMPLE_WORDS, self.rx_gain & 0x7F, dtype=np.uint8)