forked from enesbcs/rpieasy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebserver.py
3336 lines (3069 loc) · 113 KB
/
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/env python3
#############################################################################
###################### RPI Easy integrated webserver ########################
#############################################################################
#
# It's a PERVER based independent webserver in pure python used by RPIEasy
# do not call it directly.
#
# HTML source is based heavily on the ESPEasy project for which i am very grateful!
# ESPEasy licensed under GPL v3 - https://www.letscontrolit.com/
#
# Otherwise, LICENSE file must be found with the same directory with this file.
#
from perver import Perver
import os
import re
import rpieGlobals
import Settings
import time
from datetime import datetime
import rpieTime
import linux_os as OS
import misc
import commands
import linux_network as Network
import urllib
import hashlib
HTML_SYMBOL_WARNING = "⚠"
TASKS_PER_PAGE = 16
TXBuffer = ""
navMenuIndex = 0
_HEAD = False
_TAIL = True
INT_MIN = -2147483648
INT_MAX = 2147483647
WebServer = Perver()
WebServer.timeout = 10
WebServer.get_max = 65535
def isLoggedIn(pget,pcookie):
# if (not clientIPallowed()) return False
rpieGlobals.WebLoggedIn = False
if (Settings.Settings["Password"] == ""):
rpieGlobals.WebLoggedIn = True
else:
spw = str(hashlib.sha1(bytes(Settings.Settings["Password"],'utf-8')).hexdigest())
pws = str(arg("password",pget)).strip()
if pws != "":
if pws==Settings.Settings["Password"] or pws==spw:
rpieGlobals.WebLoggedIn = True
else:
for c in pcookie:
if 'password' in c:
if spw==str(pcookie[c].strip()):
rpieGlobals.WebLoggedIn = True
return rpieGlobals.WebLoggedIn
def arg(argname,parent):
return (argname in parent and parent[argname] or '')
@WebServer.route('/')
def handle_root(self):
global TXBuffer, navMenuIndex
TXBuffer=""
navMenuIndex=0
if (rpieGlobals.wifiSetup):
return self.redirect('/setup')
if (not isLoggedIn(self.get,self.cookie)):
return self.redirect('/login')
if self.type == "GET":
responsearr = self.get
else:
responsearr = self.post
cmdline = arg("cmd",responsearr).strip()
sendHeadandTail("TmplStd",_HEAD)
responsestr = ""
if len(cmdline)>0:
responsestr = str(commands.doExecuteCommand(cmdline)) # response ExecuteCommand(VALUE_SOURCE_HTTP, webrequest.c_str());
if len(responsestr)>0:
TXBuffer += "<P>"
TXBuffer += str(responsestr)
TXBuffer += "<P>"
TXBuffer += "<form>"
TXBuffer += "<table class='normal'><tr><TH style='width:150px;' align='left'>System Info<TH align='left'>Value"
TXBuffer += "<TR><TD>Unit:<TD>"
TXBuffer += str(Settings.Settings["Unit"])
TXBuffer += "<TR><TD>Local Time:<TD>" + datetime.now().strftime('%Y-%m-%d %H:%M:%S')
TXBuffer += "<TR><TD>Uptime:<TD>" + rpieTime.getuptime(1)
TXBuffer += "<TR><TD>Load:<TD>" +str( OS.read_cpu_usage() ) + " %"
TXBuffer += "<TR><TD>Free Mem:<TD>" + str( OS.FreeMem() ) + " kB"
TXBuffer += "<TR><TD>IP:<TD>" + str( OS.get_ip() )
try:
rssi = OS.get_rssi()
if str(rssi)=="-49.20051":
rssi = "Wired connection"
else:
rssi = str(rssi)+" dB"
except:
rssi = "?"
TXBuffer += "<TR><TD>Wifi RSSI:<TD>" + str(rssi)
TXBuffer += '<tr><td>Build<td>' + str(rpieGlobals.PROGNAME) + " " + str(rpieGlobals.PROGVER)
TXBuffer += "<TR><TD><TD>"
addButton("sysinfo", "More info");
TXBuffer += "</table><BR>"
if len(Settings.nodelist)>0:
TXBuffer += "<BR><table class='multirow'><TR><TH>Node List<TH>Name<TH>Build<TH>Type<TH>IP<TH>Age"
for n in Settings.nodelist:
TXBuffer += "<TR><TD>Unit "+str(n["unitno"])+"<TD>"+str(n["name"])+"<TD>"+str(n["build"])+"<TD>"
ntype = ""
if int(n["type"])==rpieGlobals.NODE_TYPE_ID_ESP_EASY_STD:
ntype = "ESP Easy"
elif int(n["type"])==rpieGlobals.NODE_TYPE_ID_ESP_EASYM_STD:
ntype = "ESP Easy Mega"
elif int(n["type"])==rpieGlobals.NODE_TYPE_ID_ESP_EASY32_STD:
ntype = "ESP Easy32"
elif int(n["type"])==rpieGlobals.NODE_TYPE_ID_ARDUINO_EASY_STD:
ntype = "Arduino Easy"
elif int(n["type"])==rpieGlobals.NODE_TYPE_ID_NANO_EASY_STD:
ntype = "Nano Easy"
elif int(n["type"])==rpieGlobals.NODE_TYPE_ID_RPI_EASY_STD:
ntype = "RPI Easy"
TXBuffer += ntype+"<TD>"
waddr = str(n["ip"])
if str(n["port"]) != "" and str(n["port"]) != "0" and str(n["port"]) != "80":
waddr += ":" + str(n["port"])
addWideButton("http://"+waddr, waddr, "")
TXBuffer += "<TD>"+str(n["age"])
TXBuffer += "</table></form>"
sendHeadandTail("TmplStd",_TAIL)
return TXBuffer
@WebServer.route('/config')
def handle_config(self):
global TXBuffer, navMenuIndex
TXBuffer=""
navMenuIndex=1
if (rpieGlobals.wifiSetup):
return self.redirect('/setup')
if (not isLoggedIn(self.get,self.cookie)):
return self.redirect('/login')
if self.type == "GET":
responsearr = self.get
else:
responsearr = self.post
netdev0 = arg("netdev0",responsearr)
netdev1 = arg("netdev1",responsearr)
nd0_dhcp=""
nd1_dhcp=""
nd0_ip=""
nd0_gw=""
nd0_mask=""
nd0_dns=""
nd1_ip=""
nd1_gw=""
nd1_mask=""
nd1_dns=""
netmanage = (arg("netman",responsearr)=="on")
saved = arg("Submit",responsearr)
if (saved):
Settings.Settings["Name"] = arg("name",responsearr).replace(" ","")
Settings.Settings["Unit"] = arg("unit",responsearr)
tpw = arg("password",responsearr)
if "**" not in tpw:
Settings.Settings["Password"] = tpw
# ...
Settings.savesettings()
# time.sleep(0.1)
if Settings.NetMan:
Settings.NetMan.APMode = arg("apmode",responsearr)
tpw = arg("apkey",responsearr)
if "**" not in tpw:
Settings.NetMan.WifiAPKey = tpw
Settings.NetMan.WifiSSID = arg("ssid",responsearr)
Settings.NetMan.WifiSSID2 = arg("ssid2",responsearr)
tpw = arg("key",responsearr)
if "**" not in tpw:
Settings.NetMan.WifiKey = tpw
tpw = arg("key2",responsearr)
if "**" not in tpw:
Settings.NetMan.WifiKey2 = tpw
else:
Settings.NetMan = Network.NetworkManager()
try:
netdev0=int(netdev0)
except:
netdev0=-1
try:
netdev1=int(netdev1)
except:
netdev1=-1
nd0_dhcp= (arg("nd0_dhcp",responsearr)=="on")
nd1_dhcp= (arg("nd1_dhcp",responsearr)=="on")
nd0_ip= arg("nd0_ip",responsearr)
nd0_gw= arg("nd0_gw",responsearr)
nd0_mask= arg("nd0_mask",responsearr)
nd0_dns= arg("nd0_dns",responsearr)
nd1_ip= arg("nd1_ip",responsearr)
nd1_gw= arg("nd1_gw",responsearr)
nd1_mask= arg("nd1_mask",responsearr)
nd1_dns= arg("nd1_dns",responsearr)
if netdev0!=-1:
Settings.NetMan.setdeviceorder(netdev0,netdev1)
Settings.NetworkDevices[netdev0].dhcp=nd0_dhcp
Settings.NetworkDevices[netdev0].ip=nd0_ip
Settings.NetworkDevices[netdev0].gw=nd0_gw
Settings.NetworkDevices[netdev0].mask=nd0_mask
Settings.NetworkDevices[netdev0].dns=nd0_dns
if netdev1!=-1:
Settings.NetworkDevices[netdev1].dhcp=nd1_dhcp
Settings.NetworkDevices[netdev1].ip=nd1_ip
Settings.NetworkDevices[netdev1].gw=nd1_gw
Settings.NetworkDevices[netdev1].mask=nd1_mask
Settings.NetworkDevices[netdev1].dns=nd1_dns
if netmanage:
Settings.NetMan.saveconfig() # save OS config files only if enabled and have root rights!!
else:
misc.addLog(rpieGlobals.LOG_LEVEL_INFO,"Settings saved without OS network settings modifications as you wish!")
Settings.savenetsettings() # save to json
else:
Settings.loadsettings()
sendHeadandTail("TmplStd",_HEAD);
TXBuffer += "<form name='frmselect' method='post'><table class='normal'>"
addFormHeader("Main Settings")
addFormTextBox( "Unit Name", "name", Settings.Settings["Name"], 25)
addFormNumericBox( "Unit Number", "unit", Settings.Settings["Unit"], 0, 256)
addFormPasswordBox( "Admin Password" , "password", Settings.Settings["Password"], 25)
# addFormCheckBox("AP Mode enable on connection failure","apmode",Settings.NetMan.APMode) # Not implemented MISSING!
# addFormPasswordBox("WPA AP Mode Key", "apkey", Settings.NetMan.WifiAPKey, 128) # Not implemented MISSING!
TXBuffer += "<TR><TD style='width:150px;' align='left'><TD>"
addSubmitButton()
oslvl = misc.getsupportlevel(1)
if oslvl in [1,2,3,10]: # maintain supported system list!!!
addFormSeparator(2)
if oslvl != 2:
addFormCheckBox("I have root rights and i really want to manage network settings below","netman", netmanage)
addFormNote("<font color=red><b>If not enabled, OS config files will not be overwritten!</b></font>")
addFormSubHeader("Wifi Settings") #/etc/wpa_supplicant/wpa_supplicant.conf
addFormTextBox( "SSID", "ssid", Settings.NetMan.WifiSSID, 32)
addFormPasswordBox("WPA Key", "key", Settings.NetMan.WifiKey, 64)
addFormTextBox( "Fallback SSID", "ssid2", Settings.NetMan.WifiSSID2, 32)
addFormPasswordBox( "Fallback WPA Key", "key2", Settings.NetMan.WifiKey2, 64)
addFormSeparator(2)
addFormSubHeader("IP Settings")
TXBuffer += "<TR><TD>Primary network device:<TD>"
netdevs = Settings.NetMan.getdevicenames()
if netdev0=="":
defaultdev = Settings.NetMan.getprimarydevice()
else:
defaultdev = int(netdev0)
if len(netdevs)>0:
addSelector_Head('netdev0',True)
for i in range(0,len(netdevs)):
addSelector_Item(netdevs[i],i,(int(i)==int(defaultdev)),False)
addSelector_Foot()
seld = defaultdev
if defaultdev<0:
seld = 0
if nd0_dhcp=="":
nd0_dhcp=Settings.NetworkDevices[seld].dhcp
if nd0_dhcp!=True:
nd0_dhcp=False
if nd0_ip=="":
nd0_ip=Settings.NetworkDevices[seld].ip
if nd0_gw=="":
nd0_gw=Settings.NetworkDevices[seld].gw
if nd0_mask=="":
nd0_mask=Settings.NetworkDevices[seld].mask
if nd0_dns=="":
nd0_dns=Settings.NetworkDevices[seld].dns
addEnabled(Settings.NetworkDevices[seld].isconnected())
addNetType(Settings.NetworkDevices[seld].iswireless())
addFormCheckBox("DHCP","nd0_dhcp",nd0_dhcp)
addFormTextBox("IP", "nd0_ip", nd0_ip,15)
addFormTextBox("GW", "nd0_gw", nd0_gw,15)
addFormTextBox("Mask", "nd0_mask",nd0_mask,15)
addFormTextBox("DNS", "nd0_dns", nd0_dns,128)
addFormNote("If DHCP enabled these fields will not be saved or used!")
else:
TXBuffer += "No device"
if len(netdevs)>1:
TXBuffer += "<TR><TD>Secondary network device:<TD>"
if netdev1=="":
defaultdev2 = Settings.NetMan.getsecondarydevice()
else:
defaultdev2=int(netdev1)
seld2 = defaultdev2
if defaultdev<0:
seld2 = 0
if seld2==seld:
if seld==0:
seld2=1
else:
seld2=0
addSelector_Head('netdev1',True)
for i in range(0,len(netdevs)):
addSelector_Item(netdevs[i],i,(int(i)==int(seld2)),False)
addSelector_Foot()
if nd1_dhcp=="":
nd1_dhcp=Settings.NetworkDevices[seld2].dhcp
if nd1_dhcp!=True:
nd1_dhcp=False
if nd1_ip=="":
nd1_ip=Settings.NetworkDevices[seld2].ip
if nd1_gw=="":
nd1_gw=Settings.NetworkDevices[seld2].gw
if nd1_mask=="":
nd1_mask=Settings.NetworkDevices[seld2].mask
if nd1_dns=="":
nd1_dns=Settings.NetworkDevices[seld2].dns
addEnabled(Settings.NetworkDevices[seld2].isconnected())
addNetType(Settings.NetworkDevices[seld2].iswireless())
addFormCheckBox("DHCP","nd1_dhcp",nd1_dhcp)
addFormTextBox("IP", "nd1_ip", nd1_ip,15)
addFormTextBox("GW", "nd1_gw", nd1_gw,15)
addFormTextBox("Mask", "nd1_mask",nd1_mask,15)
addFormTextBox("DNS", "nd1_dns", nd1_dns,15)
addFormNote("If DHCP enabled these fields will not be saved or used!")
TXBuffer += "<TR><TD style='width:150px;' align='left'><TD>"
addSubmitButton()
TXBuffer += "</table></form>"
sendHeadandTail("TmplStd",_TAIL);
return TXBuffer
@WebServer.route('/controllers')
def handle_controllers(self):
global TXBuffer, navMenuIndex
TXBuffer=""
navMenuIndex=2
if (rpieGlobals.wifiSetup):
return self.redirect('/setup')
if (not isLoggedIn(self.get,self.cookie)):
return self.redirect('/login')
sendHeadandTail("TmplStd",_HEAD);
if self.type == "GET":
responsearr = self.get
else:
responsearr = self.post
edit = arg("edit",responsearr)
controllerindex = arg("index",responsearr)
controllerNotSet = (controllerindex == 0) or (controllerindex == '')
if controllerindex!="":
controllerindex = int(controllerindex) - 1
controllerip = arg("controllerip",responsearr)
controllerport = arg("controllerport",responsearr)
protocol = arg("protocol",responsearr)
if protocol!="":
protocol=int(protocol)
else:
protocol=0
controlleruser = arg("controlleruser",responsearr)
controllerpassword = arg("controllerpassword",responsearr)
enabled = (arg("controllerenabled",responsearr)=="on")
if ((protocol == 0) and (edit=='') and (controllerindex!='')) or (arg('del',responsearr) != ''):
try:
Settings.Controllers[controllerindex].controller_exit()
except:
pass
Settings.Controllers[controllerindex] = False
controllerNotSet = True
Settings.savecontrollers()
if (controllerNotSet==False): # submitted
if (protocol > 0): # submitted
try:
if (Settings.Controllers[controllerindex]):
Settings.Controllers[controllerindex].controllerip = controllerip
Settings.Controllers[controllerindex].controllerport = controllerport
Settings.Controllers[controllerindex].controlleruser = controlleruser
if "**" not in controllerpassword:
Settings.Controllers[controllerindex].controllerpassword = controllerpassword
Settings.Controllers[controllerindex].enabled = enabled
Settings.Controllers[controllerindex].webform_save(responsearr)
Settings.savecontrollers()
except:
pass
else:
try:
if (Settings.Controllers[controllerindex]):
protocol = Settings.Controllers[controllerindex].controllerid
except:
pass
TXBuffer += "<form name='frmselect' method='post'>"
if (controllerNotSet): # show all in table
TXBuffer += "<table class='multirow' border=1px frame='box' rules='all'><TR><TH style='width:70px;'>"
TXBuffer += "<TH style='width:50px;'>Nr<TH style='width:100px;'>Enabled<TH>Protocol<TH>Host<TH>Port"
for x in range(rpieGlobals.CONTROLLER_MAX):
TXBuffer += "<tr><td><a class='button link' href=\"controllers?index="
TXBuffer += str(x + 1)
TXBuffer += "&edit=1\">Edit</a><td>"
TXBuffer += getControllerSymbol(x)
TXBuffer += "</td><td>"
try:
if (Settings.Controllers[x]):
addEnabled(Settings.Controllers[x].enabled)
TXBuffer += "</td><td>"
TXBuffer += str(Settings.Controllers[x].getcontrollername())
TXBuffer += "</td><td>"
TXBuffer += str(Settings.Controllers[x].controllerip)
TXBuffer += "</td><td>"
TXBuffer += str(Settings.Controllers[x].controllerport)
else:
TXBuffer += "<td><td><td>"
except:
TXBuffer += "<td><td><td>"
TXBuffer += "</table></form>"
else: # edit
TXBuffer += "<table class='normal'><TR><TH style='width:150px;' align='left'>Controller Settings<TH>"
TXBuffer += "<tr><td>Protocol:<td>"
addSelector_Head("protocol", True)
for x in range(len(rpieGlobals.controllerselector)):
addSelector_Item(rpieGlobals.controllerselector[x][2],int(rpieGlobals.controllerselector[x][1]),(str(protocol) == str(rpieGlobals.controllerselector[x][1])),False,"")
addSelector_Foot()
if (int(protocol) > 0):
createnewcontroller = True
try:
if (Settings.Controllers[controllerindex].getcontrollerid()==int(protocol)):
createnewcontroller = False
except:
pass
exceptstr = ""
if createnewcontroller:
for y in range(len(rpieGlobals.controllerselector)):
if int(rpieGlobals.controllerselector[y][1]) == int(protocol):
if len(Settings.Controllers)<=controllerindex:
while len(Settings.Controllers)<=controllerindex:
Settings.Controllers.append(False)
try:
m = __import__(rpieGlobals.controllerselector[y][0])
except Exception as e:
Settings.Controllers[controllerindex] = False
exceptstr += str(e)
m = False
if m:
try:
Settings.Controllers[controllerindex] = m.Controller(controllerindex)
except Exception as e:
Settings.Controllers.append(m.Controller(controllerindex))
exceptstr += str(e)
break
if Settings.Controllers[controllerindex] == False:
errormsg = "Importing failed, please double <a href='plugins'>check dependencies</a>! "+str(exceptstr)
TXBuffer += errormsg+"</td></tr></table>"
sendHeadandTail("TmplStd",_TAIL)
return TXBuffer
else:
try:
Settings.Controllers[controllerindex].controller_init() # call plugin init
if (Settings.Controllers[controllerindex]):
if (Settings.Controllers[controllerindex].enabled):
Settings.Controllers[controllerindex].setonmsgcallback(Settings.callback_from_controllers)
for x in range(0,len(Settings.Tasks)):
if (Settings.Tasks[x] and type(Settings.Tasks[x]) is not bool): # device exists
if (Settings.Tasks[x].enabled): # device enabled
if (Settings.Tasks[x].senddataenabled[controllerindex]):
if (Settings.Controllers[controllerindex]):
if (Settings.Controllers[controllerindex].enabled):
Settings.Tasks[x].controllercb[controllerindex] = Settings.Controllers[controllerindex].senddata
except:
pass
if controllerindex != '':
TXBuffer += "<input type='hidden' name='index' value='" + str(controllerindex+1) +"'>"
if int(protocol)>0:
addFormCheckBox("Enabled", "controllerenabled", Settings.Controllers[controllerindex].enabled)
addFormTextBox("Controller Host Address", "controllerip", Settings.Controllers[controllerindex].controllerip, 96)
addFormNumericBox("Controller Port", "controllerport", Settings.Controllers[controllerindex].controllerport, 1, 65535)
if Settings.Controllers[controllerindex].usesAccount:
addFormTextBox("Controller User", "controlleruser", Settings.Controllers[controllerindex].controlleruser,96)
if Settings.Controllers[controllerindex].usesPassword:
addFormPasswordBox("Controller Password", "controllerpassword", Settings.Controllers[controllerindex].controllerpassword,96)
# try:
Settings.Controllers[controllerindex].webform_load()
# except:
# pass
addFormSeparator(2)
TXBuffer += "<tr><td><td>"
TXBuffer += "<a class='button link' href=\"controllers\">Close</a>"
addSubmitButton()
if controllerindex != '':
addSubmitButton("Delete", "del")
TXBuffer += "</table></form>"
sendHeadandTail("TmplStd",_TAIL);
return TXBuffer
@WebServer.route('/hardware')
def handle_hardware(self):
global TXBuffer, navMenuIndex
TXBuffer=""
navMenuIndex=3
if (rpieGlobals.wifiSetup):
return self.redirect('/setup')
if (not isLoggedIn(self.get,self.cookie)):
return self.redirect('/login')
sendHeadandTail("TmplStd",_HEAD)
suplvl = misc.getsupportlevel()
if suplvl[0] != "N":
ar = OS.autorun()
ar.readconfig()
if self.type == "GET":
responsearr = self.get
else:
responsearr = self.post
if (arg('nokernelserial',responsearr) != ""):
OS.disable_serialsyslog()
if (arg('volume',responsearr) != ""):
try:
OS.setvolume(str(arg('volume',responsearr)))
except Exception as e:
print(e)
submit = arg("Submit",responsearr)
if (submit=="Submit") and (suplvl[0] != "N"):
stat = arg("rpiauto",responsearr)
if stat=="on":
ar.rpiauto=True
else:
ar.rpiauto=False
stat = arg("hdmienabled",responsearr)
if stat=="on":
ar.hdmienabled=True
else:
ar.hdmienabled=False
snddev = arg("snddev",responsearr)
snddev = snddev.strip()
if OS.check_permission():
ar.saveconfig()
try:
if int(snddev)>=0:
OS.updateaudiocard(snddev)
except:
pass
TXBuffer += "<form name='frmselect' method='post'><table class='normal'><tr><TH style='width:150px;' align='left' colspan=2>System"
TXBuffer += "<TR><TD>Type:<TD>"+suplvl
if suplvl[0] != "N":
TXBuffer += "<TR><TD>OS:<TD>"+str(rpieGlobals.osinuse)+" "+str(misc.getosname(1))
if "Linux" in suplvl:
TXBuffer += "<TR><TD>OS full name:<TD>"+str(OS.getosfullname())
if suplvl[0] == "L":
TXBuffer += "<TR><TD>Hardware:<TD>"+str(OS.gethardware())
if "RPI" in suplvl:
rpv = OS.getRPIVer()
if len(rpv)>1:
TXBuffer += "<TR><TD>Hardware:<TD>"+rpv["name"]+" "+rpv["ram"]
if "OPI" in suplvl:
opv = OS.getarmbianinfo()
if len(opv)>0:
TXBuffer += "<TR><TD>Hardware:<TD>"+opv["name"]
if suplvl[0] != "N":
addFormSeparator(2)
racc = OS.check_permission()
rstr = str(racc)
if racc == False:
rstr = "<font color=red>"+rstr+"</font> (system-wide settings are only for root)"
TXBuffer += "<TR><TD>Root access:<TD>"+rstr
TXBuffer += "<TR><TD>Sound playback device:<TD>"
sounddevs = OS.getsounddevs()
defaultdev = OS.getsoundsel()
if len(sounddevs)>0:
addSelector_Head('snddev',False)
for i in range(0,len(sounddevs)):
addSelector_Item(sounddevs[i][1],int(sounddevs[i][0]),(int(sounddevs[i][0])==int(defaultdev)),False)
addSelector_Foot()
vol = 100
try:
vol = OS.getvolume()
except Exception as e:
print(e)
TXBuffer += '<TR><TD>Sound volume:<TD><input type="range" id="volume" name="volume" min="0" max="100" value="'+str(vol)+'">'
else:
TXBuffer += "No device"
addFormCheckBox("RPIEasy autostart at boot","rpiauto",ar.rpiauto)
if OS.checkRPI():
addFormCheckBox("Enable HDMI at startup","hdmienabled",ar.hdmienabled)
if OS.check_permission():
TXBuffer += "<tr><td colspan=2>"
addSubmitButton()
addFormSeparator(2)
TXBuffer += "<TR><TD HEIGHT=30>"
addWideButton("plugins", "Plugin&controller dependencies", "")
TXBuffer += "</TD><TD HEIGHT=30>"
addWideButton("pinout", "Pinout&Ports", "")
TXBuffer += "<TR><TD HEIGHT=30>"
addWideButton("wifiscanner", "Scan Wifi networks", "")
TXBuffer += "</TD><TD HEIGHT=30>"
addWideButton("i2cscanner", "I2C Scan", "")
TXBuffer += "<TR><TD HEIGHT=30>"
addWideButton("blescanner", "Scan Bluetooth LE", "")
bpcont = OS.get_bootparams()
if ("ttyAMA" in bpcont) or ("ttyS" in bpcont) or ("serial" in bpcont):
addFormSeparator(2)
addSubmitButton("Disable Serial port usage by kernel","nokernelserial")
TXBuffer += "</table></form>"
sendHeadandTail("TmplStd",_TAIL)
return TXBuffer
@WebServer.route('/pinout')
def handle_pinout(self):
global TXBuffer, navMenuIndex
TXBuffer=""
navMenuIndex=3
if (rpieGlobals.wifiSetup):
return self.redirect('/setup')
if (not isLoggedIn(self.get,self.cookie)):
return self.redirect('/login')
sendHeadandTail("TmplStd",_HEAD)
try:
import gpios
except:
print("Unable to load GPIO support")
if self.type == "GET":
responsearr = self.get
else:
responsearr = self.post
submit = arg("Submit",responsearr)
setbtn = arg("set",responsearr).strip()
if arg("reread",responsearr) != '':
submit = ''
try:
gpios.HWPorts.readconfig()
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"Config read error="+str(e))
if (submit=="Submit") or (setbtn!=''):
try:
stat = arg("i2c0",responsearr)
if stat=="on":
gpios.HWPorts.enable_i2c(0)
else:
gpios.HWPorts.disable_i2c(0)
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"I2C-0 error="+str(e))
try:
stat = arg("i2c1",responsearr)
if stat=="on":
gpios.HWPorts.enable_i2c(1)
else:
gpios.HWPorts.disable_i2c(1)
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"I2C-1 error="+str(e))
try:
stat = arg("spi0",responsearr)
if stat=="on":
gpios.HWPorts.enable_spi(0,2)
else:
gpios.HWPorts.disable_spi(0)
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"SPI-0 error="+str(e))
try:
stat = int(arg("spi1",responsearr).strip())
except:
stat = 0
try:
if stat == "":
stat = 0
if stat == 0:
gpios.HWPorts.disable_spi(1)
else:
gpios.HWPorts.enable_spi(1,stat)
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"SPI-1 error="+str(e))
try:
stat = arg("uart",responsearr)
if stat=="on":
gpios.HWPorts.set_serial(1)
else:
gpios.HWPorts.set_serial(0)
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"UART init error="+str(e))
try:
stat = arg("audio",responsearr)
if stat=="on":
gpios.HWPorts.set_audio(1)
else:
gpios.HWPorts.set_audio(0)
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"Audio init error="+str(e))
try:
stat = arg("i2s",responsearr)
if stat=="on":
gpios.HWPorts.set_i2s(1)
else:
gpios.HWPorts.set_i2s(0)
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"I2S init error="+str(e))
try:
stat = int(arg("bluetooth",responsearr).strip())
except:
stat=0
try:
gpios.HWPorts.set_internal_bt(stat)
stat = arg("wifi",responsearr)
if stat=="on":
gpios.HWPorts.set_wifi(1)
else:
gpios.HWPorts.set_wifi(0)
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"WLAN init error="+str(e))
try:
stat = int(arg("gpumem",responsearr).strip())
except:
stat=16
gpios.HWPorts.gpumem = stat
for p in range(len(Settings.Pinout)):
pins = arg("pinstate"+str(p),responsearr)
if pins and pins!="" and p!= "":
try:
gpios.HWPorts.setpinstate(p,int(pins))
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"Pin "+str(p)+" "+str(e))
if OS.check_permission() and setbtn=='':
try:
gpios.HWPorts.saveconfig()
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,str(e))
try:
Settings.savepinout()
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,str(e))
if (len(Settings.Pinout)>1):
TXBuffer += "<form name='frmselect' method='post'><table class='normal'>"
TXBuffer += "<tr><th colspan=10>GPIO pinout</th></tr>"
addHtml("<tr><th>Detected function</th><th>Requested function</th><th>Pin name</th><th>#</th><th>Value</th><th>Value</th><th>#</th><th>Pin name</th><th>Requested function</th><th>Detected function</th></tr>")
for p in range(len(Settings.Pinout)):
if Settings.Pinout[p]["canchange"] != 2:
idnum = int(Settings.Pinout[p]["ID"])
if bool(idnum & 1): # left
TXBuffer += "<TR><td>"
# if Settings.Pinout[p]["canchange"]==1 and Settings.Pinout[p]["altfunc"]==0:
if Settings.Pinout[p]["canchange"]==1 and Settings.Pinout[p]["BCM"]>0:
# print pin setup infos
astate = Settings.Pinout[p]["actualstate"]
if astate<0:
astate=0
astate = Settings.PinStates[astate]
pinfunc = -1
if gpios.HWPorts.gpioinit:
pinfunc = gpios.HWPorts.gpio_function(int(Settings.Pinout[p]["BCM"]))
astate = str(gpios.HWPorts.gpio_function_name(pinfunc))
TXBuffer += astate
TXBuffer += "</td>" # actual state
else:
TXBuffer += "-</td>"
if Settings.Pinout[p]["canchange"]==1 and Settings.Pinout[p]["altfunc"]==0:
addHtml("<td>") # startupstate
addSelector("pinstate"+str(p),Settings.PinStatesMax,Settings.PinStates,False,None,Settings.Pinout[p]["startupstate"],False)
addHtml("</td>")
else:
TXBuffer += "<td>-</td>"
try:
funcorder = int(Settings.Pinout[p]["altfunc"])
except:
funcorder = 0
if funcorder>0 and len(Settings.Pinout[p]["name"])>funcorder:
TXBuffer += "<td>"+ Settings.Pinout[p]["name"][funcorder] +"</td>"
else:
TXBuffer += "<td>"+ Settings.Pinout[p]["name"][0] +"</td>"
TXBuffer += "<td>"+ str(Settings.Pinout[p]["ID"]) +"</td>"
TXBuffer += "<td style='{border-right: solid 1px #000;}'>"
if Settings.Pinout[p]["canchange"]==1 and pinfunc in [0,1]:
if gpios.HWPorts.gpioinit:
gpios.HWPorts.setpinstate(p,int(Settings.Pinout[p]["startupstate"]))
try:
TXBuffer += "("+str(gpios.HWPorts.input(int(Settings.Pinout[p]["BCM"])))+")"
except:
TXBuffer += "E"
else:
TXBuffer += "X"
TXBuffer += "</td>" # add pin value
else:
TXBuffer += "-</td>"
else: # right
pinfunc = -1
if Settings.Pinout[p]["canchange"]==1 and Settings.Pinout[p]["BCM"]>0:
TXBuffer += "<td>"
if gpios.HWPorts.gpioinit:
pinfunc = gpios.HWPorts.gpio_function(int(Settings.Pinout[p]["BCM"]))
if pinfunc in [0,1] and Settings.Pinout[p]["altfunc"]==0:
gpios.HWPorts.setpinstate(p,int(Settings.Pinout[p]["startupstate"]))
try:
TXBuffer += "("+str(gpios.HWPorts.input(int(Settings.Pinout[p]["BCM"])))+")"
except:
TXBuffer += "E"
else:
TXBuffer += "X"
TXBuffer += "</td>" # add pin value
else:
TXBuffer += "<td>-</td>"
TXBuffer += "<td>"+ str(Settings.Pinout[p]["ID"]) +"</td>"
try:
funcorder = int(Settings.Pinout[p]["altfunc"])
except:
funcorder = 0
if funcorder>0 and len(Settings.Pinout[p]["name"])>funcorder:
TXBuffer += "<td>"+ Settings.Pinout[p]["name"][funcorder] +"</td>"
else:
TXBuffer += "<td>"+ Settings.Pinout[p]["name"][0] +"</td>"
TXBuffer += "<td>"
if Settings.Pinout[p]["canchange"]==1 and Settings.Pinout[p]["altfunc"]==0:
# print pin setup infos
addSelector("pinstate"+str(p),Settings.PinStatesMax,Settings.PinStates,False,None,Settings.Pinout[p]["startupstate"],False)
addHtml("</td>")
else:
TXBuffer += "-</td>"
addHtml("<td>") # startupstate
if Settings.Pinout[p]["canchange"]==1 and Settings.Pinout[p]["BCM"]>0:
astate = Settings.Pinout[p]["actualstate"]
if astate<0:
astate=0
astate = Settings.PinStates[astate]
if gpios.HWPorts.gpioinit:
astate = str(gpios.HWPorts.gpio_function_name(pinfunc))
TXBuffer += str(astate)+"</td>" # actual state
else:
TXBuffer += "<td>-</td>"
TXBuffer += "</TR>"
TXBuffer += "</table>"
TXBuffer += "<table class='normal'><TR>"
addFormHeader("Advanced features")
for i in range(0,2):
if gpios.HWPorts.is_i2c_usable(i):
addFormCheckBox("Enable I2C-"+str(i),"i2c"+str(i),gpios.HWPorts.is_i2c_enabled(i))
if gpios.HWPorts.is_spi_usable(0):
addFormCheckBox("Enable SPI-0","spi0",gpios.HWPorts.is_spi_enabled(0))
if gpios.HWPorts.is_spi_usable(1):
selopt = 0
if gpios.HWPorts.is_spi_enabled(1):
selopt = gpios.HWPorts.spi_cs[1]
soptions = ["Disabled","Enabled with 1xCS pins","Enabled with 2xCS pins","Enabled with 3xCS pins"]
addFormSelector("SPI-1", "spi1", len(soptions), soptions, False, None, selopt, False)
addFormCheckBox("Enable UART","uart",gpios.HWPorts.is_serial_enabled())
addFormCheckBox("Enable internal Audio","audio",gpios.HWPorts.is_audio_enabled())
addFormNote("Audio might interfere with PWM! Disable audio if PWM needed.")
if gpios.HWPorts.is_i2s_usable():
addFormCheckBox("Enable I2S","i2s",(gpios.HWPorts.i2s==1))
addFormNote("I2S might interfere with PWM and SPI1")
if gpios.HWPorts.is_internal_bt_usable():
selopt = gpios.HWPorts.get_internal_bt_level()
soptions = ["Disabled","Enabled with SW","Enabled with HW (default)"]
addFormSelector("Internal Bluetooth", "bluetooth", len(soptions), soptions, False, None, selopt, False)
addFormNote("BT might interfere with UART! Disable or use SW mode if real UART needed.")
if gpios.HWPorts.is_internal_wifi_usable():
addFormCheckBox("Internal WiFi","wifi",gpios.HWPorts.is_wifi_enabled())
addFormNumericBox("GPU memory","gpumem", gpios.HWPorts.gpumem,gpios.HWPorts.gpumin,gpios.HWPorts.gpumax)
addUnit("MB")
addFormSeparator(2)
TXBuffer += "<tr><td colspan=2>"
if OS.check_permission():
addSubmitButton()
addSubmitButton("Set without save","set")
addSubmitButton("Reread config","reread")
TXBuffer += "</td></tr>"
if OS.check_permission():
if OS.checkboot_ro():
addFormNote("<font color='red'>WARNING: Your /boot partition is mounted READONLY! Changes could not be saved! Run 'sudo mount -o remount,rw /boot' or whatever necessary to solve it!")
addFormNote("WARNING: Some changes needed to reboot after submitting changes! And most changes requires root permission.")
addHtml("</table></form>")
else:
addHtml('This hardware is currently not supported!')
sendHeadandTail("TmplStd",_TAIL)
return TXBuffer
@WebServer.route('/plugins')
def handle_plugins(self):
global TXBuffer, navMenuIndex
TXBuffer=""
navMenuIndex=3
if (rpieGlobals.wifiSetup):
return self.redirect('/setup')
if (not isLoggedIn(self.get,self.cookie)):
return self.redirect('/login')
sendHeadandTail("TmplStd",_HEAD);
try:
if (plugindeps.modulelist):
pass
except:
import plugindeps
if self.type == "GET":
responsearr = self.get
else:
responsearr = self.post
moduletoinstall = arg('installmodule',responsearr).strip()
if moduletoinstall:
plugindeps.installdeps(moduletoinstall)
if OS.check_permission()==False:
TXBuffer += "Installation WILL NOT WORK without root permission!<p>"
TXBuffer += "<p><b>If you want to install a dependency, please click at the blue underlined text, where you see a red X!<b><p><br>"
TXBuffer += "<table class='multirow' border=1px frame='box' rules='all'><TR><TH colspan=4>Controllers</TH></TR>"
TXBuffer += "<TR><TH>#</TH><TH>Name</TH><TH>Dependencies</TH><TH>Usable</TH></TR>"
for x in range(len(rpieGlobals.controllerselector)):
if (rpieGlobals.controllerselector[x][1] != 0):
TXBuffer += "<tr><td>" + str(rpieGlobals.controllerselector[x][1])+"</td><td align=left>"+rpieGlobals.controllerselector[x][2]+"</td>"
depfound = -1
for y in range(len(plugindeps.controllerdependencies)):
if str(plugindeps.controllerdependencies[y]["controllerid"]) == str(rpieGlobals.controllerselector[x][1]):
depfound = y
break
TXBuffer += "<td>"
usable = True
if depfound>-1:
if (plugindeps.controllerdependencies[depfound]["modules"]):
for z in range(len(plugindeps.controllerdependencies[depfound]["modules"])):
puse = plugindeps.ismoduleusable(plugindeps.controllerdependencies[depfound]["modules"][z])
addEnabled(puse)
if puse==False:
usable = False
TXBuffer += "<a href='plugins?installmodule="+plugindeps.controllerdependencies[depfound]["modules"][z]+"'>"
TXBuffer += plugindeps.controllerdependencies[depfound]["modules"][z]+" "
if puse==False:
TXBuffer += "</a>"
else:
TXBuffer += "No dependencies"
TXBuffer += "</td><td>"
addEnabled(usable)
TXBuffer += "</td></tr>"
TXBuffer += "</table><p><table class='multirow' border=1px frame='box' rules='all'><TR><TH colspan=5>Plugins</TH></TR>"
TXBuffer += "<TR><TH>#</TH><TH>Name</TH><TH>OS</TH><TH>Dependencies</TH><TH>Usable</TH></TR>"
oslvl = misc.getsupportlevel(1)
for x in range(len(rpieGlobals.deviceselector)):
if (rpieGlobals.deviceselector[x][1] != 0):
TXBuffer += "<tr><td>" + str(rpieGlobals.deviceselector[x][1])+"</td><td align=left>"+rpieGlobals.deviceselector[x][2]+"</td>"
depfound = -1
for y in range(len(plugindeps.plugindependencies)):
if str(plugindeps.plugindependencies[y]["pluginid"]) == str(rpieGlobals.deviceselector[x][1]):
depfound = y
break
TXBuffer += "<td>"
usable = True
if depfound>-1:
try:
if oslvl in plugindeps.plugindependencies[depfound]["supported_os_level"]:
TXBuffer += "Supported"
else:
TXBuffer += "NOT Supported"
usable = False
except:
TXBuffer += "Supported"
TXBuffer += "</td><td>"
try:
if (plugindeps.plugindependencies[depfound]["modules"]):
for z in range(len(plugindeps.plugindependencies[depfound]["modules"])):