-
Notifications
You must be signed in to change notification settings - Fork 4
/
sharenow.js
61 lines (52 loc) · 1.94 KB
/
sharenow.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
const mqtt = require("mqtt");
const zlip = require("zlib");
const uuid = require("uuid-random");
class ShareNowClient {
static VEHICLELISTDELTA = "C2G/S2C/3/VEHICLELISTDELTA.GZ";
static VEHICLELIST = "C2G/S2C/3/VEHICLELIST.GZ"
vehicles = [];
#updateCallback;
connect() {
let clientId = `a:${uuid()}`;
let client = mqtt.connect('mqtts://driver.eu.share-now.com:443', {
clientId,
rejectUnauthorized: false,
reconnectPeriod: 0
});
client.on('connect', () => {
console.log("Connected to MQTT broker. Subscribing to topics.");
client.subscribe(ShareNowClient.VEHICLELIST, {qos: 0});
client.subscribe(ShareNowClient.VEHICLELISTDELTA, {qos: 1});
});
client.on("message", (topic, message) => {
let json = JSON.parse(zlip.gunzipSync(message));
if (topic === ShareNowClient.VEHICLELISTDELTA) {
this.updateVehicles(json);
if (this.#updateCallback !== undefined) {
this.#updateCallback(json);
}
} else if (topic === ShareNowClient.VEHICLELIST) {
console.log("Received initial vehicle list");
client.unsubscribe(ShareNowClient.VEHICLELIST);
this.vehicles = json.connectedVehicles;
}
});
client.on("error", error => {
console.log(`Error: ${error}`);
});
client.on("close", () => {
console.log("Close");
});
}
getVehicles(callback) {
this.#updateCallback = callback;
return this.vehicles;
}
updateVehicles(vehicleUpdate) {
this.vehicles = this.vehicles.concat(vehicleUpdate.addedVehicles);
vehicleUpdate.removedVehicles.forEach(vehicleId => {
this.vehicles = this.vehicles.filter(e => e.id !== vehicleId);
});
}
}
module.exports = ShareNowClient;