This repository has been archived by the owner on Jun 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (42 loc) · 1.46 KB
/
index.js
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
import * as config from "./config.js";
import * as mqtt from "mqtt";
import axios from "./http/axios.js";
import * as mqttUtils from "./mqtt/utils.js";
import * as mqttLogger from "./mqtt/logger.js";
import chalk from "chalk";
const topics = mqttUtils.parseTopicsDirectory();
const client = mqtt.connect(mqttUtils.formatConnectionOpts(config.mqtt));
console.log(client.options);
client.on("connect", () => {
mqttLogger.connect();
client.subscribe(topics, (err, grant) => {
if (err) {
mqttLogger.subscriptionError(err);
}
mqttLogger.subscribed(grant);
});
});
client.on("message", function (topic, message) {
message = message.toString();
mqttLogger.message(topic, message);
axios
.post("/iot/messages", {
"real_topic": topic,
"iot_message_value": message
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
// TODO: handle error + log + cache + retry
mqttLogger.log(chalk.bgRed.bold(mqttLogger.dateStr() + "AJAX ERROR"));
console.log(error.response.data);
});
});
// client.on("packetsend", mqttLogger.packetsend);
// client.on("packetreceive", mqttLogger.packetreceive);
client.on("reconnect", mqttLogger.reconnect);
client.on("close", mqttLogger.close);
client.on("offline", mqttLogger.offline);
client.on("end", mqttLogger.end);
client.on("error", mqttLogger.error);