Skip to content

Python Script without GUI

ta1_k edited this page Aug 24, 2026 · 3 revisions

Using vs_controller without the GUI

vs_controller.py (at GUI/src/gui/controller/vs_controller.py) is self-contained: its only runtime dependency is pyserial. It can be imported and driven from any Python script or Jupyter notebook

Dependencies

Install pyserial in the environment the notebook uses:

pip install pyserial

You do not need import serial in your own code. vs_controller imports it internally and wraps every serial read/write behind VoltageSourceController.

Importing

# Script sits next to a copy of the file
from vs_controller import VoltageSourceController, DataLog

Jupyter usage pattern

In a notebook, keep one VoltageSourceController alive across cells rather than reconnecting per cell. A typical layout is:

  • Cell 1 — import + vs = VoltageSourceController() + configure_output
    • connect + start_reading. Run once at the top of the session.
  • Middle cells — call send_sweep / send_steady and read samples.
  • Last cell — send_off / stop_reading / disconnect.

connect and disconnect open and close the serial port; doing them repeatedly forces the ESP through its 2.5 s cable-watchdog and drops whatever run is in flight.

Lifecycle

connect  →  start_reading  →  send_…  →  stop_reading  →  disconnect
  • connect opens the serial port and starts the 2 s cable-watchdog heartbeat.
  • start_reading spawns the background reader that parses data,… / calib,… lines and populates the per-channel ring buffer.
  • stop_reading closes any open sweep log and joins the reader.
  • disconnect stops the heartbeat and closes the port.

If you skip start_reading, no telemetry is parsed and has_new_data stays False. If you skip connect (opening serial.Serial yourself), the firmware zeros every channel after 2.5 s because no heartbeat is running.

Public API

Static helpers

  • VoltageSourceController.list_ports() → list[tuple[device, description]] — USB-looking devices sorted first (by VID + keyword score).
  • VoltageSourceController.guess_port() → str — best pick, or "" if nothing looks USB-ish.

Connection state

  • is_connected: bool (property)
  • connected_port: str (property)
  • active_sweep_channels() → list[int]

Command senders

All are fire-and-forget writes terminated with \0. Each returns False silently if the port is not open.

  • send_off(ch)
  • send_steady(ch, voltage, duration, time_unit) Runs channel ch at the constant DAC voltage. time_unit accepts the firmware's timer tokens ("Sec", "Min", "Hour") or "Inf", which runs indefinitely and ignores duration. "Inf" is the common case — use it unless you specifically want the firmware to auto-turn-off after a bounded interval.
  • send_sweep(ch, range_v, step_size_mv) — sweeps ±range_v in step_size_mv millivolt steps. range_v is clamped to vs.sweep_range_max_v (default 1.5 V) with a console warning if exceeded; override the attribute on the instance if you really need a wider sweep.
  • send_calibration(ch, r_1k, r_gain, dac_vref) — persisted in NVS on the ESP.
  • send_odr(ch, sps) — ADC output data rate.
  • send_command(raw: str) → bool — raw escape hatch.

Live data reads

The reader thread parses each data,… line into a DataLog and appends it to a bounded ring buffer per channel (deque(maxlen=4096)).

  • has_new_data(ch) → bool — set whenever a new sample has arrived since the last consume.
  • get_latest_sample(ch) → DataLog | None — returns the newest sample and clears the new-data flag. O(1); intended for the main consumer loop.
  • peek_latest_sample(ch) → DataLog | None — same, but does not touch the flag. Safe from auxiliary threads.
  • get_channel_data(ch) → list[DataLog] — full copy of the ring. Pay this cost only when you need the whole history (e.g. at sweep end).
  • clear_channel_data(ch) — wipe the ring. Call before a fresh sweep so points from a prior run do not linger.

DataLog fields:

channel_id: int
mode: int        # 0=SWEEP, 1=STEADY, 2=IDLE, 3=CALIBRATION, 4=ODR
voltage: float   # V
current: float   # µA
time_s: float    # seconds since firmware boot (NOT wall time)

Example — Jupyter setup cell

Run this once at the top of the notebook. output/sweep/ holds sweep TXTs; output/log/ holds the diag file.

from vs_controller import VoltageSourceController

vs = VoltageSourceController()
vs.log_callback = lambda s: print("[esp]", s)

# Route sweep vs. diag/steady to separate subfolders. Call before connect
# so the diag log lands in output/log/ too.
vs.configure_output("output", sweep_subdir="sweep", log_subdir="log")

vs.connect(<Your USB connection>, 115200)
vs.start_reading()   

Teardown cell (run once when done):

vs.stop_reading()
vs.disconnect()

Example — steady

Prints each new sample — swap the print for a plot append, a variable capture, or nothing at all if you only care that the bias is on.

