comparison py/uploader.py @ 145:6517ddee3187

few more bits
author Matt Johnston <matt@ucc.asn.au>
date Thu, 29 Nov 2012 23:50:40 +0800
parents
children 3b4277aaed3c
comparison
equal deleted inserted replaced
144:482d7852b511 145:6517ddee3187
1 import config
2
3 import json
4 import hmac
5 import zlib
6
7 class Uploader(gevent.Greenlet):
8 def __init__(self, server):
9 gevent.Greenlet.__init__(self)
10 self.server = server
11
12 def _run(self):
13 while True:
14 self.do()
15 gevent.sleep(config.UPLOAD_SLEEP)
16
17 def get_tosend(self, readings):
18 tosend = {}
19
20 tosend['fridge_on'] = self.server.fridge.is_on()
21
22 tosend['now'] = self.server.now()
23 tosend['readings'] = readings
24
25 tosend['wort_name'] = self.server.wort_name
26 tosend['fridge_name'] = self.server.wort_fridge_name
27
28 tosend.update(dict(self.server.params))
29
30 tosend['start_time'] = self.server.start_time
31 tosend['uptime'] = utils.uptime()
32
33 return tosend
34
35 def send(self, tosend):
36 js = json.dumps(tosend)
37 js_enc = binascii.b2a_base64(zlib.compress(js))
38 mac = hmac.new(config.HMAC_KEY, js_enc).hexdigest()
39 url_data = urllib.urlencode( {'data': js_enc, 'hmac': mac} )
40 con = urllib2.urlopen(config.UPDATE_URL, url_data)
41 result = con.read(100)
42 if result != 'OK':
43 raise Exception("Server returned %s" % result)
44
45 def do():
46 readings = self.server.take_readings()
47 try:
48 tosend = self.get_to_send(readings)
49 readings = None
50 self.send(tosend)
51 except Exception, e:
52 EX"Error in uploader: %s" % str(e))
53 finally:
54 if readings is not None:
55 self.server.pushfront(readings)