Skip to main content
Reacgen Biosystems

WebSocket API reference

Complete API for the turbidvision_ws Python client library, plus the underlying WebSocket JSON protocol.

The package exposes the TurbidVisionWS client plus the Snapshot and Info dataclasses and a TurbidVisionError exception. Read methods return nan or None when a value is unavailable; command methods raise TurbidVisionError on a transport failure, timeout, or a non-OK reply. For runnable scripts using this API, see the WebSocket examples.

Construction

TurbidVisionWS(
    host,                       # "192.168.1.42" or "turbidvision.local"
    *, port=80, path="/ws", secure=False,
    poll_interval=2.0,          # seconds between auto statusrq polls; 0 disables
    connect_timeout=10.0,
)

A background thread owns the socket, dispatches inbound events to callbacks, unblocks pending request() waiters, and (when poll_interval > 0) polls statusrq on the interval so stream_readings() and on("statusrs", ...) see fresh snapshots. Set poll_interval=0 to disable auto-polling and drive status() yourself.

Lifecycle and connection

MethodReturnsDescription
connect()TurbidVisionWSOpen the socket, start the background RX thread, and prime status/info/settings. Returns self. Called automatically on context entry.
close()NoneClose the socket, stop the RX thread, and release any blocked stream_readings() consumers.
__enter__() / __exit__()TurbidVisionWSContext-manager protocol: connects on entry, closes on exit. Use a 'with' block.
connectedboolProperty: True while the WebSocket is open.
on(event, callback)Callable[[], None]Register callback(payload) for an event; returns an unsubscribe function. event is a response name (e.g. 'statusrs', 'message') or a local pseudo-event ('connected' / 'disconnected'). Callbacks run on the RX thread.
send(command, **fields)NoneSend a raw {"command": command, ...} frame (fire-and-forget). Escape hatch for extended/diagnostic commands with no first-class method.
request(command, response_event, timeout=10.0, **fields)dictSend command and block until response_event arrives; returns the payload. Raises TurbidVisionError on timeout or a non-OK (ok == False) payload.

Status and readings

MethodReturnsDescription
status(refresh=True, timeout=5.0)SnapshotLatest status snapshot. refresh=True sends a fresh statusrq and waits for the reply; refresh=False returns the last cached snapshot without I/O (raises if none has arrived).
latest()Snapshot | NoneMost recent cached snapshot without any I/O (None if none has arrived yet).
stream_readings(timeout=None)Iterator[Snapshot]Blocking generator: yields the current snapshot first, then each snapshot whose reading_count advances. Relies on the background poll loop (poll_interval > 0). Stops on timeout or when the socket closes.
get_info(timeout=5.0)InfoRequest and return device identity (serial, firmware, RSSI, IPv4).
get_settings(timeout=5.0)dictCurrent and default measurement settings as {"settings": {...}, "defaults": {...}}.
set_settings(timeout=5.0, **kwargs)NoneUpdate one or more measurement settings (e.g. t_readings_ms=2000). Only whitelisted keys are accepted; an unknown key raises.

Commands

Each raises TurbidVisionError on a transport failure or a non-OK reply. Blank and calibration commands run asynchronously on the sensor and block until it finishes or the timeout elapses.

MethodReturnsDescription
start_job(timeout=5.0)Start the OD measurement job.
stop_job(timeout=5.0)Stop the OD job and turn off the laser.
take_blank(timeout=25.0)Capture a blank reference. Runs asynchronously on the device, up to ~20 s; raises if the device is busy or errors.
take_cal_reading(timeout=30.0)dictCapture a calibration reading (async, up to ~25 s). Returns the calrs payload (measured_reflectance, reflectance_voltage, laser_pd_voltage).
enable_ukf(timeout=5.0)Enable UKF filtering and persist the setting in sensor NVS.
disable_ukf(timeout=5.0)Disable UKF filtering and persist the setting in sensor NVS.
clear_errors(timeout=5.0)Clear the latchable error-class bits in the error vector. Warning-class bits re-assert while their condition persists.
shutdown(timeout=5.0)Graceful stop: stop the job, then deactivate the laser.

Laser

MethodDescription
set_laser_power_pct(pct, timeout=5.0)Set the laser target as a percentage of maximum (0.0 to 100.0) and activate the controller. Raises ValueError outside range.
set_laser_power_mw(mw, timeout=5.0)Set the laser optical power target in milliwatts and activate the controller.
deactivate_laser(timeout=5.0)Stop the laser power controller and turn the laser off.

Polling

MethodReturnsDescription
wait_for_status(flag, value=True, timeout=35.0, poll_interval=0.2)boolBlock until status flag equals value. flag is a status field name such as STATUS_HAS_INITIAL. Returns False on timeout.
wait_until(predicate, timeout=35.0, poll_interval=0.2)boolBlock until predicate(snapshot) is true. predicate takes a Snapshot. Returns False on timeout.

Data classes

Snapshot

Decoded statusrs payload returned by status(), latest(), and stream_readings(). Float fields are nan when unavailable; the three reflectance fields are already scaled to percent (0 to 100). snapshot.flag(name) returns a boolean status flag by field name (e.g. flag("has_initial")), and str(snapshot) gives a compact one-line summary.

