58 lines
1.8 KiB
TypeScript
58 lines
1.8 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);
|
|
|
|
const hourlyEnergy = measurement.energyForDay.values.map((value, index) => new Point('energy')
|
|
.timestamp(date.clone().set('hour', index+1).toDate())
|
|
.tag('profile', 'hourly')
|
|
.floatField('value', value)
|
|
);
|
|
|
|
const dailyEnergy = new Point('energy')
|
|
.timestamp(date.toDate())
|
|
.tag('profile', 'daily')
|
|
.floatField('value', measurement.energyForDay.sum);
|
|
|
|
const monthlyEnergy = new Point('energy')
|
|
.timestamp(date.toDate())
|
|
.tag('profile', 'monthly')
|
|
.floatField('value', measurement.energyForMonth.sum);
|
|
|
|
const annualyEnergy = new Point('energy')
|
|
.timestamp(date.toDate())
|
|
.tag('profile', 'annualy')
|
|
.floatField('value', measurement.energyForYear.sum);
|
|
|
|
const reading = new Point('reading')
|
|
.timestamp(date.clone().set('hour', 23).set('minute', 59).set('second', 59).toDate())
|
|
.floatField('value', measurement.reading.C);
|
|
|
|
hourlyEnergy.forEach(p => api.writePoint(p));
|
|
api.writePoint(dailyEnergy);
|
|
api.writePoint(monthlyEnergy);
|
|
api.writePoint(annualyEnergy);
|
|
api.writePoint(reading);
|
|
|
|
api.close();
|
|
}
|
|
} |