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
| Method | Returns | Description |
|---|---|---|
| connect() | TurbidVisionWS | Open the socket, start the background RX thread, and prime status/info/settings. Returns self. Called automatically on context entry. |
| close() | None | Close the socket, stop the RX thread, and release any blocked stream_readings() consumers. |
| __enter__() / __exit__() | TurbidVisionWS | Context-manager protocol: connects on entry, closes on exit. Use a 'with' block. |
| connected | bool | Property: 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) | None | Send 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) | dict | Send command and block until response_event arrives; returns the payload. Raises TurbidVisionError on timeout or a non-OK (ok == False) payload. |
Status and readings
| Method | Returns | Description |
|---|---|---|
| status(refresh=True, timeout=5.0) | Snapshot | Latest 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 | None | Most 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) | Info | Request and return device identity (serial, firmware, RSSI, IPv4). |
| get_settings(timeout=5.0) | dict | Current and default measurement settings as {"settings": {...}, "defaults": {...}}. |
| set_settings(timeout=5.0, **kwargs) | None | Update 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.
| Method | Returns | Description |
|---|---|---|
| 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) | dict | Capture 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
| Method | Description |
|---|---|
| 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
| Method | Returns | Description |
|---|---|---|
| wait_for_status(flag, value=True, timeout=35.0, poll_interval=0.2) | bool | Block 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) | bool | Block 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.
| Field | Type | Description |
|---|---|---|
| job_running | bool | OD measurement job active. |
| is_initializing | bool | Capturing the initial reference. |
| has_initial | bool | Initial reference captured. |
| has_blank | bool | Blank reference captured. |
| ukf_enabled | bool | UKF filtering enabled. |
| pi_running | bool | Laser PI controller running. |
| pi_stable | bool | Laser PI controller settled. |
| reflectance_stable | bool | Reflectance reading has stabilised. |
| probe_detected | bool | Optical probe installed and detected. |
| calibrated | bool | Usable calibration lookup table present. |
| reading_count | int | None | Monotonic reading counter; advances each new reading. |
| ukf_gate_counter | int | None | UKF innovation-gate rejection count. |
| error_flags | int | System error/warning vector (0 = no faults). See Error flag masks. |
| job_uptime_ms | int | None | Milliseconds since the current job started. |
| last_measured_reflectance | float (%) | Latest reflectance, already scaled to percent. nan when unavailable. |
| reflectance_avg_pct | float (%) | Rolling-average reflectance in percent. nan when unavailable. |
| measured_reflectance_avg_pct | float (%) | Blank-corrected rolling-average reflectance in percent. nan when unavailable. |
| laser_power_mw | float (mW) | Measured laser optical power. nan when unavailable. |
| reflected_power_mw | float (mW) | Reflected optical power. nan when unavailable. |
| target_laser_mw | float (mW) | Laser power target. nan when unavailable. |
| target_laser_pct | float (%) | Laser power target as percent of max. nan when unavailable. |
| dac_drive_pct | float (%) | Laser DAC drive level. nan when unavailable. |
| laser_temp_c | float (°C) | Laser NTC temperature. nan when unavailable. |
| calibrated_density | float (g/L) | Calibrated optical density. nan when unavailable. |
| ukf_filtered_density | float (g/L) | UKF-filtered density. nan when UKF is disabled. |
| ukf_growth_rate | float (1/h) | UKF specific growth rate. nan when UKF is disabled. |
| ukf_growth_rate_abs | float (g/L/h) | UKF absolute growth rate. nan when UKF is disabled. |
| ukf_innovation | float | UKF innovation magnitude. nan when unavailable. |
| raw | dict | The full original statusrs payload, retained for fields not modelled here. |
Info
Device identity returned by get_info(), decoded from an odinfo event.
| Field | Type | Description |
|---|---|---|
| sn | str | Device serial number. |
| fw | str | Firmware version. |
| rssi | int | None | WiFi signal strength in dBm, or None if unparsable. |
| ipv4 | str | Device 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.
| Constant | Field name |
|---|---|
| STATUS_JOB_RUNNING | job_running |
| STATUS_IS_INITIALIZING | is_initializing |
| STATUS_HAS_INITIAL | has_initial |
| STATUS_HAS_BLANK | has_blank |
| STATUS_UKF_ENABLED | ukf_enabled |
| STATUS_PI_RUNNING | pi_running |
| STATUS_PI_STABLE | pi_stable |
| STATUS_REFLECTANCE_STABLE | reflectance_stable |
| STATUS_PROBE_DETECTED | probe_detected |
| STATUS_CALIBRATED | calibrated |
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.
| Constant | Mask | Class | Meaning |
|---|---|---|---|
| ERR_SAFETY_CRITICAL | 0x001 | Error | Safety-critical fault. |
| ERR_SAFETY_WARNING | 0x002 | Error | Safety warning. |
| ERR_PI_FAILED | 0x004 | Error | Laser PI controller failed. |
| ERR_LOW_HEAP | 0x008 | Error | Low heap. |
| ERR_STORAGE | 0x010 | Error | Storage fault. |
| WARN_NO_BLANK | 0x020 | Warning | No blank captured. |
| WARN_NO_INITIAL | 0x040 | Warning | No initial reference. |
| WARN_WIFI_DOWN | 0x080 | Warning | WiFi down. |
| WARN_OTA | 0x100 | Warning | OTA 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().
| command | Extra fields | Response event | Notes |
|---|---|---|---|
| statusrq | - | statusrs | Full status + measurement snapshot. |
| getinforq | - | odinfo | Device identity (serial, fw, RSSI, IPv4). |
| getsettingsrq | - | settingsrs | Current and default measurement settings. |
| setsettingsrq | settings: {…} | setsettingsrs | Whitelisted keys only; unknown key returns err:"unknown_field". |
| startodrq | - | startodrs | Start the OD job. |
| stopodrq | - | stopodrs | Stop the OD job and turn off the laser. |
| blankrq | - | blankrs | Capture a blank reference. Async, up to ~20 s. |
| calrq | - | calrs | Capture a calibration reading. Async, up to ~25 s. |
| enableukfrq | - | ukfrs | Enable UKF filtering (persisted). |
| disableukfrq | - | ukfrs | Disable UKF filtering (persisted). |
| clearerrorsrq | - | clearerrorsrs | Clear the latchable error bits. |
| lasersetpctrq | percent: 0-100 | laserpctrs | Set the laser target percent. |
| setlaserpwrrq | power_mw: num | setlaserpwrrs | Set the laser target in mW; bounded 0 to max. |
| laseroffrq | - | laseroffrs | Deactivate 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.

