forked from jgyates/genmon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
genserv.py
4714 lines (4338 loc) · 169 KB
/
genserv.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
# -------------------------------------------------------------------------------
# FILE: genserv.py
# PURPOSE: Flask app for generator monitor web app
#
# AUTHOR: Jason G Yates
# DATE: 20-Dec-2016
#
# MODIFICATIONS:
# -------------------------------------------------------------------------------
from __future__ import print_function
import collections
import errno
import json
import os
import os.path
import signal
import subprocess
import sys
import threading
import time
try:
from flask import (
Flask,
jsonify,
make_response,
redirect,
render_template,
request,
send_file,
session,
url_for,
)
except Exception as e1:
print(
"\n\nThis program requires the Flask library. Please see the project documentation at https://github.com/jgyates/genmon.\n"
)
print("Error: " + str(e1))
sys.exit(2)
try:
import pyotp
except Exception as e1:
print(
"\n\nThis program requires the pyotp library. Please see the project documentation at https://github.com/jgyates/genmon.\n"
)
print("Error: " + str(e1))
sys.exit(2)
try:
from genmonlib.myclient import ClientInterface
from genmonlib.myconfig import MyConfig
from genmonlib.mylog import SetupLogger
from genmonlib.mymail import MyMail
from genmonlib.mysupport import MySupport
from genmonlib.program_defaults import ProgramDefaults
except Exception as e1:
print(
"\n\nThis program requires the modules located in the genmonlib directory in the original github repository.\n"
)
print(
"Please see the project documentation at https://github.com/jgyates/genmon.\n"
)
print("Error: " + str(e1))
sys.exit(2)
if sys.version_info[0] < 3:
from urlparse import parse_qs, parse_qsl, urlparse
else:
from urllib.parse import urlparse
from urllib.parse import parse_qs
from urllib.parse import parse_qsl
import datetime
import re
# -------------------------------------------------------------------------------
app = Flask(__name__, static_url_path="")
# this allows the flask support to be extended on a per site basis but sill allow for
# updates via the main github repository. If genservex.py exists, load it
if os.path.isfile(
os.path.join(os.path.dirname(os.path.realpath(__file__)), "genservext.py")
):
import genservext
app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 300
HTTPAuthUser = None
HTTPAuthPass = None
HTTPAuthUser_RO = None
HTTPAuthPass_RO = None
LdapServer = None
LdapBase = None
DomainNetbios = None
LdapAdminGroup = None
LdapReadOnlyGroup = None
mail = None
bUseMFA = False
SecretMFAKey = None
MFA_URL = None
bUseSecureHTTP = False
bUseSelfSignedCert = True
SSLContext = None
HTTPPort = 8000
loglocation = ProgramDefaults.LogPath
clientport = ProgramDefaults.ServerPort
log = None
console = None
AppPath = ""
favicon = "favicon.ico"
ConfigFilePath = ProgramDefaults.ConfPath
MAIL_SECTION = "MyMail"
GENMON_SECTION = "GenMon"
WebUILocked = False
LoginAttempts = 0
MaxLoginAttempts = 5
LockOutDuration = 5 * 60
LastLoginTime = datetime.datetime.now()
LastFailedLoginTime = datetime.datetime.now()
securityMessageSent = None
Closing = False
Restarting = False
ControllerType = "generac_evo_nexus"
CriticalLock = threading.Lock()
CachedToolTips = {}
CachedRegisterDescriptions = {}
# -------------------------------------------------------------------------------
@app.route("/logout")
def logout():
try:
# remove the session data
if LoginActive():
session["logged_in"] = False
session["write_access"] = False
session["mfa_ok"] = False
return redirect(url_for("root"))
except Exception as e1:
LogError("Error on logout: " + str(e1))
# -------------------------------------------------------------------------------
@app.after_request
def add_header(r):
"""
Force cache header
"""
r.headers[
"Cache-Control"
] = "no-cache, no-store, must-revalidate, public, max-age=0"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
return r
# -------------------------------------------------------------------------------
@app.route("/", methods=["GET"])
def root():
if bUseMFA:
if not "mfa_ok" in session or not session["mfa_ok"] == True:
session["logged_in"] = False
session["write_access"] = False
session["mfa_ok"] = False
redirect(url_for("root"))
return ServePage("index.html")
# -------------------------------------------------------------------------------
@app.route("/verbose", methods=["GET"])
def verbose():
return ServePage("index_verbose.html")
# -------------------------------------------------------------------------------
@app.route("/low", methods=["GET"])
def lowbandwidth():
return ServePage("index_lowbandwith.html")
# -------------------------------------------------------------------------------
@app.route("/internal", methods=["GET"])
def display_internal():
return ServePage("internal.html")
# -------------------------------------------------------------------------------
@app.route("/locked", methods=["GET"])
def locked():
LogError("Locked Page")
return render_template("locked.html")
# -------------------------------------------------------------------------------
@app.route("/upload", methods=["PUT"])
def upload():
# TODO
LogError("genserv: Upload")
return redirect(url_for("root"))
# -------------------------------------------------------------------------------
def ServePage(page_file):
if LoginActive():
if not session.get("logged_in"):
return render_template("login.html")
else:
return app.send_static_file(page_file)
else:
return app.send_static_file(page_file)
# -------------------------------------------------------------------------------
@app.route("/mfa", methods=["POST"])
def mfa_auth():
try:
if bUseMFA:
if ValidateOTP(request.form["code"]):
session["mfa_ok"] = True
return redirect(url_for("root"))
else:
session["logged_in"] = False
session["write_access"] = False
session["mfa_ok"] = False
return redirect(url_for("logout"))
else:
return redirect(url_for("root"))
except Exception as e1:
LogErrorLine("Error in mfa_auth: " + str(e1))
return render_template("login.html")
# -------------------------------------------------------------------------------
def admin_login_helper():
global LoginAttempts
LoginAttempts = 0
try:
if bUseMFA:
# GetOTP()
response = make_response(render_template("mfa.html"))
return response
else:
return redirect(url_for("root"))
except Exception as e1:
LogErrorLine("Error in admin_login_helper: " + str(e1))
return False
# -------------------------------------------------------------------------------
@app.route("/", methods=["POST"])
def do_admin_login():
CheckLockOutDuration()
if WebUILocked:
next_time = (datetime.datetime.now() - LastFailedLoginTime).total_seconds()
str_seconds = str(int(LockOutDuration - next_time))
response = make_response(render_template("locked.html", time=str_seconds))
response.headers["Content-type"] = "text/html; charset=utf-8"
response.mimetype = "text/html; charset=utf-8"
return response
if (
request.form["password"] == HTTPAuthPass
and request.form["username"].lower() == HTTPAuthUser.lower()
):
session["logged_in"] = True
session["write_access"] = True
LogError("Admin Login")
return admin_login_helper()
elif (
request.form["password"] == HTTPAuthPass_RO
and request.form["username"].lower() == HTTPAuthUser_RO.lower()
):
session["logged_in"] = True
session["write_access"] = False
LogError("Limited Rights Login")
return admin_login_helper()
elif doLdapLogin(request.form["username"], request.form["password"]):
return admin_login_helper()
elif request.form["username"] != "":
LogError("Invalid login: " + request.form["username"])
CheckFailedLogin()
return render_template("login.html")
else:
return render_template("login.html")
# -------------------------------------------------------------------------------
def CheckLockOutDuration():
global WebUILocked
global LoginAttempts
global securityMessageSent
if MaxLoginAttempts == 0:
return
if LoginAttempts >= MaxLoginAttempts:
if (
datetime.datetime.now() - LastFailedLoginTime
).total_seconds() > LockOutDuration:
WebUILocked = False
LoginAttempts = 0
else:
WebUILocked = True
# send message to user only once every 4 hours
if securityMessageSent == None or (
(datetime.datetime.now() - securityMessageSent).total_seconds()
> (4 * 60)
):
message = {
"title": "Security Warning",
"body": "Genmon login is locked due to exceeding the maximum login attempts.",
"type": "error",
"oncedaily": False,
"onlyonce": False,
}
command = "generator: notify_message=" + json.dumps(message)
data = MyClientInterface.ProcessMonitorCommand(command)
securityMessageSent = datetime.datetime.now()
# -------------------------------------------------------------------------------
def CheckFailedLogin():
global LoginAttempts
global WebUILocked
global LastFailedLoginTime
LoginAttempts += 1
LastFailedLoginTime = datetime.datetime.now()
CheckLockOutDuration()
# -------------------------------------------------------------------------------
def doLdapLogin(username, password):
if LdapServer == None or LdapServer == "":
return False
try:
from ldap3 import ALL, NTLM, Connection, Server
from ldap3.utils.dn import escape_rdn
from ldap3.utils.conv import escape_filter_chars
except ImportError as importException:
LogError(
"LDAP3 import not found, run 'sudo pip install ldap3 && sudo pip3 install ldap3'"
)
LogError(importException)
return False
HasAdmin = False
HasReadOnly = False
try:
SplitName = username.split("\\")
DomainName = SplitName[0]
DomainName = DomainName.strip()
AccountName = SplitName[1]
AccountName = AccountName.strip()
except IndexError:
LogError("Using domain name in config file")
DomainName = DomainNetbios
AccountName = username.strip()
try:
server = Server(LdapServer, get_info=ALL)
conn = Connection(
server,
user="{}\\{}".format(DomainName, AccountName),
password=password,
authentication=NTLM,
auto_bind=True,
)
loginbasestr = escape_filter_chars("(&(objectclass=user)(sAMAccountName=" + AccountName + "))")
conn.search(
LdapBase,
loginbasestr,
attributes=["memberOf"],
)
for user in sorted(conn.entries):
for group in user.memberOf:
if group.upper().find("CN=" + LdapAdminGroup.upper() + ",") >= 0:
HasAdmin = True
elif group.upper().find("CN=" + LdapReadOnlyGroup.upper() + ",") >= 0:
HasReadOnly = True
conn.unbind()
except Exception:
LogError("Error in LDAP login. Check credentials and config parameters")
session["logged_in"] = HasAdmin or HasReadOnly
session["write_access"] = HasAdmin
if HasAdmin:
LogError("Admin Login via LDAP")
elif HasReadOnly:
LogError("Limited Rights Login via LDAP")
else:
LogError("No rights for login via LDAP")
return HasAdmin or HasReadOnly
# -------------------------------------------------------------------------------
@app.route("/cmd/<command>")
def command(command):
if Closing or Restarting:
return jsonify("Closing")
if HTTPAuthUser == None or HTTPAuthPass == None:
return ProcessCommand(command)
if not session.get("logged_in"):
return render_template("login.html")
else:
return ProcessCommand(command)
# -------------------------------------------------------------------------------
def ProcessCommand(command):
try:
command_list = [
"status",
"status_json",
"outage",
"outage_json",
"maint",
"maint_json",
"logs",
"logs_json",
"monitor",
"monitor_json",
"registers_json",
"allregs_json",
"start_info_json",
"gui_status_json",
"power_log_json",
"power_log_clear",
"getbase",
"getsitename",
"setexercise",
"setquiet",
"setremote",
"settime",
"sendregisters",
"sendlogfiles",
"getdebug",
"status_num_json",
"maint_num_json",
"monitor_num_json",
"outage_num_json",
"get_maint_log_json",
"add_maint_log",
"clear_maint_log",
"delete_row_maint_log",
"edit_row_maint_log",
"support_data_json",
"fuel_log_clear",
"notify_message",
"set_button_command",
]
# LogError(request.url)
if command in command_list:
finalcommand = "generator: " + command
try:
if command in [
"setexercise",
"setquiet",
"setremote",
"add_maint_log",
"delete_row_maint_log",
"edit_row_maint_log",
] and not session.get("write_access", True):
return jsonify("Read Only Mode")
if command == "setexercise":
settimestr = request.args.get("setexercise", 0, type=str)
if settimestr:
finalcommand += "=" + settimestr
elif command == "setquiet":
# /cmd/setquiet?setquiet=off
setquietstr = request.args.get("setquiet", 0, type=str)
if setquietstr:
finalcommand += "=" + setquietstr
elif command == "setremote":
setremotestr = request.args.get("setremote", 0, type=str)
if setremotestr:
finalcommand += "=" + setremotestr
if command == "power_log_json":
# example: /cmd/power_log_json?power_log_json=1440
setlogstr = request.args.get("power_log_json", 0, type=str)
if setlogstr:
finalcommand += "=" + setlogstr
if command == "add_maint_log":
# use direct method instead of request.args.get due to unicoode
# input for add_maint_log for international users
input = request.args["add_maint_log"]
finalcommand += "=" + input
if command == "delete_row_maint_log":
# use direct method instead of request.args.get due to unicoode
# input for add_maint_log for international users
input = request.args["delete_row_maint_log"]
finalcommand += "=" + input
if command == "edit_row_maint_log":
# use direct method instead of request.args.get due to unicoode
# input for add_maint_log for international users
input = request.args["edit_row_maint_log"]
finalcommand += "=" + input
if command == "set_button_command":
input = request.args["set_button_command"]
finalcommand += "=" + input
data = MyClientInterface.ProcessMonitorCommand(finalcommand)
except Exception as e1:
data = "Retry"
LogErrorLine("Error on command function: " + str(e1))
if command in [
"status_json",
"outage_json",
"maint_json",
"monitor_json",
"logs_json",
"registers_json",
"allregs_json",
"start_info_json",
"gui_status_json",
"power_log_json",
"status_num_json",
"maint_num_json",
"monitor_num_json",
"outage_num_json",
"get_maint_log_json",
"support_data_json",
]:
if command in ["start_info_json"]:
try:
StartInfo = json.loads(data)
StartInfo["write_access"] = session.get("write_access", True)
if not StartInfo["write_access"]:
StartInfo["pages"]["settings"] = False
StartInfo["pages"]["notifications"] = False
StartInfo["LoginActive"] = LoginActive()
data = json.dumps(StartInfo, sort_keys=False)
except Exception as e1:
LogErrorLine("Error in JSON parse / decode: " + str(e1))
return data
return jsonify(data)
elif command in ["updatesoftware"]:
if session.get("write_access", True):
Update()
return "OK"
else:
return "Access denied"
elif command in ["getfavicon"]:
return jsonify(favicon)
elif command in ["settings"]:
if session.get("write_access", True):
data = ReadSettingsFromFile()
return json.dumps(data, sort_keys=False)
else:
return "Access denied"
elif command in ["notifications"]:
data = ReadNotificationsFromFile()
return jsonify(data)
elif command in ["setnotifications"]:
if session.get("write_access", True):
SaveNotifications(request.args.get("setnotifications", 0, type=str))
return "OK"
# Add on items
elif command in ["get_add_on_settings", "set_add_on_settings"]:
if session.get("write_access", True):
if command == "get_add_on_settings":
data = GetAddOnSettings()
return json.dumps(data, sort_keys=False)
elif command == "set_add_on_settings":
SaveAddOnSettings(
request.args.get("set_add_on_settings", default=None, type=str)
)
else:
return "OK"
return "OK"
elif command in ["get_advanced_settings", "set_advanced_settings"]:
if session.get("write_access", True):
if command == "get_advanced_settings":
data = ReadAdvancedSettingsFromFile()
return json.dumps(data, sort_keys=False)
elif command == "set_advanced_settings":
SaveAdvancedSettings(
request.args.get(
"set_advanced_settings", default=None, type=str
)
)
else:
return "OK"
return "OK"
elif command in ["setsettings"]:
if session.get("write_access", True):
SaveSettings(request.args.get("setsettings", 0, type=str))
return "OK"
elif command in ["getreglabels"]:
return jsonify(CachedRegisterDescriptions)
elif command in ["restart"]:
if session.get("write_access", True):
Restart()
elif command in ["stop"]:
if session.get("write_access", True):
Close()
sys.exit(0)
elif command in ["shutdown"]:
if session.get("write_access", True):
Shutdown()
sys.exit(0)
elif command in ["reboot"]:
if session.get("write_access", True):
Reboot()
sys.exit(0)
elif command in ["backup"]:
if session.get("write_access", True):
Backup() # Create backup file
# Now send the file
pathtofile = os.path.dirname(os.path.realpath(__file__))
return send_file(
os.path.join(pathtofile, "genmon_backup.tar.gz"), as_attachment=True
)
elif command in ["get_logs"]:
if session.get("write_access", True):
GetLogs() # Create log archive file
# Now send the file
pathtofile = os.path.dirname(os.path.realpath(__file__))
return send_file(
os.path.join(pathtofile, "genmon_logs.tar.gz"), as_attachment=True
)
elif command in ["test_email"]:
return SendTestEmail(request.args.get("test_email", default=None, type=str))
else:
return render_template("command_template.html", command=command)
except Exception as e1:
LogErrorLine("Error in Process Command: " + command + ": " + str(e1))
return render_template("command_template.html", command=command)
# -------------------------------------------------------------------------------
def LoginActive():
if HTTPAuthUser != None and HTTPAuthPass != None or LdapServer != None:
return True
return False
# -------------------------------------------------------------------------------
def SendTestEmail(query_string):
try:
if query_string == None or not len(query_string):
return "No parameters given for email test."
parameters = json.loads(query_string)
if not len(parameters):
return "No parameters" # nothing to change return
except Exception as e1:
LogErrorLine("Error getting parameters in SendTestEmail: " + str(e1))
return "Error getting parameters in email test: " + str(e1)
try:
smtp_server = str(parameters["smtp_server"])
smtp_server = smtp_server.strip()
smtp_port = int(parameters["smtp_port"])
email_account = str(parameters["email_account"])
email_account = email_account.strip()
sender_account = str(parameters["sender_account"])
sender_account = sender_account.strip()
if not len(sender_account):
sender_account == None
sender_name = str(parameters["sender_name"])
sender_name = sender_name.strip()
if not len(sender_name):
sender_name == None
recipient = str(parameters["recipient"])
recipient = recipient.strip()
password = str(parameters["password"])
if parameters["use_ssl"].lower() == "true":
use_ssl = True
else:
use_ssl = False
if parameters["tls_disable"].lower() == "true":
tls_disable = True
else:
tls_disable = False
if parameters["smtpauth_disable"].lower() == "true":
smtpauth_disable = True
else:
smtpauth_disable = False
except Exception as e1:
LogErrorLine("Error parsing parameters in SendTestEmail: " + str(e1))
LogError(str(parameters))
return "Error parsing parameters in email test: " + str(e1)
try:
ReturnMessage = MyMail.TestSendSettings(
smtp_server=smtp_server,
smtp_port=smtp_port,
email_account=email_account,
sender_account=sender_account,
sender_name=sender_name,
recipient=recipient,
password=password,
use_ssl=use_ssl,
tls_disable=tls_disable,
smtpauth_disable=smtpauth_disable,
)
return ReturnMessage
except Exception as e1:
LogErrorLine("Error sending test email : " + str(e1))
return "Error sending test email : " + str(e1)
# -------------------------------------------------------------------------------
def GetAddOns():
AddOnCfg = collections.OrderedDict()
# Default icon name should be "Genmon" to get a generic icon
try:
# GENGPIO
Temp = collections.OrderedDict()
AddOnCfg["gengpio"] = collections.OrderedDict()
AddOnCfg["gengpio"]["enable"] = ConfigFiles[GENLOADER_CONFIG].ReadValue(
"enable", return_type=bool, section="gengpio", default=False
)
AddOnCfg["gengpio"]["title"] = "Genmon GPIO Outputs"
AddOnCfg["gengpio"][
"description"
] = "Genmon will set Raspberry Pi GPIO outputs (see documentation for details)"
AddOnCfg["gengpio"]["icon"] = "rpi"
AddOnCfg["gengpio"][
"url"
] = "https://github.com/jgyates/genmon/wiki/1----Software-Overview#gengpiopy-optional"
AddOnCfg["gengpio"]["parameters"] = None
# GENGPIOIN
AddOnCfg["gengpioin"] = collections.OrderedDict()
AddOnCfg["gengpioin"]["enable"] = ConfigFiles[GENLOADER_CONFIG].ReadValue(
"enable", return_type=bool, section="gengpioin", default=False
)
AddOnCfg["gengpioin"]["title"] = "Genmon GPIO Inputs"
AddOnCfg["gengpioin"][
"description"
] = "Genmon will set Raspberry Pi GPIO inputs (see documentation for details)"
AddOnCfg["gengpioin"]["icon"] = "rpi"
AddOnCfg["gengpioin"][
"url"
] = "https://github.com/jgyates/genmon/wiki/1----Software-Overview#gengpioinpy-optional"
AddOnCfg["gengpioin"]["parameters"] = collections.OrderedDict()
AddOnCfg["gengpioin"]["parameters"]["trigger"] = CreateAddOnParam(
ConfigFiles[GENGPIOIN_CONFIG].ReadValue(
"trigger", return_type=str, default="falling"
),
"list",
"Set GPIO input to trigger on rising or falling edge.",
bounds="falling,rising,both",
display_name="GPIO Edge Trigger",
)
AddOnCfg["gengpioin"]["parameters"]["resistorpull"] = CreateAddOnParam(
ConfigFiles[GENGPIOIN_CONFIG].ReadValue(
"resistorpull", return_type=str, default="up"
),
"list",
"Set GPIO input internal pull up or pull down resistor.",
bounds="up,down,off",
display_name="Internal resistor pull",
)
AddOnCfg["gengpioin"]["parameters"]["bounce"] = CreateAddOnParam(
ConfigFiles[GENGPIOIN_CONFIG].ReadValue(
"bounce", return_type=int, default=0
),
"int",
"Minimum interval in milliseconds between valid input changes. Zero to disable, or positive whole number.",
bounds="number",
display_name="Software Debounce",
)
# GENGPIOLEDBLINK
AddOnCfg["gengpioledblink"] = collections.OrderedDict()
AddOnCfg["gengpioledblink"]["enable"] = ConfigFiles[GENLOADER_CONFIG].ReadValue(
"enable", return_type=bool, section="gengpioledblink", default=False
)
AddOnCfg["gengpioledblink"]["title"] = "Genmon GPIO Output to blink LED"
AddOnCfg["gengpioledblink"][
"description"
] = "Genmon will blink LED connected to GPIO pin to indicate genmon status"
AddOnCfg["gengpioledblink"]["icon"] = "rpi"
AddOnCfg["gengpioledblink"][
"url"
] = "https://github.com/jgyates/genmon/wiki/1----Software-Overview#gengpioledblinkpy-optional"
AddOnCfg["gengpioledblink"]["parameters"] = collections.OrderedDict()
AddOnCfg["gengpioledblink"]["parameters"]["ledpin"] = CreateAddOnParam(
ConfigFiles[GENGPIOLEDBLINK_CONFIG].ReadValue(
"ledpin", return_type=int, default=12
),
"int",
"GPIO pin number that an LED is connected (valid numbers are 0 - 27)",
bounds="required digits range:0:27",
display_name="GPIO LED pin",
)
# GENLOG
AddOnCfg["genlog"] = collections.OrderedDict()
AddOnCfg["genlog"]["enable"] = ConfigFiles[GENLOADER_CONFIG].ReadValue(
"enable", return_type=bool, section="genlog", default=False
)
AddOnCfg["genlog"]["title"] = "Notifications to CSV Log"
AddOnCfg["genlog"][
"description"
] = "Log Genmon and utility state changes to a file. Log file is in text CSV format."
AddOnCfg["genlog"]["icon"] = "csv"
AddOnCfg["genlog"][
"url"
] = "https://github.com/jgyates/genmon/wiki/1----Software-Overview#genlogpy-optional"
AddOnCfg["genlog"]["parameters"] = collections.OrderedDict()
Args = ConfigFiles[GENLOADER_CONFIG].ReadValue(
"args",
return_type=str,
section="genlog",
default="-f /home/pi/genmon/LogFile.csv",
)
ArgList = Args.split()
if len(ArgList) == 2:
Value = ArgList[1]
else:
Value = ""
AddOnCfg["genlog"]["parameters"]["Log File Name"] = CreateAddOnParam(
Value,
"string",
"Filename for log. Full path of the file must be included (i.e. /home/pi/genmon/LogFile.csv)",
bounds="required UnixFile",
display_name="Log File Name",
)
# GENSMS
AddOnCfg["gensms"] = collections.OrderedDict()
AddOnCfg["gensms"]["enable"] = ConfigFiles[GENLOADER_CONFIG].ReadValue(
"enable", return_type=bool, section="gensms", default=False
)
AddOnCfg["gensms"]["title"] = "Notifications via SMS - Twilio"
AddOnCfg["gensms"][
"description"
] = "Send Genmon and utility state changes via Twilio SMS"
AddOnCfg["gensms"]["icon"] = "twilio"
AddOnCfg["gensms"][
"url"
] = "https://github.com/jgyates/genmon/wiki/1----Software-Overview#gensmspy-optional"
AddOnCfg["gensms"]["parameters"] = collections.OrderedDict()
AddOnCfg["gensms"]["parameters"]["accountsid"] = CreateAddOnParam(
ConfigFiles[GENSMS_CONFIG].ReadValue(
"accountsid", return_type=str, default=""
),
"string",
"Twilio account SID. This can be obtained from a valid Twilio account",
bounds="required minmax:10:50",
display_name="Twilio Account SID",
)
AddOnCfg["gensms"]["parameters"]["authtoken"] = CreateAddOnParam(
ConfigFiles[GENSMS_CONFIG].ReadValue(
"authtoken", return_type=str, default=""
),
"string",
"Twilio authentication token. This can be obtained from a valid Twilio account",
bounds="required minmax:10:50",
display_name="Twilio Authentication Token",
)
AddOnCfg["gensms"]["parameters"]["to_number"] = CreateAddOnParam(
ConfigFiles[GENSMS_CONFIG].ReadValue(
"to_number", return_type=str, default=""
),
"string",
"Mobile number to send SMS message to. This can be any mobile number. Separate multilpe recipients with commas.",
bounds="required InternationalPhone",
display_name="Recipient Phone Number",
)
AddOnCfg["gensms"]["parameters"]["from_number"] = CreateAddOnParam(
ConfigFiles[GENSMS_CONFIG].ReadValue(
"from_number", return_type=str, default=""
),
"string",
"Number to send SMS message from. This should be a twilio phone number.",
bounds="required InternationalPhone",
display_name="Twilio Phone Number",
)
AddOnCfg = AddNotificationAddOnParam(AddOnCfg, "gensms", GENSMS_CONFIG)
AddOnCfg = AddRetryAddOnParam(AddOnCfg, "gensms", GENSMS_CONFIG)
# GENSMS_VOIP
Description = "SMS Support vis VoIP using voip.ms"
try:
import voipms
except Exception as e1:
Description = (
Description
+ "<br/><font color='red'>The required libraries for this add on are not installed, please run the installation script.</font>"
)
AddOnCfg["gensms_voip"] = collections.OrderedDict()
AddOnCfg["gensms_voip"]["enable"] = ConfigFiles[GENLOADER_CONFIG].ReadValue(
"enable", return_type=bool, section="gensms_voip", default=False
)
AddOnCfg["gensms_voip"]["title"] = "SMS via VoIP using voip.ms"
AddOnCfg["gensms_voip"]["description"] = Description
AddOnCfg["gensms_voip"]["icon"] = "voipms"
AddOnCfg["gensms_voip"][
"url"
] = "https://github.com/jgyates/genmon/wiki/1----Software-Overview#gensms_voippy-optional"
AddOnCfg["gensms_voip"]["parameters"] = collections.OrderedDict()
AddOnCfg["gensms_voip"]["parameters"]["username"] = CreateAddOnParam(
ConfigFiles[GENSMS_VOIP_CONFIG].ReadValue(
"username", return_type=str, default=""
),
"string",
"Voip.ms account username",
bounds="required minmax:5:50",
display_name="VoIP.ms User Name",
)
AddOnCfg["gensms_voip"]["parameters"]["password"] = CreateAddOnParam(
ConfigFiles[GENSMS_VOIP_CONFIG].ReadValue(
"password", return_type=str, default=""
),
"password",
"VoIP.ms API password. This is NOT the account login, but rather then API password",
bounds="required minmax:8:50",
display_name="VoIP.ms API password",
)
AddOnCfg["gensms_voip"]["parameters"]["did"] = CreateAddOnParam(
ConfigFiles[GENSMS_VOIP_CONFIG].ReadValue(
"did", return_type=str, default=""
),
"string",
"DID number for your voip.ms account to send the SMS.",
bounds="required InternationalPhone",
display_name="Sender DID Number",
)
AddOnCfg["gensms_voip"]["parameters"]["destination"] = CreateAddOnParam(
ConfigFiles[GENSMS_VOIP_CONFIG].ReadValue(
"destination", return_type=str, default=""
),
"string",
"Mobile number to send SMS message to. This can be any mobile number. Separate multilpe recipients with commas.",
bounds="required InternationalPhone",
display_name="Recipient Phone Number",
)
# GENSMS_MODEM
AddOnCfg["gensms_modem"] = collections.OrderedDict()
AddOnCfg["gensms_modem"]["enable"] = ConfigFiles[GENLOADER_CONFIG].ReadValue(
"enable", return_type=bool, section="gensms_modem", default=False
)
AddOnCfg["gensms_modem"]["title"] = "Notifications via SMS - LTE Hat"
AddOnCfg["gensms_modem"][
"description"
] = "Send Genmon and utility state changes via cellular SMS (additional hardware required)"
AddOnCfg["gensms_modem"]["icon"] = "sms"
AddOnCfg["gensms_modem"][
"url"
] = "https://github.com/jgyates/genmon/wiki/1----Software-Overview#gensms_modempy-optional"
AddOnCfg["gensms_modem"]["parameters"] = collections.OrderedDict()
AddOnCfg["gensms_modem"]["parameters"]["recipient"] = CreateAddOnParam(
ConfigFiles[MYMODEM_CONFIG].ReadValue(
"recipient", return_type=str, default=""
),
"string",
"Mobile number to send SMS message. This can be any mobile number. No dashes or spaces.",