Sensors
Read battery levels, RSSI, pressure, buttons, and position sensors
const battery = await device.readSensor("Battery");
console.log(`Battery: ${battery}%`);Sensors provide input data from a Device. The library supports two access patterns: one-shot reads for polling a value, and subscriptions for continuous updates.
Sensor Types
| Type | Description | Typical Values |
|---|---|---|
Battery | Battery charge level | Integer in device range (e.g. 0 -- 100) |
RSSI | Bluetooth signal strength | Negative integer (dBm) |
Pressure | Pressure sensor reading | Integer in device range |
Button | Physical button state | 0 (released) or 1 (pressed) |
Position | Position sensor reading | Integer in device range |
Not every device exposes every sensor type. Always check capabilities before reading.
One-Shot Reads
readSensor() performs a single read and returns the numeric value. The optional second argument selects a specific sensor when the device has multiple of the same type.
if (device.canRead("Battery")) {
const level = await device.readSensor("Battery");
console.log(`Battery: ${level}`);
}
// Read the second pressure sensor (index 1)
const pressure = await device.readSensor("Pressure", 1);The method sends an InputCmd with Read, waits for the server's InputReading response, and extracts the value. It throws a DeviceError if the sensor does not exist or does not support reads.
Subscriptions
subscribeSensor() registers a callback that fires each time the server pushes a new reading. It returns an async unsubscribe function.
const unsubscribe = await device.subscribeSensor(
"Button",
(value) => {
console.log(`Button: ${value === 1 ? "pressed" : "released"}`);
}
);
// Later, stop receiving updates
await unsubscribe();The callback receives the raw numeric value from the server. Subscriptions are registered on the server after the subscribe command succeeds -- if the server rejects the request, no local state is created.
You can also unsubscribe explicitly by type and sensor index:
await device.unsubscribe("Button", 0);Sensor subscriptions are automatically cleaned up when a device is removed or the client disconnects.
Capability Checks
Always verify that a sensor exists and supports the operation you need:
if (device.canRead("RSSI")) {
const rssi = await device.readSensor("RSSI");
}
if (device.canSubscribe("Pressure")) {
await device.subscribeSensor("Pressure", (v) => { /* ... */ });
}canRead() checks for at least one sensor of the given type that supports one-shot reads. canSubscribe() checks for subscription support. A device may support reading a sensor type without supporting subscriptions, or vice versa.
For the full sensor API, see the Device reference.