Skip to content

Instantly share code, notes, and snippets.

@BlueskyFR
Created October 8, 2024 22:55
Show Gist options
  • Save BlueskyFR/5229d9d58b9261bcfcfd9f01a6b61f66 to your computer and use it in GitHub Desktop.
Save BlueskyFR/5229d9d58b9261bcfcfd9f01a6b61f66 to your computer and use it in GitHub Desktop.
import debug from "debug";
import type { Sensor } from "./types";
let dbg = debug("sauter:LineProtocol");
// Log to stdout instead of stderr by default
dbg.log = console.log.bind(console);
// Escape special chars depending on the field (see https://is.gd/wdaALB)
const escape = {
mesurement: (s: string) => s.replace(/[,\s]/g, "\\$&"),
tagKeyOrValue: (s: string) => s.replace(/[,=\s]/g, "\\$&"),
fieldKey: (s: string) => s.replace(/[,=\s]/g, "\\$&"),
fieldValue: (s: string) => s.replace(/["\\]/g, "\\$&"),
};
// Formatter helper for the Line Protocol used by InfluxDB as data point input format
// (reference: https://is.gd/B4LclV)
export default class LineProtocol {
private mesurement: string;
constructor(mesurement: string) {
this.mesurement = escape.mesurement(mesurement);
}
// Format a sensor object into a line protocol string
format({ id, code, category, unit, name, longName, value }: Sensor): string {
if (value === undefined) throw new Error("value cannot be undefined!");
// Escape all fields based on their role in the line protocol string
code = escape.tagKeyOrValue(code);
category = escape.tagKeyOrValue(category);
let sensor_id: string = escape.tagKeyOrValue(id.toString());
if (typeof value === "string") value = `"${value}"`;
value = escape.fieldValue(value.toString());
let unitField = "";
// Create a unit field if it exists
if (unit !== undefined) unitField = `,unit=${escape.tagKeyOrValue(unit)}`;
return (
`${this.mesurement},sensor_id=${sensor_id},sensor_code=${code},category=${category}${unitField}` +
` value=${value} ${Date.now()}`
);
}
}
// sauter,sensor_id=1107,sensor_code=SM01-MTE01.M01_SS09-HPE,category=EXTRACTEUR\ HFO,unit=°C value=22.5 1722357994543
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment