Mercurial > templog
annotate web/log.py @ 125:397ac5c079bf
avoid bad values
author | Matt Johnston <matt@ucc.asn.au> |
---|---|
date | Wed, 10 Oct 2012 22:58:35 +0800 |
parents | 7f3fc0980df1 |
children | 6a9419ac8f77 |
rev | line source |
---|---|
78 | 1 # -*- coding: utf-8 -*- |
37
8da0fdadc8d7
- Getting there, update has problems
Matt Johnston <matt@ucc.asn.au>
parents:
33
diff
changeset
|
2 #:vim:et:ts=4:sts=4:sw=4: |
27 | 3 import rrdtool |
4 import os | |
29 | 5 import os.path |
27 | 6 import sys |
29 | 7 import glob |
31
5e75e08d20ac
- Various fixes for web server, kind of works
Matt Johnston <matt@ucc.asn.au>
parents:
29
diff
changeset
|
8 import hashlib |
5e75e08d20ac
- Various fixes for web server, kind of works
Matt Johnston <matt@ucc.asn.au>
parents:
29
diff
changeset
|
9 import tempfile |
37
8da0fdadc8d7
- Getting there, update has problems
Matt Johnston <matt@ucc.asn.au>
parents:
33
diff
changeset
|
10 import time |
8da0fdadc8d7
- Getting there, update has problems
Matt Johnston <matt@ucc.asn.au>
parents:
33
diff
changeset
|
11 import syslog |
44 | 12 import sqlite3 |
49
206294a354a7
update values one at a time, ignore failure
Matt Johnston <matt@ucc.asn.au>
parents:
45
diff
changeset
|
13 import traceback |
67 | 14 import datetime |
75
ca08442635ca
report raw ds18b20 values instead
Matt Johnston <matt@ucc.asn.au>
parents:
73
diff
changeset
|
15 import struct |
77 | 16 import binascii |
29 | 17 from colorsys import hls_to_rgb |
27 | 18 |
28 | 19 import config |
27 | 20 |
21 def sensor_rrd_path(s): | |
28 | 22 return '%s/sensor_%s.rrd' % (config.DATA_PATH, s) |
27 | 23 |
29 | 24 # returns (path, sensor_name) tuples |
25 def all_sensors(): | |
26 return [(r, os.path.basename(r[:-4])) | |
27 for r in glob.glob('%s/*.rrd' % config.DATA_PATH)] | |
28 | |
27 | 29 def create_rrd(sensor_id): |
43
ea99aae87884
Create with a start date so that it works
Matt Johnston <matt@ucc.asn.au>
parents:
40
diff
changeset
|
30 # start date of 10 seconds into 1970 is used so that we can |
ea99aae87884
Create with a start date so that it works
Matt Johnston <matt@ucc.asn.au>
parents:
40
diff
changeset
|
31 # update with prior values straight away. |
61 | 32 if 'voltage' in sensor_id: |
63 | 33 args = [ |
34 '--step', '3600', | |
35 'DS:temp:GAUGE:7200:1:10', | |
36 'RRA:AVERAGE:0.5:1:87600'] | |
61 | 37 else: |
63 | 38 args = [ |
39 '--step', '300', | |
88
6f4497a448e8
increase temperature logging range
Matt Johnston <matt@ucc.asn.au>
parents:
78
diff
changeset
|
40 'DS:temp:GAUGE:600:-100:500', |
61 | 41 'RRA:AVERAGE:0.5:1:1051200'] |
27 | 42 |
61 | 43 rrdtool.create(sensor_rrd_path(sensor_id), |
63 | 44 '--start', 'now-60d', |
61 | 45 *args) |
29 | 46 |
47 # stolen from viewmtn, stolen from monotone-viz | |
48 def colour_from_string(str): | |
49 def f(off): | |
50 return ord(hashval[off]) / 256.0 | |
31
5e75e08d20ac
- Various fixes for web server, kind of works
Matt Johnston <matt@ucc.asn.au>
parents:
29
diff
changeset
|
51 hashval = hashlib.sha1(str).digest() |
29 | 52 hue = f(5) |
53 li = f(1) * 0.15 + 0.55 | |
54 sat = f(2) * 0.5 + .5 | |
55 return ''.join(["%.2x" % int(x * 256) for x in hls_to_rgb(hue, li, sat)]) | |
56 | |
57 def graph_png(start, length): | |
104
7f3fc0980df1
- few more web tweaks. don't fsync, it's slow.
Matt Johnston <matt@ucc.asn.au>
parents:
103
diff
changeset
|
58 os.environ['MATT_PNG_BODGE_COMPRESS'] = '4' |
7f3fc0980df1
- few more web tweaks. don't fsync, it's slow.
Matt Johnston <matt@ucc.asn.au>
parents:
103
diff
changeset
|
59 os.environ['MATT_PNG_BODGE_FILTER'] = 'paeth' |
29 | 60 rrds = all_sensors() |
61 | |
62 graph_args = [] | |
61 | 63 have_volts = False |
29 | 64 for n, (rrdfile, sensor) in enumerate(rrds): |
61 | 65 if 'avrtemp' in sensor: |
66 continue | |
67 if 'voltage' in sensor: | |
68 have_volts = True | |
69 vname = 'scalevolts' | |
71
7d243ba2dd39
swap the left and right scales, kind of clunky
Matt Johnston <matt@ucc.asn.au>
parents:
69
diff
changeset
|
70 graph_args.append('DEF:%(vname)s=%(rrdfile)s:temp:AVERAGE:step=3600' % locals()) |
78 | 71 unit = 'V' |
61 | 72 else: |
73 vname = 'temp%d' % n | |
71
7d243ba2dd39
swap the left and right scales, kind of clunky
Matt Johnston <matt@ucc.asn.au>
parents:
69
diff
changeset
|
74 graph_args.append('DEF:raw%(vname)s=%(rrdfile)s:temp:AVERAGE' % locals()) |
101 | 75 # limit max temp to 50 |
76 graph_args.append('CDEF:%(vname)s=raw%(vname)s,35,GT,UNKN,raw%(vname)s,0.1,*,2,+,IF' % locals()) | |
78 | 77 unit = '<span face="Liberation Serif">º</span>C' |
78 | |
125 | 79 try: |
80 last_value = float(rrdtool.info(rrdfile)['ds[temp].last_ds']) | |
81 format_last_value = ('%f' % last_value).rstrip('0') + unit | |
82 except ValueError: | |
83 format_last_value = 'Bad' | |
29 | 84 width = config.LINE_WIDTH |
85 legend = config.SENSOR_NAMES.get(sensor, sensor) | |
31
5e75e08d20ac
- Various fixes for web server, kind of works
Matt Johnston <matt@ucc.asn.au>
parents:
29
diff
changeset
|
86 colour = config.SENSOR_COLOURS.get(legend, colour_from_string(sensor)) |
78 | 87 print_legend = '%s (%s)' % (legend, format_last_value) |
88 graph_args.append('LINE%(width)f:%(vname)s#%(colour)s:%(print_legend)s' % locals()) | |
29 | 89 |
67 | 90 end = int(start+length) |
91 start = int(start) | |
92 | |
29 | 93 tempf = tempfile.NamedTemporaryFile() |
67 | 94 dateformat = '%H:%M:%S %Y-%m-%d' |
95 watermark = ("Now %s\t" | |
96 "Start %s\t" | |
97 "End %s" % ( | |
98 datetime.datetime.now().strftime(dateformat), | |
99 datetime.datetime.fromtimestamp(start).strftime(dateformat), | |
100 datetime.datetime.fromtimestamp(end).strftime(dateformat) )) | |
101 | |
102 args = [tempf.name, '-s', str(start), | |
103 '-e', str(end), | |
31
5e75e08d20ac
- Various fixes for web server, kind of works
Matt Johnston <matt@ucc.asn.au>
parents:
29
diff
changeset
|
104 '-w', str(config.GRAPH_WIDTH), |
5e75e08d20ac
- Various fixes for web server, kind of works
Matt Johnston <matt@ucc.asn.au>
parents:
29
diff
changeset
|
105 '-h', str(config.GRAPH_HEIGHT), |
29 | 106 '--slope-mode', |
31
5e75e08d20ac
- Various fixes for web server, kind of works
Matt Johnston <matt@ucc.asn.au>
parents:
29
diff
changeset
|
107 '--border', '0', |
73
0a8639039453
Get rid of axes labels, tidy html
Matt Johnston <matt@ucc.asn.au>
parents:
71
diff
changeset
|
108 # '--vertical-label', 'Voltage', |
71
7d243ba2dd39
swap the left and right scales, kind of clunky
Matt Johnston <matt@ucc.asn.au>
parents:
69
diff
changeset
|
109 '--y-grid', '0.1:1', |
7d243ba2dd39
swap the left and right scales, kind of clunky
Matt Johnston <matt@ucc.asn.au>
parents:
69
diff
changeset
|
110 '--dynamic-labels', |
56 | 111 '--grid-dash', '1:0', |
77 | 112 '--zoom', str(config.ZOOM), |
56 | 113 '--color', 'GRID#00000000', |
114 '--color', 'MGRID#aaaaaa', | |
31
5e75e08d20ac
- Various fixes for web server, kind of works
Matt Johnston <matt@ucc.asn.au>
parents:
29
diff
changeset
|
115 '--color', 'BACK#ffffff', |
67 | 116 '--disable-rrdtool-tag', |
78 | 117 '--pango-markup', |
67 | 118 '--watermark', watermark, |
31
5e75e08d20ac
- Various fixes for web server, kind of works
Matt Johnston <matt@ucc.asn.au>
parents:
29
diff
changeset
|
119 '--imgformat', 'PNG'] \ |
29 | 120 + graph_args |
67 | 121 args += ['--font', 'DEFAULT:12:%s' % config.GRAPH_FONT] |
122 args += ['--font', 'WATERMARK:10:%s' % config.GRAPH_FONT] | |
61 | 123 if have_volts: |
71
7d243ba2dd39
swap the left and right scales, kind of clunky
Matt Johnston <matt@ucc.asn.au>
parents:
69
diff
changeset
|
124 args += ['--right-axis', '10:-20', # matches the scalevolts CDEF above |
73
0a8639039453
Get rid of axes labels, tidy html
Matt Johnston <matt@ucc.asn.au>
parents:
71
diff
changeset
|
125 '--right-axis-format', '%.0lf', |
0a8639039453
Get rid of axes labels, tidy html
Matt Johnston <matt@ucc.asn.au>
parents:
71
diff
changeset
|
126 # '--right-axis-label', 'Temperature' |
0a8639039453
Get rid of axes labels, tidy html
Matt Johnston <matt@ucc.asn.au>
parents:
71
diff
changeset
|
127 ] |
61 | 128 |
104
7f3fc0980df1
- few more web tweaks. don't fsync, it's slow.
Matt Johnston <matt@ucc.asn.au>
parents:
103
diff
changeset
|
129 print>>sys.stderr, ' '.join("'%s'" % s for s in args) |
29 | 130 rrdtool.graph(*args) |
104
7f3fc0980df1
- few more web tweaks. don't fsync, it's slow.
Matt Johnston <matt@ucc.asn.au>
parents:
103
diff
changeset
|
131 #return tempf |
29 | 132 return tempf.read() |
133 | |
125 | 134 def validate_values(measurements): |
135 for m in measurements: | |
136 if m == 85: | |
137 yield 'U' | |
138 else: | |
139 yield '%f' % m | |
140 | |
27 | 141 def sensor_update(sensor_id, measurements, first_real_time, time_step): |
142 try: | |
143 open(sensor_rrd_path(sensor_id)) | |
144 except IOError, e: | |
145 create_rrd(sensor_id) | |
146 | |
37
8da0fdadc8d7
- Getting there, update has problems
Matt Johnston <matt@ucc.asn.au>
parents:
33
diff
changeset
|
147 if measurements: |
125 | 148 values = ['%d:%s' % p for p in |
37
8da0fdadc8d7
- Getting there, update has problems
Matt Johnston <matt@ucc.asn.au>
parents:
33
diff
changeset
|
149 zip((first_real_time + time_step*t for t in xrange(len(measurements))), |
125 | 150 validate_values(measurements))] |
27 | 151 |
37
8da0fdadc8d7
- Getting there, update has problems
Matt Johnston <matt@ucc.asn.au>
parents:
33
diff
changeset
|
152 rrdfile = sensor_rrd_path(sensor_id) |
40 | 153 # XXX what to do here when it fails... |
49
206294a354a7
update values one at a time, ignore failure
Matt Johnston <matt@ucc.asn.au>
parents:
45
diff
changeset
|
154 for v in values: |
206294a354a7
update values one at a time, ignore failure
Matt Johnston <matt@ucc.asn.au>
parents:
45
diff
changeset
|
155 try: |
206294a354a7
update values one at a time, ignore failure
Matt Johnston <matt@ucc.asn.au>
parents:
45
diff
changeset
|
156 rrdtool.update(rrdfile, v) |
63 | 157 except rrdtool.error, e: |
104
7f3fc0980df1
- few more web tweaks. don't fsync, it's slow.
Matt Johnston <matt@ucc.asn.au>
parents:
103
diff
changeset
|
158 print>>sys.stderr, "Bad rrdtool update '%s': %s" % (v, str(e)) |
49
206294a354a7
update values one at a time, ignore failure
Matt Johnston <matt@ucc.asn.au>
parents:
45
diff
changeset
|
159 traceback.print_exc(file=sys.stderr) |
33 | 160 |
37
8da0fdadc8d7
- Getting there, update has problems
Matt Johnston <matt@ucc.asn.au>
parents:
33
diff
changeset
|
161 # be paranoid |
104
7f3fc0980df1
- few more web tweaks. don't fsync, it's slow.
Matt Johnston <matt@ucc.asn.au>
parents:
103
diff
changeset
|
162 #f = file(rrdfile) |
7f3fc0980df1
- few more web tweaks. don't fsync, it's slow.
Matt Johnston <matt@ucc.asn.au>
parents:
103
diff
changeset
|
163 #os.fsync(f.fileno()) |
27 | 164 |
103 | 165 def debug_file(mode='r'): |
166 return open('%s/debug.log' % config.DATA_PATH, mode) | |
167 | |
33 | 168 def record_debug(lines): |
103 | 169 f = debug_file('a+') |
37
8da0fdadc8d7
- Getting there, update has problems
Matt Johnston <matt@ucc.asn.au>
parents:
33
diff
changeset
|
170 f.write('===== %s =====\n' % time.strftime('%a, %d %b %Y %H:%M:%S')) |
33 | 171 f.writelines(('%s\n' % s for s in lines)) |
172 f.flush() | |
173 return f | |
174 | |
103 | 175 |
176 def tail_debug_log(): | |
177 f = debug_file() | |
178 f.seek(0, 2) | |
179 size = f.tell() | |
180 f.seek(max(0, size-30000)) | |
181 return '\n'.join(l.strip() for l in f.readlines()[-400:]) | |
182 | |
75
ca08442635ca
report raw ds18b20 values instead
Matt Johnston <matt@ucc.asn.au>
parents:
73
diff
changeset
|
183 def convert_ds18b20_12bit(reading): |
ca08442635ca
report raw ds18b20 values instead
Matt Johnston <matt@ucc.asn.au>
parents:
73
diff
changeset
|
184 value = struct.unpack('>h', binascii.unhexlify(reading))[0] |
ca08442635ca
report raw ds18b20 values instead
Matt Johnston <matt@ucc.asn.au>
parents:
73
diff
changeset
|
185 return value * 0.0625 |
ca08442635ca
report raw ds18b20 values instead
Matt Johnston <matt@ucc.asn.au>
parents:
73
diff
changeset
|
186 |
94 | 187 def time_rem(name, entries): |
188 val_ticks = int(entries[name]) | |
95 | 189 val_rem = int(entries['%s_rem' % name]) |
99
1a88bb989afb
fix off-by-one in remainder code
Matt Johnston <matt@ucc.asn.au>
parents:
95
diff
changeset
|
190 tick_wake = int(entries['tick_wake']) + 1 |
94 | 191 tick_secs = int(entries['tick_secs']) |
192 return val_ticks + float(val_rem) * tick_secs / tick_wake | |
193 | |
27 | 194 def parse(lines): |
104
7f3fc0980df1
- few more web tweaks. don't fsync, it's slow.
Matt Johnston <matt@ucc.asn.au>
parents:
103
diff
changeset
|
195 |
7f3fc0980df1
- few more web tweaks. don't fsync, it's slow.
Matt Johnston <matt@ucc.asn.au>
parents:
103
diff
changeset
|
196 start_time = time.time() |
33 | 197 |
37
8da0fdadc8d7
- Getting there, update has problems
Matt Johnston <matt@ucc.asn.au>
parents:
33
diff
changeset
|
198 debugf = record_debug(lines) |
33 | 199 |
27 | 200 entries = dict(l.split('=', 1) for l in lines) |
31
5e75e08d20ac
- Various fixes for web server, kind of works
Matt Johnston <matt@ucc.asn.au>
parents:
29
diff
changeset
|
201 if len(entries) != len(lines): |
27 | 202 raise Exception("Keys are not unique") |
203 | |
204 num_sensors = int(entries['sensors']) | |
37
8da0fdadc8d7
- Getting there, update has problems
Matt Johnston <matt@ucc.asn.au>
parents:
33
diff
changeset
|
205 num_measurements = int(entries['measurements']) |
27 | 206 |
37
8da0fdadc8d7
- Getting there, update has problems
Matt Johnston <matt@ucc.asn.au>
parents:
33
diff
changeset
|
207 sensors = [entries['sensor_id%d' % n] for n in xrange(num_sensors)] |
27 | 208 |
209 meas = [] | |
210 for s in sensors: | |
211 meas.append([]) | |
212 | |
213 for n in xrange(num_measurements): | |
77 | 214 vals = [convert_ds18b20_12bit(x) for x in entries["meas%d" % n].strip().split()] |
27 | 215 if len(vals) != num_sensors: |
216 raise Exception("Wrong number of sensors for measurement %d" % n) | |
217 # we make an array of values for each sensor | |
218 for s in xrange(num_sensors): | |
219 meas[s].append(vals[s]) | |
220 | |
94 | 221 avr_now = time_rem('now', entries) |
222 avr_first_time = time_rem('first_time', entries) | |
223 avr_comms_time = time_rem('comms_time', entries) | |
27 | 224 time_step = float(entries['time_step']) |
225 | |
94 | 226 debugf.write('now %f, comms_time %f, first_time %f, delta %f\n' % |
227 (avr_now, avr_comms_time, avr_first_time, avr_now - avr_comms_time)) | |
228 | |
61 | 229 if 'avrtemp' in entries: |
230 avrtemp = val_scale(int(entries['avrtemp'])) | |
231 sensor_update('avrtemp', [avrtemp], time.time(), 1) | |
232 | |
233 if 'voltage' in entries: | |
234 voltage = 0.001 * int(entries['voltage']) | |
235 sensor_update('voltage', [voltage], time.time(), 1) | |
236 | |
40 | 237 #sqlite |
238 # - time | |
239 # - voltage | |
240 # - boot time | |
241 | |
27 | 242 first_real_time = time.time() - (avr_now - avr_first_time) |
243 | |
244 for sensor_id, measurements in zip(sensors, meas): | |
40 | 245 # XXX sqlite add |
27 | 246 sensor_update(sensor_id, measurements, first_real_time, time_step) |
33 | 247 |
104
7f3fc0980df1
- few more web tweaks. don't fsync, it's slow.
Matt Johnston <matt@ucc.asn.au>
parents:
103
diff
changeset
|
248 timedelta = time.time() - start_time |
7f3fc0980df1
- few more web tweaks. don't fsync, it's slow.
Matt Johnston <matt@ucc.asn.au>
parents:
103
diff
changeset
|
249 debugf.write("Updated %d sensors in %.2f secs\n" % (len(sensors), timedelta)) |
33 | 250 debugf.flush() |