forked from robertmuth/PyZwaver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_webserver.py
executable file
·1438 lines (1216 loc) · 44.3 KB
/
example_webserver.py
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
# Copyright 2016 Robert Muth <[email protected]>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 3
# of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
"""
Simple Webserver built on top of PyZwaver
Usage:
Run
./example_webserver --serial_port=<usb-zwave-device>
Common values for usb-zwave-device are:
/dev/ttyUSBx
/dev/ttyACMx
Then navigate to
http:://localhost:55555
in your browser.
"""
# python import
import atexit
import datetime
import logging
import math
import multiprocessing
import shelve
import sys
import time
import traceback
import json
import threading
import tornado.autoreload
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
from pyzwaver.value import CompactifyParams, SENSOR_KIND_SWITCH_BINARY, SENSOR_KIND_BATTERY, \
SENSOR_KIND_RELATIVE_HUMIDITY
from pyzwaver import zmessage
from pyzwaver.controller import Controller, EVENT_UPDATE_COMPLETE
from pyzwaver.driver import Driver, MakeSerialDevice
from pyzwaver.command import NodeDescription
from pyzwaver.command_translator import CommandTranslator
from pyzwaver.node import Node, Nodeset, NODE_STATE_INTERVIEWED, NODE_STATE_DISCOVERED
from pyzwaver import zwave as z
HTML = """
<html>
<head>
<base href="/" />
<link rel="stylesheet" type="text/css" href="%(css_path)s" />
<meta name="viewport" content="width=device-width" />
<script language="javascript" type="text/javascript" src="static/list.min.js"></script>
<title>%(title)s</title>
</head>
<body>
%(body)s
<script>
%(script)s
</script>
</body>
</html>
"""
# language=HTML
BODY = """
<div id=menu>
<button class=menu onclick='HandleTab(event)' data-param='tab-controller'>Controller</button>
<button class=menu onclick='HandleTab(event)' data-param='tab-all-nodes'>Nodes</button>
<button class=menu onclick='HandleTab(event)' data-param='tab-logs'>Logs</button>
<button class=menu onclick='HandleTab(event)' data-param='tab-slow'>Slow</button>
<button class=menu onclick='HandleTab(event)' data-param='tab-failed'>Failed</button>
Simple demo app using the pyzwaver library
</div>
<hr>
<div id=display-area>
<!-- ============================================================ -->
<div class=tab id=tab-controller>
<h2>Basics</h2>
<div id=controller_basics></div>
<h2>Connectivity</h2>
<div id=controller_routes></div>
<h2>Actions</h2>
<div id=controller_buttons</div>
<button onclick='HandleAction(event)' data-param='/controller/refresh'>
Refresh</button>
<button onclick='HandleAction(event)' data-param='/controller/soft_reset'>
Soft Reset</button>
<button onclick='HandleAction(event)' data-param='/controller/hard_reset'>
Hard Reset</button>
</div>
<h2>Pairing</h2>
<button onclick='HandleAction(event)' data-param='/controller/add_node'>
Add Node</button>
<button onclick='HandleAction(event)' data-param='/controller/remove_node'>
Remove Node</button>
<button onclick='HandleAction(event)' data-param='/controller/add_controller_primary'>
Add Primary Controller</button>
<button onclick='HandleAction(event)' data-param='/controller/set_learn_mode'>
Enter Learn Mode</button>
<h2>APIs</h2>
<div id=controller_apis></div>
</div>
<!-- ============================================================ -->
<div class=tab id=tab-all-nodes>
<table width=100%>
<tbody class='node_rows'>
<tr class='node_row'>
<td class=node_actions valign='top'>
<button class='node_name' onclick='HandleTabNode(event)' data-param='<CURRENT>'>name</button>
<p>
<button onclick='HandleAction(event)' data-param='/node/<CURRENT>/ping'>Ping Node</button>
<button class='node_switch_off' onclick='HandleAction(event)'
data-param='/node/<CURRENT>/binary_switch/0'>Off</button>
<button class='node_switch_on' onclick='HandleAction(event)' class='multilevel'
data-param='/node/<CURRENT>/binary_switch/99'>On</button>
<input class='node_slide' onchange='HandleAction(event)' data-args='node_slide'
data-param='/node/<CURRENT>/multilevel_switch/' type=range min=0 max=100 value=0>
</p>
</td>
<td class=node_info valign='top'>
<div class=node_readings class=readings>READINGS</div>
<p>
<span class=node_no>node</span>
<span class=node_last_contact>last contact</span>
<span class=node_state>state</span>
<span class=node_product>product</span>
</p>
</td>
</tr>
</tbody>
</table>
</div>
<!-- ============================================================ -->
<div class=tab id=tab-one-node>
<h2>Basics</h2>
<div class=node_basics></div>
<table width='100%'>
<tr>
<td width='45%' valign='top'><h2>Actions</h2>
<div class=node_actions>
<button class='node_switch_off' onclick='HandleAction(event)'
data-param='/node/<CURRENT>/binary_switch/0'>Off</button>
<button class='node_switch_on' onclick='HandleAction(event)' class='multilevel'
data-param='/node/<CURRENT>/binary_switch/99'>On</button>
<input class='node_slide' onchange='HandleAction(event)' data-args='node_slide'
data-param='/node/<CURRENT>/multilevel_switch/' type=range min=0 max=100 value=0>
</td>
<td width='45%' valign='top'><h2>Readings</h2>
<div class=node_readings></div>
</td>
</tr>
</table>
<h2>Maintenance</h2>
<table width='100%' class=node_maintenance>
<tr>
<td width='45%' valign='top'>
<button onclick='HandleAction(event)' data-param='/node/<CURRENT>/ping'>
Ping Node</button>
<button class=node_documentation onclick='HandleUrl(event)' data-param=''>
Search Documentation</button>
<p>
<button onclick='HandleAction(event)' data-param='/node/<CURRENT>/refresh_dynamic'>
Refresh Dynamic</button>
<button onclick='HandleAction(event)' data-param='/node/<CURRENT>/refresh_semistatic'>
Refresh Semi Static</button>
<button onclick='HandleAction(event)' data-param='/node/<CURRENT>/refresh_static'>
Refresh Static</button>
<p>
<button onclick='HandleAction(event)' data-param='/node/<CURRENT>/refresh_commands'>
Probe Command</button>
<button onclick='HandleAction(event)' data-param='/node/<CURRENT>/refresh_parameters'>
Probe Configuration</button>
<button class='node_scene_refresh' onclick='HandleAction(event)' data-param='/node/<CURRENT>/refresh_scenes'>
Probe Scenes</button>
</td>
<td width='45%' valign='top'>
<button onclick='HandleAction(event)'
data-param='/node/<CURRENT>/set_name/'
data-args='node_name'>
Change Node Name</button>
<input type=text class=node_name>
<p>
<button onclick='HandleAction(event)'
data-param='/node/<CURRENT>/change_parameter/'
data-args='config_num,config_size,config_value'>
Change Config Param</button>
no <input class=config_num type='number' value=0 min=1 max=232 style='width: 3em'>
size <select class=config_size name='size'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='4'>4</option>
</select>
value <input class=config_value type='number' value=0 style='width: 7em'>
<p>
<button onclick='HandleAction(event)'
data-param='/node/<CURRENT>/change_scene/'
data-args='scene_num,scene_level,scene_delay,scene_extra'>
Change Scene Config</button>
no <input class=scene_num type='number' value=1 min=1 max=255 style='width: 3em'>
level <input class=scene_level type='number' value=0 min=0 max=255 style='width: 3em'>
delay <input class=scene_delay type='number' value=0 min=0 max=255 style='width: 3em'>
<select class=scene_extra name='extra'>
<option value='128'>on</option>
<option value='0'>off</option>
</select>
<p>
Association group <input class=assoc_group type='number' name='level' value=1 min=0 max=255 style='width: 3em'>
node <input class=assoc_node type='number' name='level' value=0 min=0 max=255 style='width: 3em'>
<button onclick='HandleAction(event)'
data-param='/node/<CURRENT>/association_remove/'
data-args='assoc_group,assoc_node'>
Remove</button>
<button onclick='HandleAction(event)'
data-param='/node/<CURRENT>/association_add/'
data-args='assoc_group,assoc_node'>
Add</button>
</td>
</tr>
</table>
<h2>Associations</h2>
<div class=node_associations></div>
<h2>Values</h2>
<div class=node_values></div>
<table width='100%'>
<tr>
<td width='33%' valign='top'>
<h2>Command Classes</h2>
<div class=node_classes></div>
</td>
<td width='33%' valign='top'>
<h2>Configuration</h2>
<div class=node_configurations></div>
</td>
<td width='33%' valign='top'>
<h2>Scenes</h2>
<div class=node_scenes></div>
</td>
</tr>
</table>
</div>
<!-- ============================================================ -->
<div class=tab id=tab-logs>
<p>
<input type=search
oninput='InstallLogFilter(event)'
id=log_filter_regexp
placeholder="Regexp Filter"/>
</p>
<!-- see http://www.listjs.com/ -->
<div id="driverlog">
<table border=1>
<!-- IMPORTANT, class="list" have to be at tbody -->
<tbody class="list">
<tr><td class="t"></td><td class="c"></td><td class="d"></td><td class="m"></td></tr>
</tbody>
</table>
</div>
</div>
<!-- ============================================================ -->
<div class=tab id=tab-slow>
<!-- see http://www.listjs.com/ -->
<div id="driverslow">
<table border=1>
<!-- IMPORTANT, class="list" have to be at tbody -->
<tbody class="list">
<tr><td class="t"></td><td class="d"></td><td class="m"></td></tr>
</tbody>
</table>
</div>
</div>
<!-- ============================================================ -->
<div class=tab id=tab-failed>
<!-- see http://www.listjs.com/ -->
<div id="driverfailed">
<table border=1>
<!-- IMPORTANT, class="list" have to be at tbody -->
<tbody class="list">
<tr><td class="t"></td><td class="d"></td><td class="m"></td></tr>
</tbody>
</table>
</div>
</div>
<hr>
<table>
<tr>
<td><pre id=driver></td>
<td><div id=activity></div><div id=status></div></td>
<td><pre id=history></pre></td>
</tr>
</table>
<hr>
<p><tt id=timestamp></tt></p>
"""
# language="JShell snippet"
SCRIPT = """
"use strict";
// ============================================================
// The JS part of this demo is intentionally kept at a minimum.
// Whenever possible work his shifted to Python code.
// ============================================================
// Node that is currently shown in 'tab-one-node'
var currentNode = "0";
let gEventHistory = ["", "", "", "", "", ""];
const gDebug = 0;
// "enums" for tabs
const TAB_CONTROLLER = "tab-controller";
const TAB_ALL_NODES = "tab-all-nodes";
const TAB_ONE_NODE = "tab-one-node";
const TAB_LOGS = "tab-logs";
const TAB_SLOW = "tab-slow";
const TAB_FAILED = "tab-failed";
const STATUS_FIELD = "status";
const ACTIVITY_FIELD = "activity"
const HISTORY_FIELD = "history";
const DRIVE_FIELD = "driver";
// Is there a literal notation for this?
const tabToDisplay = {
[TAB_CONTROLLER]: function() {return "/display/controller"; },
[TAB_ALL_NODES]: function() {return "/display/nodes"; },
[TAB_ONE_NODE]: function() {return "/display/node/" + currentNode; },
[TAB_LOGS]: function() {return "/display/logs"; },
[TAB_SLOW]: function() {return "/display/slow"; },
[TAB_FAILED]: function() {return "/display/failed"; },
};
// List visualization using the http://listjs.com/
// t: timestamp
// c: completion status
// d: direction
// m: message
const listLog = new List('driverlog', {valueNames: [ 't', 'c', 'd', 'm' ]});
const listSlow = new List('driverslow', {valueNames: [ 'd', 't', 'm' ]});
const listFailed = new List('driverfailed', {valueNames: [ 'd', 't', 'm' ]});
function InstallLogFilter(ev) {
if (ev) {
ev.preventDefault();
ev.stopPropagation();
}
let text = document.getElementById('log_filter_regexp').value;
listLog.filter();
console.log(`Filter is: /${text}/`);
if (text) {
listLog.filter(
function (item) {
return item.values().m.match(new RegExp(text));
});
}
}
function OpenSocket() {
const loc = window.location;
const prefix = loc.protocol === 'https:' ? 'wss://' : 'ws://';
return new WebSocket(prefix + loc.host + "/updates");
}
function ShowHideControls(root, controls) {
for (let key in controls) {
let e = root.getElementsByClassName(key);
if (e.length > 0) {
let val = controls[key];
//console.log(`${e[0]}: ${key} -> ${val} [${e[0].dataset.param}]`);
e[0].hidden = ! val;
}
}
}
// Redraws work by triggering event in the Python code that will result
// in HTML fragments being sent to socket.
function SocketMessageHandler(e) {
const colon = e.data.indexOf(":");
const tag = e.data.slice(0, colon);
const val = e.data.slice(colon + 1);
if (gDebug) console.log("socket: " + tag);
if (tag == "A") {
// ACTION
document.getElementById(ACTIVITY_FIELD).innerHTML = val;
} else if (tag == "S") {
// STATUS
document.getElementById(STATUS_FIELD).innerHTML = val;
} else if (tag == "E") {
gEventHistory.push(val);
gEventHistory.shift();
document.getElementById(HISTORY_FIELD).innerHTML = gEventHistory.join("\\n");
} else if (tag == "c") {
// CONTROLLER
const values = JSON.parse(val);
document.getElementById('controller_basics').innerHTML =
values.controller_basics;
document.getElementById('controller_routes').innerHTML =
values.controller_routes;
document.getElementById('controller_apis').innerHTML =
values.controller_apis;
} else if (tag == "l") {
// LOGS (list)
const values = JSON.parse(val);
listLog.clear();
listLog.add(values);
InstallLogFilter(null);
} else if (tag == "b") {
// BAD (list)
const values = JSON.parse(val);
listSlow.clear();
listSlow.add(values);
} else if (tag == "f") {
// FAILED (list)
const values = JSON.parse(val);
listFailed.clear();
listFailed.add(values);
} else if (tag == "a") {
// ALL-NODES
const values = JSON.parse(val);
const rows = document.getElementsByClassName("node_row");
console.log(`found ${rows.length} rows`);
for (let i = 0; i < rows.length; ++i) {
const root= rows[i];
const data = values[i + 1];
if (!data) {
root.hidden = true;
continue;
}
root.hidden = false;
root.getElementsByClassName("node_name")[0].innerHTML = data.name;
root.getElementsByClassName("node_slide")[0].value = data.switch_level;
root.getElementsByClassName("node_readings")[0].innerHTML = data.readings;
root.getElementsByClassName("node_last_contact")[0].innerHTML = data.last_contact;
root.getElementsByClassName("node_product")[0].innerHTML = data.product;
root.getElementsByClassName("node_state")[0].innerHTML = data.state;
root.getElementsByClassName("node_no")[0].innerHTML = data.no;
ShowHideControls(root, data.controls);
}
//document.getElementById(TAB_ALL_NODES).innerHTML = val;
} else if (tag[0] == "o") {
// ONE-NODE
const values = JSON.parse(val);
const node = tag.slice(1);
if (node == currentNode) {
const root = document.getElementById(TAB_ONE_NODE);
root.getElementsByClassName("node_basics")[0].innerHTML = values.basics;
root.getElementsByClassName("node_classes")[0].innerHTML = values.classes;
root.getElementsByClassName("node_associations")[0].innerHTML = values.associations;
root.getElementsByClassName("node_values")[0].innerHTML = values.values;
root.getElementsByClassName("node_configurations")[0].innerHTML = values.configurations;
root.getElementsByClassName("node_readings")[0].innerHTML = values.readings;
root.getElementsByClassName("node_scenes")[0].innerHTML = values.scenes;
root.getElementsByClassName("node_documentation")[0].dataset.param = values.link;
root.getElementsByClassName("node_name")[0].value = values.name;
root.getElementsByClassName("node_slide")[0].value = values.switch_level;
ShowHideControls(root, values.controls);
}
} else if (tag == "d") {
// DRIVER
document.getElementById(DRIVE_FIELD).innerHTML = val;
}
}
// Show one tab while hiding the others.
function ShowTab(id) {
const tabs = document.getElementsByClassName("tab");
for (let i = 0; i < tabs.length; i++) {
tabs[i].style.display = "none";
}
document.getElementById(id).style.display = "block";
UpdateSome(id);
UpdateDriver();
}
function RequestURL(url) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send();
}
function RequestActionURL(param, args) {
const base = "//" + window.location.host + param;
RequestURL(base + args.join("/"));
}
function HandleAction(ev) {
ev.preventDefault();
ev.stopPropagation();
const param = ev.target.dataset.param.replace("<CURRENT>", currentNode);
const root = ev.target.parentNode;
// console.log(`${root}: ${ev.target.dataset.args}`)
let args= [];
const elem_list = ev.target.dataset.args;
if (elem_list) {
for (let elem of elem_list.split(',')) {
args.push(root.getElementsByClassName(elem)[0].value);
}
}
console.log("HandleAction: " + param + ": " + args);
RequestActionURL(param, args);
}
function HandleUrl(ev) {
window.location = ev.target.dataset.param;
}
function HandleUrlInput(ev) {
ev.preventDefault();
ev.stopPropagation();
const param = ev.target.dataset.param.replace("<CURRENT>", currentNode);
const input_elem = ev.target.parentElement.getElementsByTagName("input")[0];
console.log("HandleUrl: " + param + ": " + input_elem.value + " " + ev.target);
RequestActionURL(param, [input_elem.value]);
}
function HandleTab(ev) {
ev.preventDefault();
ev.stopPropagation();
const param = ev.target.dataset.param;
console.log("HandleTab: " + param + ": " + ev.target);
ShowTab(param);
window.history.pushState({}, "", "#" + param);
}
function HandleTabNode(ev) {
ev.preventDefault();
ev.stopPropagation();
const param = ev.target.dataset.param;
console.log("HandleTabNode: " + param + ": " + ev.target);
currentNode = param;
ShowTab(TAB_ONE_NODE);
window.history.pushState({}, "", "#tab-one-node/" + param);
}
function UpdateSome(tab) {
RequestURL(tabToDisplay[tab]());
}
function UpdateDriver() {
RequestURL("/display/driver");
}
function ProcessUrlHash() {
let hash = window.location.hash;
if (hash == "") {
hash = "tab-controller";
} else {
hash = hash.slice(1);
}
const tokens = hash.split("/");
console.log(`Hash: [${tokens.length}] ${tokens}`);
if (tokens.length > 1) {
currentNode = tokens[1];
}
ShowTab(tokens[0]);
}
function DateToString(d) {
console.log(d);
function pad(n, digits) {
let s = "" + n;
while (s.length < digits) s = '0' + s;
return s;
}
const out = [
pad(d.getUTCFullYear(), 4), '-',
pad(d.getUTCMonth()+1, 2), '-',
pad(d.getUTCDate(), 2),
' ',
pad(d.getUTCHours(), 2), ':',
pad(d.getUTCMinutes(), 2), ':',
pad(d.getUTCSeconds(), 2),
' UTC',
];
return out.join("");
}
// ============================================================
// Initialization
// ============================================================
window.onload = function () {
ProcessUrlHash();
// Replicate node row in node overview page
const node_row_template = document.getElementsByClassName("node_rows")[0];
const table = node_row_template.parentNode;
const text = node_row_template.innerHTML;
const all = [];
for (let i = 1 ; i < 256; ++i) {
all.push(text.replace(new RegExp("<CURRENT>", "g"), "" + i));
}
table.innerHTML = all.join("");
const created = DateToString(new Date());
document.getElementById("timestamp").innerHTML = "" + created;
console.log("on load finished");
};
// we use window.parent to make this work even from within an iframe
window.parent.onpopstate = function(event) {
ProcessUrlHash();
};
const gSocket = OpenSocket();
gSocket.onopen = function (e) {
console.log("Connected to server socket");
};
gSocket.onmessage = SocketMessageHandler;
gSocket.onerror = function (e) {
const m = "Cannot connect to Server: try reloading";
console.log("ERROR: " + m);
document.getElementById(STATUS_FIELD).innerHTML = m;
tab.innerHTML = "ERROR: Cannot connect to Server: try reloading";
}
gSocket.onclose = function (e) {
const m = "Server connection lost: you must reload";
console.log("ERROR: " + m);
document.getElementById(STATUS_FIELD).innerHTML = m;
}
"""
# ======================================================================
tornado.options.define("port",
default=55555,
type=int,
help="server port")
tornado.options.define("tasks",
default=4,
type=int,
help="size of task pool")
tornado.options.define("node_auto_refresh_secs",
default=300,
type=int,
help="seconds between refreshs")
tornado.options.define("pairing_timeout_secs",
default=30,
type=int,
help="seconds before pairing is auto aborted")
tornado.options.define("css_style_file",
default="static/pyzwaver.css",
type=str,
help="style file path")
tornado.options.define("db",
default="pyzwaver.shelf",
type=str,
help="where state is persisted, e.g. node names, etc.")
tornado.options.define("serial_port",
default="/dev/ttyUSB0",
# default="/dev/ttyACM0",
type=str,
help="serial port")
OPTIONS = tornado.options.options
# ======================================================================
def TimeFormat(t):
return time.strftime("%H:%M:%S", time.localtime(t))
def TimeFormatMs(t):
ms = ".%03d" % int(1000 * (t - math.floor(t)))
return TimeFormat(t) + ms
class Db(object):
"""Simple persistent storage"""
def __init__(self, shelf_path):
self._shelf = shelve.open(shelf_path)
atexit.register(self._shelf.close)
def SetNodeName(self, num, name):
key = "NodeName:%d" % num
self._shelf[key] = name
def GetNodeName(self, num, ):
key = "NodeName:%d" % num
return self._shelf.get(key, "Node %d" % num)
# ======================================================================
# A few globals
# ======================================================================
DRIVER: Driver = None
CONTROLLER: Controller = None
TRANSLATOR: CommandTranslator = None
NODESET: Nodeset = None
DB: Db = None
# ======================================================================
# WebSocket Stuff
#
# The webserver sends updates to the browser
# d: RenderDriver()
# S: event
# A: action
# l:
# c: RenderController()
# o#: RenderNode()
#
# ======================================================================
SOCKETS = set()
def SendToSocket(mesg: str):
# logging.error("Sending to socket: %d", len(SOCKETS))
for s in SOCKETS:
s.write_message(mesg)
# logging.error("Sending to socket done: %d", len(SOCKETS))
def SendToSocketJson(prefix: str, data: object):
SendToSocket(prefix + json.dumps(data, sort_keys=True, indent=4))
class NodeUpdater(object):
def __init__(self):
self._nodes_to_update = set()
self._update_driver = False
timerThread = threading.Thread(target=self._refresh_thread)
timerThread.daemon = True
timerThread.start()
def _refresh_thread(self):
logging.warning("Refresher thread started")
count = 0
while True:
if self._update_driver or DRIVER.HasInflight():
SendToSocket("d:" + RenderDriver(DRIVER))
if not NODESET:
continue
for n in self._nodes_to_update:
node = NODESET.GetNode(n)
SendToSocket("o%d:" % n + json.dumps(RenderNode(node, DB),
sort_keys=True, indent=4))
self._update_driver = False
self._nodes_to_update.clear()
if count % 20 == 0:
for n in CONTROLLER.nodes:
node: Node = NODESET.GetNode(n)
if node.state < NODE_STATE_DISCOVERED:
TRANSLATOR.Ping(n, 3, False, "refresher")
time.sleep(0.5)
elif node.state < NODE_STATE_INTERVIEWED:
logging.warning("[%d] (%s) trigger static", n, node.state)
node.RefreshStaticValues()
count += 1
time.sleep(1.0)
def put(self, n, _ts, _key, _values):
#print ("got event ", n, _key, _values)
# SendToSocket("E:[%d] %s" % (n, "@NO EVENT@"))
self._nodes_to_update.add(n)
self._update_driver = True
def ControllerEventCallback(action, event):
SendToSocket("S:" + event)
SendToSocket("A:" + action)
if event == EVENT_UPDATE_COMPLETE:
SendToSocket("c:" + json.dumps(RenderController(CONTROLLER),
sort_keys=True, indent=4))
class EchoWebSocket(tornado.websocket.WebSocketHandler):
def open(self):
logging.info("WebSocket opened")
SOCKETS.add(self)
# not really used but good for testing
def on_message(self, message):
logging.info("received socket message: %s", repr(message))
def on_close(self):
logging.info("WebSocket closed")
SOCKETS.remove(self)
def RenderReading(kind, unit, val):
if kind == SENSOR_KIND_BATTERY and val == 100:
return ""
elif kind == SENSOR_KIND_SWITCH_BINARY:
if val == 0:
return "Off"
else:
return "On"
elif kind == SENSOR_KIND_RELATIVE_HUMIDITY and unit == "%":
unit = "% (rel. hum.)"
return "%.1f%s" % (val, unit)
def RenderReadings(readings):
seen = set()
out = []
for key, kind, unit, val in sorted(readings):
if unit in seen:
continue
out.append("<span class=reading>" +
RenderReading(kind, unit, val) + "</span>")
seen.add(unit)
return out
def RenderNodes(application_nodes, controller, db):
out = {}
nodes = controller.nodes
failed = controller.failed_nodes
for node in sorted(application_nodes.nodes.values()):
if node.n not in nodes:
continue
out[node.n] = RenderNodeBrief(node, db, node.n in failed)
return out
def RenderController(controller):
out = {
"controller_basics": "<pre>%s</pre>" % controller.StringBasic(),
"controller_routes": "<pre>%s</pre>" % controller.StringRoutes(),
"controller_apis": "<pre>%s</pre>" % controller.props.StringApis(),
}
return out
def RenderDriver(driver):
return "<pre>" + str(driver) + "</pre>"
def DriverLogs(driver):
out = []
for t, sent, m, comment in driver._raw_history:
t = TimeFormatMs(t)
d = sent and "=>" or "<="
m = zmessage.PrettifyRawMessage(m)
out.append({"t": t, "c": comment, "d": d, "m": m})
return out
def DriverSlow(driver):
out = []
for m in driver._history:
if not m.end:
continue
dur = int(1000.0 * (m.end - m.start))
if dur < 300:
continue
d = "%4d%s" % (dur, "*" if m.WasAborted() else " ")
t = TimeFormatMs(m.start)
m = zmessage.PrettifyRawMessage(m.payload)
out.append({"d": d, "t": t, "m": m})
return out
def DriverBad(driver):
out = []
for m in driver._history:
if not m.end:
continue
if not m.WasAborted():
continue
dur = int(1000.0 * (m.end - m.start))
d = "%4d" % dur
t = TimeFormatMs(m.start)
m = zmessage.PrettifyRawMessage(m.payload)
out.append({"d": d, "t": t, "m": m})
return out
def GetControls(node: Node):
is_switch = node.values.HasCommandClass(z.SwitchBinary)
out = {
"node_switch_on": is_switch,
"node_switch_off": is_switch,
"node_slide": node.values.HasCommandClass(z.SwitchMultilevel),
"node_scene_refresh": node.values.HasCommandClass(z.SceneActuatorConf),
}
return out
def RenderAssociationGroup(no, group, name, info, lst):
group_name = ""
if name:
group_name = name["name"]
out = ["<tr>"
"<th>", "Group %d %s [%d]:" % (
no, group_name, group["count"]), "</th>",
"<td>",
]
for n in group["nodes"]:
out += ["%d" % n,
" "]