Mercurial > templog
annotate py/uploader.py @ 509:e45649618a5e
improve README
author | Matt Johnston <matt@ucc.asn.au> |
---|---|
date | Thu, 26 Jun 2014 21:35:23 +0800 |
parents | 1865674794c3 |
children | 4d82099d1fe0 |
rev | line source |
---|---|
444 | 1 import json |
2 import hmac | |
3 import zlib | |
459 | 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 | |
444 | 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): | |
459 | 20 gevent.sleep(5) |
444 | 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 | |
459 | 34 tosend['fridge_name'] = self.server.wort_name |
444 | 35 |
490 | 36 tosend['current_params'] = dict(self.server.params) |
444 | 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 | |
459 | 53 def do(self): |
444 | 54 readings = self.server.take_readings() |
55 try: | |
445
5b9dc87c988f
update web to handle new style params
Matt Johnston <matt@ucc.asn.au>
parents:
444
diff
changeset
|
56 tosend = self.get_tosend(readings) |
459 | 57 nreadings = len(readings) |
444 | 58 self.send(tosend) |
459 | 59 readings = None |
462 | 60 D("Sent updated %d readings" % nreadings) |
459 | 61 except urllib2.HTTPError, e: |
62 E("Error in uploader: %s" % str(e)) | |
444 | 63 except Exception, e: |
459 | 64 EX("Error in uploader: %s" % str(e)) |
444 | 65 finally: |
66 if readings is not None: | |
67 self.server.pushfront(readings) |