forked from wborn/openhab-grafana
-
Notifications
You must be signed in to change notification settings - Fork 0
/
openhab-grafana.js
604 lines (518 loc) · 17.9 KB
/
openhab-grafana.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
/**
* openHAB Grafana panel utilities
*
* Updates the source URL of Grafana <iframe> panels using openHAB server side events (SSE).
* OHSubscriber is based on the javascript of the openHAB Basic UI by Vlad Ivanov.
*
* @author Wouter Born
*/
/* exported addGrafanaPanel, GrafanaPanel */
/* eslint-env browser */
/* eslint no-undef:2 */
/* eslint no-new:0 */
/* eslint no-underscore-dangle:0 */
"use strict";
var
OHG_DEFAULTS = {
// library
debug: "false",
render: "false",
refresh: "0",
// OH sitemap
sitemap: "default",
// Grafana URL
urlPrefix: "http://grafana:3000",
panelPath: "/dashboard-solo/db/",
renderPanelPath: "/render/dashboard-solo/db/",
// Grafana panel parameters
from: "now-1d",
to: "now",
theme: "light",
// Grafana render panel parameters
width: "auto",
height: "auto"
};
function queryParams(param) {
if (!param) {
return {};
}
var
match,
url = param.toString(),
queryIndex = url.indexOf("?"),
query = queryIndex !== -1 ? url.substring(queryIndex + 1) : "",
re = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); },
result = {};
do {
match = re.exec(query);
if (match) {
result[decode(match[1])] = decode(match[2]);
}
} while (match);
return result;
}
var
urlParams = queryParams(window.location),
parentUrlParams = queryParams(window.parent.location.href);
function resolveParam(params, name) {
if (params !== undefined && params[name] !== undefined) {
return params[name];
} else if (urlParams !== undefined && urlParams[name] !== undefined) {
return urlParams[name];
} else if (parentUrlParams !== undefined && parentUrlParams[name] !== undefined) {
return parentUrlParams[name];
} else {
return OHG_DEFAULTS[name];
}
}
function OHSubscriber(params) {
var
p = params,
initialized = false,
initializedListeners = [],
items = {},
subscription = {
id: "",
page: resolveParam(p, "w"),
sitemap: resolveParam(p, "sitemap")
};
this.addItemListener = function(itemName, listener) {
if (typeof listener !== "function") {
throw new Error("addItemListener 'listener' is not a function");
}
if (items[itemName] !== undefined) {
if (!items[itemName].listeners.includes(listener)) {
items[itemName].listeners.push(listener);
}
} else {
items[itemName] = {listeners: [listener], value: undefined};
}
};
this.addInitializedListener = function(listener) {
if (typeof listener !== "function") {
throw new Error("addInitializedListener 'listener' is not a function");
}
initializedListeners.push(listener);
};
this.isInitialized = function() {
return initialized;
};
function ajax(params) {
var
p = params,
type = typeof p.type !== "undefined" ? p.type : "GET",
data = typeof p.data !== "undefined" ? p.data : "",
headers = typeof p.headers !== "undefined" ? p.headers : {},
request = new XMLHttpRequest();
request.open(type, p.url, true);
for (var h in headers) {
request.setRequestHeader(h, headers[h]);
}
request.onload = function() {
if (request.status < 200 || request.status > 400) {
if (typeof p.error === "function") {
p.error(request);
}
return;
}
if (typeof p.callback === "function") {
p.callback(request);
}
};
request.onerror = function() {
if (typeof p.error === "function") {
p.error(request);
}
};
request.send(data);
return request;
}
function uninitializedItemNames() {
var result = [];
for (var itemName in items) {
if (items[itemName].value === undefined) {
result.push(itemName);
}
}
return result;
}
function areAllItemsInitialized() {
return uninitializedItemNames().length === 0;
}
function updateInitialized() {
if (!initialized && areAllItemsInitialized()) {
initialized = true;
for (var i = 0; i < initializedListeners.length; i++) {
initializedListeners[i]();
}
}
}
function updateItem(itemName, value) {
if (items[itemName].value === value) {
return;
}
items[itemName].value = value;
var itemListeners = items[itemName].listeners;
for (var i = 0; i < itemListeners.length; i++) {
var listener = itemListeners[i];
listener(itemName, value);
}
updateInitialized();
}
function ChangeListenerEventsource(subscribeLocation) {
var
_t = this;
_t.navigate = function(){};
_t.source = new EventSource(subscribeLocation);
_t.source.addEventListener("event", function(payload) {
if (_t.paused) {
return;
}
var
data = JSON.parse(payload.data),
itemName = data.item.name,
value;
if (items[itemName] === undefined) {
return;
}
if (
(typeof(data.label) === "string") &&
(data.label.indexOf("[") !== -1) &&
(data.label.indexOf("]") !== -1)
) {
var
pos = data.label.indexOf("[");
value = data.label.substr(
pos + 1,
data.label.lastIndexOf("]") - (pos + 1)
);
} else {
value = data.item.state;
}
updateItem(itemName, value);
});
}
function ChangeListenerLongpolling() {
var
_t = this;
function applyChanges(response) {
try {
response = JSON.parse(response);
} catch (e) {
return;
}
function walkWidgets(widgets) {
widgets.forEach(function(widget) {
if (widget.item === undefined) {
return;
}
var
itemName = widget.item.name,
value = widget.item.state;
if (items[itemName] !== undefined) {
updateItem(itemName, value);
}
});
}
if (response.leaf) {
walkWidgets(response.widgets);
} else {
response.widgets.forEach(function(frameWidget) {
walkWidgets(frameWidget.widgets);
});
}
}
function start() {
var
cacheSupression = Math.random().toString(16).slice(2);
_t.request = ajax({
url: "/rest/sitemaps/" + subscription.sitemap + "/" + subscription.page + "?_=" + cacheSupression,
headers: {"X-Atmosphere-Transport": "long-polling"},
callback: function(request) {
applyChanges(request.responseText);
setTimeout(function() {
start();
}, 1);
},
error: function() {
// Wait 1s and restart long-polling
setTimeout(function() {
start();
}, 1000);
}
});
}
start();
}
function ChangeListener() {
var
_t = this;
_t.startSubscriber = function(response) {
var
responseJSON,
subscribeLocation,
subscribeLocationArray;
try {
responseJSON = JSON.parse(response.responseText);
} catch (e) {
return;
}
if (responseJSON.status !== "CREATED") {
return;
}
try {
subscribeLocation = responseJSON.context.headers.Location[0];
} catch (e) {
return;
}
subscribeLocationArray = subscribeLocation.split("/");
subscription.id = subscribeLocationArray[subscribeLocationArray.length - 1];
if ("EventSource" in window) {
ChangeListenerEventsource.call(_t, subscribeLocation +
"?sitemap=" + subscription.sitemap +
"&pageid=" + subscription.page);
} else {
ChangeListenerLongpolling.call(_t);
}
};
ajax({
url: "/rest/sitemaps/events/subscribe",
type: "POST",
callback: _t.startSubscriber
});
}
function ValuesInitializer() {
var
_t = this;
_t.valueHandler = function(response) {
var
responseJSON;
try {
responseJSON = JSON.parse(response.responseText);
} catch (e) {
return;
}
updateItem(responseJSON.name, responseJSON.state);
};
var itemNames = uninitializedItemNames();
for (var i = 0; i < itemNames.length; i++) {
ajax({
url: "/rest/items/" + itemNames[i],
type: "GET",
callback: _t.valueHandler
});
}
updateInitialized();
}
function initialize() {
if (subscription.page === undefined) {
subscription.page = subscription.sitemap;
}
document.addEventListener("DOMContentLoaded", function() {
subscription.valuesInitializer = new ValuesInitializer();
subscription.changeListener = new ChangeListener();
});
}
initialize();
}
var ohSubscriber = new OHSubscriber();
function GrafanaPanel(params) {
var
p = params,
refreshTimerId = undefined,
resizeTimerId = undefined,
frame = resolveParam(p, "frame"),
urlPrefix = resolveParam(p, "urlPrefix"),
panelPath = resolveParam(p, "panelPath"),
renderPanelPath = resolveParam(p, "renderPanelPath"),
libVars = {
debug: {
value: resolveParam(p, "debug"),
itemName: resolveParam(p, "debugItem"),
itemFunction: params.debugItemFunction
},
render: {
value: resolveParam(p, "render"),
itemName: resolveParam(p, "renderItem"),
itemFunction: params.renderItemFunction
},
refresh: {
value: resolveParam(p, "refresh"),
itemName: resolveParam(p, "refreshItem"),
itemFunction: params.refreshItemFunction
}
},
urlVars = {
dashboard: {
value: resolveParam(p, "dashboard"),
itemName: resolveParam(p, "dashboardItem"),
itemFunction: params.dashboardItemFunction
},
from: {
key: "from",
value: resolveParam(p, "from"),
itemName: resolveParam(p, "fromItem"),
itemFunction: params.fromItemFunction
},
to: {
key: "to",
value: resolveParam(p, "to"),
itemName: resolveParam(p, "toItem"),
itemFunction: params.toItemFunction
},
panel: {
key: "panelId",
value: resolveParam(p, "panel"),
itemName: resolveParam(p, "panelItem"),
itemFunction: params.panelItemFunction
},
theme: {
key: "theme",
value: resolveParam(p, "theme"),
itemName: resolveParam(p, "themeItem"),
itemFunction: params.themeItemFunction
},
width: {
key: "width",
value: resolveParam(p, "width"),
itemName: resolveParam(p, "widthItem"),
itemFunction: params.widthItemFunction
},
height: {
key: "height",
value: resolveParam(p, "height"),
itemName: resolveParam(p, "heightItem"),
itemFunction: params.heightItemFunction
}
};
function updateFrameSourceURL() {
var debug = libVars.debug.value;
var render = libVars.render.value;
var refresh = libVars.refresh.value;
var iframe = document.getElementById(frame);
var idocument = iframe.contentWindow.document;
var url = urlPrefix;
url += render === "true" ? renderPanelPath : panelPath;
url += urlVars.dashboard.value;
var firstParameter = true;
for (var uvKey in urlVars) {
var key = urlVars[uvKey].key;
var value = urlVars[uvKey].value;
if (key === "width") {
value = render === "false" ? undefined : (value === "auto" ? idocument.body.clientWidth : value);
} else if (key === "height") {
value = render === "false" ? undefined : (value === "auto" ? idocument.body.clientHeight : value);
}
if (key !== undefined && value !== undefined) {
url += (firstParameter ? "?" : "&") + key + "=" + value;
firstParameter = false;
}
}
if (render === "true") {
// append cache busting parameter
url += "&cacheBuster=" + Date.now();
}
// update frame content
if (debug === "true") {
idocument.open();
idocument.write("<a href=\"" + url + "\">" + url + "</a>");
idocument.close();
} else if (render === "true") {
var htmlUrl = url.replace(renderPanelPath, panelPath);
idocument.open();
idocument.write("<style>body{margin:0px}p{margin:0px}</style>");
idocument.write("<p style=\"text-align:center;\"><a href=\"" + htmlUrl + "\"><img src=\"" + url + "\"></a></p>");
idocument.close();
} else if (document.getElementById(frame).src !== url) {
// replace the URL so changes are not added to the browser history
iframe.contentWindow.location.replace(url);
}
// schedule/cancel rendered image refresh
if (render === "true" && refresh > 0) {
clearTimeout(refreshTimerId);
refreshTimerId = setTimeout(updateFrameSourceURL, refresh);
} else if (refreshTimerId !== undefined) {
clearTimeout(refreshTimerId);
}
}
function updateFrameOnResize() {
if (libVars.render.value === "true" && (urlVars.width.value === "auto" || urlVars.height.value === "auto")) {
clearTimeout(resizeTimerId);
resizeTimerId = setTimeout(updateFrameSourceURL, 500);
} else {
clearTimeout(resizeTimerId);
}
}
function updateVarsOnItemUpdate(vars, itemName, value) {
for (var key in vars) {
if (vars[key].itemName !== undefined && vars[key].itemName === itemName) {
if (vars[key].itemFunction) {
value = vars[key].itemFunction(value);
}
vars[key].value = value;
}
}
}
function onItemUpdated(itemName, value) {
updateVarsOnItemUpdate(libVars, itemName, value);
updateVarsOnItemUpdate(urlVars, itemName, value);
if (ohSubscriber.isInitialized()) {
updateFrameSourceURL();
}
}
function assertPropertyDefined(name, value) {
if (value === undefined) {
throw new Error("Property '" + name + "' is undefined");
}
}
function assertVarsDefinedOrSubscribeToOH(vars) {
for (var key in vars) {
var itemName = vars[key].itemName;
if (itemName !== undefined) {
ohSubscriber.addItemListener(itemName, onItemUpdated);
} else if (vars[key].value === undefined) {
throw new Error("Property '" + key + "' requires a default value or itemName to obtain the value from");
}
}
}
function initialize() {
assertPropertyDefined("frame", frame);
assertPropertyDefined("urlPrefix", urlPrefix);
assertPropertyDefined("panelPath", panelPath);
assertPropertyDefined("renderPanelPath", renderPanelPath);
assertVarsDefinedOrSubscribeToOH(libVars);
assertVarsDefinedOrSubscribeToOH(urlVars);
ohSubscriber.addInitializedListener(updateFrameSourceURL);
window.addEventListener("resize", updateFrameOnResize);
}
initialize();
}
var grafanaPanels = [];
function createGuid()
{
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c === "x" ? r : (r&0x3|0x8);
return v.toString(16);
});
}
function addGrafanaPanel(uniqueId, params) {
if (uniqueId === undefined) {
uniqueId = createGuid();
}
var div = document.createElement("div");
div.id = "panel-" + uniqueId + "-container";
div.className = "panel-container";
document.body.appendChild(div);
var frame = document.createElement("iframe");
frame.id = "panel-" + uniqueId + "-frame";
frame.className = "panel-frame";
frame.scrolling = "no";
div.appendChild(frame);
if (params === undefined) {
params = {};
}
params.frame = frame.id;
var panel = new GrafanaPanel(params);
grafanaPanels.push(panel);
}