Metadata-Version: 2.5
Name: brick-instruments
Version: 0.9.0
Summary: Host drivers for the Brick modular instrument system
Project-URL: Source, https://github.com/amccaugh/pcb-designs
Author-email: Adam McCaughan <amccaugh@gmail.com>
License-Expression: GPL-3.0-or-later
License-File: LICENSE
Keywords: adc,cryogenic,dac,instrument,measurement
Requires-Python: >=3.9
Requires-Dist: pyserial
Provides-Extra: test
Requires-Dist: pytest; extra == 'test'
Description-Content-Type: text/markdown

# brick-instruments

Host drivers for the Brick modular instrument system: a Brick08 mainframe
holding up to four daughter bricks, all behind one USB serial port.

Published as `brick-instruments`, imported as `brick`.

```bash
pip install brick-instruments      # not published yet
```

Building it on a network that intercepts TLS (NIST's does) needs uv pointed
at the system certificate store, or it cannot reach PyPI to fetch the build
backend:

```bash
uv build --system-certs
```

## Using it

One mainframe owns the serial port and hands you an object per slot.

```python
from brick import Brick

brick = Brick()                          # the only mainframe connected
brick.slots
# {1: DiodeReadout(slot=1), 2: ACResistanceBridge(slot=2),
#  3: IsolatedVoltageSource(slot=3), 4: None}

vs = brick.slots[3]
vs.set_voltage(0.47)                     # the relay is still open
vs.set_output(True)                      # now it is live on the BNC
vs.get_calibration()                     # what the source is corrected by

brick.slots[1].get_voltage()             # a diode's forward voltage
brick.slots[2].get_resistance()          # a thermometer, 4-wire AC excited

brick.reset()
brick.close()                            # or use Brick(...) as a context manager
```

Nothing is discovered by you: each brick stores its own type in an on-board
EEPROM, the mainframe reads it, and `brick.slots` gives you the matching
class. You never tell the package what is plugged in where.

## Finding the right mainframe

`Brick()` finds the one that is connected, matching on the USB identity its
`boot.py` sets rather than guessing from device names, so an Arduino on the
next port is not a candidate. With more than one connected it raises and
lists them, because connecting to the wrong mainframe produces plausible
readings from the wrong instrument.

```python
from brick import Brick, find_bricks

find_bricks()
# [{'port': '/dev/cu.usbmodem2101', 'serial_number': 'E46550789F0E4A26',
#   'name': 'flaming-spoon', 'manufacturer': 'brick-mainframe'}]

brick = Brick(serial_number='E46550789F0E4A26')
```

**Address a board by its serial number, not its port.** The port name
changes every time the board re-enumerates; the serial number is the QSPI
flash chip's 64-bit ID and belongs to the board. It is also exactly what
`brick.uid()` returns, so you can read it once from a mainframe and hard-code
it in a script for ever.

## A guided tour

[`example_script.py`](example_script.py) is every call in the package with
the values it returned, flat, in the order you would meet them. Read it top
to bottom or step through it a cell at a time with its `# %%` markers, and
the comments show what each call actually returned on a loaded mainframe.

It runs as-is. The lines that would write a brick's EEPROM, reset the board
or drop the USB connection are commented out and say so, because an example
that quietly erased your calibration would be a trap.

## A brand-new brick

Bricks ship with a blank ID EEPROM, so a board the mainframe cannot identify
arrives as a placeholder that says what to do rather than as `None`:

```python
>>> brick.slots[4]
Unprovisioned(slot=4) -- call .initialize(<type>); brick.types() lists them
>>> brick.types()
('VoltageSource04', 'DiodeReadout', 'ACResistance')
>>> brick.slots[4].initialize('DiodeReadout')
DiodeReadout(slot=4)
```

That is the whole out-of-box procedure: one call, no reboot, nothing in a
configuration file. `brick._erase_all(4)` puts it back to factory state
— underscored, like the rest of the raw EEPROM access.

| `brick.slots[n]` | means |
| --- | --- |
| a module instance | ready to use |
| `None` | nothing plugged in |
| `Unprovisioned(...)` | a brick with a blank EEPROM |
| `UnknownType(...)` | a brick naming a type this package has no class for |

## Calibration

Calibration lives in each brick's own EEPROM, so it travels with the board
rather than with the mainframe or a host config file. Keys are specific to
the brick, and are validated — a misspelling raises rather than being
silently stored and never read.

```python
bridge = brick.slots[2]
bridge.set_calibration(sense_resistor=4701.52,
                       notes='against a 2699.3 ohm reference')
bridge.get_calibration()
# {'calibration': {'sense_resistor': 4701.51953},
#  'date': 20261106, 'notes': 'against a 2699.3 ohm reference'}
```

| Brick | Constants | To calibrate it you need |
| --- | --- | --- |
| `DiodeReadout` | `sense_resistor`, `vref`, `voltage_offset`, `current_offset` | a wire and a ~100 kΩ precision resistor; a 6½-digit meter for absolute voltage |
| `ACResistanceBridge` | `sense_resistor`, `excitation_offsets` | a precision resistor under 5.6 kΩ |
| `IsolatedVoltageSource` | `gain`, `offset` | a 6½-digit meter |

Each board's doc has a step-by-step procedure under **Calibrating it
yourself**, written to be followed without knowing the circuit: what to
connect, what to type, the arithmetic, and a check that catches a bad
reading before it is stored.

All optional: an uncalibrated brick falls back to nominal values, so a new
board works before it has ever been calibrated. Every record also gets a
`date` and a `notes` string, because a constant whose provenance nobody
wrote down is a constant nobody can defend later.

`set_calibration` reloads the brick afterwards. Without that the EEPROM
reads back correctly while the board goes on measuring with its cached
constants, which is the kind of error that does not look like one.

## The boards, in depth

[`example_script.py`](example_script.py) lists every call the package
offers. The reasoning behind the ones that have any lives in `docs/`, one
file per board:

| | |
| --- | --- |
| [Brick08-Mainframe](docs/Brick08-Mainframe.md) | addressing a board, naming, slots, the ID EEPROMs, startup |
| [Brick09-DiodeReadout](docs/Brick09-DiodeReadout.md) | the excitation current and what holding it costs, stale readings, status words |
| [Brick10-ACResistance](docs/Brick10-ACResistance.md) | excitations, the bridge ratio, what holding the reference costs |
| [Brick07-VoltageSource04](docs/Brick07-VoltageSource04.md) | the DAC register versus the BNC, the relay ordering |

## Three things that will bite you otherwise

Each is explained in the doc for its board; this is the short version.

**Both ADC bricks return a cached sample.** They convert continuously and a
reading takes whatever already landed, so reading faster than a conversion
period hands you the *same* conversion again. Back-to-back readings then
show a spread of exactly zero, which looks like a perfect instrument and
measures nothing. Space repeatability samples by at least one period, or use
`set_averaging()`, which paces its own reads. `read()` reports the age of
what went into the reading on both bricks.

**Both re-measure their excitation on every reading**, which is why you can
trust a resistance: nothing you read was divided by a number you did not
watch being measured. On the diode that also makes `get_resistance()` slow,
157 ms, because its ADC has to visit the current channel; the bridge's
sequences both channels itself, so a call there stays about 10 ms. One number
relaxes that — `set_current_max_age()` on the diode,
`set_reference_max_age()` on the bridge — and it is a different trade on the
two boards. On the diode it is 17× faster and costs ppm. On the bridge it is
only about 2× faster, and what it costs depends entirely on whether your
sensor moves: a few ppm parked, up to 1692 ppm across a 1 k to 2.6 k swing at
excitation 1.

**The voltage source's `get_voltage()` reads the DAC register, not the BNC.**
It tells you what the DAC was told, not what the output is doing, and it
reads the same whether the relay is open or closed.

## Where things live

```
src/brick/
  mainframe.py    Brick: the connection, slot discovery, slot-level operations
  eeprom.py       record layout, CRC32, chunked access
  modules/        one file per brick type, plus the placeholders
```

The dividing line, which decides where any new method goes:

> **`Brick` owns the slot. The module owns its own behaviour.**

Initialising a blank brick, erasing a record and dumping raw bytes are
type-independent and have to work where no module object exists yet, so they
are on `Brick`. Measurement and calibration need to know which brick they
are talking to, so they are on the module.

`modules/__init__.py` holds the only map from a firmware type name to a
class, and is the only file a new board needs added to.

## Firmware

This package talks to the Rev4 firmware in the same repository
(`Brick/brick-code`). `eeprom.py` mirrors the firmware's record layout; the
copy is kept honest by having the board compute the CRC over what actually
landed and comparing it against the host's, so a divergence fails at write
time instead of corrupting a record.

## License

Copyright (C) 2026 Adam McCaughan.

This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version. It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See [LICENSE](LICENSE)
for the full text.
