Mercurial > templog
annotate py/uploader.py @ 196:e27075b1e088
Make sure we close descriptor before rename
author | Matt Johnston <matt@ucc.asn.au> |
---|---|
date | Wed, 12 Feb 2014 20:57:30 +0800 |
parents | f4aabbf0da67 |
children | 4d82099d1fe0 |
rev | line source |
---|---|
145 | 1 import json |
2 import hmac | |
3 import zlib | |
160 | 4 import binascii |
5 import urllib | |
6 import urllib2 | |
7 | |
8 import gevent | |
9 | |
10 import config | |
11 from utils import L,D,EX,W,E | |
12 import utils | |
145 | 13 |
14 class Uploader(gevent.Greenlet): | |
15 def __init__(self, server): | |
16 gevent.Greenlet.__init__(self) | |
17 self.server = server | |
18 | |
19 def _run(self): | |
160 | 20 gevent.sleep(5) |
145 | 21 while True: |
22 self.do() | |
23 gevent.sleep(config.UPLOAD_SLEEP) | |
24 | |
25 def get_tosend(self, readings): | |
26 tosend = {} | |
27 | |
28 tosend['fridge_on'] = self.server.fridge.is_on() | |
29 | |
30 tosend['now'] = self.server.now() | |
31 tosend['readings'] = readings | |
32 | |
33 tosend['wort_name'] = self.server.wort_name | |
160 | 34 tosend['fridge_name'] = self.server.wort_name |
145 | 35 |
190 | 36 tosend['current_params'] = dict(self.server.params) |
145 | 37 |
38 tosend['start_time'] = self.server.start_time | |
39 tosend['uptime'] = utils.uptime() | |
40 | |
41 return tosend | |
42 | |
43 def send(self, tosend): | |
44 js = json.dumps(tosend) | |
45 js_enc = binascii.b2a_base64(zlib.compress(js)) | |
46 mac = hmac.new(config.HMAC_KEY, js_enc).hexdigest() | |
47 url_data = urllib.urlencode( {'data': js_enc, 'hmac': mac} ) | |
48 con = urllib2.urlopen(config.UPDATE_URL, url_data) | |
49 result = con.read(100) | |
50 if result != 'OK': | |
51 raise Exception("Server returned %s" % result) | |
52 | |
160 | 53 def do(self): |
145 | 54 readings = self.server.take_readings() |
55 try: | |
146
3b4277aaed3c
update web to handle new style params
Matt Johnston <matt@ucc.asn.au>
parents:
145
diff
changeset
|
56 tosend = self.get_tosend(readings) |
160 | 57 nreadings = len(readings) |
145 | 58 self.send(tosend) |
160 | 59 readings = None |
163 | 60 D("Sent updated %d readings" % nreadings) |
160 | 61 except urllib2.HTTPError, e: |
62 E("Error in uploader: %s" % str(e)) | |
145 | 63 except Exception, e: |
160 | 64 EX("Error in uploader: %s" % str(e)) |
145 | 65 finally: |
66 if readings is not None: | |
67 self.server.pushfront(readings) |