forked from jgyates/genmon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenmon.py
3120 lines (2543 loc) · 132 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/
import datetime, time, sys, smtplib, signal, os, threading, socket, serial
import crcmod.predefined, crcmod, mymail, atexit, ConfigParser
import mymail, mylog
#------------ SerialDevice class --------------------------------------------
class SerialDevice:
def __init__(self, name, rate=9600):
self.DeviceName = name
self.BaudRate = rate
self.Buffer = []
self.BufferLock = threading.Lock()
self.RxPacketCount = 0
self.TxPacketCount = 0
self.CrcError = 0
self.DiscardedBytes = 0
self.Restarts = 0
# log errors in this module to a file
self.log = mylog.SetupLogger("myserial", "/var/log/myserial.log")
#Starting serial connection
self.SerialDevice = serial.Serial()
self.SerialDevice.port = name
self.SerialDevice.baudrate = rate
self.SerialDevice.bytesize = serial.EIGHTBITS #number of bits per bytes
self.SerialDevice.parity = serial.PARITY_NONE #set parity check: no parity
self.SerialDevice.stopbits = serial.STOPBITS_ONE #number of stop bits
self.SerialDevice.timeout = None # should be blocking to help with CPU load
self.SerialDevice.xonxoff = False #disable software flow control
self.SerialDevice.rtscts = False #disable hardware (RTS/CTS) flow control
self.SerialDevice.dsrdtr = False #disable hardware (DSR/DTR) flow control
self.SerialDevice.writeTimeout = None #timeout for write, return when packet sent
#Check if port failed to open
if (self.SerialDevice.isOpen() == False):
try:
self.SerialDevice.open()
except Exception, e:
self.FatalError( "Error on open serial port %s: " % self.DeviceName + str(e))
return None
else:
self.FatalError( "Serial port already open: %s" % self.DeviceName)
return None
self.Flush()
# ---------- SerialDevice::StartReadThread------------------
def StartReadThread(self):
# start read thread to monitor incoming data commands
self.ReadThreadObj = threading.Thread(target=self.ReadThread, name = "SerialReadThread")
self.ReadThreadObj.daemon = True
self.ReadThreadObj.start() # start Read thread
return self.ReadThreadObj
# ---------- SerialDevice::ReadThread------------------
def ReadThread(self):
while True:
try:
self.Flush()
while True:
for c in self.Read():
with self.BufferLock:
self.Buffer.append(ord(c))
except Exception, e1:
self.LogError( "Resetting SerialDevice:ReadThread Error: " + self.DeviceName + ":"+ str(e1))
# if we get here then this is likely due to the following exception:
# "device reports readiness to read but returned no data (device disconnected?)"
# This is believed to be a kernel issue so let's just reset the device and hope
# for the best (actually this works)
self.Restarts += 1
self.SerialDevice.close()
self.SerialDevice.open()
#------------SerialDevice::DiscardByte------------
def DiscardByte(self):
if len(self.Buffer):
discard = self.Buffer.pop(0)
self.DiscardedBytes += 1
return discard
# ---------- SerialDevice::Close------------------
def Close(self):
self.SerialDevice.close()
# ---------- SerialDevice::Flush------------------
def Flush(self):
try:
self.SerialDevice.flushInput() #flush input buffer, discarding all its contents
self.SerialDevice.flushOutput() #flush output buffer, aborting current output
with self.BufferLock: # will block if lock is already held
del self.Buffer[:]
except Exception, e1:
self.FatalError( "Error in SerialDevice:Flush : " + self.DeviceName + ":" + str(e1))
# ---------- SerialDevice::Read------------------
def Read(self):
return self.SerialDevice.read()
# ---------- SerialDevice::Write-----------------
def Write(self, data):
return self.SerialDevice.write(data)
#---------------------SerialDevice::FatalError------------------------
def LogError(self, Message):
self.log.error(Message)
#---------------------SerialDevice::FatalError------------------------
def FatalError(self, Message):
self.log.error(Message)
raise Exception(Message)
#--------------------- MODBUS specific Const defines for Generator class
MBUS_ADDRESS = 0x00
MBUS_ADDRESS_SIZE = 0x01
MBUS_COMMAND = 0x01
MBUS_COMMAND_SIZE = 0x01
MBUS_WR_REQ_BYTE_COUNT = 0x06
MBUS_CRC_SIZE = 0x02
MBUS_RES_LENGTH_SIZE = 0x01
MBUS_RES_PAYLOAD_SIZE_MINUS_LENGTH = MBUS_ADDRESS_SIZE + MBUS_COMMAND_SIZE + MBUS_RES_LENGTH_SIZE + MBUS_CRC_SIZE
MBUS_RESPONSE_LEN = 0x02
MIN_PACKET_LENGTH_REQ = 0x08
MIN_PACKET_LENGTH_WR_REQ= 0x09
MIN_PACKET_LENGTH_RES = 0x07
MIN_PACKET_LENGTH_WR_RES= 0x08
MBUS_CMD_READ_REGS = 0x03
MBUS_CMD_WRITE_REGS = 0x10
#-------------------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 = 215
#------------ 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.ThreadList = [] # list of thread 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.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.SerialInit = False # set to true once serial is init
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], # Unknown, possibly product line code
"0005" : [2, 0], # Exercise Time Hi Byte = Hour, Lo Byte = Min (Read Only)
"0006" : [2, 0], # Exercise Time Hi Byte = Day of Week 00=Sunday 01=Monday, Low Byte = 00=quiet=no, 01=yes
"0007" : [2, 0], # Engine RPM
"0008" : [2, 0], # Freq - value includes Hz to the tenths place i.e. 59.9 Hz
"000a" : [2, 0], # battery voltage Volts to tenths place i.e. 13.9V
"000c" : [2, 0], # engine run time hours
"000e" : [2, 0], # Read / Write: Generator Time Hi byte = hours, Lo byte = min
"000f" : [2, 0], # Read / Write: Generator Time Hi byte = month, Lo byte = day of the month
"0010" : [2, 0], # Read / Write: Generator Time = Hi byte Day of Week 00=Sunday 01=Monday, Lo byte = last 2 digits of year
"0011" : [2, 0], # Utility Threshold, ML Does not read this
"0012" : [2, 0], # Gen output voltage
"001a" : [2, 0], # Hours until next service
"002a" : [2, 0], # hardware (high byte) (Hardware V1.04 = 0x68) and firmware version (low byte) (Firmware V1.33 = 0x85)
"003c" : [2, 0], # Unknown sensor 1 ramps up to 300 (30.0 ?)
"0058" : [2, 0], # Unknown sensor 2, once engine starts ramps up to 1600 decimal (160.0?)
"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
"0059" : [2, 0], # Set Voltage from Dealer Menu (not currently used)
"023b" : [2, 0], # Pick Up Voltage
"023e" : [2, 0], # Exercise time duration
"0054" : [2, 0], # Hours since generator activation (hours of protection)
"005f" : [2, 0], # Total engine time in minutes
"01f1" : [2, 0], # Unknown Status (WIP)
"01f2" : [2, 0], # Unknown Status (WIP)
"001b" : [2, 0], # Unknown Read by ML
"001c" : [2, 0], # Unknown Read by ML
"001d" : [2, 0], # Unknown Read by ML
"001e" : [2, 0], # Unknown Read by ML
"001f" : [2, 0], # Unknown Read by ML
"0020" : [2, 0], # Unknown Read by ML
"0021" : [2, 0], # Unknown Read by ML
"0019" : [2, 0], # Unknown Read by ML
"0057" : [2, 0], # Unknown Looks like some status bits (changes when engine starts / stops)
"0055" : [2, 0], # Unknown
"0056" : [2, 0], # Unknown Looks like some status bits (changes when engine starts / stops)
"005a" : [2, 0],
"005c" : [2, 0]}
# 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], # Output relay status register (battery charging, transfer switch, Change at startup and stop
"0052" : [2, 0], # 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 Quite Mode=1 Not Quiet Mode = 0
self.REGLEN = 0
self.REGMONITOR = 1
try:
# read config file
config = ConfigParser.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')
# 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.PetroleumFuel = True
self.OutageLog = ""
# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
self.SiteName = config.get('GenMon', 'sitename')
self.SerialPort = config.get('GenMon', 'port')
self.IncomingEmailFolder = config.get('GenMon', 'incoming_mail_folder') # imap folder for incoming mail
self.ProcessedEmailFolder = config.get('GenMon', '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('GenMon', 'server_port')
self.Address = int(config.get('GenMon', 'address'),16) # modbus address
self.LogLocation = config.get('GenMon', 'loglocation')
self.AlarmFile = config.get('GenMon', 'alarmfile')
self.LiquidCooled = config.getboolean('GenMon', 'liquidcooled')
# 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('GenMon', 'evolutioncontroller'):
self.EvolutionController = config.getboolean('GenMon', 'evolutioncontroller')
if config.has_option('GenMon', 'petroleumfuel'):
self.PetroleumFuel = config.getboolean('GenMon', 'petroleumfuel')
if config.has_option('GenMon', 'displayoutput'):
self.bDisplayOutput = config.getboolean('GenMon', 'displayoutput')
if config.has_option('GenMon', 'displaymonitor'):
self.bDisplayMonitor = config.getboolean('GenMon', 'displaymonitor')
if config.has_option('GenMon', 'displayregisters'):
self.bDisplayRegisters = config.getboolean('GenMon', 'displayregisters')
if config.has_option('GenMon', 'displaystatus'):
self.bDisplayStatus = config.getboolean('GenMon', 'displaystatus')
if config.has_option('GenMon', 'displaymaintenance'):
self.bDisplayMaintenance = config.getboolean('GenMon', 'displaymaintenance')
if config.has_option('GenMon', 'enabledebug'):
self.EnableDebug = config.getboolean('GenMon', 'enabledebug')
if config.has_option('GenMon', 'displayunknown'):
self.bDisplayUnknownSensors = config.getboolean('GenMon', 'displayunknown')
if config.has_option('GenMon', 'uselegacysetexercise'):
self.bUseLegacyWrite = config.getboolean('GenMon', 'uselegacysetexercise')
if config.has_option('GenMon', 'outagelog'):
self.OutageLog = config.get('GenMon', 'outagelog')
except Exception, e1:
raise Exception("Missing config file or config file entries: " + str(e1))
return None
# log errors in this module to a file
self.log = mylog.SetupLogger("genmon", self.LogLocation + "genmon.log")
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 serial connection
self.Slave = SerialDevice(self.SerialPort, self.BaudRate)
self.SerialInit = True
self.ThreadList.append(self.Slave.StartReadThread())
except Exception, 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 )
# check for ALARM.txt file present
try:
if self.EvolutionController:
with open(self.AlarmFile,"r") as AlarmFile: #
self.printToScreen("Validated alarm file present")
except Exception, e1:
self.FatalError("Unable to open alarm file: " + str(e1))
if self.mail.GetSendEmailThreadObject():
self.ThreadList.append(self.mail.GetSendEmailThreadObject())
if self.mail.GetEmailMonitorThreadObject():
self.ThreadList.append(self.mail.GetEmailMonitorThreadObject())
try:
# CRCMOD library, used for CRC calculations
self.ModbusCrc = crcmod.predefined.mkCrcFun('modbus')
except Exception, e1:
self.FatalError("Unable to find crcmod package: " + str(e1))
# start read thread to process incoming data commands
self.StartThread(self.ProcessThread, Name = "ProcessThread")
# start read thread to monitor registers as they change
self.StartThread(self.MonitorThread, Name = "MonitorThread")
# start thread to accept incoming sockets for nagios heartbeat and command / status clients
self.StartThread(self.InterfaceServerThread, Name = "InterfaceServerThread")
# start thread to accept incoming sockets for nagios heartbeat
self.StartThread(self.ComWatchDog, Name = "ComWatchDog")
if self.EnableDebug:
self.StartThread(self.DebugThread, Name = "DebugThread") # for debugging registers
# ---------- GeneratorDevice::StartThread------------------
def StartThread(self, ThreadFunction, Name = None):
ThreadObj = threading.Thread(target=ThreadFunction, name = Name)
ThreadObj.daemon = True
ThreadObj.start() # start monitor thread
self.ThreadList.append(ThreadObj)
# ---------- 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.Flush()
self.InitDevice()
while True:
try:
self.MasterEmulation()
if self.EnableDebug:
self.DebugRegisters()
except Exception, e1:
self.LogError("Error in GeneratorDevice:ProcessThread (1), continue: " + str(e1))
except Exception, 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.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, e1:
self.LogError("Error in GeneratorDevice:MonitorThread " + str(e1))
#------------GeneratorDevice::Flush-----------------------
def Flush(self):
self.Slave.Flush()
# ---------- GeneratorDevice::GetPacketFromSlave------------------
# This function returns two values, the first is boolean. The seconds is
# a packet (list). If the return value is True and an empty packet, then
# keep looking because the data has not arrived yet, if return is False there
# is and error. If True and a non empty packet then it is valid data
def GetPacketFromSlave(self):
LocalErrorCount = 0
Packet = []
EmptyPacket = [] # empty packet
if len(self.Slave.Buffer) < MIN_PACKET_LENGTH_RES:
return True, EmptyPacket
if len(self.Slave.Buffer) >= MIN_PACKET_LENGTH_RES:
if self.Slave.Buffer[MBUS_ADDRESS] == self.Address and self.Slave.Buffer[MBUS_COMMAND] in [MBUS_CMD_READ_REGS]:
# it must be a read command response
length = self.Slave.Buffer[MBUS_RESPONSE_LEN] # our packet tells us the length of the payload
# if the full length of the packet has not arrived, return and try again
if (length + MBUS_RES_PAYLOAD_SIZE_MINUS_LENGTH) > len(self.Slave.Buffer):
return True, EmptyPacket
for i in range(0, length + MBUS_RES_PAYLOAD_SIZE_MINUS_LENGTH):
Packet.append(self.Slave.Buffer.pop(0)) # pop Address, Function, Length, message and CRC
if self.CheckCRC(Packet):
self.Slave.RxPacketCount += 1
return True, Packet
else:
self.Slave.CrcError += 1
return False, EmptyPacket
elif self.Slave.Buffer[MBUS_ADDRESS] == self.Address and self.Slave.Buffer[MBUS_COMMAND] in [MBUS_CMD_WRITE_REGS]:
# it must be a write command response
if len(self.Slave.Buffer) < MIN_PACKET_LENGTH_WR_RES:
return True, EmptyPacket
for i in range(0, MIN_PACKET_LENGTH_WR_RES):
Packet.append(self.Slave.Buffer.pop(0)) # address, function, address hi, address low, quantity hi, quantity low, CRC high, crc low
if self.CheckCRC(Packet):
self.Slave.RxPacketCount += 1
return True,Packet
else:
self.Slave.CrcError += 1
return False, EmptyPacket
else:
self.DiscardByte()
self.Flush()
return False, EmptyPacket
return True, EmptyPacket # technically not a CRC error, we really should never get here
#-------------GeneratorDevice::InitDevice------------------------------------
# One time reads, and read all registers once
def InitDevice(self):
self.ProcessMasterSlaveTransaction("%04x" % MODEL_REG, MODEL_REG_LENGTH)
self.DetectController()
if self.EvolutionController:
self.ProcessMasterSlaveTransaction("%04x" % ALARM_LOG_STARTING_REG, ALARM_LOG_STRIDE)
else:
self.ProcessMasterSlaveTransaction("%04x" % NEXUS_ALARM_LOG_STARTING_REG, NEXUS_ALARM_LOG_STRIDE)
self.ProcessMasterSlaveTransaction("%04x" % START_LOG_STARTING_REG, START_LOG_STRIDE)
if self.EvolutionController:
self.ProcessMasterSlaveTransaction("%04x" % SERVICE_LOG_STARTING_REG, SERVICE_LOG_STRIDE)
for PrimeReg, PrimeInfo in self.PrimeRegisters.items():
self.ProcessMasterSlaveTransaction(PrimeReg, 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.ProcessMasterSlaveTransaction(Reg, Info[self.REGLEN] / 2)
self.CheckForAlarms() # check for unknown events (i.e. events we are not decoded) and send an email if they occur
#-------------GeneratorDevice::DetectController------------------------------------
def DetectController(self):
if self.EvolutionController == None:
# issue modbus read
self.ProcessMasterSlaveTransaction("0000", 1)
# read register from cached list.
Value = self.GetRegisterValueFromList("0000")
if len(Value) != 4:
return ""
ProductModel = int(Value,16)
# if reg 000 is 3 or less then assume we have a Nexus Controller
if ProductModel <= 0x03:
self.EvolutionController = False #"Nexus"
self.printToScreen("Nexus Controller Detected")
else:
self.EvolutionController = True #"Evolution"
self.printToScreen("Evolution Controller Detected")
if not self.EvolutionController: # if we are using a Nexus Controller, force legacy writes
self.bUseLegacyWrite = True
#-------------GeneratorDevice::DebugRegisters------------------------------------
def DebugRegisters(self):
# reg 200 - -3e7 and 4af - 4e2 and 5af - 600 (already got 5f1 5f4 and 5f5?
for Reg in range(0x05 , 0x600):
RegStr = "%04x" % Reg
if not self.RegisterIsKnown(RegStr):
self.ProcessMasterSlaveTransaction(RegStr, 1)
#-------------GeneratorDevice::MasterEmulation------------------------------------
def MasterEmulation(self):
counter = 0
for Reg, Info in self.BaseRegisters.items():
if counter % 6 == 0:
for PrimeReg, PrimeInfo in self.PrimeRegisters.items():
self.ProcessMasterSlaveTransaction(PrimeReg, PrimeInfo[self.REGLEN] / 2)
self.CheckForAlarms() # check for unknown events (i.e. events we are not decoded) and send an email if they occur
#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.ProcessMasterSlaveTransaction(Reg, Info[self.REGLEN] / 2)
counter += 1
#-------------GeneratorDevice::ProcessMasterSlaveTransaction--------------------
def ProcessMasterSlaveWriteTransaction(self, Register, Length, Data):
MasterPacket = []
MasterPacket = self.CreateMasterPacket(Register, Length, MBUS_CMD_WRITE_REGS, Data)
if len(MasterPacket) == 0:
return
return self.ProcessOneTransaction(MasterPacket, True) # True to skip writing results to cached reg values
#-------------GeneratorDevice::ProcessMasterSlaveTransaction--------------------
def ProcessMasterSlaveTransaction(self, Register, Length):
MasterPacket = []
MasterPacket = self.CreateMasterPacket(Register, Length)
if len(MasterPacket) == 0:
return
return self.ProcessOneTransaction(MasterPacket)
#------------GeneratorDevice::ProcessOneTransaction
def ProcessOneTransaction(self, MasterPacket, skiplog = False):
with self.CommAccessLock: # this lock should allow calls from multiple threads
self.SendPacketAsMaster(MasterPacket)
SentTime = datetime.datetime.now()
while True:
# be kind to other processes, we know we are going to have to wait for the packet to arrive
# so let's sleep for a bit before we start polling
time.sleep(0.01)
RetVal, SlavePacket = self.GetPacketFromSlave()
if RetVal == True and len(SlavePacket) != 0: # we receive a packet
break
if RetVal == False:
self.LogError("Error Receiving slave packet for register %x%x" % (MasterPacket[2],MasterPacket[3]) )
self.Flush()
return False
msElapsed = self.MillisecondsElapsed(SentTime)
# This normally takes about 30 ms however in some instances it can take up to 950ms
# the theory is this is either a delay due to how python does threading, or
# delay caused by the generator controller.
# each char time is about 1 millisecond so assuming a 10 byte packet transmitted
# and a 10 byte received with about 5 char times of silence in between should give
# us about 25ms
if msElapsed > 1000:
self.LogError("Error: timeout receiving slave packet for register %x%x Buffer:%d" % (MasterPacket[2],MasterPacket[3], len(self.Slave.Buffer)) )
return False
# update our cached register dict
if not skiplog:
self.UpdateRegistersFromPacket(MasterPacket, SlavePacket)
return True
# ---------- GeneratorDevice::CreateMasterPacket------------------
# the length is the register length in words, as required by modbus
# build Packet
def CreateMasterPacket(self, Register, Length, command = MBUS_CMD_READ_REGS, Data=[]):
Packet = []
if command == MBUS_CMD_READ_REGS:
Packet.append(self.Address) # address
Packet.append(command) # command
Packet.append(int(Register,16) >> 8) # reg hi
Packet.append(int(Register,16) & 0x00FF) # reg low
Packet.append(Length >> 8) # length hi
Packet.append(Length & 0x00FF) # length low
CRCValue = self.GetCRC(Packet)
Packet.append(CRCValue & 0x00FF) # CRC low
Packet.append(CRCValue >> 8) # CRC high
elif command == MBUS_CMD_WRITE_REGS:
if len(Data) == 0:
self.LogError("Validation Error: CreateMasterPacket invalid length (1) %x %x" % (len(Data), Length))
return Packet
if len(Data)/2 != Length:
self.LogError("Validation Error: CreateMasterPacket invalid length (2) %x %x" % (len(Data), Length))
return Packet
Packet.append(self.Address) # address
Packet.append(command) # command
Packet.append(int(Register,16) >> 8) # reg hi
Packet.append(int(Register,16) & 0x00FF) # reg low
Packet.append(Length >> 8) # Num of Reg hi
Packet.append(Length & 0x00FF) # Num of Reg low
Packet.append(len(Data)) # byte count
for b in range(0, len(Data)):
Packet.append(Data[b]) # data
CRCValue = self.GetCRC(Packet)
Packet.append(CRCValue & 0x00FF) # CRC low
Packet.append(CRCValue >> 8) # CRC high
else:
self.LogError("Validation Error: Invalid command in CreateMasterPacket!")
return Packet
#-------------GeneratorDevice::SendPacketAsMaster---------------------------------
def SendPacketAsMaster(self, Packet):
ByteArray = bytearray(Packet)
self.Slave.Write(ByteArray)
self.Slave.TxPacketCount += 1
#-------------GeneratorDevice::UpdateLogRegistersAsMaster
def UpdateLogRegistersAsMaster(self):
# Start / Stop Log
for Register in self.LogRange(START_LOG_STARTING_REG , LOG_DEPTH,START_LOG_STRIDE):
RegStr = "%04x" % Register
if not self.ProcessMasterSlaveTransaction(RegStr, START_LOG_STRIDE):
break
if self.EvolutionController:
# Service Log
for Register in self.LogRange(SERVICE_LOG_STARTING_REG , LOG_DEPTH, SERVICE_LOG_STRIDE):
RegStr = "%04x" % Register
if not self.ProcessMasterSlaveTransaction(RegStr, SERVICE_LOG_STRIDE):
break
# Alarm Log
for Register in self.LogRange(ALARM_LOG_STARTING_REG , LOG_DEPTH, ALARM_LOG_STRIDE):
RegStr = "%04x" % Register
if not self.ProcessMasterSlaveTransaction(RegStr, ALARM_LOG_STRIDE):
break
else:
# Alarm Log
for Register in self.LogRange(NEXUS_ALARM_LOG_STARTING_REG , LOG_DEPTH, NEXUS_ALARM_LOG_STRIDE):
RegStr = "%04x" % Register
if not self.ProcessMasterSlaveTransaction(RegStr, NEXUS_ALARM_LOG_STRIDE):
break
# ---------- GeneratorDevice::MillisecondsElapsed------------------
def MillisecondsElapsed(self, ReferenceTime):
CurrentTime = datetime.datetime.now()
Delta = CurrentTime - ReferenceTime
return Delta.total_seconds() * 1000
#---------- GeneratorDevice::SetGeneratorRemoteStartStop-------------------------------
def SetGeneratorRemoteStartStop(self, CmdString):
msgbody = "Invalid command syntax for command setremote (1)"
try:
#Format we are looking for is "setremote=start"
marker0 = CmdString.lower().find("setremote")
marker1 = CmdString.find("=", marker0)
marker2 = CmdString.find(" ",marker1+1)
if -1 in [marker0, marker1]:
self.LogError("Validation Error: Error parsing command string in SetGeneratorRemoteStartStop (parse): " + CmdString)
return msgbody
if marker2 == -1: # was this the last char in the string or now space given?
Command = CmdString[marker1+1:]
else:
Command = CmdString[marker1+1:marker2]
except Exception, e1:
self.LogError("Validation Error: Error parsing command string in SetGeneratorRemoteStartStop: " + CmdString)
self.LogError( str(e1))
return msgbody
# Index register 0001 controls remote start (data written 0001 to start,I believe ).
# Index register 0002 controls remote transfer switch (Not sure of the data here )
Register = 0
Value = 0
if Command == "start":
Register = 0x0001
Value = 0x0000 # writing any value to index register 0001 will remote start (radio start)
elif Command == "stop":
Register = 0x0000 #
Value = 0x0000 # writing any value to index register 0000 will remote stop (radio stop)
elif Command == "starttransfer":
Register = 0x0002 #
Value = 0x0000 # writing any value to index register 0002 will start the generator, then engage the transfer transfer switch
elif Command == "startexercise":
Register = 0x0003 #
Value = 0x0000 # writing any value to index register 0003 will remote run in quiet mode (exercise)
else:
return "Invalid command syntax for command setremote (2)"
with self.CommAccessLock:
#
LowByte = Value & 0x00FF
HighByte = Value >> 8
Data= []
Data.append(HighByte) # Value for indexed register (High byte)
Data.append(LowByte) # Value for indexed register (Low byte)
self.ProcessMasterSlaveWriteTransaction("0004", len(Data) / 2, Data)
LowByte = Register & 0x00FF
HighByte = Register >> 8
Data= []
Data.append(HighByte) # indexed register to be written (High byte)
Data.append(LowByte) # indexed register to be written (Low byte)
self.ProcessMasterSlaveWriteTransaction("0003", len(Data) / 2, Data)
return "Remote command sent successfully"
#-------------MonitorUnknownRegisters--------------------------------------------------------
def MonitorUnknownRegisters(self,Register, FromValue, ToValue):
msgbody = ""
if self.RegisterIsKnown(Register):
if not self.MonitorRegister(Register):
return
msgbody = "%s changed from %s to %s" % (Register, FromValue, ToValue)
msgbody += "\n"
msgbody += self.DisplayRegisters(ToString = True)
msgbody += "\n"
msgbody += self.DisplayStatus(ToString = True)
self.mail.sendEmail("Monitor Register Alert: " + Register, msgbody)
else:
# bulk register monitoring goes here and an email is sent out in a batch
if self.EnableDebug:
self.RegistersUnderTestData += "Register %s changed from %s to %s\n" % (Register, FromValue, ToValue)
#---------- GeneratorDevice::CalculateExerciseTime-------------------------------
# helper routine for AltSetGeneratorExerciseTime
def CalculateExerciseTime(self,MinutesFromNow):
ReturnedValue = 0x00
Remainder = MinutesFromNow
# convert minutes from now to weighted bit value
if Remainder >= 8738:
ReturnedValue |= 0x1000
Remainder -= 8738
if Remainder >= 4369:
ReturnedValue |= 0x0800
Remainder -= 4369
if Remainder >= 2184:
ReturnedValue |= 0x0400
Remainder -= 2185
if Remainder >= 1092:
ReturnedValue |= 0x0200
Remainder -= 1092
if Remainder >= 546:
ReturnedValue |= 0x0100
Remainder -= 546
if Remainder >= 273:
ReturnedValue |= 0x0080
Remainder -= 273
if Remainder >= 136:
ReturnedValue |= 0x0040
Remainder -= 137
if Remainder >= 68:
ReturnedValue |= 0x0020
Remainder -= 68
if Remainder >= 34:
ReturnedValue |= 0x0010
Remainder -= 34
if Remainder >= 17:
ReturnedValue |= 0x0008
Remainder -= 17
if Remainder >= 8:
ReturnedValue |= 0x0004
Remainder -= 8
if Remainder >= 4:
ReturnedValue |= 0x0002
Remainder -= 4
if Remainder >= 2:
ReturnedValue |= 0x0001
Remainder -= 2
return ReturnedValue
#---------- GeneratorDevice::AltSetGeneratorExerciseTime-------------------------------
# Note: This method is a bit odd but it is how ML does it. It can result in being off by
# a min or two
def AltSetGeneratorExerciseTime(self, CmdString):
# extract time of day and day of week from command string
# format is day:hour:min Monday:15:00
msgsubject = "Generator Command Notice at " + self.SiteName
msgbody = "Invalid command syntax for command setexercise"
try:
#Format we are looking for is "setexercise=Monday,12:20"
marker0 = CmdString.lower().find("setexercise")
marker1 = CmdString.find("=", marker0)
marker2 = CmdString.find(",",marker1)
marker3 = CmdString.find(":",marker2+1)
marker4 = CmdString.find(" ",marker3+1)
if -1 in [marker0, marker1, marker2, marker3]:
self.LogError("Validation Error: Error parsing command string in AltSetGeneratorExerciseTime (parse): " + CmdString)
self.mail.sendEmail(msgsubject, msgbody)
return
DayStr = CmdString[marker1+1:marker2]
HourStr = CmdString[marker2+1:marker3]
if marker4 == -1: # was this the last char in the string or now space given?
MinuteStr = CmdString[marker3+1:]
else:
MinuteStr = CmdString[marker3+1:marker4]
Minute = int(MinuteStr)
Hour = int(HourStr)
DayOfWeek = { "monday": 0, # decode for register values with day of week
"tuesday": 1, # NOTE: This decodes for datetime i.e. Monday=0
"wednesday": 2, # the generator firmware programs Sunday = 0, but
"thursday": 3, # this is OK since we are calculating delta minutes
"friday": 4, # since time of day to set exercise time
"saturday": 5,
"sunday": 6}
Day = DayOfWeek.get(DayStr.lower(), -1)
if Day == -1:
self.LogError("Validation Error: Error parsing command string in AltSetGeneratorExerciseTime (day of week): " + CmdString)
self.mail.sendEmail(msgsubject, msgbody)
return
except Exception, e1:
self.LogError("Validation Error: Error parsing command string in AltSetGeneratorExerciseTime: " + CmdString)
self.LogError( str(e1))
self.mail.sendEmail(msgsubject, msgbody)
return
if Minute >59 or Hour > 23 or Day > 6: # validate minute
self.LogError("Validation Error: Error parsing command string in AltSetGeneratorExerciseTime (v1): " + CmdString)
self.mail.sendEmail(msgsubject, msgbody)
return
# Get System time and create a new datatime item with the target exercise time
GeneratorTime = datetime.datetime.strptime(self.GetDateTime(), "%A %B %d, %Y %H:%M")
# fix hours and min in gen time to the requested exercise time
TargetExerciseTime = GeneratorTime.replace(hour = Hour, minute = Minute, day = GeneratorTime.day)
# now change day of week
while TargetExerciseTime.weekday() != Day:
TargetExerciseTime += datetime.timedelta(1)
# convert total minutes between two datetime objects
DeltaTime = TargetExerciseTime - GeneratorTime
days, seconds = DeltaTime.days, DeltaTime.seconds
delta_hours = days * 24 + seconds // 3600
delta_minutes = (seconds % 3600) // 60
total_delta_min = (delta_hours * 60 + delta_minutes)
WriteValue = self.CalculateExerciseTime(total_delta_min)
with self.CommAccessLock:
# have seen the following values 0cf6,0f8c,0f5e
Last = WriteValue & 0x00FF
First = WriteValue >> 8
Data= []
Data.append(First) # Hour 0 - 23
Data.append(Last) # Min 0 - 59
self.ProcessMasterSlaveWriteTransaction("0004", len(Data) / 2, Data)
#
Data= []
Data.append(0) # The value for reg 0003 is always 0006. This appears
Data.append(6) # to be an indexed register
self.ProcessMasterSlaveWriteTransaction("0003", len(Data) / 2, Data)
return "Set Exercise Time Command sent (using legacy write)"
#---------- GeneratorDevice::SetGeneratorExerciseTime-------------------------------
def SetGeneratorExerciseTime(self, CmdString):
# use older style write to set exercise time if this flag is set
if self.bUseLegacyWrite:
return self.AltSetGeneratorExerciseTime(CmdString)
# extract time of day and day of week from command string
# format is day:hour:min Monday:15:00
msgbody = "Invalid command syntax for command setexercise"
try:
#Format we are looking for is "setexercise=Monday,12:20"
marker0 = CmdString.lower().find("setexercise")
marker1 = CmdString.find("=", marker0)
marker2 = CmdString.find(",",marker1)
marker3 = CmdString.find(":",marker2+1)
marker4 = CmdString.find(" ",marker3+1)
if -1 in [marker0, marker1, marker2, marker3]:
self.LogError("Validation Error: Error parsing command string in SetGeneratorExerciseTime (parse): " + CmdString)
return msgbody
DayStr = CmdString[marker1+1:marker2]
HourStr = CmdString[marker2+1:marker3]
if marker4 == -1: # was this the last char in the string or now space given?
MinuteStr = CmdString[marker3+1:]
else:
MinuteStr = CmdString[marker3+1:marker4]
Minute = int(MinuteStr)
Hour = int(HourStr)
DayOfWeek = { "sunday": 0,
"monday": 1, # decode for register values with day of week
"tuesday": 2, # NOTE: This decodes for datetime i.e. Sunday = 0, Monday=1
"wednesday": 3, #
"thursday": 4, #
"friday": 5, #
"saturday": 6,
}