forked from jgyates/genmon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
genmon.py
1702 lines (1480 loc) · 66.3 KB
/
genmon.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 python
# -------------------------------------------------------------------------------
# FILE: genmon.py
# PURPOSE: Monitor for Generator
#
# AUTHOR: Jason G Yates
# DATE: 05-Oct-2016
# 23-Apr-2018
#
# MODIFICATIONS:
# -------------------------------------------------------------------------------
from __future__ import ( # For python 3.x compatibility with print function
print_function,
)
import collections
import datetime
import getopt
import json
import os
import signal
import socket
import sys
import threading
import time
try:
from genmonlib.custom_controller import CustomController
from genmonlib.generac_evolution import Evolution
from genmonlib.generac_HPanel import HPanel
from genmonlib.generac_powerzone import PowerZone
from genmonlib.myconfig import MyConfig
from genmonlib.mylog import SetupLogger
from genmonlib.mymail import MyMail
from genmonlib.mypipe import MyPipe
from genmonlib.myplatform import MyPlatform
from genmonlib.mysupport import MySupport
from genmonlib.mythread import MyThread
from genmonlib.myweather import MyWeather
from genmonlib.program_defaults import ProgramDefaults
except Exception as e1:
print(
"\n\nThis program requires the modules located in the genmonlib directory in the github repository.\n"
)
print(
"Please see the project documentation at https://github.com/jgyates/genmon.\n"
)
print("Error: " + str(e1))
sys.exit(2)
# ------------ Monitor class ----------------------------------------------------
class Monitor(MySupport):
def __init__(self, ConfigFilePath=ProgramDefaults.ConfPath):
super(Monitor, self).__init__()
self.ProgramName = "Generator Monitor"
self.Version = "Unknown"
self.log = None
self.IsStopping = False
self.ProgramComplete = False
if ConfigFilePath == None or ConfigFilePath == "":
self.ConfigFilePath = ProgramDefaults.ConfPath
else:
self.ConfigFilePath = ConfigFilePath
self.ConnectionList = [] # list of incoming connections for heartbeat
# defautl values
self.SiteName = "Home"
self.ServerSocket = None
self.ServerIPAddress = ""
# server socket for nagios heartbeat and command/status
self.ServerSocketPort = ProgramDefaults.ServerPort
self.IncomingEmailFolder = "Generator"
self.ProcessedEmailFolder = "Generator/Processed"
self.FeedbackLogFile = os.path.join(self.ConfigFilePath, "feedback.json")
self.LogLocation = ProgramDefaults.LogPath
self.LastLogFileSize = 0
self.NumberOfLogSizeErrors = 0
# set defaults for optional parameters
self.NewInstall = False # True if newly installed or newly upgraded version
# True if sending autoated feedback on missing information
self.FeedbackEnabled = False
self.FeedbackMessages = {}
self.MailInit = False # set to true once mail is init
# Flag to let the heartbeat thread know we are communicating
self.CommunicationsActive = False
self.Controller = None
self.ControllerSelected = None
self.bDisablePlatformStats = False
self.ReadOnlyEmailCommands = False
self.SlowCPUOptimization = False
# weather parameters
self.WeatherAPIKey = None
self.WeatherLocation = None
self.UseMetric = False
self.WeatherMinimum = True
self.DisableWeather = False
self.MyWeather = None
self.UpdateAvailable = False
self.UpdateVersion = None
# Time Sync Related Data
self.bSyncTime = False # Sync gen to system time
self.bSyncDST = False # sync time at DST change
self.bDST = False # Daylight Savings Time active if True
# simulation
self.Simulation = False
self.SimulationFile = None
self.console = SetupLogger("genmon_console", log_file="", stream=True)
if not MySupport.PermissionsOK():
self.LogConsole(
"You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'."
)
sys.exit(1)
if not os.path.isfile(os.path.join(self.ConfigFilePath, "genmon.conf")):
self.LogConsole(
"Missing config file : "
+ os.path.join(self.ConfigFilePath, "genmon.conf")
)
sys.exit(1)
if not os.path.isfile(os.path.join(self.ConfigFilePath, "mymail.conf")):
self.LogConsole(
"Missing config file : "
+ os.path.join(self.ConfigFilePath, "mymail.conf")
)
sys.exit(1)
self.config = MyConfig(
filename=os.path.join(self.ConfigFilePath, "genmon.conf"),
section="GenMon",
log=self.console,
)
# read config file
if not self.GetConfig():
self.LogConsole("Failure in Monitor GetConfig")
sys.exit(1)
# log errors in this module to a file
self.log = SetupLogger("genmon", os.path.join(self.LogLocation, "genmon.log"))
self.config.log = self.log
if self.IsLoaded(): # this checks based on the port used for the API
self.LogConsole("ERROR: genmon.py is already loaded.")
self.LogError("ERROR: genmon.py is already loaded.")
sys.exit(1)
# this check is based on the file name.
if MySupport.IsRunning(
os.path.basename(__file__), multi_instance=self.multi_instance
):
self.LogConsole("ERROR: genmon.py is already loaded.")
self.LogError("ERROR: genmon.py is already loaded (2).")
sys.exit(1)
if self.NewInstall:
self.LogError(
"New version detected: Old = %s, New = %s"
% (self.Version, ProgramDefaults.GENMON_VERSION)
)
self.Version = ProgramDefaults.GENMON_VERSION
self.ProgramStartTime = datetime.datetime.now() # used for com metrics
# this will wait one day for an update, change to
# datetime.datetime(1, 1, 1, 0, 0) to check immediately on load
self.LastSoftwareUpdateCheck = datetime.datetime.now()
signal.signal(signal.SIGTERM, self.SignalClose)
signal.signal(signal.SIGINT, self.SignalClose)
# this allows the genmon socket interface to be intercepted and
# triggered for actions like GPIO, etc with interfering with
# updates via the main github repository. If genmonext.py exists, load it
self.genmonext = None
if os.path.isfile(
os.path.join(os.path.dirname(os.path.realpath(__file__)), "genmonext.py")
):
import genmonext
self.genmonext = genmonext.GenmonExt(log=self.log)
# start thread to accept incoming sockets for nagios heartbeat and command / status clients
self.Threads["InterfaceServerThread"] = MyThread(
self.InterfaceServerThread, Name="InterfaceServerThread"
)
try:
# init mail, start processing incoming email
self.mail = MyMail(
monitor=True,
incoming_folder=self.IncomingEmailFolder,
processed_folder=self.ProcessedEmailFolder,
incoming_callback=self.ProcessCommand,
loglocation=self.LogLocation,
ConfigFilePath=ConfigFilePath,
)
self.Threads = self.MergeDicts(self.Threads, self.mail.Threads)
self.MailInit = True
except Exception as e1:
self.LogErrorLine("Error loading mail support: " + str(e1))
sys.exit(1)
self.FeedbackPipe = MyPipe(
"Feedback",
self.FeedbackReceiver,
log=self.log,
debug = self.debug,
ConfigFilePath=self.ConfigFilePath,
)
self.Threads = self.MergeDicts(self.Threads, self.FeedbackPipe.Threads)
self.MessagePipe = MyPipe(
"Message",
self.MessageReceiver,
log=self.log,
debug = self.debug,
nullpipe=self.mail.DisableSNMP,
ConfigFilePath=self.ConfigFilePath,
)
self.Threads = self.MergeDicts(self.Threads, self.MessagePipe.Threads)
try:
# Starting device connection
if self.Simulation:
self.LogError("Simulation Running")
if not self.ControllerSelected == None and len(self.ControllerSelected):
self.LogError("Selected Controller: " + str(self.ControllerSelected))
else:
self.ControllerSelected = "generac_evo_nexus"
if self.ControllerSelected.lower() == "h_100":
self.Controller = HPanel(
self.log,
newinstall=self.NewInstall,
simulation=self.Simulation,
simulationfile=self.SimulationFile,
message=self.MessagePipe,
feedback=self.FeedbackPipe,
config=self.config,
)
elif self.ControllerSelected.lower() == "powerzone":
self.Controller = PowerZone(
self.log,
newinstall=self.NewInstall,
simulation=self.Simulation,
simulationfile=self.SimulationFile,
message=self.MessagePipe,
feedback=self.FeedbackPipe,
config=self.config,
)
elif self.ControllerSelected.lower() == "custom":
self.Controller = CustomController(
self.log,
newinstall=self.NewInstall,
simulation=self.Simulation,
simulationfile=self.SimulationFile,
message=self.MessagePipe,
feedback=self.FeedbackPipe,
config=self.config,
)
else:
self.Controller = Evolution(
self.log,
self.NewInstall,
simulation=self.Simulation,
simulationfile=self.SimulationFile,
message=self.MessagePipe,
feedback=self.FeedbackPipe,
config=self.config,
)
self.Threads = self.MergeDicts(self.Threads, self.Controller.Threads)
except Exception as e1:
self.LogErrorLine("Error opening controller device: " + str(e1))
sys.exit(1)
self.StartThreads()
self.ProcessFeedbackInfo()
# send mail to tell we are starting
IP = self.GetNetworkIp()
self.MessagePipe.SendMessage(
"Generator Monitor Starting at " + self.SiteName,
"Generator Monitor Starting at "
+ self.SiteName
+ " using IP address "
+ IP,
msgtype="info",
)
self.LogError(
"GenMon Loaded for site: "
+ self.SiteName
+ " using python "
+ str(sys.version_info.major)
+ "."
+ str(sys.version_info.minor)
+ ": VEnv: "
+ str(self.InVirtualEnvironment())
)
# ------------------------ Monitor::StartThreads----------------------------
def StartThreads(self, reload=False):
try:
# start thread to accept incoming sockets for nagios heartbeat
self.Threads["ComWatchDog"] = MyThread(self.ComWatchDog, Name="ComWatchDog")
if self.bSyncDST or self.bSyncTime: # Sync time thread
self.Threads["TimeSyncThread"] = MyThread(
self.TimeSyncThread, Name="TimeSyncThread"
)
if (
not self.DisableWeather
and not self.WeatherAPIKey == None
and len(self.WeatherAPIKey)
and not self.WeatherLocation == None
and len(self.WeatherLocation)
):
Unit = "metric" if self.UseMetric else "imperial"
self.MyWeather = MyWeather(
self.WeatherAPIKey,
location=self.WeatherLocation,
unit=Unit,
log=self.log,
)
self.Threads = self.MergeDicts(self.Threads, self.MyWeather.Threads)
except Exception as e1:
self.LogErrorLine("Error in StartThreads: " + str(e1))
# -------------------- Monitor::GetConfig-----------------------------------
def GetConfig(self):
try:
if self.config.HasOption("sitename"):
self.SiteName = self.config.ReadValue("sitename")
self.debug = self.config.ReadValue("debug", return_type=bool, default=False)
self.multi_instance = self.config.ReadValue(
"multi_instance", return_type=bool, default=False
)
if self.config.HasOption("incoming_mail_folder"):
self.IncomingEmailFolder = self.config.ReadValue(
"incoming_mail_folder"
) # imap folder for incoming mail
if self.config.HasOption("processed_mail_folder"):
self.ProcessedEmailFolder = self.config.ReadValue(
"processed_mail_folder"
) # imap folder for processed mail
# server_port, must match value in myclient.py and check_monitor_system.py and any calling client apps
if self.config.HasOption("server_port"):
self.ServerSocketPort = self.config.ReadValue(
"server_port", return_type=int
)
self.ServerIPAddress = self.config.ReadValue("genmon_server_address", default = "")
self.LogLocation = self.config.ReadValue(
"loglocation", default=ProgramDefaults.LogPath
)
self.UserDefinedDataPath = self.config.ReadValue(
"userdatalocation", default=os.path.dirname(os.path.realpath(__file__))
)
if self.config.HasOption("syncdst"):
self.bSyncDST = self.config.ReadValue("syncdst", return_type=bool)
if self.config.HasOption("synctime"):
self.bSyncTime = self.config.ReadValue("synctime", return_type=bool)
if self.config.HasOption("disableplatformstats"):
self.bDisablePlatformStats = self.config.ReadValue(
"disableplatformstats", return_type=bool
)
if self.config.HasOption("simulation"):
self.Simulation = self.config.ReadValue("simulation", return_type=bool)
if self.config.HasOption("simulationfile"):
self.SimulationFile = self.config.ReadValue("simulationfile")
if self.config.HasOption("controllertype"):
self.ControllerSelected = self.config.ReadValue("controllertype")
if self.config.HasOption("disableweather"):
self.DisableWeather = self.config.ReadValue(
"disableweather", return_type=bool
)
else:
self.DisableWeather = False
if self.config.HasOption("weatherkey"):
self.WeatherAPIKey = self.config.ReadValue("weatherkey")
if self.config.HasOption("weatherlocation"):
self.WeatherLocation = self.config.ReadValue("weatherlocation")
if self.config.HasOption("metricweather"):
self.UseMetric = self.config.ReadValue(
"metricweather", return_type=bool
)
if self.config.HasOption("minimumweatherinfo"):
self.WeatherMinimum = self.config.ReadValue(
"minimumweatherinfo", return_type=bool
)
if self.config.HasOption("readonlyemailcommands"):
self.ReadOnlyEmailCommands = self.config.ReadValue(
"readonlyemailcommands", return_type=bool
)
if self.config.HasOption("optimizeforslowercpu"):
self.SlowCPUOptimization = self.config.ReadValue(
"optimizeforslowercpu", return_type=bool
)
self.AdditionalWatchdogTime = self.config.ReadValue(
"watchdog_addition", return_type=int, default=0
)
if self.config.HasOption("version"):
self.Version = self.config.ReadValue("version")
if not self.Version == ProgramDefaults.GENMON_VERSION:
self.config.WriteValue("version", ProgramDefaults.GENMON_VERSION)
self.NewInstall = True
else:
self.config.WriteValue("version", ProgramDefaults.GENMON_VERSION)
self.NewInstall = True
self.Version = ProgramDefaults.GENMON_VERSION
self.config.WriteValue("install", str(datetime.datetime.now()))
if not self.config.HasOption("install"):
try:
stat = os.stat(self.config.FileName)
self.config.WriteValue("install", str(datetime.datetime.fromtimestamp(stat.st_atime)))
except:
self.config.WriteValue("install", "Unknown")
self.InstallTime = self.config.ReadValue("install", default = "Unknown")
if self.config.HasOption("autofeedback"):
self.FeedbackEnabled = self.config.ReadValue(
"autofeedback", return_type=bool
)
else:
self.config.WriteValue("autofeedback", "False")
self.FeedbackEnabled = False
# Load saved feedback log if log is present
if os.path.isfile(self.FeedbackLogFile):
try:
with open(self.FeedbackLogFile) as infile:
self.FeedbackMessages = json.load(infile)
except Exception as e1:
os.remove(self.FeedbackLogFile)
self.UpdateCheck = self.config.ReadValue(
"update_check", return_type=bool, default=True
)
self.UserURL = self.config.ReadValue("user_url", default="").strip()
except Exception as e1:
self.Console(
"Missing config file or config file entries (genmon): " + str(e1)
)
return False
return True
# ---------------------------------------------------------------------------
def ProcessFeedbackInfo(self):
try:
if self.FeedbackEnabled:
for Key, Entry in self.FeedbackMessages.items():
self.MessagePipe.SendMessage(
"Generator Monitor Submission",
Entry,
recipient=self.MaintainerAddress,
files=self.GetLogFileNames(),
msgtype="error",
)
# delete unsent Messages
if os.path.isfile(self.FeedbackLogFile):
os.remove(self.FeedbackLogFile)
except Exception as e1:
self.LogErrorLine("Error in ProcessFeedbackInfo: " + str(e1))
# ---------------------------------------------------------------------------
def FeedbackReceiver(self, Message):
try:
FeedbackDict = {}
FeedbackDict = json.loads(Message)
self.SendFeedbackInfo(
FeedbackDict["Reason"],
Always=FeedbackDict["Always"],
Message=FeedbackDict["Message"],
FullLogs=FeedbackDict["FullLogs"],
NoCheck=FeedbackDict["NoCheck"],
)
except Exception as e1:
self.LogErrorLine("Error in FeedbackReceiver: " + str(e1))
self.LogError("Size : " + str(len(Message)))
self.LogError("Message : " + str(Message))
# ---------------------------------------------------------------------------
def MessageReceiver(self, Message):
try:
MessageDict = {}
MessageDict = json.loads(Message)
self.mail.sendEmail(
MessageDict["subjectstr"],
MessageDict["msgstr"],
recipient=MessageDict["recipient"],
files=MessageDict["files"],
deletefile=MessageDict["deletefile"],
msgtype=MessageDict["msgtype"],
)
except Exception as e1:
self.LogErrorLine("Error in MessageReceiver: " + str(e1))
# ---------------------------------------------------------------------------
def SendFeedbackInfo(
self, Reason, Always=False, Message=None, FullLogs=True, NoCheck=False
):
try:
if self.NewInstall or Always:
CheckedSent = self.FeedbackMessages.get(Reason, "")
if not CheckedSent == "" and not NoCheck:
return
if not NoCheck:
self.LogError(Reason + " : " + Message)
msgbody = "Reason = " + Reason + "\n"
if Message != None:
msgbody += "Message : " + Message + "\n"
msgbody += self.printToString(
self.ProcessDispatch(self.GetStartInfo(NoTile=True), "")
)
if not self.bDisablePlatformStats:
msgbody += self.printToString(
self.ProcessDispatch(
{"Platform Stats": self.GetPlatformStats()}, ""
)
)
msgbody += self.printToString(
self.ProcessDispatch(
{"Comm Stats": self.Controller.GetCommStatus()}, ""
)
)
msgbody += "\n" + self.GetSupportData() + "\n"
if self.FeedbackEnabled:
self.MessagePipe.SendMessage(
"Generator Monitor Submission",
msgbody,
recipient=self.MaintainerAddress,
files=self.GetLogFileNames(),
msgtype="error",
)
self.FeedbackMessages[Reason] = msgbody
# if feedback not enabled, save the log to file
if not self.FeedbackEnabled:
with open(self.FeedbackLogFile, "w") as outfile:
json.dump(
self.FeedbackMessages,
outfile,
sort_keys=True,
indent=4,
ensure_ascii=False,
)
except Exception as e1:
self.LogErrorLine("Error in SendFeedbackInfo: " + str(e1))
# ---------- Monitor::EmailSendIsEnabled-------------------------------------
def EmailSendIsEnabled(self):
EmailThread = self.Threads.get("SendMailThread", None)
if EmailThread == None:
return False
return True
# ---------- Monitor::GetSupportData-----------------------------------------
def GetSupportData(self):
SupportData = collections.OrderedDict()
try:
SupportData["Program Run Time"] = self.GetProgramRunTime()
SupportData["Install"] = self.InstallTime
SupportData["Monitor Health"] = self.GetSystemHealth()
SupportData["Controller Selected"] = self.ControllerSelected.lower()
SupportData["StartInfo"] = self.GetStartInfo(NoTile=True)
SupportData["Comm Stats"] = self.Controller.GetCommStatus()
if not self.bDisablePlatformStats:
SupportData["PlatformStats"] = self.GetPlatformStats()
#SupportData["Data"] = self.Controller.DisplayRegisters(AllRegs=True, DictOut=True)
# Raw Modbus data
SupportData["Holding"] = self.Controller.Holding
SupportData["Strings"] = self.Controller.Strings
SupportData["FileData"] = self.Controller.FileData
SupportData["Coils"] = self.Controller.Coils
SupportData["Inputs"] = self.Controller.Inputs
except Exception as e1:
self.LogErrorLine("Error in GetSupportData: " + str(e1))
try:
# indent 4 will keep some mail servers from having problems.
return json.dumps(SupportData, indent=4, sort_keys=False)
except Exception as e1:
self.LogErrorLine("Error in GetSupportData (2): " + str(e1))
return "Error Getting JSON data: " + str(e1)
# ---------- Monitor::GetLogFileNames----------------------------------------
def GetLogFileNames(self):
try:
LogList = []
FilesToSend = [
"genmon.log",
"genserv.log",
"mymail.log",
"myserial.log",
"mymodbus.log",
"gengpio.log",
"gengpioin.log",
"gensms.log",
"gensms_modem.log",
"genmqtt.log",
"genmqttin.log",
"genpushover.log",
"gensyslog.log",
"genloader.log",
"myserialtcp.log",
"genlog.log",
"genslack.log",
"gencallmebot.log",
"genexercise.log",
"genemail2sms.log",
"gentankutil.log",
"genalexa.log",
"gensnmp.log",
"gentemp.log",
"gentankdiy.log",
"gengpioledblink.log",
"gencthat.log",
"genmopeka.log",
"gencustomgpio.log",
"gensms_voip.log",
]
DataFilesToSend = [
"update.txt" # time stamp of software update
]
# Files in /var/log
for File in FilesToSend:
LogFile = self.LogLocation + File
if os.path.isfile(LogFile):
LogList.append(LogFile)
# Non settings realated files in conf folder (typically /etc/genmon)
for File in DataFilesToSend:
LogFile = self.ConfigFilePath + File
if os.path.isfile(LogFile):
LogList.append(LogFile)
return LogList
except Exception as e1:
return None
# ---------- Monitor::SendSupportInfo----------------------------------------
def SendSupportInfo(self, SendLogs=True):
try:
if not self.EmailSendIsEnabled():
self.LogError("Error in SendSupportInfo: send email is not enabled")
return "Send Email is not enabled."
msgbody = ""
msgbody += self.printToString(
self.ProcessDispatch(self.GetStartInfo(NoTile=True), "")
)
if not self.bDisablePlatformStats:
msgbody += self.printToString(
self.ProcessDispatch(
{"Platform Stats": self.GetPlatformStats()}, ""
)
)
msgbody += self.printToString(
self.ProcessDispatch(
{"Comm Stats": self.Controller.GetCommStatus()}, ""
)
)
#msgbody += self.Controller.DisplayRegisters(AllRegs=True)
# get data in JSON format
msgbody += "\n" + self.GetSupportData() + "\n"
msgtitle = "Generator Monitor Log File Submission"
if SendLogs == True:
LogList = self.GetLogFileNames()
else:
msgtitle = "Generator Monitor Register Submission"
LogList = None
self.MessagePipe.SendMessage(
msgtitle,
msgbody,
recipient=self.MaintainerAddress,
files=LogList,
msgtype="error",
)
return "Log files submitted"
except Exception as e1:
self.LogErrorLine("Error in SendSupportInfo: " + str(e1))
# ---------- Send message ---------------------------------------------------
def SendMessage(self, CmdString):
try:
self.LogDebug("ENTER SendMessage")
if CmdString == None or CmdString == "":
return "Error: invalid command in SendMessage"
CmdList = CmdString.split("=")
if len(CmdList) != 2:
self.LogError(
"Validation Error: Error parsing command string in SendMessage (parse): "
+ CmdString
)
return "Error in SendMessage"
data = json.loads(CmdList[1])
msgtitle = self.SiteName + ": " + data["title"]
if not "onlyonce" in data:
onlyonce = False
else:
onlyonce = data["onlyonce"]
if not "oncedaily" in data:
oncedaily = False
else:
oncedaily = data["oncedaily"]
self.LogDebug("SENDMSG:" + str(data))
self.MessagePipe.SendMessage(
msgtitle, data["body"], msgtype=data["type"], onlyonce=onlyonce, oncedaily=oncedaily
)
return "OK"
except Exception as e1:
self.LogErrorLine("Error in SendMessage: " + str(e1))
return "OK"
# ---------- process command from email and socket --------------------------
def ProcessCommand(self, command, fromsocket=False):
LocalError = False
if isinstance(command, bytes):
command = command.decode("utf-8")
try:
msgsubject = "Genmon Command Response at " + self.SiteName
if not fromsocket:
msgbody = "\n"
else:
msgbody = ""
if (len(command)) == 0:
msgsubject = "Error in Genmon Command (Lenght is zero)"
msgbody += "Invalid GENERATOR command: zero length command."
LocalError = True
if not LocalError:
if not command.lower().startswith("generator:"):
msgsubject = "Error in Genmon Command (command prefix)"
msgbody += 'Invalid GENERATOR command: all commands must be prefixed by "generator: "'
LocalError = True
if LocalError:
if not fromsocket:
self.MessagePipe.SendMessage(msgsubject, msgbody, msgtype="error")
return "" # ignored by email module
else:
msgbody += "EndOfMessage"
return msgbody
if self.genmonext != None:
try:
self.genmonext.PreProcessCommand(command)
except Exception as e1:
self.LogErrorLine("Error Calling GenmonExt:PreProcessCommand: " + str(e1))
if command.lower().startswith("generator:"):
command = command[len("generator:") :]
CommandDict = {
"registers": [self.Controller.DisplayRegisters,(False,),False,], # display registers
"allregs": [self.Controller.DisplayRegisters,(True,),False,], # display registers
"logs": [self.Controller.DisplayLogs, (True, False), False],
"status": [self.Controller.DisplayStatus,(),False,], # display decoded generator info
"maint": [self.Controller.DisplayMaintenance, (), False],
"monitor": [self.DisplayMonitor, (), False],
"outage": [self.Controller.DisplayOutage, (), False],
"settime": [self.StartTimeThread, (), False], # set time and date
"setexercise": [self.Controller.SetGeneratorExerciseTime,(command.lower(),),False,],
"setquiet": [self.Controller.SetGeneratorQuietMode,(command.lower(),),False,],
"setremote": [
self.Controller.SetGeneratorRemoteCommand,
(command.lower(),),
False,
],
"testcommand": [self.Controller.TestCommand, (command.lower(),), False],
"network_status": [self.InternetConnected, (), False],
"help": [self.DisplayHelp, (), False], # display help screen
## These commands are used by the web / socket interface only
"power_log_json": [
self.Controller.GetPowerHistory,
(command.lower(),),
True,
],
"power_log_clear": [self.Controller.ClearPowerLog, (), True],
"fuel_log_clear": [self.Controller.ClearFuelLog, (), True],
"start_info_json": [self.GetStartInfo, (), True],
"registers_json": [
self.Controller.DisplayRegisters,
(False, True),
True,
], # display registers
"allregs_json": [
self.Controller.DisplayRegisters,
(True, True),
True,
], # display registers
"logs_json": [self.Controller.DisplayLogs, (True, True), True],
"status_json": [self.Controller.DisplayStatus, (True,), True],
"status_num_json": [self.Controller.DisplayStatus, (True, True), True],
"maint_json": [self.Controller.DisplayMaintenance, (True,), True],
"maint_num_json": [self.Controller.DisplayMaintenance, (True, True), True],
"monitor_json": [self.DisplayMonitor, (True,), True],
"monitor_num_json": [self.DisplayMonitor, (True, True), True],
"weather_json": [self.DisplayWeather, (True,), True],
"outage_json": [self.Controller.DisplayOutage, (True,), True],
"outage_num_json": [self.Controller.DisplayOutage, (True, True), True],
"gui_status_json": [self.GetStatusForGUI, (), True],
"get_maint_log_json": [self.Controller.GetMaintLogJSON, (), True],
"add_maint_log": [
self.Controller.AddEntryToMaintLog,
(command,),
True,
], # Do not do command.lower() since this input is JSON
"delete_row_maint_log": [
self.Controller.DeleteMaintLogRow,
(command.lower(),),
True,
],
"edit_row_maint_log": [
self.Controller.EditMaintLogRow,
(command,),
True,
], # Do not do command.lower() since this input is JSON
"clear_maint_log": [self.Controller.ClearMaintLog, (), True],
"getsitename": [self.GetSiteName, (), True],
"getbase": [
self.Controller.GetBaseStatus,
(),
True,
], # (UI changes color based on exercise, running , ready status)
"gethealth": [self.GetSystemHealth, (), True],
"getregvalue": [
self.Controller.GetRegValue,
(command.lower(),),
True,
], # only used for debug purposes, read a cached register value
"readregvalue": [
self.Controller.ReadRegValue,
(command.lower(),),
True,
], # only used for debug purposes, Read Register Non Cached
# only used for debug purposes, Read Register Non Cached
"writeregvalue": [self.Controller.WriteRegValue,(command.lower(),),True,],
# only used for debug purposes. If a thread crashes it tells you the thread name
"getdebug": [self.GetDeadThreadName,(),True,],
"sendregisters": [self.SendSupportInfo, (False,), True],
"sendlogfiles": [self.SendSupportInfo, (True,), True],
"support_data_json": [self.GetSupportData, (), True],
"set_tank_data": [self.Controller.SetExternalTankData, (command,), True],
"set_sensor_data": [self.Controller.SetExternalSensorData,(command,),True,],
"set_external_gauge_data": [self.Controller.SetExternalGaugeData,(command,),True,],
"set_power_data": [self.Controller.SetExternalCTData, (command,), True],
"notify_message": [self.SendMessage, (command,), True],
"getreglabels_json": [self.Controller.GetRegisterLabels, (), True],
"set_button_command": [self.Controller.SetCommandButton, (command,), True]
}
CommandList = command.split(" ")
except Exception as e1:
msgbody = "Error in ProcessCommand: " + str(e1)
msgbody += "EndOfMessage"
return msgbody
ValidCommand = False
try:
for item in CommandList:
if not len(item):
continue
item = item.strip()
LookUp = item
if "=" in item:
BaseCmd = item.split("=")
LookUp = BaseCmd[0]
# check if we disallow write commands via email
if (
self.ReadOnlyEmailCommands
and not fromsocket
and LookUp in ["settime", "setexercise", "setquiet", "setremote"]
):
continue
ExecList = CommandDict.get(LookUp.lower(), None)
if ExecList == None:
continue
if ExecList[0] == None:
continue
if not fromsocket and ExecList[2]:
continue
# Execute Command
ReturnMessage = ExecList[0](*ExecList[1])
ValidCommand = True
if LookUp.lower().endswith("_json") and not isinstance(
ReturnMessage, str
):
msgbody += json.dumps(ReturnMessage, sort_keys=False)
else:
msgbody += ReturnMessage
if not fromsocket:
msgbody += "\n"
except Exception as e1:
self.LogErrorLine("Error Processing Commands: " + command + ": " + str(e1))
if not ValidCommand:
msgbody += "No valid command recognized."
if not fromsocket:
self.MessagePipe.SendMessage(msgsubject, msgbody, msgtype="warn")
return "" # ignored by email module
else:
msgbody += "EndOfMessage"
return msgbody
# ------------ Monitor::DisplayHelp -----------------------------------------
def DisplayHelp(self):
outstring = ""
outstring += "Help:\n"
outstring += self.printToString("\nCommands:")
outstring += self.printToString(
" status - display engine and line information"
)
outstring += self.printToString(
" maint - display maintenance and service information"
)
outstring += self.printToString(
" outage - display current and last outage (since program launched)"
)
outstring += self.printToString(
" info, also shows utility min and max values"
)
outstring += self.printToString(
" monitor - display communication statistics and monitor health"
)
outstring += self.printToString(
" logs - display all alarm, on/off, and maintenance logs"
)
outstring += self.printToString(
" registers - display contents of registers being monitored"
)
outstring += self.printToString(
" settime - set generator time to system time"
)
outstring += self.printToString(
" setexercise - set the exercise time of the generator. "
)
outstring += self.printToString(
" i.e. setexercise=Monday,13:30,Weekly"
)
outstring += self.printToString(