-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
77 lines (63 loc) · 2.2 KB
/
Copy pathindex.js
File metadata and controls
77 lines (63 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const influx = require('influx');
const mqtt = require('mqtt');
const config = require('./config');
const logOutput = config.outputType === 'console' ? console.log : () => {};
const setupInfluxWriter = async (influxConfig) => {
const {host, databaseName, measurement, schema} = { ...influxConfig };
logOutput(`Connecting to InfluxDB at ${host}...`);
const influxClient = new influx.InfluxDB({
host: host,
database: databaseName,
schema: schema,
});
logOutput(`Checking if database '${databaseName}' exists...`);
const existingDatabases = await influxClient.getDatabaseNames();
if (!existingDatabases.includes(databaseName)) {
logOutput(`Database '${databaseName}' created.`);
await influxClient.createDatabase(databaseName);
}
const writeAction = async (measurementObject) => {
await influxClient.writeMeasurement(measurement, [
// TODO put this in the config
{
fields: {
temp: measurementObject.temp,
humidity: measurementObject.humidity,
},
tags: { sensor: measurementObject.sensor },
},
]);
};
logOutput('Database setup complete.')
return writeAction;
}
const connectMqtt = (mqttConfig, databaseWriteAction) => {
const {brokerLocation, brokerTopic} = { ...mqttConfig };
logOutput(`Connecting to broker at ${brokerLocation}...`);
const mqttClient = mqtt.connect(brokerLocation);
const onSubscribe = (error) => {
logOutput(`Subscribed to '${brokerTopic}', listening for messages...`);
if (error) {
logOutput(`Unable to subscribe to ${brokerTopic}`);
logOutput(error);
}
};
const onConnect = (connack) => {
logOutput(`Connected to broker at ${brokerLocation}, subscribing to ${brokerTopic}...`);
mqttClient.subscribe(brokerTopic, onSubscribe);
};
const onRecieveMessage = (topic, message) => {
logOutput(`${topic}: ${message.toString()}`);
try {
databaseWriteAction(JSON.parse(message));
} catch (error) {
logOutput(`Error writing message: ${error}`);
}
};
mqttClient.on('connect', onConnect);
mqttClient.on('message', onRecieveMessage);
};
const main = async () => {
connectMqtt(config.mqtt, await setupInfluxWriter(config.influx));
}
main();