forked from jgyates/genmon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenmon.py
4685 lines (3815 loc) · 198 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 MODBUS port on Generac Generator
#
# AUTHOR: Jason G Yates
# DATE: 05-Oct-2016
#
# MODIFICATIONS:
#------------------------------------------------------------
## Notes:
# Pin 8 (white) appears to be TX from Controller
# Pin 7 (black) appears to be TX from mobile link
# http://modbus.rapidscada.net/
from __future__ import print_function # For python 3.x compatibility with print function
import datetime, time, sys, smtplib, signal, os, threading, socket
import atexit, json, collections, random
import httplib, re
try:
from ConfigParser import RawConfigParser
except ImportError as e:
from configparser import RawConfigParser
from genmonlib import myserial, mymail, mylog, mythread, mymodbus
GENMON_VERSION = "V1.6.5"
#-------------------Generator specific const defines for Generator class
LOG_DEPTH = 50
START_LOG_STARTING_REG = 0x012c # the most current start log entry should be at this register
START_LOG_STRIDE = 4
START_LOG_END_REG = ((START_LOG_STARTING_REG + (START_LOG_STRIDE * LOG_DEPTH)) - START_LOG_STRIDE)
ALARM_LOG_STARTING_REG = 0x03e8 # the most current alarm log entry should be at this register
ALARM_LOG_STRIDE = 5
ALARM_LOG_END_REG = ((ALARM_LOG_STARTING_REG + (ALARM_LOG_STRIDE * LOG_DEPTH)) - ALARM_LOG_STRIDE)
SERVICE_LOG_STARTING_REG= 0x04e2 # the most current service log entry should be at this register
SERVICE_LOG_STRIDE = 4
SERVICE_LOG_END_REG = ((SERVICE_LOG_STARTING_REG + (SERVICE_LOG_STRIDE * LOG_DEPTH)) - SERVICE_LOG_STRIDE)
# Register for Model number
MODEL_REG = 0x01f4
MODEL_REG_LENGTH = 5
NEXUS_ALARM_LOG_STARTING_REG = 0x064
NEXUS_ALARM_LOG_STRIDE = 4
NEXUS_ALARM_LOG_END_REG = ((NEXUS_ALARM_LOG_STARTING_REG + (NEXUS_ALARM_LOG_STRIDE * LOG_DEPTH)) - NEXUS_ALARM_LOG_STRIDE)
DEFAULT_THRESHOLD_VOLTAGE = 143
DEFAULT_PICKUP_VOLTAGE = 190
#------------ GeneratorDevice class --------------------------------------------
class GeneratorDevice:
def __init__(self):
self.ProgramName = "Generator Monitor"
self.BaudRate = 9600 # data rate of the serial port (default 9600)
self.Registers = {} # dict for registers and values
self.RegistersUnderTest = {}# dict for registers we are testing
self.RegistersUnderTestData = ""
self.NotChanged = 0 # stats for registers
self.Changed = 0 # stats for registers
self.TotalChanged = 0.0 # ratio of changed ragisters
self.LastAlarmValue = 0xFF # Last Value of the Alarm Register
self.ConnectionList = [] # list of incoming connections for heartbeat
self.ServerSocket = 0 # server socket for nagios heartbeat and command/status
self.Threads = {} # Dict of mythread objects
self.GeneratorInAlarm = False # Flag to let the heartbeat thread know there is a problem
self.SystemInOutage = False # Flag to signal utility power is out
self.TransferActive = False # Flag to signal transfer switch is allowing gen supply power
self.CommunicationsActive = False # Flag to let the heartbeat thread know we are communicating
self.CommAccessLock = threading.RLock() # lock to synchronize access to the serial port comms
self.CheckForAlarmEvent = threading.Event() # Event to signal checking for alarm
self.UtilityVoltsMin = 0 # Minimum reported utility voltage above threshold
self.UtilityVoltsMax = 0 # Maximum reported utility voltage above pickup
self.MailInit = False # set to true once mail is init
self.InitComplete = False # set to true once init is complete
self.NewInstall = False # True if newly installed or newly upgraded version
self.FeedbackEnabled = False # True if sending autoated feedback on missing information
self.FeedbackMessages = {}
self.Version = "Unknown"
self.DaysOfWeek = { 0: "Sunday", # decode for register values with day of week
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday"}
self.MonthsOfYear = { 1: "January", # decode for register values with month
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December"}
# base registers and their length in bytes
# note: the lengths are in bytes. The request packet should be in words
# and due to the magic of python, we often deal with the response in string values
# dict format Register: [ Length in bytes: monitor change 0 - no, 1 = yes]
self.BaseRegisters = { # base registers read by master
"0000" : [2, 0], # possibly product line code (Nexus, EvoAQ, EvoLQ)
"0005" : [2, 0], # Exercise Time Hi Byte = Hour, Lo Byte = Min (Read Only) (Nexus, EvoAQ, EvoLQ)
"0006" : [2, 0], # Exercise Time Hi Byte = Day of Week 00=Sunday 01=Monday, Low Byte = 00=quiet=no, 01=yes (Nexus, EvoAQ, EvoLQ)
"0007" : [2, 0], # Engine RPM (Nexus, EvoAQ, EvoLQ)
"0008" : [2, 0], # Freq - value includes Hz to the tenths place i.e. 59.9 Hz (Nexus, EvoAQ, EvoLQ)
"000a" : [2, 0], # battery voltage Volts to tenths place i.e. 13.9V (Nexus, EvoAQ, EvoLQ)
"000b" : [2, 0], # engine run time hours High
"000c" : [2, 0], # engine run time hours Low
"000e" : [2, 0], # Read / Write: Generator Time Hi byte = hours, Lo byte = min (Nexus, EvoAQ, EvoLQ)
"000f" : [2, 0], # Read / Write: Generator Time Hi byte = month, Lo byte = day of the month (Nexus, EvoAQ, EvoLQ)
"0010" : [2, 0], # Read / Write: Generator Time = Hi byte Day of Week 00=Sunday 01=Monday, Lo byte = last 2 digits of year (Nexus, EvoAQ, EvoLQ)
"0011" : [2, 0], # Utility Threshold, ML Does not read this (Nexus, EvoAQ, EvoLQ) (possibly read / write)
"0012" : [2, 0], # Gen output voltage (Nexus, EvoAQ, EvoLQ)
"0019" : [2, 0], # Model ID register, (EvoAC, NexusAC)
"001a" : [2, 0], # Hours Until Service A
"001b" : [2, 0], # Date Service A Due
"001c" : [2, 0], # Service Info Hours (Nexus)
"001d" : [2, 0], # Service Info Date (Nexus)
"001e" : [2, 0], # Hours Until Service B
"001f" : [2, 0], # Hours util Service (NexusAC), Date Service Due (Evo)
"0020" : [2, 0], # Service Info Date (NexusAC)
"0021" : [2, 0], # Service Info Hours (NexusAC)
"0022" : [2, 0], # Service Info Date (NexusAC, EvoAC)
"002a" : [2, 0], # hardware (high byte) (Hardware V1.04 = 0x68) and firmware version (low byte) (Firmware V1.33 = 0x85) (Nexus, EvoAQ, EvoLQ)
"002b" : [2, 0], # Startup Delay (Evo AC)
"002c" : [2, 0], # Evo (Exercise Time) Exercise Time HH:MM
"002d" : [2, 0], # Evo AC (Weekly, Biweekly, Monthly)
"002e" : [2, 0], # Evo (Exercise Time) Exercise Day Sunday =0, Monday=1
"002f" : [2, 0], # Evo (Quiet Mode)
"0059" : [2, 0], # Set Voltage from Dealer Menu (not currently used)
"023b" : [2, 0], # Pick Up Voltage (Evo LQ only)
"023e" : [2, 0], # Exercise time duration (Evo LQ only)
"0054" : [2, 0], # Hours since generator activation (hours of protection) (Evo LQ only)
"005e" : [2, 0], # Total engine time in minutes High (EvoLC)
"005f" : [2, 0], # Total engine time in minutes Low (EvoLC)
"0057" : [2, 0], # Unknown Looks like some status bits (0002 to 0005 when engine starts, back to 0002 on stop)
"0055" : [2, 0], # Unknown
"0056" : [2, 0], # Unknown Looks like some status bits (0000 to 0003, back to 0000 on stop)
"005a" : [2, 0], # Unknown (zero except Nexus)
"000d" : [2, 0], # Bit changes when the controller is updating registers.
"003c" : [2, 0], # Raw RPM Sensor Data (Hall Sensor)
"0058" : [2, 0], # CT Sensor (EvoLC)
"005d" : [2, 0], # Unknown sensor 3, Moves between 0x55 - 0x58 continuously even when engine off
"05ed" : [2, 0], # Unknown sensor 4, changes between 35, 37, 39 (Ambient Temp Sensor) EvoLC
"05ee" : [2, 0], # Unknown sensor 5 (Battery Charging Sensor)
"05fa" : [2, 0], # Evo AC (Status?)
"0033" : [2, 0], # Evo AC (Status?)
"0034" : [2, 0], # Evo AC (Status?) Goes from FFFF 0000 00001 (Nexus and Evo AC)
"0032" : [2, 0], # Evo AC (Sensor?) starts 0x4000 ramps up to ~0x02f0
"0036" : [2, 0], # Evo AC (Sensor?) Unknown
"0037" : [2, 0], # CT Sensor (EvoAC)
"0038" : [2, 0], # Evo AC (Sensor?) FFFE, FFFF, 0001, 0002 random - not linear
"0039" : [2, 0], # Evo AC (Sensor?)
"003a" : [2, 0], # Evo AC (Sensor?) Nexus and Evo AC
"003b" : [2, 0], # Evo AC (Sensor?) Nexus and Evo AC
"0239" : [2, 0], # Startup Delay (Evo AC)
"0237" : [2, 0], # Set Voltage (Evo LC)
"0208" : [2, 0], # Calibrate Volts (Evo)
"005c" : [2, 0], # Unknown , possible model reg on EvoLC
"05f3" : [2, 0], # EvoAC, EvoLC, counter of some type
"05f4" : [2, 0], # Evo AC Current 1
"05f5" : [2, 0], # Evo AC Current 2
"05f6" : [2, 0], # Evo AC Current Cal 1
"05f7" : [2, 0], # Evo AC Current Cal 1
}
# registers that need updating more frequently than others to make things more responsive
self.PrimeRegisters = {
"0001" : [4, 0], # Alarm and status register
"0053" : [2, 0], # Evo LC Output relay status register (battery charging, transfer switch, Change at startup and stop
"0052" : [2, 0], # Evo LC Input status register (sensors) only tested on liquid cooled Evo
"0009" : [2, 0], # Utility voltage
"05f1" : [2, 0]} # Last Alarm Code
self.WriteRegisters = { # 0003 and 0004 are index registers, used to write exercise time and other unknown stuff (remote start, stop and transfer)
"002c" : 2, # Read / Write: Exercise Time HH:MM
"002e" : 2, # Read / Write: Exercise Day Sunday =0, Monday=1
"002f" : 2} # Read / Write: Exercise Quiet Mode=1 Not Quiet Mode = 0
self.REGLEN = 0
self.REGMONITOR = 1
self.Address = 0x9d
self.LogLocation = "/var/log/"
self.SiteName = "Home"
# set defaults for optional parameters
self.bDisplayOutput = False
self.bDisplayMonitor = False
self.bDisplayRegisters = False
self.bDisplayStatus = False
self.EnableDebug = False
self.bDisplayUnknownSensors = False
self.bDisplayMaintenance = False
self.bUseLegacyWrite = False
self.EvolutionController = None
self.LiquidCooled = None
# The values "Unknown" are checked to validate conf file items are found
self.FuelType = "Unknown"
self.NominalFreq = "Unknown"
self.NominalRPM = "Unknown"
self.NominalKW = "Unknown"
self.Model = "Unknown"
self.PowerLogMaxSize = 15 # 15 MB max size
self.PowerLog = os.path.dirname(os.path.realpath(__file__)) + "/kwlog.txt"
self.OutageLog = os.path.dirname(os.path.realpath(__file__)) + "/outage.txt"
self.FeedbackLogFile = os.path.dirname(os.path.realpath(__file__)) + "/feedback.json"
self.DisableOutageCheck = False
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
self.bEnhancedExerciseFrequency = False # True if controller supports biweekly and monthly exercise times
# read config file
if not self.GetConfig():
return None
# log errors in this module to a file
self.log = mylog.SetupLogger("genmon", self.LogLocation + "genmon.log")
if self.NewInstall:
self.LogError("New version detected: Old = %s, New = %s" % (self.Version, GENMON_VERSION))
self.Version = GENMON_VERSION
self.ProgramStartTime = datetime.datetime.now() # used for com metrics
self.OutageStartTime = self.ProgramStartTime # if these two are the same, no outage has occured
self.LastOutageDuration = self.OutageStartTime - self.OutageStartTime
atexit.register(self.Close)
try:
#Starting device connection
self.ModBus = mymodbus.ModbusProtocol(self.UpdateRegisterList, self.Address, self.SerialPort, self.BaudRate, loglocation = self.LogLocation)
self.Threads["SerialReadThread"] = self.ModBus.Slave.StartReadThread()
except Exception as e1:
self.FatalError("Error opening serial device: " + str(e1))
return None
# init mail, start processing incoming email
self.mail = mymail.MyMail(monitor=True, incoming_folder = self.IncomingEmailFolder, processed_folder =self.ProcessedEmailFolder,incoming_callback = self.ProcessCommand)
self.MailInit = True
# send mail to tell we are starting
self.mail.sendEmail("Generator Monitor Starting at " + self.SiteName, "Generator Monitor Starting at " + self.SiteName , msgtype = "info")
# check for ALARM.txt file present
try:
self.AlarmFile = os.path.dirname(os.path.realpath(__file__)) + "/ALARMS.txt"
with open(self.AlarmFile,"r") as AlarmFile: #
self.printToScreen("Validated alarm file present")
except Exception as e1:
self.FatalError("Unable to open alarm file: " + str(e1))
if self.mail.GetSendEmailThreadObject():
self.Threads["SendMailThread"] = self.mail.GetSendEmailThreadObject()
if self.mail.GetEmailMonitorThreadObject():
self.Threads["EmailCommandThread"] = self.mail.GetEmailMonitorThreadObject()
self.ProcessFeedbackInfo()
self.StartThreads()
self.LogError("GenMon Loadded for site: " + self.SiteName)
# ---------- GeneratorDevice::StartThreads------------------
def StartThreads(self, reload = False):
self.Threads["CheckForAlarmThread"] = mythread.MyThread(self.CheckForAlarmThread, Name = "CheckForAlarmThread")
# start read thread to process incoming data commands
self.Threads["ProcessThread"] = mythread.MyThread(self.ProcessThread, Name = "ProcessThread")
# start thread to accept incoming sockets for nagios heartbeat
self.Threads["ComWatchDog"] = mythread.MyThread(self.ComWatchDog, Name = "ComWatchDog")
if not reload:
# This thread remains open during a reload
# start thread to accept incoming sockets for nagios heartbeat and command / status clients
self.Threads["InterfaceServerThread"] = mythread.MyThread(self.InterfaceServerThread, Name = "InterfaceServerThread")
# start thread to accept incoming sockets for nagios heartbeat
self.Threads["PowerMeter"] = mythread.MyThread(self.PowerMeter, Name = "PowerMeter")
# start read thread to monitor registers as they change
self.Threads["MonitorThread"] = mythread.MyThread(self.MonitorThread, Name = "MonitorThread")
if self.bSyncDST or self.bSyncTime: # Sync time thread
self.Threads["TimeSyncThread"] = mythread.MyThread(self.TimeSyncThread, Name = "TimeSyncThread")
if self.EnableDebug: # for debugging registers
self.Threads["DebugThread"] = mythread.MyThread(self.DebugThread, Name = "DebugThread")
# ---------- GeneratorDevice::KillThread------------------
def KillThread(self, Name, CleanupSelf = False):
try:
MyThreadObj = self.Threads.get(Name, None)
if MyThreadObj == None:
del self.Threads[Name]
self.LogError("Error getting thread name in KillThread: " + Name)
return False
del self.Threads[Name]
if CleanupSelf:
MyThreadObj.Stop()
MyThreadObj.WaitForThreadToEnd()
except Exception as e1:
return
# ---------- GeneratorDevice::KillReloadThread------------------
def IsStopSignaled(self, Name):
Thread = self.Threads.get(Name, None)
if Thread == None:
self.LogError("Error getting thread name in IsStopSignaled: " + Name)
return False
return Thread.StopSignaled()
# ---------- GeneratorDevice::Reload------------------
def Reload(self):
try:
RetStr = ""
self.KillThread("ProcessThread")
self.KillThread("MonitorThread")
self.KillThread("CheckForAlarmThread")
self.KillThread("PowerMeter")
self.KillThread("ComWatchDog")
if self.bSyncDST or self.bSyncTime:
self.KillThread("TimeSyncThread")
if self.EnableDebug:
self.KillThread("DebugThread")
if self.MailInit:
self.mail.Cleanup()
try:
del self.Threads["SendMailThread"]
del self.Threads["EmailCommandThread"]
except Exception as e1:
RetStr = "" # no error to report, using exception if send or rx email was disabled.
self.MailInit = False
if self.ModBus.DeviceInit:
self.ModBus.Slave.Close()
self.ModBus.DeviceInit = False
if not self.GetConfig(reload = True):
RetStr = "Error reloading, error reading config file"
# log errors in this module to a file
self.log = mylog.SetupLogger("genmon", self.LogLocation + "genmon.log")
try:
#Starting device connection
self.ModBus = mymodbus.ModbusProtocol(self.UpdateRegisterList, self.Address, self.SerialPort, self.BaudRate, loglocation = self.LogLocation)
self.Threads["SerialReadThread"] = self.ModBus.Slave.StartReadThread()
except Exception as e1:
self.LogError("Error in Reload (serial): " + str(e1))
RetStr = "Failed to reload serial port."
# init mail, start processing incoming email
self.mail = mymail.MyMail(monitor=True, incoming_folder = self.IncomingEmailFolder, processed_folder =self.ProcessedEmailFolder,incoming_callback = self.ProcessCommand)
self.MailInit = True
if self.mail.GetSendEmailThreadObject():
self.Threads["SendMailThread"] = self.mail.GetSendEmailThreadObject()
if self.mail.GetEmailMonitorThreadObject():
self.Threads["EmailCommandThread"] = self.mail.GetEmailMonitorThreadObject()
# send mail to tell we are starting again
self.mail.sendEmail("Generator Monitor Reload at " + self.SiteName, "Generator Monitor Reload at " + self.SiteName , msgtype = "info")
self.StartThreads(reload = True)
self.LogError("RELOAD COMPLETE")
if RetStr == "":
return "Genmon reloaded"
else:
return RetStr
except Exception as e1:
self.LogError("Error in Reload: " + str(e1))
return "Genmon failed to reload"
# ---------- GeneratorDevice::GetConfig------------------
def GetConfig(self, reload = False):
ConfigSection = "GenMon"
try:
# read config file
config = RawConfigParser()
# config parser reads from current directory, when running form a cron tab this is
# not defined so we specify the full path
config.read('/etc/genmon.conf')
# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
if config.has_option(ConfigSection, 'sitename'):
self.SiteName = config.get(ConfigSection, 'sitename')
self.SerialPort = config.get(ConfigSection, 'port')
self.IncomingEmailFolder = config.get(ConfigSection, 'incoming_mail_folder') # imap folder for incoming mail
self.ProcessedEmailFolder = config.get(ConfigSection, 'processed_mail_folder') # imap folder for processed mail
# heartbeat server port, must match value in check_monitor_system.py and any calling client apps
self.ServerSocketPort = config.getint(ConfigSection, 'server_port')
if config.has_option(ConfigSection, 'address'):
self.Address = int(config.get(ConfigSection, 'address'),16) # modbus address
if config.has_option(ConfigSection, 'loglocation'):
self.LogLocation = config.get(ConfigSection, 'loglocation')
# optional config parameters, by default the software will attempt to auto-detect the controller
# this setting will override the auto detect
if config.has_option(ConfigSection, 'evolutioncontroller'):
self.EvolutionController = config.getboolean(ConfigSection, 'evolutioncontroller')
if config.has_option(ConfigSection, 'liquidcooled'):
self.LiquidCooled = config.getboolean(ConfigSection, 'liquidcooled')
if config.has_option(ConfigSection, 'disableoutagecheck'):
self.DisableOutageCheck = config.getboolean(ConfigSection, 'disableoutagecheck')
if config.has_option(ConfigSection, 'displayoutput'):
self.bDisplayOutput = config.getboolean(ConfigSection, 'displayoutput')
if config.has_option(ConfigSection, 'displaymonitor'):
self.bDisplayMonitor = config.getboolean(ConfigSection, 'displaymonitor')
if config.has_option(ConfigSection, 'displayregisters'):
self.bDisplayRegisters = config.getboolean(ConfigSection, 'displayregisters')
if config.has_option(ConfigSection, 'displaystatus'):
self.bDisplayStatus = config.getboolean(ConfigSection, 'displaystatus')
if config.has_option(ConfigSection, 'displaymaintenance'):
self.bDisplayMaintenance = config.getboolean(ConfigSection, 'displaymaintenance')
if config.has_option(ConfigSection, 'enabledebug'):
self.EnableDebug = config.getboolean(ConfigSection, 'enabledebug')
if config.has_option(ConfigSection, 'displayunknown'):
self.bDisplayUnknownSensors = config.getboolean(ConfigSection, 'displayunknown')
if config.has_option(ConfigSection, 'uselegacysetexercise'):
self.bUseLegacyWrite = config.getboolean(ConfigSection, 'uselegacysetexercise')
if config.has_option(ConfigSection, 'outagelog'):
self.OutageLog = config.get(ConfigSection, 'outagelog')
if config.has_option(ConfigSection, 'kwlog'):
self.PowerLog = config.get(ConfigSection, 'kwlog')
if config.has_option(ConfigSection, 'kwlogmax'):
self.PowerLogMaxSize = config.getint(ConfigSection, 'kwlogmax')
if config.has_option(ConfigSection, 'syncdst'):
self.bSyncDST = config.getboolean(ConfigSection, 'syncdst')
if config.has_option(ConfigSection, 'synctime'):
self.bSyncTime = config.getboolean(ConfigSection, 'synctime')
if config.has_option(ConfigSection, 'enhancedexercise'):
self.bEnhancedExerciseFrequency = config.getboolean(ConfigSection, 'enhancedexercise')
if config.has_option(ConfigSection, 'nominalfrequency'):
self.NominalFreq = config.get(ConfigSection, 'nominalfrequency')
if config.has_option(ConfigSection, 'nominalRPM'):
self.NominalRPM = config.get(ConfigSection, 'nominalRPM')
if config.has_option(ConfigSection, 'nominalKW'):
self.NominalKW = config.get(ConfigSection, 'nominalKW')
if config.has_option(ConfigSection, 'model'):
self.Model = config.get(ConfigSection, 'model')
if config.has_option(ConfigSection, 'fueltype'):
self.FuelType = config.get(ConfigSection, 'fueltype')
if config.has_option(ConfigSection, 'version'):
self.Version = config.get(ConfigSection, 'version')
if not self.Version == GENMON_VERSION:
self.AddItemToConfFile('version', GENMON_VERSION)
self.NewInstall = True
else:
self.AddItemToConfFile('version', GENMON_VERSION)
self.NewInstall = True
if config.has_option(ConfigSection, "autofeedback"):
self.FeedbackEnabled = config.getboolean(ConfigSection, 'autofeedback')
else:
self.AddItemToConfFile('autofeedback', "False")
self.FeedbackEnabled = False
# Load saved feedback log if log is present
if os.path.isfile(self.FeedbackLogFile):
with open(self.FeedbackLogFile) as infile:
self.FeedbackMessages = json.load(infile)
except Exception as e1:
if not reload:
raise Exception("Missing config file or config file entries: " + str(e1))
else:
self.LogError("Error reloading config file" + str(e1))
return False
return True
#------------------------------------------------------------
# Add or update config item
def AddItemToConfFile(self, Entry, Value):
FileName = "/etc/genmon.conf"
try:
Found = False
ConfigFile = open(FileName,'r')
FileString = ConfigFile.read()
ConfigFile.close()
ConfigFile = open(FileName,'w')
for line in FileString.splitlines():
if not line.isspace(): # blank lines
newLine = line.strip() # strip leading spaces
if len(newLine):
if not newLine[0] == "#": # not a comment
items = newLine.split(' ') # split items in line by spaces
for strings in items: # loop thru items
strings = strings.strip() # strip any whitespace
if Entry == strings or strings.lower().startswith(Entry+"="): # is this our value?
line = Entry + " = " + Value # replace it
Found = True
break
ConfigFile.write(line+"\n")
if not Found:
ConfigFile.write(Entry + " = " + Value + "\n")
ConfigFile.close()
return True
except Exception as e1:
self.LogError("Error in AddItemToConfFile: " + str(e1))
return False
# ---------- GeneratorDevice::CheckForAlarmThread------------------
# When signaled, this thread will check for alarms
def CheckForAlarmThread(self):
while True:
try:
time.sleep(0.25)
if self.IsStopSignaled("CheckForAlarmThread"):
break
if self.CheckForAlarmEvent.is_set():
self.CheckForAlarmEvent.clear()
self.CheckForAlarms()
except Exception as e1:
self.FatalError("Error in CheckForAlarmThread" + str(e1))
# ---------- GeneratorDevice::ProcessThread------------------
# remove items from Buffer, form packets
# all read and writes to serial port(s) should occur in this thread so we can
# serialize access to the ports
def ProcessThread(self):
try:
self.ModBus.Flush()
self.InitDevice()
while True:
if self.IsStopSignaled("ProcessThread"):
break
try:
self.MasterEmulation()
if self.EnableDebug:
self.DebugRegisters()
except Exception as e1:
self.LogError("Error in GeneratorDevice:ProcessThread (1), continue: " + str(e1))
except Exception as e1:
self.FatalError("Exiting GeneratorDevice:ProcessThread (2)" + str(e1))
# ---------- GeneratorDevice::MonitorThread------------------
# This thread will analyze the cached registers. It should not write to the serial port(s)
def MonitorThread(self):
while True:
try:
time.sleep(5)
if self.IsStopSignaled("MonitorThread"):
break
if self.bDisplayMonitor:
self.DisplayMonitor() # display communication stats
if self.bDisplayRegisters:
self.DisplayRegisters() # display registers
if self.bDisplayStatus:
self.DisplayStatus() # display generator engine status
if self.bDisplayMaintenance:
self.DisplayMaintenance() # display Maintenance
except Exception as e1:
self.LogError("Error in GeneratorDevice:MonitorThread " + str(e1))
#-------------GeneratorDevice::InitDevice------------------------------------
# One time reads, and read all registers once
def InitDevice(self):
self.ModBus.ProcessMasterSlaveTransaction("%04x" % MODEL_REG, MODEL_REG_LENGTH)
self.DetectController()
if self.EvolutionController:
self.ModBus.ProcessMasterSlaveTransaction("%04x" % ALARM_LOG_STARTING_REG, ALARM_LOG_STRIDE)
else:
self.ModBus.ProcessMasterSlaveTransaction("%04x" % NEXUS_ALARM_LOG_STARTING_REG, NEXUS_ALARM_LOG_STRIDE)
self.ModBus.ProcessMasterSlaveTransaction("%04x" % START_LOG_STARTING_REG, START_LOG_STRIDE)
if self.EvolutionController:
self.ModBus.ProcessMasterSlaveTransaction("%04x" % SERVICE_LOG_STARTING_REG, SERVICE_LOG_STRIDE)
for PrimeReg, PrimeInfo in self.PrimeRegisters.items():
self.ModBus.ProcessMasterSlaveTransaction(PrimeReg, int(PrimeInfo[self.REGLEN] / 2))
for Reg, Info in self.BaseRegisters.items():
#The divide by 2 is due to the diference in the values in our dict are bytes
# but modbus makes register request in word increments so the request needs to
# in word multiples, not bytes
self.ModBus.ProcessMasterSlaveTransaction(Reg, int(Info[self.REGLEN] / 2))
# check for model specific info in read from conf file, if not there then add some defaults
self.CheckModelSpecificInfo()
self.InitComplete = True
# check for unknown events (i.e. events we are not decoded) and send an email if they occur
self.CheckForAlarmEvent.set()
#------------------------------------------------------------
def ProcessFeedbackInfo(self):
if self.FeedbackEnabled:
for Key, Entry in self.FeedbackMessages.items():
self.mail.sendEmail("Generator Monitor Submission", Entry , recipient = "[email protected]", msgtype = "error")
# delete unsent Messages
if os.path.isfile(self.FeedbackLogFile):
os.remove(self.FeedbackLogFile)
#------------------------------------------------------------
def SendFeedbackInfo(self, Reason, Always = False, Message = None, FullLogs = False):
try:
if self.NewInstall or Always:
CheckedSent = self.FeedbackMessages.get(Reason, "")
if not CheckedSent == "":
return
msgbody = "Reason = " + Reason + "\n"
if Message != None:
msgbody += "Message : " + Message + "\n"
msgbody += "Version: " + GENMON_VERSION
msgbody += self.DisplayRegisters(AllRegs = FullLogs, ToString = True)
if self.FeedbackEnabled:
self.mail.sendEmail("Generator Monitor Submission", msgbody , recipient = "[email protected]", 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.LogError("Error in SendFeedbackInfo: " + str(e1))
#------------------------------------------------------------
def CheckModelSpecificInfo(self):
if self.NominalFreq == "Unknown" or not len(self.NominalFreq):
self.NominalFreq = self.GetModelInfo("Frequency")
if self.NominalFreq == "Unknown":
self.NominalFreq = "60"
self.AddItemToConfFile("nominalfrequency", self.NominalFreq)
# This is not correct for 50Hz models
if self.NominalRPM == "Unknown" or not len(self.NominalRPM):
if self.LiquidCooled:
if self.NominalFreq == "50":
self.NominalRPM = "1500"
else:
self.NominalRPM = "1800"
else:
if self.NominalFreq == "50":
self.NominalRPM = "3000"
else:
self.NominalRPM = "3600"
self.AddItemToConfFile("nominalRPM", self.NominalRPM)
TempStr = self.GetModelInfo("KW")
if TempStr == "Unknown":
self.SendFeedbackInfo("ModelID", Message="Model ID register is unknown")
if self.NominalKW == "Unknown" or self.Model == "Unknown" or not len(self.NominalKW) or not len(self.Model) or self.NewInstall:
self.NominalKW = self.GetModelInfo("KW")
if not self.LookUpSNInfo(SkipKW = (not self.NominalKW == "Unknown")):
if self.LiquidCooled:
self.Model = "Generic Liquid Cooled"
if self.NominalKW == "Unknown":
self.NominalKW = "60"
else:
self.Model = "Generic Air Cooled"
if self.NominalKW == "Unknown":
self.NominalKW = "22"
self.AddItemToConfFile("model", self.Model)
self.AddItemToConfFile("nominalKW", self.NominalKW)
if self.FuelType == "Unknown" or not len(self.FuelType):
if self.Model.startswith("RD"):
self.FuelType = "Diesel"
elif self.Model.startswith("RG") or self.Model.startswith("QT"):
self.FuelType = "Natural Gas"
elif self.LiquidCooled and self.EvolutionController: # EvoLC
self.FuelType = "Diesel"
else:
self.FuelType = "Natural Gas" # NexusLC, NexusAC, EvoAC
self.AddItemToConfFile("fueltype", self.FuelType)
#------------ GeneratorDevice::GetModelInfo-------------------------------
def GetModelInfo(self, Request):
UnknownList = ["Unknown", "Unknown", "Unknown", "Unknown"]
# Nexus LQ is the QT line
# 50Hz : QT02724MNAX
# QT022, QT027, QT036, QT048, QT080, QT070,QT100,QT130,QT150
ModelLookUp_NexusLC = {}
# Nexus AC
ModelLookUp_NexusAC = {
0 : ["8KW", "60", "120/240", "1"],
2 : ["14KW", "60", "120/240", "1"],
4 : ["20KW", "60", "120/240", "1"]
}
# This should cover the guardian line
ModelLookUp_EvoAC = { #ID : [KW or KVA Rating, Hz Rating, Voltage Rating, Phase]
1 : ["9KW", "60", "120/240", "1"],
2 : ["14KW", "60", "120/240", "1"],
3 : ["17KW", "60", "120/240", "1"],
4 : ["20KW", "60", "120/240", "1"],
5 : ["8KW", "60", "120/240", "1"],
7 : ["13KW", "60", "120/240", "1"],
8 : ["15KW", "60", "120/240", "1"],
9 : ["16KW", "60", "120/240", "1"],
10 : ["20KW", "VSCF", "120/240", "1"], #Variable Speed Constant Frequency
11 : ["15KW", "ECOVSCF", "120/240", "1"], # Eco Variable Speed Constant Frequency
12 : ["8KVA", "50", "220,230,240", "1"], # 3 distinct models 220, 230, 240
13 : ["10KVA", "50", "220,230,240", "1"], # 3 distinct models 220, 230, 240
14 : ["13KVA", "50", "220,230,240", "1"], # 3 distinct models 220, 230, 240
15 : ["11KW", "60" ,"240", "1"],
17 : ["22KW", "60", "120/240", "1"],
21 : ["11KW", "60", "240 LS", "1"],
32 : ["Trinity", "60", "208 3Phase", "3"], # G007077
33 : ["Trinity", "50", "380,400,416", "3"] # 3 distinct models 380, 400 or 416
}
# Evolution LC is the Protector series
# 50Hz Models: RG01724MNAX, RG02224MNAX, RG02724RNAX
# RG022, RG025,RG030,RG027,RG036,RG032,RG045,RG038,RG048,RG060
# RD01523,RD02023,RD03024,RD04834,RD05034
ModelLookUp_EvoLC = {
13: ["48KW", "60", "120/240", "1"]
}
Register = "None"
LookUp = None
if not self.LiquidCooled:
Register = "0019"
if self.EvolutionController:
LookUp = ModelLookUp_EvoAC
else:
LookUp = ModelLookUp_NexusAC
elif self.EvolutionController and self.LiquidCooled:
Register = "005c"
LookUp = ModelLookUp_EvoLC
else:
LookUp = ModelLookUp_NexusLC
return "Unknown" # Nexus LC is not known
Value = self.GetRegisterValueFromList(Register)
if not len(Value):
return "Unknown"
ModelInfo = LookUp.get(int(Value,16), UnknownList)
if Request.lower() == "frequency":
if ModelInfo[1] == "60" or ModelInfo[1] == "50":
return ModelInfo[1]
elif Request.lower() == "kw":
if "kw" in ModelInfo[0].lower():
return self.removeAlpha(ModelInfo[0])
elif "kva" in ModelInfo[0].lower():
# TODO: This is not right, I think if we take KVA * 0.8 it should equal KW for single phase
return self.removeAlpha(ModelInfo[0])
else:
return "Unknown"
elif Request.lower() == "phase":
return ModelInfo[3]
return "Unknown"
#------------------------------------------------------------
def LookUpSNInfo(self, SkipKW = False):
productId = None
ModelNumber = None
SerialNumber = self.GetSerialNumber()
Controller = self.GetController()
if not len(SerialNumber) or not len(Controller):
self.LogError("Error in LookUpSNInfo: bad input")
return False
if "None" in SerialNumber.lower(): # serial number is not present due to controller being replaced
return False
try:
# for diagnostic reasons we will log the internet search
self.LogError("Looking up model info on internet")
myregex = re.compile('<.*?>')
try:
conn = httplib.HTTPSConnection("www.generac.com", 443, timeout=10)
conn.request("GET", "/GeneracCorporate/WebServices/GeneracSelfHelpWebService.asmx/GetSearchResults?query=" + SerialNumber, "",
headers={"User-Agent": "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"})
r1 = conn.getresponse()
except Exception as e1:
conn.close()
self.LogError("Error in LookUpSNInfo (request 1): " + str(e1))
return False
try:
data1 = r1.read()
data2 = re.sub(myregex, '', data1)
myresponse1 = json.loads(data2)
ModelNumber = myresponse1["SerialNumber"]["ModelNumber"]
if not len(ModelNumber):
self.LogError("Error in LookUpSNInfo: Model (response1)")
conn.close()
return False
self.LogError("Found: Model: %s" % str(ModelNumber))
self.Model = ModelNumber
except Exception as e1:
self.LogError("Error in LookUpSNInfo (parse request 1): " + str(e1))
conn.close()
return False
try:
productId = myresponse1["Results"][0]["Id"]
except Exception as e1:
self.LogError("Note LookUpSNInfo (parse request 1), (product ID not found): " + str(e1))
productId = SerialNumber
if SkipKW:
return True
try:
if productId == SerialNumber:
conn.request("GET", "/service-support/product-support-lookup/product-manuals?modelNo="+productId, "",
headers={"User-Agent": "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"})
else:
conn.request("GET", "/GeneracCorporate/WebServices/GeneracSelfHelpWebService.asmx/GetProductById?productId="+productId, "",
headers={"User-Agent": "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"})
r1 = conn.getresponse()
data1 = r1.read()
conn.close()
data2 = re.sub(myregex, '', data1)
except Exception as e1:
self.LogError("Error in LookUpSNInfo (parse request 2, product ID): " + str(e1))
try:
if productId == SerialNumber:
#within the formatted HTML we are looking for something like this : "Manuals: 17KW/990 HNYWL+200A SE"
ListData = re.split("<div", data1) #
for Count in range(len(ListData)):
if "Manuals:" in ListData[Count]:
KWStr = re.findall(r"(\d+)KW", ListData[Count])[0]
if len(KWStr) and KWStr.isdigit():
self.NominalKW = KWStr
else:
myresponse2 = json.loads(data2)
kWRating = myresponse2["Attributes"][0]["Value"]
if "kw" in kWRating.lower():
kWRating = self.removeAlpha(kWRating)
elif "watts" in kWRating.lower():
kWRating = self.removeAlpha(kWRating)
kWRating = str(int(kWRating) / 1000)
else:
kWRating = str(int(kWRating) / 1000)
self.NominalKW = kWRating
if not len(kWRating):
self.LogError("Error in LookUpSNInfo: KW")
return False
self.LogError("Found: KW: %skW" % str(kWRating))
except Exception as e1:
self.LogError("Error in LookUpSNInfo: (parse KW)" + str(e1))
return False
return True
except Exception as e1:
self.LogError("Error in LookUpSNInfo: " + str(e1))
return False
#-------------GeneratorDevice::DetectController------------------------------------
def DetectController(self):
# issue modbus read
self.ModBus.ProcessMasterSlaveTransaction("0000", 1)
# read register from cached list.
Value = self.GetRegisterValueFromList("0000")
if len(Value) != 4:
return ""
ProductModel = int(Value,16)
# 0x03 Nexus, Air Cooled
# 0x06 Nexus, Liquid Cooled
# 0x09 Evolution, Air Cooled
# 0x0c Evolution, Liquid Cooled
msgbody = "\nThis email is a notification informing you that the software has detected a generator "
msgbody += "model variant that has not been validated by the authors of this sofrware. "
msgbody += "The software has made it's best effort to identify your generator controller type however since "
msgbody += "your generator is one that we have not validated, your generator controller may be incorrectly identified. "
msgbody += "To validate this variant, please submit the output of the following command (generator: registers)"
msgbody += "and your model numbert to the following project thread: https://github.com/jgyates/genmon/issues/10. "
msgbody += "Once your feedback is receivd we an add your model product code and controller type to the list in the software."
if self.EvolutionController == None:
# if reg 000 is 3 or less then assume we have a Nexus Controller
if ProductModel == 0x03 or ProductModel == 0x06:
self.EvolutionController = False #"Nexus"
self.printToScreen("Nexus Controller Detected")
elif ProductModel == 0x09 or ProductModel == 0x0c:
self.EvolutionController = True #"Evolution"
self.printToScreen("Evolution Controller Detected")
else:
# set a reasonable default
if ProductModel <= 0x06:
self.EvolutionController = False
else:
self.EvolutionController = True
self.LogError("Warning in DetectController (Nexus / Evolution): Unverified value detected in model register (%04x)" % ProductModel)
self.mail.sendEmail("Generator Monitor (Nexus / Evolution): Warning at " + self.SiteName, msgbody, msgtype = "warn" )
else:
self.LogError("DetectController auto-detect override (controller). EvolutionController now is %s" % str(self.EvolutionController))
if self.LiquidCooled == None:
if ProductModel == 0x03 or ProductModel == 0x09:
self.LiquidCooled = False # Air Cooled
self.printToScreen("Air Cooled Model Detected")
elif ProductModel == 0x06 or ProductModel == 0x0c:
self.LiquidCooled = True # Liquid Cooled
self.printToScreen("Liquid Cooled Model Detected")
else:
# set a reasonable default
self.LiquidCooled = False
self.LogError("Warning in DetectController (liquid / air cooled): Unverified value detected in model register (%04x)" % ProductModel)
self.mail.sendEmail("Generator Monitor (liquid / air cooled: Warning at " + self.SiteName, msgbody, msgtype = "warn" )
else:
self.LogError("DetectController auto-detect override (Liquid Cooled). Liquid Cooled now is %s" % str(self.LiquidCooled))
if not self.EvolutionController: # if we are using a Nexus Controller, force legacy writes
self.bUseLegacyWrite = True
#---------- GeneratorDevice:GetController ---------------------------------
def GetController(self, Actual = True):
outstr = ""
if Actual:
ControllerDecoder = {
0x03 : "Nexus, Air Cooled",
0x06 : "Nexus, Liquid Cooled",
0x09 : "Evolution, Air Cooled",
0x0c : "Evolution, Liquid Cooled"
}