import time

ch, applied_v = 0, 0.25
vs.send_steady(ch, applied_v, 0, "Inf")

try:
    while vs.is_connected:
        s = vs.peek_latest_sample(ch)
        if s is not None:
            print(f"{s.voltage:.6f} V, {s.current:.6f} µA, {s.voltage / s.current} Ohm")
        time.sleep(1.0)   # sampling cadence
except KeyboardInterrupt:
    pass
finally:
    vs.send_off(ch)       

Example — sweep

Saves to user specified txt file name. Sweep range is software capped at $\pm 1.5V$

import time
import matplotlib.pyplot as plt

ch = 0
vs.clear_channel_data(ch)                              # discard prior samples
vs.start_sweep_log(ch, filename="sweep_A_1p5V.txt")    # optional TXT → output/sweep/
vs.send_sweep(ch, range_v=1.5, step_size_mv=10)

try:
    # Wait for the firmware to report OFF (mode == 2) after finishing the sweep.
    while vs.is_connected:
        s = vs.peek_latest_sample(ch)
        if s is not None and s.mode >= 2:
            break
        time.sleep(0.1)

    data = vs.get_channel_data(ch)          # list[DataLog], in arrival order
    voltages = [d.voltage for d in data]    # or: np.array([...])
    currents = [d.current for d in data]

    plt.plot(voltages, currents)
    plt.xlabel("Voltage (V)")
    plt.ylabel("Current (µA)")
    plt.show()
finally:
    vs.stop_sweep_log(ch)
    vs.send_off(ch)

Skip start_sweep_log / stop_sweep_log entirely if you don't want a TXT on disk — get_channel_data(ch) still works

vs stays connected between cells; only the teardown cell calls stop_reading / disconnect.

Output folder layout

  • configure_output(output_dir="output", sweep_subdir=None, log_subdir=None) — set where sweep TXTs and the diag log go. When both *_subdir args are None (the GUI default) everything lands flat in output_dir. Pass e.g. sweep_subdir="sweep", log_subdir="log" to split them into output/sweep/*.txt and output/log/*.log. Safe to call before connect — do it early if you want the diag log routed into log_subdir from the start.
  • start_reading accepts the same three kwargs and forwards them to configure_output, so a notebook can do it all in one call.

Sweep TXT logging

Automatic once start_reading is running: every data,… line with mode == 0 is written to the channel's open sweep file.

  • start_sweep_log(ch, filename=None) → path — auto-rotates by timestamp when filename is None. A bare filename is placed under the configured sweep dir; an absolute path is used as-is. Useful in notebooks where you want a run-specific name ("cooldown_A_1p2V.txt") rather than a timestamp.
  • stop_sweep_log(ch)
  • sweep_log_path(ch) → str

The start_steady_log / write_steady_row helpers are shaped around the GUI's meter-poll workflow (hard-coded pcb_current_uA + per-meter columns, row written only when the caller explicitly hands over a meter reading). For a pcb-only headless recording, ignore those helpers and stream peek_latest_sample(ch) yourself — see the steady example below.

Callbacks

Optional. Both default to None.

  • vs.log_callback = fn(msg: str) — every non-data, line from the firmware (boot banners, ESP_LOGx, printf, watchdog messages).
  • vs.calib_callback = fn(ch, r_1k, r_gain, dac_vref) — fires when the firmware sends a calib,… line (in reply to send_calibration, and on every boot).

Threads

All threads are daemon threads and live entirely inside vs_controller — no external ticker is required.

  1. Reader thread (start_reading) — parses data,… and calib,…; forwards everything else to log_callback; writes sweep rows.
  2. Heartbeat thread (connect) — writes hb every 2 s. The firmware zeros every channel after 4s without input. connect starts it, disconnect stops it.
  3. Reconnect thread — appears only after a USB drop, polls list_ports() for the last-known device, and re-runs connect + start_reading when it reappears. Bounded by _reconnect_timeout_s = 30 s. Set vs._auto_reconnect = False before disconnect() to opt out.

A diagnostic file vs_diag_<timestamp>.log is opened on each connect. It lands in the configured log dir (output_dir/log_subdir if you passed log_subdir, otherwise flat output_dir) and captures every non-data, line and heartbeat scheduling gaps. Line-buffered so it survives a killed process.

Somethings to be careful

  • connect alone does not spawn the reader — you must call start_reading.
  • send_command returns False silently if the port is not open. Check the return value or is_connected if you care.
  • DataLog.time_s is a firmware clock, not epoch. Stamp time.time() yourself when you read if you need wall time.
  • The class is thread-safe for the exposed operations. Do not reach into _serial or _data_buffers directly — use the accessors above.

Clone this wiki locally