Repository navigation
Python Script without 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
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.
# Script sits next to a copy of the file
from vs_controller import VoltageSourceController, DataLogIn 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_steadyand 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.
connect → start_reading → send_… → stop_reading → disconnect
-
connectopens the serial port and starts the 2 s cable-watchdog heartbeat. -
start_readingspawns the background reader that parsesdata,…/calib,…lines and populates the per-channel ring buffer. -
stop_readingcloses any open sweep log and joins the reader. -
disconnectstops 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.
-
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.
-
is_connected: bool(property) -
connected_port: str(property) active_sweep_channels() → list[int]
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 channelchat the constant DAC voltage.time_unitaccepts the firmware's timer tokens ("Sec","Min","Hour") or"Inf", which runs indefinitely and ignoresduration."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_vinstep_size_mvmillivolt steps.range_vis clamped tovs.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.
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)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()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) Saves to user specified txt file name.
Sweep range is software capped at
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.
-
configure_output(output_dir="output", sweep_subdir=None, log_subdir=None)— set where sweep TXTs and the diag log go. When both*_subdirargs are None (the GUI default) everything lands flat inoutput_dir. Pass e.g.sweep_subdir="sweep", log_subdir="log"to split them intooutput/sweep/*.txtandoutput/log/*.log. Safe to call beforeconnect— do it early if you want the diag log routed intolog_subdirfrom the start. -
start_readingaccepts the same three kwargs and forwards them toconfigure_output, so a notebook can do it all in one call.
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 whenfilenameis None. A barefilenameis 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_rowhelpers are shaped around the GUI's meter-poll workflow (hard-codedpcb_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 streampeek_latest_sample(ch)yourself — see the steady example below.
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 acalib,…line (in reply tosend_calibration, and on every boot).
All threads are daemon threads and live entirely inside vs_controller — no
external ticker is required.
-
Reader thread (
start_reading) — parsesdata,…andcalib,…; forwards everything else tolog_callback; writes sweep rows. -
Heartbeat thread (
connect) — writeshbevery 2 s. The firmware zeros every channel after 4s without input.connectstarts it,disconnectstops it. -
Reconnect thread — appears only after a USB drop, polls
list_ports()for the last-known device, and re-runsconnect+start_readingwhen it reappears. Bounded by_reconnect_timeout_s = 30 s. Setvs._auto_reconnect = Falsebeforedisconnect()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.
-
connectalone does not spawn the reader — you must callstart_reading. -
send_commandreturnsFalsesilently if the port is not open. Check the return value oris_connectedif you care. -
DataLog.time_sis a firmware clock, not epoch. Stamptime.time()yourself when you read if you need wall time. - The class is thread-safe for the exposed operations. Do not reach into
_serialor_data_buffersdirectly — use the accessors above.