Created
October 8, 2024 22:55
-
-
Save BlueskyFR/5229d9d58b9261bcfcfd9f01a6b61f66 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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