Skip to main content
Reacgen Biosystems

WebSocket examples

Walk through every common scenario over WiFi from any networked host (laptop, server, or Raspberry Pi) using the turbidvision_ws client library.

These examples use the turbidvision_ws WebSocket library. Install it first. Every method, dataclass, and constant is in the WebSocket API reference; the same scenarios over a wired I²C bus are on the Python examples page.

Setup

Import the library, open one connection, and keep it for the rest of the session. Set HOST to your probe's IP address or mDNS hostname (turbidvision.local where supported). connect() opens the socket, starts a background receive thread, and primes status/info/settings. The fmt() helper prints floats with NaN shown explicitly.

import math, time
from turbidvision_ws import (
    TurbidVisionWS,
    STATUS_JOB_RUNNING, STATUS_HAS_INITIAL, STATUS_HAS_BLANK,
    STATUS_REFLECTANCE_STABLE,
)

HOST = "turbidvision.local"          # <-- set to your probe's IP or 'turbidvision.local'


def fmt(x):
    "Pretty-print a float that may be NaN."
    if x is None:
        return "None"
    if isinstance(x, float) and math.isnan(x):
        return "nan"
    return f"{x:.4f}"


probe = TurbidVisionWS(HOST).connect()
info = probe.get_info()
print("Connected to", probe.url)
print(f"  serial={info.sn}  fw={info.fw}  ip={info.ipv4}  rssi={info.rssi} dBm")

1. Discovery and status

status() sends a statusrq and waits for the statusrs snapshot. Snapshot.flag(name) reads a named boolean flag. At power-on with no job running, all flags are False.

s = probe.status()                   # sends statusrq, waits for statusrs
flags = ["job_running", "has_initial", "has_blank", "ukf_enabled",
         "reflectance_stable", "probe_detected", "calibrated"]
for name in flags:
    print(f"  {name:<20} {'X' if s.flag(name) else '.'}")
print(f"  error_flags          0x{s.error_flags:X}")

2. Start an OD job and stream readings

This is the headline WebSocket feature: stream_readings() is a blocking generator that yields each new snapshot as the probe reports it, with no manual polling loop. Start the job, wait for has_initial, then iterate.

probe.start_job()
if not probe.wait_for_status(STATUS_HAS_INITIAL, timeout=60):
    raise SystemExit("Initial reference not captured in 60 s")

print("  reading   density(g/L)   laser(mW)")
for r in probe.stream_readings(timeout=30):
    print(f"  {str(r.reading_count):>7}   {fmt(r.calibrated_density):>10}   "
          f"{fmt(r.laser_power_mw):>9}")
    if r.reading_count and r.reading_count > 10:
        break

3. Take a blank reference

A blank captures the reflectance of clear media so the sensor can normalize later readings. Stop the job, swap in the blank sample, capture, then restart. take_blank() blocks until the device finishes (up to ~20 s) and raises if it is busy or errors.

probe.stop_job()
input("Insert the BLANK sample, then press Enter...")
probe.take_blank(timeout=25)
print("Blank captured:", probe.status().has_blank)
probe.start_job()

4. Read a full snapshot

The Snapshot dataclass exposes every status flag and measurement in one object. Float fields are nan when unavailable (job not started, or UKF disabled for the UKF-derived fields).

s = probe.status()
rows = [
    ("reading_count", s.reading_count),
    ("calibrated_density (g/L)", fmt(s.calibrated_density)),
    ("ukf_filtered_density (g/L)", fmt(s.ukf_filtered_density)),
    ("ukf_growth_rate (1/h)", fmt(s.ukf_growth_rate)),
    ("laser_power_mw (mW)", fmt(s.laser_power_mw)),
    ("reflectance_avg_pct (%)", fmt(s.reflectance_avg_pct)),
    ("laser_temp_c (C)", fmt(s.laser_temp_c)),
]
for name, val in rows:
    print(f"  {name:<28} {val}")

5. Set laser power

set_laser_power_pct(pct) sets the target as a percentage of maximum (0 to 100 %) and activates the laser power controller. Wait for reflectance_stable, then read the target and measured power back.

probe.set_laser_power_pct(80.0)
probe.wait_for_status(STATUS_REFLECTANCE_STABLE, timeout=20)
s = probe.status()
print(f"  target_laser_pct = {fmt(s.target_laser_pct)} %")
print(f"  laser_power_mw   = {fmt(s.laser_power_mw)} mW")

6. Collect and plot density

Stream for a fixed duration and plot raw vs UKF-filtered density with matplotlib. If the UKF is disabled the filtered series is all NaN and is omitted.

import matplotlib.pyplot as plt

t0 = time.monotonic()
ts, raw, filt = [], [], []
for r in probe.stream_readings(timeout=10):
    ts.append(time.monotonic() - t0)
    raw.append(r.calibrated_density)
    filt.append(r.ukf_filtered_density)
    if time.monotonic() - t0 > 60:
        break

plt.figure(figsize=(8, 4))
plt.plot(ts, raw, ".", label="calibrated_density")
if any(not math.isnan(x) for x in filt):
    plt.plot(ts, filt, "-", label="ukf_filtered_density")
plt.xlabel("time (s)"); plt.ylabel("density (g/L)"); plt.legend(); plt.grid(True)
plt.show()

7. UKF growth-rate monitoring

Enable the UKF and tabulate density, filtered density, and growth rate. The UKF-derived fields are nan until the filter is enabled and has converged.

probe.enable_ukf()
print("  density   filtered   growth(1/h)   abs(g/L/h)")
n = 0
for r in probe.stream_readings(timeout=30):
    print(f"  {fmt(r.calibrated_density):>7}   {fmt(r.ukf_filtered_density):>8}   "
          f"{fmt(r.ukf_growth_rate):>11}   {fmt(r.ukf_growth_rate_abs):>10}")
    n += 1
    if n >= 10:
        break

8. Graceful shutdown

shutdown() stops the job and turns the laser off. Verify the probe returns to idle, then close the connection to stop the background thread.

probe.shutdown()
probe.wait_for_status(STATUS_JOB_RUNNING, value=False, timeout=10)
s = probe.status()
print("  job_running =", s.job_running)

probe.close()
print("Disconnected.")

Library quick reference

TaskCall
ConnectTurbidVisionWS(host).connect() / with TurbidVisionWS(host) as p:
Latest snapshotp.status() -> Snapshot, p.latest()
Stream readingsfor r in p.stream_readings(): ...
Push callbackp.on('statusrs', cb) / p.on('message', cb)
Device infop.get_info() -> Info
Settingsp.get_settings(), p.set_settings(t_readings_ms=2000)
Job controlp.start_job(), p.stop_job(), p.take_blank(), p.take_cal_reading()
Laserp.set_laser_power_pct(), p.set_laser_power_mw(), p.deactivate_laser()
UKFp.enable_ukf(), p.disable_ukf()
Waitp.wait_for_status(flag, value=True), p.wait_until(pred)
Graceful stopp.shutdown()
Escape hatchp.send(cmd, **f), p.request(cmd, event, **f)

Float fields are nan when unavailable; guard with math.isnan(). For every method, dataclass, and constant, plus the JSON message protocol, see the WebSocket API reference; for install and downloads, see Code libraries.