-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMMM-PingTime.js
109 lines (94 loc) · 2.97 KB
/
MMM-PingTime.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
Module.register("MMM-PingTime", {
defaults: {
updateInterval: 4000,
startupDelay: 2000,
timePrefix: "",
timeSuffix: "ms",
connectedText: "Connected",
disconnectedText: "Disconnected",
loadingIcon: 'loading-icon fas fa-sync fa-spin',
connectedIcon: 'success-icon fas fa-check',
disconnectedIcon: 'warning-icon fas fa-ban',
pingFontColor: "--color-text",
connectedFontCollor: "--color-text",
disconnectedFontColor: "--color-text",
fontSize: 1,
server: {
websocketUrl: "wss://echo.websocket.org",
outgoingMessage: "ping",
incomingMessage: "ping",
bypassCheck: false
}
},
getTemplate: function() {
return "MMM-PingTime.njk";
},
getTemplateData: function() {
return {
pingResult: this.pingResult,
config: this.config,
connectedText: this.config.connectedText,
disconnectedText: this.config.disconnectedText
};
},
start: function() {
console.log("Starting module: " + this.name);
this.updateDom();
setTimeout(() => {
this.connect();
}, this.config.startupDelay);
},
connect: function() {
this.socket = new WebSocket(this.config.server.websocketUrl);
this.socket.onopen = () => {
console.log("WebSocket connected");
this.pingResult = "cn";
this.updateDom();
this.startPinging();
};
this.socket.onclose = () => {
console.log("WebSocket disconnected");
this.pingResult = "dc";
this.pingStartTime = 0;
this.updateDom();
this.stopPinging();
// Try to reconnect after a delay
setTimeout(() => {
this.connect();
}, 5000);
};
this.socket.onmessage = (event) => {
const latency = Date.now() - this.pingStartTime;
if(event.data === this.config.server.incomingMessage || this.config.server.bypassCheck) {
this.pingResult = this.config.timePrefix + latency + " " + this.config.timeSuffix;
}
this.updateDom();
};
},
startPinging: function() {
console.log("Starting pinging");
this.pingInterval = setInterval(() => {
this.ping();
}, this.config.updateInterval);
},
stopPinging: function() {
if (this.pingInterval) {
clearInterval(this.pingInterval);
}
},
ping: function() {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
this.pingStartTime = Date.now();
this.socket.send(this.config.server.outgoingMessage);
}
},
suspend: function() {
this.stopPinging();
if (this.socket) {
this.socket.close();
}
},
resume: function() {
this.connect();
}
});