bpod_core.bpod.threads.ReadThread
- class bpod_core.bpod.threads.ReadThread
Bases:
ThreadSerial reader thread for one Bpod trial.
Runs for the lifetime of a single trial. Reads the hardware confirmation, then enters a tight loop parsing the two-byte opcode packets the Bpod streams over serial:
Opcode 1 – hardware events: reads
paramevent bytes followed by a 4-byteuInt32cycle count. Timestamps are derived asstart_micros_us + n_cycles * cycle_period_usand each event is pushed toqueue_eventsas aRawEvent. AnEXITbyte (255) triggersstop().Opcode 2 – softcodes: the
parambyte (1-indexed) is forwarded toqueue_softcodes.
Hot-loop optimisations:
Two fixed
bytearraybuffers (opcode_buf: 2 bytes,event_data_buf: 259 bytes) are allocated once before the loop.serial.readinto()writes directly into them — no per-packet allocation.A
memoryviewoverevent_data_bufallows zero-copy slicing for both the variable-length event payload and the trailing cycle-count word.struct.unpack_from()unpacks the cycle count in-place from the memoryview without creating an intermediate bytes object.Frequently accessed instance attributes (
serial, queues,cycle_period_us) are cached as locals before the loop to avoid repeatedLOAD_ATTRbytecode overhead.
After the loop, the thread reads the 12-byte end-of-trial packet (
uInt32cycle count +uInt64µs timestamp, unpacked via_struct_exit) and enqueuesEND_FSM_CYCLESandEND_FSM_MICROS. ASTOP_SENTINELis always enqueued infinallysoEventThreadcan detect termination regardless of how the trial ended.- __init__(*, serial, state_machine_hash, trial, cycle_period_us, queue_events, queue_softcodes) None
Initialize the ReadThread.
- Parameters:
serial (
ExtendedSerial) – The serial connection to the Bpod device.state_machine_hash (
bytes) – The hash of the state machine.trial (
int) – Zero-based trial index.cycle_period_us (
int) – The cycle period of the Bpod device in microseconds.queue_events (
SimpleQueue[RawEvent]) – Queue for storing events.queue_softcodes (
SimpleQueue[RawSoftcode]) – Queue for storing softcodes.
- Return type:
None