forked from jgyates/genmon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgencthat.py
287 lines (228 loc) · 10.8 KB
/
gencthat.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
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# FILE: gencthat.py
# PURPOSE: gencthat.py add external current transformers via a RPi hat
#
# AUTHOR: jgyates
# DATE: 12-07-2021
#
# MODIFICATIONS:
#-------------------------------------------------------------------------------
import datetime, time, sys, signal, os, threading, collections, json, ssl
import atexit, getopt, requests
import math
try:
from spidev import SpiDev
except Exception as e1:
print("\n\nThis program requires the spidev module to be installed.\n")
print("Error: " + str(e1))
sys.exit(2)
try:
from genmonlib.myclient import ClientInterface
from genmonlib.mylog import SetupLogger
from genmonlib.myconfig import MyConfig
from genmonlib.mysupport import MySupport
from genmonlib.mycommon import MyCommon
from genmonlib.mythread import MyThread
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)
#------------ MCP3008 class ----------------------------------------------------
class MCP3008(MyCommon):
#---------- MCP3008::init -------------------------------------------------
def __init__(self, bus = 0, device = 0, log = None):
self.log = log
self.console = None
self.bus, self.device = bus, device
try:
self.spi = SpiDev()
self.open()
self.spi.max_speed_hz = 1000000 # 1MHz
except Exception as e1:
self.LogErrorLine("Error in MPC308 init: " + str(e1))
self.FatalError( "Error on opening SPI device: enable SPI or install CT HAT")
#---------- MCP3008::open -------------------------------------------------
def open(self):
try:
self.spi.open(self.bus, self.device)
self.spi.max_speed_hz = 1000000 # 1MHz
except Exception as e1:
self.LogErrorLine("Error in MPC308 open: " + str(e1))
#---------- MCP3008::read -------------------------------------------------
def read(self, channel = 0):
try:
adc = self.spi.xfer2([1, (8 + channel) << 4, 0])
data = ((adc[1] & 3) << 8) + adc[2]
return data
except Exception as e1:
self.LogErrorLine("Error in MPC308 read: " + str(e1))
#---------- MCP3008::close ------------------------------------------------
def close(self):
try:
self.spi.close()
except Exception as e1:
self.LogErrorLine("Error in MPC308 close: " + str(e1))
#------------ GenCTHat class ---------------------------------------------------
class GenCTHat(MySupport):
#------------ GenCTHat::init------------------------------------------------
def __init__(self,
log = None,
loglocation = ProgramDefaults.LogPath,
ConfigFilePath = MyCommon.DefaultConfPath,
host = ProgramDefaults.LocalHost,
port = ProgramDefaults.ServerPort,
console = None):
super(GenCTHat, self).__init__()
#https://tutorials-raspberrypi.com/mcp3008-read-out-analog-signals-on-the-raspberry-pi/
#https://forums.raspberrypi.com/viewtopic.php?t=237182
self.LogFileName = os.path.join(loglocation, "gencthat.log")
self.AccessLock = threading.Lock()
self.log = log
self.console = console
self.MonitorAddress = host
self.PollTime = 2
self.SampleTimeMS = 80
self.debug = False
configfile = os.path.join(ConfigFilePath, 'gencthat.conf')
try:
if not os.path.isfile(configfile):
self.LogConsole("Missing config file : " + configfile)
self.LogError("Missing config file : " + configfile)
sys.exit(1)
self.config = MyConfig(filename = configfile, section = 'gencthat', log = self.log)
self.PollTime = self.config.ReadValue('poll_frequency', return_type = float, default = 60)
self.Multiplier = self.config.ReadValue('multiplier', return_type = float, default = 0.218)
self.powerfactor = self.config.ReadValue('powerfactor', return_type = float, default = 1.0)
self.bus = self.config.ReadValue('bus', return_type = int, default = 1)
self.device = self.config.ReadValue('device', return_type = int, default = 0)
self.strict = self.config.ReadValue('strict', return_type = bool, default = True)
self.singlelegthreshold = self.config.ReadValue('singlelegthreshold', return_type = float, default = 0.6)
self.debug = self.config.ReadValue('debug', return_type = bool, default = False)
if self.MonitorAddress == None or not len(self.MonitorAddress):
self.MonitorAddress = ProgramDefaults.LocalHost
except Exception as e1:
self.LogErrorLine("Error reading " + configfile + ": " + str(e1))
self.LogConsole("Error reading " + configfile + ": " + str(e1))
sys.exit(1)
try:
self.adc = MCP3008(bus = self.bus, device = self.device, log = self.log)
self.adc.open()
self.Generator = ClientInterface(host = self.MonitorAddress, port = port, log = self.log)
#if not self.CheckGeneratorRequirement():
# self.LogError("Requirements not met. Exiting.")
# sys.exit(1)
# start thread monitor time for exercise
self.Threads["SensorCheckThread"] = MyThread(self.SensorCheckThread, Name = "SensorCheckThread", start = False)
self.Threads["SensorCheckThread"].Start()
signal.signal(signal.SIGTERM, self.SignalClose)
signal.signal(signal.SIGINT, self.SignalClose)
except Exception as e1:
self.LogErrorLine("Error in GenCTHat init: " + str(e1))
self.console.error("Error in GenCTHat init: " + str(e1))
sys.exit(1)
#---------- GenCTHat::SendCommand -----------------------------------------
def SendCommand(self, Command):
if len(Command) == 0:
return "Invalid Command"
try:
with self.AccessLock:
data = self.Generator.ProcessMonitorCommand(Command)
except Exception as e1:
self.LogErrorLine("Error calling ProcessMonitorCommand: " + str(Command))
data = ""
return data
#---------- GenCTHat::CheckGeneratorRequirement ---------------------------
def CheckGeneratorRequirement(self):
try:
data = self.SendCommand("generator: start_info_json")
StartInfo = {}
StartInfo = json.loads(data)
if not "evolution" in StartInfo["Controller"].lower() and not "nexus" in StartInfo["Controller"].lower():
self.LogError("Error: Only Evolution or Nexus controllers are supported for this feature: " + StartInfo["Controller"])
return False
return True
except Exception as e1:
self.LogErrorLine("Error in CheckGeneratorRequirement: " + str(e1))
return False
# ---------- GenCTHat::MillisecondsElapsed----------------------------------
def MillisecondsElapsed(self, ReferenceTime):
CurrentTime = datetime.datetime.now()
Delta = CurrentTime - ReferenceTime
return Delta.total_seconds() * 1000
# ---------- GenCTHat::SensorCheckThread------------------------------------
def SensorCheckThread(self):
time.sleep(1)
while True:
try:
CT1 = self.GetCTReading(channel = 0)
CT2 = self.GetCTReading(channel = 1)
if CT1 <= self.singlelegthreshold:
CT1 = 0
if CT2 <= self.singlelegthreshold:
CT2 = 0
self.LogDebug("CT1: %.2f, CT2: %.2f" % (CT1, CT2))
data = {}
data['strict'] = self.strict
data['current'] = CT1 + CT2
data['ctdata'] = [CT1, CT2]
data['powerfactor'] = self.powerfactor
return_string = json.dumps(data)
self.Generator.ProcessMonitorCommand("generator: set_power_data=" + return_string )
if self.WaitForExit("SensorCheckThread", float(self.PollTime)):
return
except Exception as e1:
self.LogErrorLine("Error in SensorCheckThread: " + str(e1))
if self.WaitForExit("SensorCheckThread", float(self.PollTime)):
return
# ----------GenCTHat::GetCTReading------------------------------------------
def GetCTReading(self, channel = 0):
try:
StartTime = datetime.datetime.now()
num_samples = 0
max = 0
min = 512
return_data = 0
while True:
sample = self.adc.read(channel = channel)
if sample > max :
max = sample
if sample < min :
min = sample
num_samples += 1
msElapsed = self.MillisecondsElapsed(StartTime)
if msElapsed > self.SampleTimeMS:
break
if max == 0 and min == 512:
self.LogDebug("No data read in GetCTSample")
return 0
else:
offset = max - 512
if 511 - min > offset :
offset = 511 - min
if offset <= 2:
offset = 0 #1 or 2 is most likely just noise on the clamps or in the traces on the board
self.LogDebug("sample: %d, max: %d, min: %d" % (sample, max, min))
self.LogDebug("ms elapsed: %d, num samples %d" % (msElapsed, num_samples))
return_data = offset * self.Multiplier
return return_data
except Exception as e1:
self.LogErrorLine("Error in GetCTReading: " + str(e1))
return 0
# ----------GenCTHat::SignalClose-------------------------------------------
def SignalClose(self, signum, frame):
self.Close()
sys.exit(1)
# ----------GenCTHat::Close-------------------------------------------------
def Close(self):
self.KillThread("SensorCheckThread")
self.Generator.Close()
#-------------------------------------------------------------------------------
if __name__ == "__main__":
console, ConfigFilePath, address, port, loglocation, log = MySupport.SetupAddOnProgram("gencthat")
GenCTHatInstance = GenCTHat(log = log, loglocation = loglocation, ConfigFilePath = ConfigFilePath, host = address, port = port, console = console)
while True:
time.sleep(0.5)
sys.exit(1)