Author: Alistair Keiller
InfluxDB
CAN-to-InfluxDB Telemetry (Line Protocol)
Transforms strongly-typed telemetry readings into InfluxDB Line Protocol after MQTT verification. The key helper is to_line_protocol, which turns any Reading into a write-ready line.
Function: to_line_protocol<T: Reading>(message: &T) -> String
- Measurement: Uses
T::topic()as the measurement name. - Fields: Serializes number, string, and boolean fields; unsupported types are skipped.
- Timestamp: Appends current UTC time in nanoseconds.
Field Formatting
- Integers (
i64,u64): Suffixed withi, e.g.,rpm=1200i. - Floats: Written as-is, e.g.,
voltage=12.34. - Strings: Quoted, e.g.,
state="OK". - Booleans: Lowercase
true/false.
Example Output
- Input:
TelemetryData { rpm: 1200, voltage: 12.34, state: "OK", fault: false } - Topic:
telemetry - Output:
telemetry rpm=1200i,voltage=12.34,state="OK",fault=false 1734043200000000000
Workflow Inside to_line_protocol
- Start with
T::topic()as the measurement. - Serialize
messageto JSON (serde_json::to_value). - Iterate object fields, formatting supported values and comma-separating them.
- Append the UTC nanosecond timestamp from
chrono::Utc::now().timestamp_nanos_opt(). - Return the completed line protocol string.
End-to-End Flow
- Collect CAN telemetry (speed, torque, voltage, current, temps, fault states) into a
TelemetryDatathat implementsReading. - Publish the struct as JSON to the
telemetryMQTT topic with QoSAtLeastOnce. - MQTT listener verifies the payload matches the expected
TelemetryData. - On verification success, convert to line protocol via
to_line_protocoland write to InfluxDB.
Writing to InfluxDB
- Endpoint: HTTP
POST /api/v2/write?org=<org>&bucket=<bucket>&precision=nsor the official Influx client. - Body: The string returned by
to_line_protocol. - Auth:
Authorization: Token <token>header. - Precision:
nsto match the timestamp source. - Reliability: Add retries/backoff for transient failures and log write errors.
Minimal sketch:
let lp = to_line_protocol(&telemetry);- POST
lpto the write endpoint withprecision=ns.
Testing Guidance
- Unit tests: verify integer
isuffixing, string quoting, boolean casing, and timestamp inclusion. - Integration: pair with the MQTT listener test to cover publish → verify → convert → write.
Troubleshooting
- Missing fields: Ensure fields are serde-serializable scalars (no nested objects/arrays).
- Wrong measurement: Confirm
T::topic()returns the intended measurement. - Write failures: Check token, bucket, org, precision, and server availability.
- Timestamp
None: Verify system clock andtimestamp_nanos_opt()support on the target platform.