forked from jgyates/genmon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gentemp.py
289 lines (232 loc) · 10.8 KB
/
gentemp.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
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# FILE: gentemp.py
# PURPOSE: gentemp.py add support for type K thermocouples and DS18B20 temp sesnsors
#
# AUTHOR: jgyates
# DATE: 09-12-2019
#
# MODIFICATIONS:
#-------------------------------------------------------------------------------
import datetime, time, sys, signal, os, threading, collections, json, ssl
import atexit, getopt
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)
try:
import os, time, glob
except Exception as e1:
print("Error importing modules! :" + str(e1))
sys.exit(2)
# Typical reading
# 73 01 4b 46 7f ff 0d 10 41 : crc=41 YES
# 73 01 4b 46 7f ff 0d 10 41 t=23187
#------------ GenTemp class ----------------------------------------------------
class GenTemp(MySupport):
#------------ GenTemp::init-------------------------------------------------
def __init__(self,
log = None,
loglocation = ProgramDefaults.LogPath,
ConfigFilePath = MyCommon.DefaultConfPath,
host = ProgramDefaults.LocalHost,
port = ProgramDefaults.ServerPort,
console = None):
super(GenTemp, self).__init__()
self.LogFileName = os.path.join(loglocation, "gentemp.log")
self.AccessLock = threading.Lock()
# log errors in this module to a file
self.log = log
self.console = console
self.LastValues = {}
self.MonitorAddress = host
self.debug = False
self.PollTime = 1
self.BlackList = None
configfile = os.path.join(ConfigFilePath, 'gentemp.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 = 'gentemp', log = self.log)
self.UseMetric = self.config.ReadValue('use_metric', return_type = bool, default = False)
self.PollTime = self.config.ReadValue('poll_frequency', return_type = float, default = 1)
self.debug = self.config.ReadValue('debug', return_type = bool, default = False)
self.DeviceLabels = self.GetParamList(self.config.ReadValue('device_labels', default = None))
self.BlackList = self.GetParamList(self.config.ReadValue('blacklist', default = None))
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.Generator = ClientInterface(host = self.MonitorAddress, port = port, log = self.log)
self.DeviceList = self.EnumDevices()
if not len(self.DeviceList):
self.LogConsole("No sensors found.")
self.LogError("No sensors found.")
sys.exit(1)
# start thread monitor time for exercise
self.Threads["GenTempThread"] = MyThread(self.GenTempThread, Name = "GenTempThread", start = False)
self.Threads["GenTempThread"].Start()
signal.signal(signal.SIGTERM, self.SignalClose)
signal.signal(signal.SIGINT, self.SignalClose)
except Exception as e1:
self.LogErrorLine("Error in GenTemp init: " + str(e1))
self.LogConsole("Error in GenTemp init: " + str(e1))
sys.exit(1)
#---------- GenTemp::GetParamList -----------------------------------------
def GetParamList(self, input_string):
ReturnValue = []
try:
if input_string != None:
if len(input_string):
ReturnList = input_string.strip().split(",")
if len(ReturnList):
for Items in ReturnList:
Items = Items.strip()
if len(Items):
ReturnValue.append(Items)
if len(ReturnValue):
return ReturnValue
return None
except Exception as e1:
self.LogErrorLine("Error in GetParamList: " + str(e1))
return None
#---------- GenTemp::EnumDevices ------------------------------------------
def EnumDevices(self):
DeviceList = []
try:
# enum DS18B20 temp sensors
for sensor in glob.glob("/sys/bus/w1/devices/28-*/w1_slave"):
if not self.CheckBlackList(sensor) and self.DeviceValid(sensor):
self.LogDebug("Found DS18B20 : " + sensor)
DeviceList.append(sensor)
# enum type K thermocouples
#for sensor in glob.glob("/sys/bus/w1/devices/w1_bus_master*/3b-*/w1_slave"):
for sensor in glob.glob("/sys/bus/w1/devices/3b-*/w1_slave"):
if not self.CheckBlackList(sensor) and self.DeviceValid(sensor):
self.LogDebug("Found type K thermocouple : " + sensor)
DeviceList.append(sensor)
return DeviceList
except Exception as e1:
self.LogErrorLine("Error in EnumDevices: " + str(e1))
return DeviceList
#------------ GenTemp::ReadData --------------------------------------------
def ReadData(self, device):
try:
f = open(device, "r")
data = f.read()
f.close()
return data
except Exception as e1:
self.LogErrorLine("Error in ReadData for " + device + " : " + str(e1))
return None
#------------ GenTemp::DeviceValid -----------------------------------------
def DeviceValid(self, device):
try:
data = self.ReadData(device)
if isinstance(data, str) and "YES" in data and " crc=" in data and " t=" in data:
return True
return False
except Exception as e1:
self.LogErrorLine("Error in DeviceValid for " + device + " : " + str(e1))
return False
#------------ GenTemp::ParseData -------------------------------------------
def ParseData(self, data):
try:
if self.UseMetric:
units = "C"
else:
units = "F"
if not isinstance(data, str):
return None, units
if not len(data):
return None, units
(discard, sep, reading) = data.partition(' t=')
t = float(reading) / 1000.0
if not self.UseMetric:
return self.ConvertCelsiusToFahrenheit(t), units
else:
return t, units
except Exception as e1:
self.LogErrorLine("Error in ParseData: " + str(e1))
return None, units
#------------ GenTemp::GetIDFromDeviceName ---------------------------------
def GetIDFromDeviceName(self, device):
try:
if "28-" in device or "3b-" in device:
id = device.split("/")[5]
return id
except Exception as e1:
self.LogErrorLine("Error in GetIDFromDeviceName for " + device + " : " + str(e1))
return "UNKNOWN_ID"
#---------- GenTemp::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
# ---------- GenTemp::CheckBlackList-----------------------------------------
def CheckBlackList(self, device):
if not isinstance(self.BlackList, list):
return False
return any(blacklistitem in device for blacklistitem in self.BlackList)
# ---------- GenTemp::GenTempThread-----------------------------------------
def GenTempThread(self):
time.sleep(1)
while True:
try:
labelIndex = 0
ReturnDeviceData = []
for sensor in self.DeviceList:
temp, units = self.ParseData(self.ReadData(sensor))
if temp != None:
self.LogDebug("Device: %s Reading: %.2f %s" % (self.GetIDFromDeviceName(sensor), temp, units))
if isinstance(self.DeviceLabels, list) and len(self.DeviceLabels) and (labelIndex < len(self.DeviceLabels)):
device_label = self.DeviceLabels[labelIndex]
else:
device_label = self.GetIDFromDeviceName(sensor)
ReturnDeviceData.append({device_label : "%.2f %s" % (temp, units)})
labelIndex += 1
return_string = json.dumps({"External Temperature Sensors": ReturnDeviceData})
self.SendCommand("generator: set_temp_data=" + return_string )
self.LogDebug(return_string)
if self.WaitForExit("GenTempThread", float(self.PollTime)):
return
except Exception as e1:
self.LogErrorLine("Error in GenTempThread: " + str(e1))
if self.WaitForExit("GenTempThread", float(self.PollTime * 60)):
return
# ----------GenTemp::SignalClose--------------------------------------------
def SignalClose(self, signum, frame):
self.Close()
sys.exit(1)
# ----------GenTemp::Close----------------------------------------------
def Close(self):
self.LogError("GenTemp Exit")
self.KillThread("GenTempThread")
self.Generator.Close()
#-------------------------------------------------------------------------------
if __name__ == "__main__":
console, ConfigFilePath, address, port, loglocation, log = MySupport.SetupAddOnProgram("gentemp")
GenTempInstance = GenTemp(log = log, loglocation = loglocation, ConfigFilePath = ConfigFilePath, host = address, port = port, console = console)
while True:
time.sleep(0.5)
sys.exit(1)