145
|
1 # -*- coding: utf-8 -*- |
|
2 import collections |
|
3 import json |
157
|
4 import signal |
160
|
5 import StringIO |
157
|
6 |
|
7 import gevent |
|
8 |
145
|
9 import config |
148
|
10 from utils import W,L,E,EX |
145
|
11 |
|
12 _FIELD_DEFAULTS = { |
|
13 'fridge_setpoint': 16, |
|
14 'fridge_difference': 0.2, |
|
15 'overshoot_delay': 720, # 12 minutes |
|
16 'overshoot_factor': 1, # ÂșC |
|
17 } |
|
18 |
|
19 class Params(dict): |
|
20 class Error(Exception): |
|
21 pass |
|
22 |
|
23 def __init__(self): |
|
24 self.update(_FIELD_DEFAULTS) |
157
|
25 gevent.signal(signal.SIGHUP, self.reload_signal) |
145
|
26 |
|
27 def __getattr__(self, k): |
|
28 return self[k] |
|
29 |
|
30 def __setattr__(self, k, v): |
|
31 # fail if we set a bad value |
|
32 self[k] |
|
33 self[k] = v |
|
34 |
|
35 def load(self, f = None): |
|
36 if not f: |
148
|
37 try: |
|
38 f = file(config.PARAMS_FILE, 'r') |
|
39 except IOError, e: |
|
40 W("Missing parameter file, using defaults. %s", e) |
|
41 return |
157
|
42 try: |
|
43 u = json.load(f) |
|
44 except Exception, e: |
|
45 raise self.Error(e) |
|
46 |
145
|
47 for k in u: |
|
48 if k not in self: |
|
49 raise self.Error("Unknown parameter %s=%s in file '%s'" % (str(k), str(u[k]), getattr(f, 'name', '???'))) |
|
50 self.update(u) |
|
51 |
160
|
52 L("Loaded parameters") |
|
53 L(self.save_string()) |
|
54 |
|
55 |
145
|
56 def save(self, f = None): |
|
57 if not f: |
|
58 f = file(config.PARAMS_FILE, 'w') |
|
59 json.dump(self, f, sort_keys=True, indent=4) |
155
|
60 f.write('\n') |
145
|
61 f.flush() |
157
|
62 |
160
|
63 def save_string(self): |
|
64 s = StringIO.StringIO() |
|
65 self.save(s) |
|
66 return s.getvalue() |
|
67 |
157
|
68 def reload_signal(self): |
|
69 try: |
|
70 self.load() |
160
|
71 L("Reloaded.") |
157
|
72 except self.Error, e: |
|
73 W("Problem reloading: %s" % str(e)) |