FieldTypeDescription
job_runningboolOD measurement job active.
is_initializingboolCapturing the initial reference.
has_initialboolInitial reference captured.
has_blankboolBlank reference captured.
ukf_enabledboolUKF filtering enabled.
pi_runningboolLaser PI controller running.
pi_stableboolLaser PI controller settled.
reflectance_stableboolReflectance reading has stabilised.
probe_detectedboolOptical probe installed and detected.
calibratedboolUsable calibration lookup table present.
reading_countint | NoneMonotonic reading counter; advances each new reading.
ukf_gate_counterint | NoneUKF innovation-gate rejection count.
error_flagsintSystem error/warning vector (0 = no faults). See Error flag masks.
job_uptime_msint | NoneMilliseconds since the current job started.
last_measured_reflectancefloat (%)Latest reflectance, already scaled to percent. nan when unavailable.
reflectance_avg_pctfloat (%)Rolling-average reflectance in percent. nan when unavailable.
measured_reflectance_avg_pctfloat (%)Blank-corrected rolling-average reflectance in percent. nan when unavailable.
laser_power_mwfloat (mW)Measured laser optical power. nan when unavailable.
reflected_power_mwfloat (mW)Reflected optical power. nan when unavailable.
target_laser_mwfloat (mW)Laser power target. nan when unavailable.
target_laser_pctfloat (%)Laser power target as percent of max. nan when unavailable.
dac_drive_pctfloat (%)Laser DAC drive level. nan when unavailable.
laser_temp_cfloat (°C)Laser NTC temperature. nan when unavailable.
calibrated_densityfloat (g/L)Calibrated optical density. nan when unavailable.
ukf_filtered_densityfloat (g/L)UKF-filtered density. nan when UKF is disabled.
ukf_growth_ratefloat (1/h)UKF specific growth rate. nan when UKF is disabled.
ukf_growth_rate_absfloat (g/L/h)UKF absolute growth rate. nan when UKF is disabled.
ukf_innovationfloatUKF innovation magnitude. nan when unavailable.
rawdictThe full original statusrs payload, retained for fields not modelled here.

Info

Device identity returned by get_info(), decoded from an odinfo event.

FieldTypeDescription
snstrDevice serial number.
fwstrFirmware version.
rssiint | NoneWiFi signal strength in dBm, or None if unparsable.
ipv4strDevice IPv4 address.

TurbidVisionError

Subclass of IOError, raised on a transport failure, a response timeout, or a non-OK (ok == False) payload.

Constants

Status flag names

The WebSocket status payload carries named booleans, not a packed byte, so wait_for_status() takes a flag name rather than a bit mask. These module-level constants (also class attributes for the common ones) are the field names on Snapshot.

ConstantField name
STATUS_JOB_RUNNINGjob_running
STATUS_IS_INITIALIZINGis_initializing
STATUS_HAS_INITIALhas_initial
STATUS_HAS_BLANKhas_blank
STATUS_UKF_ENABLEDukf_enabled
STATUS_PI_RUNNINGpi_running
STATUS_PI_STABLEpi_stable
STATUS_REFLECTANCE_STABLEreflectance_stable
STATUS_PROBE_DETECTEDprobe_detected
STATUS_CALIBRATEDcalibrated

Error flag masks

Decode the error_flags field of a Snapshot. Bits 0 to 4 are error-class (latching; cleared with clear_errors()); bits 5 to 8 are warning-class and re-assert while their condition persists.

ConstantMaskClassMeaning
ERR_SAFETY_CRITICAL0x001ErrorSafety-critical fault.
ERR_SAFETY_WARNING0x002ErrorSafety warning.
ERR_PI_FAILED0x004ErrorLaser PI controller failed.
ERR_LOW_HEAP0x008ErrorLow heap.
ERR_STORAGE0x010ErrorStorage fault.
WARN_NO_BLANK0x020WarningNo blank captured.
WARN_NO_INITIAL0x040WarningNo initial reference.
WARN_WIFI_DOWN0x080WarningWiFi down.
WARN_OTA0x100WarningOTA in progress.

WebSocket protocol

The sensor exposes a WebSocket endpoint at ws://<device-ip>/ws carrying UTF-8 JSON text frames (port 80, up to 5 concurrent clients). Client requests are {"command": "<name>", ...}; every server message is a single-key envelope {"<event>": <payload>}, so you branch on the one key. A {"message": "..."} frame is a human-readable toast, not a command reply. Payloads that report success carry an ok boolean and, on failure, an err string. Responses are broadcast to every connected client. The endpoint has no authentication: only expose the sensor on a trusted network.

Like I²C, the device does not push telemetry unsolicited; the client polls statusrq and watches reading_count for changes. The user-facing commands below map to the library methods above. Diagnostic and maintenance commands (adcrq, extdiag, OTA, factory reset, USB terminal, and others) have no first-class method; reach them through request() / send().

commandExtra fieldsResponse eventNotes
statusrq-statusrsFull status + measurement snapshot.
getinforq-odinfoDevice identity (serial, fw, RSSI, IPv4).
getsettingsrq-settingsrsCurrent and default measurement settings.
setsettingsrqsettings: {…}setsettingsrsWhitelisted keys only; unknown key returns err:"unknown_field".
startodrq-startodrsStart the OD job.
stopodrq-stopodrsStop the OD job and turn off the laser.
blankrq-blankrsCapture a blank reference. Async, up to ~20 s.
calrq-calrsCapture a calibration reading. Async, up to ~25 s.
enableukfrq-ukfrsEnable UKF filtering (persisted).
disableukfrq-ukfrsDisable UKF filtering (persisted).
clearerrorsrq-clearerrorsrsClear the latchable error bits.
lasersetpctrqpercent: 0-100laserpctrsSet the laser target percent.
setlaserpwrrqpower_mw: numsetlaserpwrrsSet the laser target in mW; bounded 0 to max.
laseroffrq-laseroffrsDeactivate the laser power controller.

Units caveat: in the statusrs payload the three reflectance fields are already multiplied by 100 (percent); density and power fields are in their stated absolute units. Non-finite floats are serialized as JSON null and decoded to nan.

For install and downloads, see Code libraries; for the same scenarios over a wired bus, see the I²C interface reference and Python API reference.