diff py/tempserver.py @ 448:fe729664a5e6

working better. logging works properly, cleanup fridge.off() happens.
author Matt Johnston <matt@ucc.asn.au>
date Sun, 16 Dec 2012 22:14:46 +0800
parents 8fdf86ea41e7
children d03157c7ad60
line wrap: on
line diff
--- a/py/tempserver.py	Sat Dec 15 23:49:08 2012 +0800
+++ b/py/tempserver.py	Sun Dec 16 22:14:46 2012 +0800
@@ -2,10 +2,13 @@
 
 import sys
 import os
+import logging
+
 import gevent
 import gevent.monkey
 
 import utils
+from utils import L,D,EX,W
 import fridge
 import config
 import sensor_ds18b20
@@ -16,21 +19,32 @@
     def __init__(self):
         self.readings = []
         self.current = (None, None)
+        self.fridge = None
 
         # don't patch os, fork() is used by daemonize
         gevent.monkey.patch_all(os=False, thread=False)
 
-        self.start_time = self.now()
-
+    def __enter__(self):
         self.params = params.Params()
+        self.fridge = fridge.Fridge(self)
         self.params.load()
+        self.set_sensors(sensor_ds18b20.DS18B20s(self))
+        return self
 
-        self.fridge = fridge.Fridge(self)
-        self.fridge.start()
-
-        self.set_sensors(sensor_ds18b20.DS18B20s(self))
+    def __exit__(self, exc_type, exc_value, traceback):
+        L("Exiting, cleanup handler");
+        self.fridge.off()
 
     def run(self):
+
+        if self.fridge is None:
+            raise Exception("Tempserver.run() must be within 'with Tempserver() as server'")
+
+        # XXX do these go here or in __enter_() ?
+        self.start_time = self.now()
+        self.fridge.start()
+        self.sensors.start()
+
         # won't return.
         while True:
             gevent.sleep(60)
@@ -69,15 +83,15 @@
 def setup_logging():
     logging.basicConfig(format='%(asctime)s %(message)s', 
             datefmt='%m/%d/%Y %I:%M:%S %p',
-            level=logging.INFO)
+            level=logging.DEBUG)
 
 def main():
-    server = Tempserver()
+    setup_logging()
 
     if '--daemon' in sys.argv:
         utils.cheap_daemon()
-
-    server.run()
+    with Tempserver() as server:
+        server.run()
 
 if __name__ == '__main__':
     main()