Mercurial > templog
annotate py/uploader.py @ 228:d9e81a563923
porting to asyncio
author | Matt Johnston <matt@ucc.asn.au> |
---|---|
date | Fri, 20 Mar 2015 20:12:25 +0800 |
parents | 16a83e2c97a0 |
children | 185621f47040 |
rev | line source |
---|---|
145 | 1 import json |
2 import hmac | |
3 import zlib | |
160 | 4 import binascii |
215
4d82099d1fe0
use requests rather than urllib2, better ipv6->ipv4 fallback
Matt Johnston <matt@ucc.asn.au>
parents:
190
diff
changeset
|
5 import logging |
228 | 6 import asyncio |
160 | 7 |
228 | 8 import aiohttp |
160 | 9 |
10 import config | |
11 from utils import L,D,EX,W,E | |
12 import utils | |
145 | 13 |
228 | 14 class Uploader(object): |
145 | 15 def __init__(self, server): |
16 self.server = server | |
17 | |
228 | 18 @asyncio.coroutine |
19 def run(self): | |
20 # wait for the first read | |
21 yield from asyncio.sleep(5) | |
145 | 22 while True: |
228 | 23 yield from self.do() |
24 yield from self.server.sleep(config.UPLOAD_SLEEP) | |
145 | 25 |
26 def get_tosend(self, readings): | |
27 tosend = {} | |
28 | |
29 tosend['fridge_on'] = self.server.fridge.is_on() | |
30 | |
31 tosend['now'] = self.server.now() | |
32 tosend['readings'] = readings | |
33 | |
34 tosend['wort_name'] = self.server.wort_name | |
160 | 35 tosend['fridge_name'] = self.server.wort_name |
145 | 36 |
190 | 37 tosend['current_params'] = dict(self.server.params) |
145 | 38 |
39 tosend['start_time'] = self.server.start_time | |
40 tosend['uptime'] = utils.uptime() | |
41 | |
42 return tosend | |
43 | |
228 | 44 @asyncio.coroutine |
145 | 45 def send(self, tosend): |
46 js = json.dumps(tosend) | |
47 js_enc = binascii.b2a_base64(zlib.compress(js)) | |
48 mac = hmac.new(config.HMAC_KEY, js_enc).hexdigest() | |
215
4d82099d1fe0
use requests rather than urllib2, better ipv6->ipv4 fallback
Matt Johnston <matt@ucc.asn.au>
parents:
190
diff
changeset
|
49 send_data = {'data': js_enc, 'hmac': mac} |
228 | 50 r = yield from asyncio.wait_for(aiohttp.request('post', config.UPDATE_URL, data=send_data), 60) |
51 result = yield from asyncio.wait_for(r.text(), 60) | |
145 | 52 if result != 'OK': |
53 raise Exception("Server returned %s" % result) | |
54 | |
228 | 55 @asyncio.coroutine |
160 | 56 def do(self): |
145 | 57 readings = self.server.take_readings() |
58 try: | |
146
3b4277aaed3c
update web to handle new style params
Matt Johnston <matt@ucc.asn.au>
parents:
145
diff
changeset
|
59 tosend = self.get_tosend(readings) |
160 | 60 nreadings = len(readings) |
228 | 61 yield from self.send(tosend) |
160 | 62 readings = None |
163 | 63 D("Sent updated %d readings" % nreadings) |
145 | 64 except Exception, e: |
160 | 65 EX("Error in uploader: %s" % str(e)) |
145 | 66 finally: |
67 if readings is not None: | |
68 self.server.pushfront(readings) |