Newer
Older
#!/usr/bin/env python2.7
# encoding: utf-8
import os
import sys
os.environ["USB_DEVFS_PATH"] = "/dev/bus/usb/temper"
import socket
import temper
import threading
import time
import Queue
import smtplib
from email.mime.text import MIMEText
from email.Utils import formatdate
READINGINTERVAL = 10
EXPORTINTERVAL = 10
UNIX_SOCKET = "/var/run/collectd-unixsock"
HOSTNAME = "hugin.stusta.mhn.de"
FLOOR_LIMIT = 25
CEILING_LIMIT = 30
MAX_OUTDOOR_DIFF = 10
MAILINTERVAL = 3600
class TempReader(threading.Thread):
def __init__(self, mq):
threading.Thread.__init__(self)
self.mq = mq
self.last_mail = 0
self.iteration = 0
def run(self):
while True:
try:
th = temper.TemperHandler()
# TODO naming things is hard!
for i, temp_device in th._devices.iteritems():
temp_sensor = temperature_sensors.get(i)
if temp_sensor:
try:
temp_c = temp_device.get_temperature(calibration=temp_sensor.calibration)
temp_sensor.update(temp_c)
except:
pass
ow.init( 'localhost:4304' )
for a, owid in iter(temperature_sensors):
if a == 'serial':
temp_sensor = temperature_sensors.get((a, owid))
try:
temp_c = float(ow.Sensor( '/uncached/'+ owid ).temperature)
if temp_c != float('85'):
temp_sensor.update(temp_c)
except:
pass
ow.finish()
floor = temperature_sensors_usb_by_name['floor'].temperature
floorserial = temperature_sensors_serial_by_name['floorserial'].temperature
ceiling = temperature_sensors_usb_by_name['ceiling'].temperature
ceilserial = temperature_sensors_serial_by_name['ceilserial'].temperature
outdoor = temperature_sensors_usb_by_name['outdoor'].temperature
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
# error case: some sensor is not working!
if floor is None:
floor = 9000
if ceiling is None:
ceiling = 9001
if outdoor is None:
# for the difference ...
outdoor = 0
if self.iteration > 1 and self.last_mail + MAILINTERVAL < time.time() and \
((floor > FLOOR_LIMIT and floor - MAX_OUTDOOR_DIFF > outdoor) or \
(ceiling > CEILING_LIMIT and ceiling - MAX_OUTDOOR_DIFF > outdoor)):
self.last_mail = time.time()
if DEBUG:
print "write mail ..."
body = u'''DON'T PANIC!
... aber die Temperatur im Serverraum beträgt:
Boden: {:.2f} ℃
Decke: {:.2f} ℃
Outdoor: {:.2f} ℃
Der Temperator
--
oooo$$$$$$$$$$$$oooo
oo$$$$$$$$$$$$$$$$$$$$$$$$o
oo$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$o o$ $$ o$
o $ oo o$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$o $$ $$ $$o$
oo $ $ "$ o$$$$$$$$$ $$$$$$$$$$$$$ $$$$$$$$$o $$$o$$o$
"$$$$$$o$ o$$$$$$$$$ $$$$$$$$$$$ $$$$$$$$$$o $$$$$$$$
$$$$$$$ $$$$$$$$$$$ $$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$ $$$$$$$$$$$$$$ """$$$
"$$$""""$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ "$$$
$$$ o$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ "$$$o
o$$" $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$o
$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$" "$$$$$$ooooo$$$$o
o$$$oooo$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ o$$$$$$$$$$$$$$$$$
$$$$$$$$"$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$""""""""
"""" $$$$ "$$$$$$$$$$$$$$$$$$$$$$$$$$$$" o$$$
"$$$o """$$$$$$$$$$$$$$$$$$"$$" $$$
$$$o "$$""$$$$$$"""" o$$$
$$$$o o$$$"
"$$$$o o$$$$$$o"$$$$o o$$$$
"$$$$$oo ""$$$$o$$$$$o o$$$$""
""$$$$$oooo "$$$o$$$$$$$$$"""
""$$$$$$$oo $$$$$$$$$$
""""$$$$$$$$$$$
$$$$$$$$$$$$
$$$$$$$$$$"
"$$$""""
'''
msg = MIMEText(body.format(floor, ceiling, outdoor), _charset="UTF-8")
src = "Temperator <root@hugin.stusta.mhn.de>"
msg['Subject'] = u"Temperaturalarm Serverraum"
msg['From'] = src
dst = ["jn@stusta.de", "maxi@stusta.de"]
else:
dst = ["admins@stustanet.de"]
msg['To'] = ", ".join(dst)
msg['Date'] = formatdate(localtime=True)
self.mq.put((src, dst, msg.as_string()))
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
time.sleep(READINGINTERVAL)
class Mail0r(threading.Thread):
def __init__(self, mq):
threading.Thread.__init__(self)
self.mq = mq
def run(self):
while True:
try:
sender, recipient, msg = self.mq.get(True, 3600)
except Exception as e:
if DEBUG:
print e
continue
try:
s = smtplib.SMTP("localhost")
s.sendmail(sender, recipient, msg)
s.quit()
except Exception as e:
if DEBUG:
print e
pass
class Exp0rt0r(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.socket = None
def run(self):
while True:
if not self.socket:
s = socket.socket(socket.AF_UNIX)
try:
s.connect(UNIX_SOCKET)
self.socket = s
except Exception as e:
if DEBUG:
print e
pass
for temp_sensor in temperature_sensors.values():
temp_c, exported = temp_sensor.get_export()
if self.socket and not exported:
data = "PUTVAL \"%s/tail-temperature/temperature-%s\" interval=%i N:%f\n" % \
(HOSTNAME, temp_sensor.name, EXPORTINTERVAL, temp_c)
try:
if DEBUG:
recv = []
while True:
try:
recv = self.socket.recv(2**12)
except socket.error as e:
if e.errno == 11: #EAGAIN
break
raise e
recv = ''.join(recv)
if DEBUG:
print "socket read", recv.strip()
except Exception as e:
if DEBUG:
print e
try:
self.socket.close()
except:
pass
self.socket = None
time.sleep(EXPORTINTERVAL)
#TODO: baseclass TempSensor?
class TempSensorUSB():
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
def __init__(self, name, calibration, bus, device):
self.name = name
self.calibration = calibration
self.bus = bus
self.device = device
self.last_updated = None
self.temperature = None
self.exported = True
self._lock = threading.RLock()
@property
def usb_id(self):
return self.bus, self.device
def update(self, temperature):
with self._lock:
self.temperature = temperature
self.exported = False
self.last_updated = time.time()
if DEBUG:
print "update", self
def get_export(self):
with self._lock:
exported = self.exported
self.exported = True
if DEBUG:
print "read", self
return self.temperature, exported
def __str__(self):
with self._lock:
return "%s (bus:%s, device:%s, calibration:%i) temperature: %s, last_updated:%s, exported:%s" % \
(self.name, self.bus, self.device, self.calibration, self.temperature, self.last_updated,
self.exported)
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
class TempSensorSerial():
def __init__(self, name, owid):
self.name = name
self.owid = owid
self.last_updated = None
self.temperature = None
self.exported = True
self._lock = threading.RLock()
def update(self, temperature):
with self._lock:
self.temperature = temperature
self.exported = False
self.last_updated = time.time()
if DEBUG:
print "update", self
def get_export(self):
with self._lock:
exported = self.exported
self.exported = True
if DEBUG:
print "read", self
return self.temperature, exported
def __str__(self):
with self._lock:
return "%s (owid:%s) temperature: %s, last_updated:%s, exported:%s" % \
(self.name, self.owid, self.temperature, self.last_updated,
self.exported)
#TODO:Type in key, only one dict?
temperature_sensors_usb_by_name = {}
temperature_sensors_serial_by_name = {}
for name, calibration, bus, device in [('floor', 500, '001', '001'), ('ceiling', 300, '002', '001'), ('outdoor', 330, '003', '001')]:
temperature_sensors[(bus, device)] = TempSensorUSB(name, calibration, bus, device)
temperature_sensors_usb_by_name[name] = temperature_sensors[(bus, device)]
for name, owid in [('floorserial', '10.C238A5010800'), ('ceilserial', '10.0C33A5010800')]:
temperature_sensors[('serial', owid)] = TempSensorSerial(name, owid)
temperature_sensors_serial_by_name[name] = temperature_sensors[('serial', owid)]
if __name__ == "__main__":
mailqueue = Queue.Queue()
readerfred = TempReader(mailqueue)
readerfred.setDaemon(True)
readerfred.start()
time.sleep(2)
exp0rtfred = Exp0rt0r()
exp0rtfred.setDaemon(True)
exp0rtfred.start()
mail0r = Mail0r(mailqueue)
mail0r.setDaemon(True)
mail0r.start()
while True:
time.sleep(3600)