-
Notifications
You must be signed in to change notification settings - Fork 65
/
example4.agent.nut
1364 lines (1171 loc) · 54.5 KB
/
example4.agent.nut
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
// -----------------------------------------------------------------------------
class Rocky
{
_handlers = null;
_timeout = 10;
// --------------------[ PUBLIC FUNCTIONS ]---------------------------------
// .........................................................................
constructor() {
_handlers = { timeout = null, notfound = null, exception = null, authorise = null, unauthorised = null};
http.onrequest(_onrequest.bindenv(this));
}
// .........................................................................
function on(verb, signature, callback) {
// Register this signature and verb against the callback
// Note that signatures ARE caps sensitive and UTF8 compliant. The URLs are decoded before matching which means
// that if the URL has an encoded slash in it, it may fail to match a regular expression.
verb = verb.toupper();
if (!(signature in _handlers)) _handlers[signature] <- {};
_handlers[signature][verb] <- callback;
return this;
}
// .........................................................................
function post(signature, callback) {
return on("POST", signature, callback);
}
// .........................................................................
function get(signature, callback) {
return on("GET", signature, callback);
}
// .........................................................................
function put(signature, callback) {
return on("PUT", signature, callback);
}
// .........................................................................
function timeout(callback, timeout = 10) {
_handlers.timeout <- callback;
_timeout = timeout;
}
// .........................................................................
function notfound(callback) {
_handlers.notfound <- callback;
}
// .........................................................................
function exception(callback) {
_handlers.exception <- callback;
}
// .........................................................................
function authorise(callback) {
_handlers.authorise <- callback;
}
// .........................................................................
function unauthorised(callback) {
_handlers.unauthorised <- callback;
}
// .........................................................................
// This should come from the context bind not the class
function access_control() {
// We should probably put this as a default OPTION handler, but for now this will do
// It is probably never required tho as this is an API handler not a HTML handler
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
}
// -------------------------[ PRIVATE FUNCTIONS ]---------------------------
// .........................................................................
function _onrequest(req, res) {
// Setup the context for the callbacks
local context = Context(req, res);
try {
// Immediately reject insecure connections
if ("x-forwarded-proto" in req.headers && req.headers["x-forwarded-proto"] != "https") {
context.send(405, "HTTP not allowed.");
return;
}
// Parse the request body back into the body
try {
req.body = _parse_body(req);
} catch (e) {
server.log("Parse error '" + e + "' when parsing:\r\n" + req.body)
context.send(400, e);
return;
}
// Are we authorised
if (_handlers.authorise) {
local credentials = _parse_authorisation(context);
if (_handlers.authorise(context, credentials)) {
// The application accepted the user credentials. No need to keep anything but the user name.
context.user = credentials.user;
} else {
// The application rejected the user credentials
if (_handlers.unauthorised) {
_handlers.unauthorised(context);
}
context.send(401, "Unauthorized");
return;
}
}
// Do we have a handler for this request?
local handler = _handler_match(req);
if (!handler && _handlers.notfound) {
// No, be we have a not found handler
handler = _extract_parts(_handlers.notfound, req.path)
}
// If we have a handler, then execute it
if (handler) {
context.path = handler.path;
context.matches = handler.matches;
context.set_timeout(_timeout, _handlers.timeout);
handler.callback(context);
} else {
// We have no handler
context.send(404)
}
} catch (e) {
// Offload to the provided exception handler if we have one
if (_handlers.exception) {
_handlers.exception(context, e);
} else {
server.log("Exception: " + e)
}
// If we get to here without sending anything, send something.
context.send(500, "Unhandled exception")
}
}
// .........................................................................
function _parse_body(req) {
if ("content-type" in req.headers && req.headers["content-type"].find("application/json") != null) {
if (req.body == "" || req.body == null) return null;
return http.jsondecode(req.body);
}
if ("content-type" in req.headers && req.headers["content-type"].find("application/x-www-form-urlencoded") != null) {
return http.urldecode(req.body);
}
if ("content-type" in req.headers && req.headers["content-type"].find("multipart/form-data") != null) {
local parts = [];
local boundary = req.headers["content-type"].slice(30);
local bindex = -1;
do {
bindex = req.body.find("--" + boundary + "\r\n", bindex+1);
if (bindex != null) {
// Locate all the parts
local hstart = bindex + boundary.len() + 4;
local nstart = req.body.find("name=\"", hstart) + 6;
local nfinish = req.body.find("\"", nstart);
local fnstart = req.body.find("filename=\"", hstart) + 10;
local fnfinish = req.body.find("\"", fnstart);
local bstart = req.body.find("\r\n\r\n", hstart) + 4;
local fstart = req.body.find("\r\n--" + boundary, bstart);
// Pull out the parts as strings
local headers = req.body.slice(hstart, bstart);
local name = null;
local filename = null;
local type = null;
foreach (header in split(headers, ";\n")) {
local kv = split(header, ":=");
if (kv.len() == 2) {
switch (strip(kv[0]).tolower()) {
case "name":
name = strip(kv[1]).slice(1, -1);
break;
case "filename":
filename = strip(kv[1]).slice(1, -1);
break;
case "content-type":
type = strip(kv[1]);
break;
}
}
}
local data = req.body.slice(bstart, fstart);
local part = { "name": name, "filename": filename, "data": data, "content-type": type };
parts.push(part);
}
} while (bindex != null);
return parts;
}
// Nothing matched, send back the original body
return req.body;
}
// .........................................................................
function _parse_authorisation(context) {
if ("authorization" in context.req.headers) {
local auth = split(context.req.headers.authorization, " ");
if (auth.len() == 2 && auth[0] == "Basic") {
// Note the username and password can't have colons in them
local creds = http.base64decode(auth[1]).tostring();
creds = split(creds, ":");
if (creds.len() == 2) {
return { authtype = "Basic", user = creds[0], pass = creds[1] };
}
} else if (auth.len() == 2 && auth[0] == "Bearer") {
// The bearer is just the password
if (auth[1].len() > 0) {
return { authtype = "Bearer", user = auth[1], pass = auth[1] };
}
}
}
return { authtype = "None", user = "", pass = "" };
}
// .........................................................................
function _extract_parts(callback, path, regexp = null) {
local parts = {path = [], matches = [], callback = callback};
// Split the path into parts
foreach (part in split(path, "/")) {
parts.path.push(part);
}
// Capture regular expression matches
if (regexp != null) {
local caps = regexp.capture(path);
local matches = [];
foreach (cap in caps) {
parts.matches.push(path.slice(cap.begin, cap.end));
}
}
return parts;
}
// .........................................................................
function _handler_match(req) {
local signature = http.urldecode("val=" + req.path).val;
local verb = req.method.toupper();
if ((signature in _handlers) && (verb in _handlers[signature])) {
// We have an exact signature match
return _extract_parts(_handlers[signature][verb], signature);
} else if ((signature in _handlers) && ("*" in _handlers[signature])) {
// We have a partial signature match
return _extract_parts(_handlers[signature]["*"], signature);
} else {
// Let's iterate through all handlers and search for a regular expression match
foreach (_signature,_handler in _handlers) {
if (typeof _handler == "table") {
foreach (_verb,_callback in _handler) {
if (_verb == verb || _verb == "*") {
try {
local ex = regexp(_signature);
if (ex.match(signature)) {
// We have a regexp handler match
return _extract_parts(_callback, signature, ex);
}
} catch (e) {
// Don't care about invalid regexp.
}
}
}
}
}
}
return false;
}
}
// -----------------------------------------------------------------------------
class Context
{
req = null;
res = null;
sent = false;
id = null;
time = null;
user = null;
path = null;
matches = null;
timer = null;
static _contexts = {};
constructor(_req, _res) {
req = _req;
res = _res;
sent = false;
time = date();
// Identify and store the context
do {
id = math.rand();
} while (id in _contexts);
_contexts[id] <- this;
}
// .........................................................................
function get(id) {
if (id in _contexts) {
return _contexts[id];
} else {
return null;
}
}
// .........................................................................
function isbrowser() {
return (("accept" in req.headers) && (req.headers.accept.find("text/html") != null));
}
// .........................................................................
function header(key, def = null) {
key = key.tolower();
if (key in req.headers) return req.headers[key];
else return def;
}
// .........................................................................
function set_header(key, value) {
return res.header(key, value);
}
// .........................................................................
function send(code, message = null) {
// Cancel the timeout
if (timer) {
imp.cancelwakeup(timer);
timer = null;
}
// Remove the context from the store
if (id in _contexts) {
delete Context._contexts[id];
}
// Has this context been closed already?
if (sent) {
return false;
}
if (message == null && typeof code == "integer") {
// Empty result code
res.send(code, "");
} else if (message == null && typeof code == "string") {
// No result code, assume 200
res.send(200, code);
} else if (message == null && (typeof code == "table" || typeof code == "array")) {
// No result code, assume 200 ... and encode a json object
res.header("Content-Type", "application/json; charset=utf-8");
res.send(200, http.jsonencode(code));
} else if (typeof code == "integer" && (typeof message == "table" || typeof message == "array")) {
// Encode a json object
res.header("Content-Type", "application/json; charset=utf-8");
res.send(code, http.jsonencode(message));
} else {
// Normal result
res.send(code, message);
}
sent = true;
}
// .........................................................................
function set_timeout(timeout, callback) {
// Set the timeout timer
if (timer) imp.cancelwakeup(timer);
timer = imp.wakeup(timeout, function() {
if (callback == null) {
send(502, "Timeout");
} else {
callback(this);
}
}.bindenv(this))
}
// .........................................................................
function redirect(url) {
set_header("Location", url);
send(301, "Redirect");
}
}
// -----------------------------------------------------------------------------
class Persist
{
cache = null;
// .........................................................................
function read(key = null, def = null) {
if (cache == null) {
cache = server.load();
}
return (key in cache) ? cache[key] : def;
}
// .........................................................................
function write(key, value) {
if (cache == null) {
cache = server.load();
}
if (key in cache) {
if (cache[key] != value || typeof value == "table" || typeof value == "array") {
cache[key] <- value;
server.save(cache);
}
} else {
cache[key] <- value;
server.save(cache);
}
return value;
}
}
// -----------------------------------------------------------------------------
class Poller
{
_pollers = {};
_interrupt = null;
_callback = null;
_timer = null;
_name = null;
// .........................................................................
constructor(name = "default") {
_name = name;
if (!(_name in _pollers)) _pollers[_name] <- [];
}
// .........................................................................
// Internal method for repeatedly calling until an interrupt or timeout
function _poll() {
if (_interrupt == true || _timer == null) {
_shutdown();
_callback();
} else {
imp.wakeup(0.1, _poll.bindenv(this));
}
}
// .........................................................................
// Called after LIMIT seconds with no interrupt
function _timeout() {
// The timeout has fired, so tell the poller to stop
_timer = null;
}
// .........................................................................
// Deregister this poller and stop its timeout timer
function _shutdown() {
if (_timer) imp.cancelwakeup(_timer);
for (local i = 0; i < _pollers[_name].len(); i++) {
if (_pollers[_name][i] == this) {
_pollers[_name].remove(i);
return;
}
}
}
// .........................................................................
// Request the poller start and provide a callback function too call
// when it is finished
function poll(callback, limit=60) {
// Setup the poll, register the poller.
_callback = callback;
_timer = imp.wakeup(limit, _timeout.bindenv(this));
_pollers[_name].push(this);
// Start
_poll();
}
// .........................................................................
// Updates ALL pollers to indicate an interrupt event has occured
function interrupt() {
for (local i = 0; i < _pollers[_name].len(); i++) {
_pollers[_name][i]._interrupt = true;
}
}
}
// -----------------------------------------------------------------------------
function constants() {
const html = @"
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'>
<meta name='apple-mobile-web-app-capable' content='yes'>
<meta name='apple-touch-fullscreen' content='yes'>
<meta name='apple-mobile-web-app-status-bar-style' content='black'>
<link rel='icon' href='https://i.stack.imgur.com/IA7uX.png' type='image/png' />
<link rel='apple-touch-icon' href='https://i.stack.imgur.com/IA7uX.png' type='image/png' />
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.4/css/jquery-ui.min.css' />
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css' />
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap-theme.min.css' />
<STYLE>
html, body { height: 100% }
body { background-color: black; padding-top: 20px; } // Make the main window black and clear some space at the top
.btn:focus { outline: none; } // Remove Chrome's halo around the buttons
#wrap {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -50px;
}
#footer {
position: absolute;
height: 50px;
bottom: 10px;
left: 0px;
right: 0px;
}
.btn-group-justified>.btn {
width: 100%; // Fix the gear button width. Must be after the #footer.
}
.sortable li {
cursor: row-resize;
}
</STYLE>
<TITLE>Imp Remote</TITLE>
</HEAD>
<BODY>
<!-- Main panel containing all the buttons -->
<div id='wrap' class='container-fluid'>
<!-- Holds the buttons -->
<div id='buttons' class='mainpanels col-md-4 col-md-offset-4 text-center'>
<img id='banner' src='https://electricimp.com/public/img/heroicons.png' width='100%' />
<!-- Div to hold group all the buttons together -->
<div id='keys' class='btn-group btn-group-justified'>
<!-- New key buttons will be appended into here -->
</div>
</div>
<!-- Dropup menu -->
<div id='footer' class='mainpanels col-md-4 col-md-offset-4 text-center'>
<div class='btn-group btn-group-justified dropup' style='width: 100%'>
<!-- The setup button -->
<a id='setup' type='button' class='btn btn-large btn-success dropdown-toggle' data-toggle='dropdown' style='padding: 10px 10px 10px 10px;'>
<span class='glyphicon glyphicon-cog'></span>
<span id='status' style='font-size: 20px;'></span>
</a>
<!-- The dropdown menu items -->
<ul class='dropdown-menu' role='menu'>
<li><a href='#' id='add'><span class='glyphicon glyphicon-plus'></span> Add</a></li>
<li><a href='#' id='remove'><span class='glyphicon glyphicon-minus'></span> Remove</a></li>
<li><a href='#' id='rename'><span class='glyphicon glyphicon-cog'></span> Rename</a></li>
<li><a href='#' id='reorder'><span class='glyphicon glyphicon-sort'></span> Reorder</a></li>
<li><a href='#' id='refresh'><span class='glyphicon glyphicon-refresh'></span> Refresh</a></li>
<li><hr/></li>
<li><a href='#' id='learn'><span class='glyphicon glyphicon-eye-open'></span> Learn</a></li>
<li><a href='#' id='assign'><span class='glyphicon glyphicon-star'></span> Assign</a></li>
<li><a href='#' id='clear'><span class='glyphicon glyphicon-trash'></span> Clear</a></li>
</ul>
</div>
</div>
</div>
<!-- The order of the first four items here is critical. -->
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/html5sortable/0.1.1/html.sortable.min.js'></script>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js'></script>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js'></script>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.min.js'></script>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/modal.min.js'></script>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.3.0/bootbox.min.js'></script>
<script type='text/javascript'>
$(function() {
const READY = 0;
const KEYS = 1;
const LEARNING = 2;
const ASSIGNING = 3;
const REMOVING = 4;
const RENAMING = 5;
const OFFLINE = 6;
var state = READY;
var keys = {};
var buttons = {};
var codes = {};
var learning_request = null;
var learning_key = null;
var poll_timer = null;
// Set the new key configuration
function setKeys(newkeys) {
if ('error' in newkeys) return bootbox.alert(newkeys.error);
if (newkeys) keys = newkeys;
redrawKeys();
redrawButtons();
redrawCSS(); // Now fix the broken CSS
checkOverlap(); // Now make sure the buttons all fit
}
// Set the new code configuration
function setCodes(newcodes) {
if ('error' in newcodes) {
resetState();
return bootbox.alert(newcodes.error);
}
if (newcodes) codes = newcodes;
redrawButtons();
}
// Set the new button configuration
function setButtons(newbuttons) {
if ('error' in newbuttons) return bootbox.alert(newbuttons.error);
if (newbuttons) buttons = newbuttons;
redrawButtons();
}
// Redraw the keys buttons
function redrawKeys(buttons_per_row) {
if (buttons_per_row == undefined) {
// How many buttons do we have room for in one row?
buttons_per_row = parseInt($('#buttons').outerWidth() / 120);
}
$('.key').remove();
$('.button-pair').remove();
for (var i = 0; i < keys.length; i += buttons_per_row) {
var newgroup = $('<div />', { 'class': 'btn-group btn-group-justified spaced-out button-pair' });
for (var j = i; j < i+buttons_per_row; ++j) {
var label = keys[j]; if (!label) continue;
var key = label;
var newbutton = $('<a/>', { 'class': 'key btn btn-default', 'href': '#', 'id': key, 'label': label, 'click': keyPress });
newbutton.html(label);
newgroup.append(newbutton)
}
$('#keys').before($(newgroup));
}
}
// Redraw the buttons that have been selected
function redrawButtons() {
$('.key').each(function() {
var id = $(this).attr('id'); // play, left, right, etc
var label = $(this).attr('label'); // Play, Left, Right, etc
for (var button in buttons) {
if (buttons[button] == id) {
label += ' [' + button + ']';
}
}
$(this).text(label);
if (state == KEYS) {
$(this).removeClass('btn-primary');
$(this).addClass('btn-default');
$(this).removeClass('btn-danger');
} else if (state == LEARNING && id == learning_key) {
$(this).removeClass('btn-primary');
$(this).removeClass('btn-default');
$(this).addClass('btn-danger');
} else if (id in codes) {
$(this).addClass('btn-primary');
$(this).removeClass('btn-default');
$(this).removeClass('btn-danger');
} else {
$(this).addClass('btn-default');
$(this).removeClass('btn-primary');
$(this).removeClass('btn-danger');
}
});
}
// Redraw the command buttons
function redrawMenu() {
switch (state) {
case LEARNING:
$('#status').html('Learning');
$('#setup').removeClass('btn-danger');
$('#setup').removeClass('btn-success');
$('#setup').addClass('btn-warning');
$('#setup').click(resetState);
$('#setup').removeClass('disabled');
$('body').css('background-color', '#000030');
break;
case ASSIGNING:
$('#status').html('Assigning');
$('#setup').removeClass('btn-danger');
$('#setup').removeClass('btn-success');
$('#setup').addClass('btn-warning');
$('#setup').click(resetState);
$('#setup').removeClass('disabled');
$('body').css('background-color', '#003000');
break;
case REMOVING:
$('#status').html('Removing');
$('#setup').removeClass('btn-danger');
$('#setup').removeClass('btn-success');
$('#setup').addClass('btn-warning');
$('#setup').click(resetState);
$('#setup').removeClass('disabled');
$('body').css('background-color', '#300000');
break;
case RENAMING:
$('#status').html('Renaming');
$('#setup').removeClass('btn-danger');
$('#setup').removeClass('btn-success');
$('#setup').addClass('btn-warning');
$('#setup').click(resetState);
$('#setup').removeClass('disabled');
$('body').css('background-color', '#303000');
break;
case OFFLINE:
$('#status').html('Offline');
$('#setup').removeClass('btn-success');
$('#setup').removeClass('btn-warning');
$('#setup').addClass('btn-danger');
$('#setup').addClass('disabled');
$('#setup').click(resetState);
$('body').css('background-color', '#600000');
break;
default:
$('#status').html('');
$('#setup').removeClass('btn-danger');
$('#setup').removeClass('btn-warning');
$('#setup').addClass('btn-success');
$('#setup').removeClass('disabled');
$('body').css('background-color', 'black');
break;
}
}
// Fix the CSS whenever required
function redrawCSS() {
$('.key').css('height', '50px'); // Make the buttons taller
$('.spaced-out').css('margin-top', '5px'); // Space the buttons from each other
$('#keys').css('margin-top', '10px'); // Make the buttons taller
}
// Clear the menu back to the normal state
function resetState(e) {
// Cancel outstanding learning requests
if (learning_request) {
$.ajax({url: 'learn', type: 'PUT'});
learning_request.abort();
learning_request = null;
learning_key = null;
}
state = READY;
redrawMenu()
redrawButtons();
if (e) e.stopPropagation(); // Stop the menu from dropping down
$('#setup').off('click');
}
// Hide any buttons that overlapping with the footer
function checkOverlap() {
$('.key').show();
var footer_top = $('#footer').offset().top;
$('.key').each(function() {
var key_bottom = $(this).offset().top + $(this).outerHeight(true);
if (key_bottom + 10 >= footer_top) {
// console.log($(this).attr('label'), key_bottom, footer_top);
$(this).hide();
}
})
}
// Poll the status of the imp itself
function pollDevice(result) {
// Make sure this is the only poller running
if (poll_timer) clearTimeout(poll_timer);
poll_timer = null;
// Poll the agent for the state compared to what we think it is
var connected = (state == OFFLINE) ? 'disconnected' : 'connected';
$.get('status/' + connected, function(status) {
if (status.connected) {
// Bring the device back to READY
if (state == OFFLINE) resetState();
} else {
// Mark the status as offline
state = OFFLINE;
redrawMenu()
redrawButtons();
}
}).always(function() {
poll_timer = setTimeout(pollDevice, 1);
});
}
// Resyncs with the server and redraws everything
function refresh() {
$.get('keys', function(keys) {
setKeys(keys);
$.get('buttons', function(buttons) {
setButtons(buttons);
$.get('codes', function(codes) {
setCodes(codes);
pollDevice();
})
})
})
}
// This is the click handler for all the key buttons
function keyPress() {
var id = $(this).attr('id');
var label = $(this).attr('label');
switch (state) {
case ASSIGNING:
bootbox.dialog({
title: 'Assign',
message: '<p>Please select which button to assign the [' + label + '] key to.</p>',
buttons: {
'Button 1': function() {
$.ajax({url: 'button/1/' + id, type: 'PUT', success: setButtons});
},
'Button 2': function() {
$.ajax({url: 'button/2/' + id, type: 'PUT', success: setButtons});
},
'Cancel': {}
}
});
break;
case LEARNING:
learning_key = id;
redrawButtons();
if (learning_request) learning_request.abort();
learning_request = $.ajax({
url: 'learn/' + id,
type: 'PUT',
success: function(codes) {
learning_request = null;
learning_key = null;
setCodes(codes);
}
});
break;
case REMOVING:
bootbox.confirm('Are you sure you want to delete [' + label + ']?', function(result) {
if (result) {
resetState();
$.ajax({url: 'code', data: id, contentType: 'text/plain', type: 'DELETE', success: setCodes});
$.ajax({url: 'button', data: id, contentType: 'text/plain', type: 'DELETE', success: setButtons});
$.ajax({url: 'key', data: label, contentType: 'text/plain', type: 'DELETE', success: setKeys});
}
})
break;
case RENAMING:
bootbox.prompt('What would you like the new name for this button to be?', function(newlabel) {
if (newlabel && newlabel.length > 0) {
resetState();
var fromkey = label;
var tokey = newlabel;
$.ajax({
url: 'key',
type: 'PATCH',
data: {from: label, to: newlabel},
success: function(newkeys) {
setKeys(newkeys);
$.ajax({
url: 'code',
type: 'PATCH',
data: {from: fromkey, to: tokey},
success: function(newcodes) {
setCodes(newcodes);
$.ajax({
url: 'button',
type: 'PATCH',
data: {from: fromkey, to: tokey},
success: function(newbuttons) {
setButtons(newbuttons);
}
})
}
})
}
})
}
})
break;
case OFFLINE:
bootbox.alert('The Imp is currently offline.');
break;
default:
if (id in codes) {
$('body').css('background-color', '#000025');
$.post('code/' + id, function() {
$('body').css('background-color', 'black');
});
} else {
bootbox.alert('The code for [' + label + '] has not been learned yet.');
}
break;
}
}
// Initialise the buttons by setting click event handlers
$('#learn').click(function() {
state = LEARNING;
redrawMenu()
redrawButtons();
})
$('#assign').click(function() {
state = ASSIGNING;
redrawMenu()
redrawButtons();
})
$('#clear').click(function() {
bootbox.confirm('Are you sure?', function(result) {
if (result) {
resetState();
$.ajax({url: 'codes', type: 'DELETE', success: setCodes});
$.ajax({url: 'buttons', type: 'DELETE', success: setButtons});
$.ajax({url: 'keys', type: 'DELETE', success: setKeys});
}
})
})
$('#add').click(function() {
bootbox.prompt('How would you like to label this new button?', function(label) {
if (label && label.length > 0) {
$.ajax({
url: 'key',
type: 'PUT',
data: label,
contentType: 'text/plain',
success: setKeys
});
}
})
})
$('#remove').click(function() {
state = REMOVING;
redrawMenu();
redrawButtons();