-
Notifications
You must be signed in to change notification settings - Fork 0
/
listerner.js
75 lines (59 loc) · 1.85 KB
/
listerner.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
const fs = require('fs');
const mqtt = require('mqtt');
// Global variables
const LOCAL_DIR_TO_COPY_TO = "./images/";
const TOPIC_TO_SUBSCRIBE_TO = "smart/parking/polimi/image";
const HOST = "broker.hivemq.com"
const SAVE_EVERY = 300000 //milliseconds
const clientId = `parking_${Math.random().toString(16).slice(3)}`
const client = mqtt.connect('mqtt://'+HOST, {
clientId,
clean: true,
connectTimeout: 4000,
reconnectPeriod: 1000,
});
let buffer;
let timer;
let filename;
let oldFilename = "";
client.on('connect', function() {
client.subscribe(TOPIC_TO_SUBSCRIBE_TO, () => {
console.log('Subscribed to ', TOPIC_TO_SUBSCRIBE_TO);
});
});
client.on("connect", function(){
console.log("Client connected");
});
client.on('message', function(topic, payload) {
if (topic === TOPIC_TO_SUBSCRIBE_TO) {
console.log('message::' + topic);
buffer = Buffer.from(payload.toString(), "base64");
filename = getFilename()
}
});
client.on('error', (error) => {
console.log(error)
})
saveImagePeriodic()
function saveImagePeriodic() {
timer = setInterval(function() {
if (filename != oldFilename) {
fs.writeFileSync(LOCAL_DIR_TO_COPY_TO + filename, buffer);
console.log("Pic saved: ", filename);
oldFilename = filename
}
else {
console.log("warning::pic already saved. Skipping")
}
}, SAVE_EVERY);
}
function getFilename() {
let date_ob = new Date();
let day = ("0" + date_ob.getDate()).slice(-2);
let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);
let year = date_ob.getFullYear();
let hours = ("0" + date_ob.getHours()).slice(-2);
let minutes = ("0" + date_ob.getMinutes()).slice(-2);
let seconds = ("0" + date_ob.getSeconds()).slice(-2);
return year+month+day+"-"+hours+minutes+seconds+".png"
}