-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
87 lines (72 loc) · 2.33 KB
/
app.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import express from "express";
import mqtt from "mqtt";
import path from 'path';
import { fileURLToPath } from 'url';
import pageRoute from './routes/routePage.js';
import connectDB from "./config/db.js";
const __filename = fileURLToPath(import.meta.url); // get the resolved path to the file
const __dirname = path.dirname(__filename); // get the name of the directory
// const client = mqtt.connect("wss://jarprojects:pU1p1SKIPuCpjsUk@jarprojects.cloud.shiftr.io");
const client = mqtt.connect("wss://broker.emqx.io:8084/mqtt");
const app = express();
// EJS
app.set('view engine', 'ejs');
app.set("views", "views");
app.use(express.static("public"));
app.use('/', pageRoute);
const port = 5000;
app.listen(port, () => {
console.log(`Listening on port ${port}`)
})
connectDB();
// MQTT
// Subscribe to topic
client.subscribe('absensi_guru', { qos: 1}, (err) => {
if (err){
console.error("Failed Sub Topic: ", err);
} else {
// console.log("Subscribe to topic", topic);
client.on("message", (topic, payload) => {
console.log(topic)
console.log(payload.toString())
})
}
});
// const topic = 'uuid_rfid';
client.subscribe('uuid_rfid', { qos: 1 }, (err) => {
if (err){
console.error("Failed Sub Topic: ", err);
} else {
// console.log("Subscribe to topic: ", topic);
client.on("message", (topic, payload) => {
console.log(topic)
console.log(payload.toString())
const dataUUID = payload.toString();
app.locals.dataUUID = dataUUID; // Menyimpan variabel global
})
}
});
// Pub to topic
app.post('/publish', (req, res) => {
const { message } = req.body;
client.publish(topic, message, { qos: 1 }, (err) => {
if (err) {
console.error("Failed Pub data to Topic: ", err);
} else {
console.log("Success Pub data to Topic: ", topic);
res.status(200).send('Data berhasil dipublish');
}
});
});
let connectionStatus = 'Tidak Terhubung';
client.on('connect', () => {
console.log('Connected to MQTT broker');
connectionStatus = 'Terhubung ke Broker';
app.locals.connectionStatus = connectionStatus; // Menyimpan variabel global
});
client.on('disconnect', () => {
console.log('Gagal terhubung ke MQTT broker');
connectionStatus = 'Terputus';
app.locals.connectionStatus = connectionStatus; // Menyimpan variabel global
});
export default app;