-
Notifications
You must be signed in to change notification settings - Fork 2
/
mqtt.js
50 lines (35 loc) · 1.17 KB
/
mqtt.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
const net = require("net");
const url = require("url");
const WebSocket = require("ws");
process.env = Object.assign({
BACKEND_URL: "http://localhost:8080",
BACKEND_PROTOCOL: "http"
}, process.env);
const logger = require("./system/logger.js");
const log = logger.create("forwarder/mqtt");
let uri = new url.URL(process.env.BACKEND_URL);
uri.protocol = (process.env.BACKEND_PROTOCOL === "https" ? "wss" : "ws");
uri.pathname = "/api/mqtt";
uri.search = `x-auth-token=${process.env.AUTH_TOKEN}`;
const ws = new WebSocket(uri);
const socket = new net.Socket();
ws.on("close", (code) => {
log.debug(`Disconnected from ${ws.url}`, code);
socket.destroy();
});
socket.on("connect", () => {
log.info(`Client connected to tcp://${process.env.MQTT_HOST}:${process.env.MQTT_PORT}`);
socket.on("data", (data) => {
log.trace("Message on tcp socket received", data);
ws.send(data);
});
});
ws.on("message", (data) => {
log.trace("Send message to tcp socket", data);
socket.write(data);
});
ws.on("open", () => {
log.info(`Connected to ${ws.url}`);
// bind socket
socket.connect(process.env.MQTT_PORT, process.env.MQTT_HOST);
});