74 lines
2.4 KiB
TypeScript
74 lines
2.4 KiB
TypeScript
import { readFileSync } from "fs";
|
|
import { InfluxDB, Point } from "@influxdata/influxdb-client";
|
|
import { InfluxDBConfig, Measurement } from "@types";
|
|
import { Consumer } from "./abstract";
|
|
import { Dayjs } from "dayjs";
|
|
|
|
export class InfluxDBConsumer extends Consumer<InfluxDBConfig> {
|
|
public name = 'influxdb';
|
|
|
|
protected requiredFields = [
|
|
'databaseURL',
|
|
'apiToken',
|
|
'organization',
|
|
'bucket',
|
|
] as const;
|
|
|
|
protected async publish({ databaseURL, apiToken, organization, bucket }: InfluxDBConfig, date: Dayjs, measurement: Measurement) {
|
|
const db = new InfluxDB({
|
|
url: databaseURL,
|
|
token: readFileSync(apiToken, 'utf8'),
|
|
});
|
|
|
|
const api = db.getWriteApi(organization, bucket);
|
|
|
|
measurement.energyForDay.values
|
|
.filter(v => {
|
|
if (!v) {
|
|
console.warn(`No hourly energy value for ${date.format("YYYY-MM-DD")}`);
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
})
|
|
.map((value, index) => new Point('energy')
|
|
.timestamp(date.startOf('day').hour(index + 1).minute(0).toDate())
|
|
.tag('profile', 'hourly')
|
|
.floatField('value', value)
|
|
)
|
|
.forEach(p => api.writePoint(p));
|
|
|
|
if(measurement.energyForDay.sum) {
|
|
const data = new Point('energy')
|
|
.timestamp(date.toDate())
|
|
.tag('profile', 'daily')
|
|
.floatField('value', measurement.energyForDay.sum);
|
|
api.writePoint(data);
|
|
} else console.warn(`No daily energy value for ${date.format("YYYY-MM-DD")}`)
|
|
|
|
if(measurement.energyForMonth.sum) {
|
|
const data = new Point('energy')
|
|
.timestamp(date.toDate())
|
|
.tag('profile', 'monthly')
|
|
.floatField('value', measurement.energyForMonth.sum);
|
|
api.writePoint(data);
|
|
} else console.warn(`No monthly energy value for ${date.format("YYYY-MM-DD")}`)
|
|
|
|
if(measurement.energyForYear.sum) {
|
|
const data = new Point('energy')
|
|
.timestamp(date.toDate())
|
|
.tag('profile', 'annualy')
|
|
.floatField('value', measurement.energyForYear.sum);
|
|
api.writePoint(data);
|
|
} else console.warn(`No anually energy value for ${date.format("YYYY-MM-DD")}`)
|
|
|
|
if(measurement.reading.C) {
|
|
const data = new Point('reading')
|
|
.timestamp(date.hour(23).minute(59).second(59).toDate())
|
|
.floatField('value', measurement.reading.C);
|
|
api.writePoint(data);
|
|
} else console.warn(`No reading data value for ${date.format("YYYY-MM-DD")}`)
|
|
|
|
api.close();
|
|
}
|
|
} |