forked from roramirez/MagicMirror-Module-Template
-
Notifications
You must be signed in to change notification settings - Fork 4
/
octomirror-module.js
289 lines (253 loc) · 11.2 KB
/
octomirror-module.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/* global Module */
/* jshint esversion: 6 */
/* Magic Mirror
* Module: OctoMirror-Module
*
* By Kieran Ramnarine
* MIT Licensed.
*/
Module.register("octomirror-module", {
defaults: {
updateInterval: 60 * 1000,
retryDelay: 2500,
showStream: true,
showTemps: true,
showDetailsWhenOffline: true,
interactive: true, // Set to false to hide the file drop down and only show the stream.
debugMode: false, // Set to true to log all messages from OctoPrint Socket
showOnlyWhilePrinting: false,
},
//Override dom generator.
getDom: function() {
var self = this;
var wrapper = document.createElement("div");
if (this.config.showStream) {
var stream = document.createElement("img");
stream.src = (this.config.streamUrl) ? this.config.streamUrl : this.config.url + ":8080/?action=stream";
wrapper.appendChild(stream);
}
if (this.config.interactive) {
var fileMenu = document.createElement("div");
var fileList = document.createElement("select");
for (var f in this.files) {
var option = document.createElement("option");
option.setAttribute("value", this.files[f]);
option.appendChild(document.createTextNode(this.files[f]));
fileList.appendChild(option);
}
var printButton = document.createElement("button");
printButton.appendChild(document.createTextNode("Send to Printer"));
printButton.addEventListener("click", function() {
self.sendPrint(fileList.value);
});
var fileUpload = document.createElement("div");
var uploadFileInput = document.createElement("input");
uploadFileInput.setAttribute("type", "file");
var uploadButton = document.createElement("button");
uploadButton.appendChild(document.createTextNode("Upload Files"));
uploadButton.addEventListener("click", function() {
self.uploadFile(uploadFileInput.value);
});
fileUpload.appendChild(uploadFileInput);
fileUpload.appendChild(uploadButton);
fileMenu.appendChild(fileList);
fileMenu.appendChild(printButton);
fileMenu.appendChild(fileUpload);
wrapper.appendChild(fileMenu);
}
var infoWrapper = document.createElement("div");
infoWrapper.className = "small";
infoWrapper.innerHTML = `<span>${this.translate("STATE")}: </span><span id="opStateIcon"></span> <span id="opState" class="title bright"> </span>
<br />
<div id="opMoreInfo">
<span>${this.translate("FILE")}: </span><span id="opFile" class="title bright">N/A</span>
<br />
<span>${this.translate("ELAPSED")}: </span><span id="opPrintTime" class="title bright">N/A</span>
<span> | ${this.translate("REMAINING")}: </span><span id="opPrintTimeRemaining" class="title bright">N/A</span>
<span> | ${this.translate("PERCENT")}: </span><span id="opPercent" class="title bright">N/A</span>
<br />`;
if (this.config.showTemps) {
infoWrapper.innerHTML += `
<span>${this.translate("TEMPS")} : ${this.translate("NOZZLE")}: </span><span id="opNozzleTemp" class="title bright">N/A</span>
<span> ${this.translate("TARGET")}: (<span id="opNozzleTempTgt">N/A</span><span>) | ${this.translate("BED")}: </span><span id="opBedTemp" class="title bright">N/A</span>
<span> ${this.translate("TARGET")}: (<span id="opBedTempTgt">N/A</span><span>)</span>
</div>
`;
}
wrapper.appendChild(infoWrapper);
wrapper.appendChild(document.createElement("br"));
return wrapper;
},
start: function() {
Log.info("Starting module: " + this.name);
this.files = [];
this.loaded = false;
if (this.config.interactive) { this.scheduleUpdate(this.config.initialLoadDelay); }
this.updateTimer = null;
this.opClient = new OctoPrintClient();
this.opClient.options.baseurl = this.config.url;
this.opClient.options.apikey = this.config.api_key;
},
initializeSocket: function() {
var self = this;
let user = "_api", session = "";
$.ajax({
url: this.config.url + "/api/login",
type: 'post',
data: { passive: true },
headers: {
"X-Api-Key": this.config.api_key
},
dataType: 'json',
}).done((data)=>{
if (this.config.debugMode) { console.log("Octoprint login response:",data); }
session = data.session;
// Subscribe to live push updates from the server
this.opClient.socket.connect();
});
this.opClient.socket.onMessage("connected", (message) => {
this.opClient.socket.socket.send(JSON.stringify({ auth: `${user}:${session}`}));
});
if (this.config.debugMode) {
this.opClient.socket.onMessage("*", (message) => {
// Reference: http://docs.octoprint.org/en/master/api/push.html#sec-api-push-datamodel-currentandhistory
console.log("Octoprint", message);
});
}
this.opClient.socket.onMessage("history", (message) => {
this.updateData(message.data);
});
this.opClient.socket.onMessage("current", (message) => {
this.updateData(message.data);
});
},
getScripts: function() {
return [
this.file('jquery.min.js'),
this.file('lodash.min.js'),
this.file('sockjs.min.js'),
this.file('packed_client.js'),
];
},
getTranslations: function() {
return {
en: "translations/en.json",
de: "translations/de.json"
};
},
processFiles: function(data) {
this.files = [];
for (var x in data.files) {
this.files.push(data.files[x].name);
}
this.show(this.config.animationSpeed, { lockString: this.identifier });
this.loaded = true;
this.updateDom(this.config.animationSpeed);
},
scheduleUpdate: function(delay) {
var nextLoad = this.config.updateInterval;
if (typeof delay !== "undefined" && delay >= 0) {
nextLoad = delay;
}
var self = this;
clearTimeout(this.updateTimer);
this.updateTimer = setTimeout(function() {
self.updateFiles();
}, nextLoad);
},
updateFiles: function() {
var self = this;
this.opClient.files.list()
.done(function(response) {
self.processFiles(response);
});
},
sendPrint: function(filename) {
this.opClient.files.select("local", filename, true);
},
uploadFile: function(file) {
var self = this;
this.opClient.files.upload("local", file)
.done(function(response) {
self.updateFiles();
});
},
updateData: function(data) {
console.log("Updating OctoPrint Data");
console.log($("#opState")[0]);
$("#opState")[0].textContent = (data.state.text.startsWith("Offline (Error: SerialException")) ? this.translate("OFFLINE") : data.state.text;
var icon = $("#opStateIcon")[0];
if (data.state.flags.printing) {
icon.innerHTML = `<i class="fa fa-print" aria-hidden="true" style="color:green;"></i>`;
if (!this.config.showDetailsWhenOffline) { $("#opMoreInfo").show(); }
} else if (data.state.flags.closedOrError) {
icon.innerHTML = `<i class="fa fa-exclamation-triangle" aria-hidden="true" style="color:red;"></i>`;
if (!this.config.showDetailsWhenOffline) { $("#opMoreInfo").hide(); }
} else if (data.state.flags.paused) {
icon.innerHTML = `<i class="fa fa-pause" aria-hidden="true" style="color:yellow;"></i>`;
if (!this.config.showDetailsWhenOffline) { $("#opMoreInfo").show(); }
} else if (data.state.flags.error) {
icon.innerHTML = `<i class="fa fa-exclamation-triangle" aria-hidden="true" style="color:red;"></i>`;
if (!this.config.showDetailsWhenOffline) { $("#opMoreInfo").hide(); }
} else if (data.state.flags.ready) {
icon.innerHTML = `<i class="fa fa-check-circle" aria-hidden="true" style="color:green;"></i>`;
if (!this.config.showDetailsWhenOffline) { $("#opMoreInfo").show(); }
} else if (data.state.flags.operational) {
icon.innerHTML = `<i class="fa fa-check-circle" aria-hidden="true" style="color:green;"></i>`;
if (!this.config.showDetailsWhenOffline) { $("#opMoreInfo").show(); }
}
$("#opFile")[0].textContent = (data.job.file.name) ? data.job.file.name : "N/A";
$("#opPrintTime")[0].textContent = (data.progress.printTime) ? data.progress.printTime.toHHMMSS() : "N/A";
$("#opPrintTimeRemaining")[0].textContent = (data.progress.printTimeLeft) ? data.progress.printTimeLeft.toHHMMSS() : "N/A";
$("#opPercent")[0].textContent = (data.progress.completion) ? Math.round(data.progress.completion) + "%" : "N/A";
if (this.config.showTemps) {
var temps = data.temps[data.temps.length - 1];
if (typeof temps.bed === "undefined") { // Sometimes the last data point is time only, so back up 1.
temps = data.temps[data.temps.length - 2];
}
$("#opNozzleTemp")[0].innerHTML = (temps.tool0.actual) ? temps.tool0.actual.round10(1) + "°C" : "N/A";
$("#opNozzleTempTgt")[0].innerHTML = (temps.tool0.target) ? Math.round(temps.tool0.target) + "°C" : "N/A";
$("#opBedTemp")[0].innerHTML = (temps.bed.actual) ? temps.bed.actual.round10(1) + "°C" : "N/A";
$("#opBedTempTgt")[0].innerHTML = (temps.bed.target) ? Math.round(temps.bed.target) + "°C" : "N/A";
}
if (data.state.text != "Printing" & this.config.showOnlyWhilePrinting){
this.hide();
}
else {
this.show();
}
},
notificationReceived: function(notification, payload, sender) {
if (notification === 'DOM_OBJECTS_CREATED') {
this.initializeSocket();
this.scheduleUpdate(1);
}
}
});
Number.prototype.toHHMMSS = function() {
var seconds = Math.floor(this),
hours = Math.floor(seconds / 3600);
seconds -= hours * 3600;
var minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
var time = "";
if (hours !== 0) {
time = hours + ":";
}
if (minutes !== 0 || time !== "") {
minutes = (minutes < 10 && time !== "") ? "0" + minutes : String(minutes);
time += minutes + ":";
}
if (time === "") {
time = seconds + "s";
} else {
time += (seconds < 10) ? "0" + seconds : String(seconds);
}
return time;
};
Number.prototype.round10 = function(precision) {
var factor = Math.pow(10, precision);
var tempNumber = this * factor;
var roundedTempNumber = Math.round(tempNumber);
return roundedTempNumber / factor;
};