Mercurial > templog
annotate py/uploader.py @ 528:61e61de49a50
test sensor
author | Matt Johnston <matt@ucc.asn.au> |
---|---|
date | Fri, 10 Apr 2015 23:55:07 +0800 |
parents | dd8895652485 |
children | 185621f47040 |
rev | line source |
---|---|
444 | 1 import json |
2 import hmac | |
3 import zlib | |
459 | 4 import binascii |
513
56cdea43b366
use requests rather than urllib2, better ipv6->ipv4 fallback
Matt Johnston <matt@ucc.asn.au>
parents:
490
diff
changeset
|
5 import logging |
527 | 6 import asyncio |
459 | 7 |
527 | 8 import aiohttp |
459 | 9 |
10 import config | |
11 from utils import L,D,EX,W,E | |
12 import utils | |
444 | 13 |
527 | 14 class Uploader(object): |
444 | 15 def __init__(self, server): |
16 self.server = server | |
17 | |
527 | 18 @asyncio.coroutine |
19 def run(self): | |
20 # wait for the first read | |
21 yield from asyncio.sleep(5) | |
444 | 22 while True: |
527 | 23 yield from self.do() |
24 yield from self.server.sleep(config.UPLOAD_SLEEP) | |
444 | 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 | |
459 | 35 tosend['fridge_name'] = self.server.wort_name |
444 | 36 |
490 | 37 tosend['current_params'] = dict(self.server.params) |
444 | 38 |
39 tosend['start_time'] = self.server.start_time | |
40 tosend['uptime'] = utils.uptime() | |
41 | |
42 return tosend | |
43 | |
527 | 44 @asyncio.coroutine |
444 | 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() | |
513
56cdea43b366
use requests rather than urllib2, better ipv6->ipv4 fallback
Matt Johnston <matt@ucc.asn.au>
parents:
490
diff
changeset
|
49 send_data = {'data': js_enc, 'hmac': mac} |
527 | 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) | |
444 | 52 if result != 'OK': |
53 raise Exception("Server returned %s" % result) | |
54 | |
527 | 55 @asyncio.coroutine |
459 | 56 def do(self): |
444 | 57 readings = self.server.take_readings() |
58 try: | |
445
5b9dc87c988f
update web to handle new style params
Matt Johnston <matt@ucc.asn.au>
parents:
444
diff
changeset
|
59 tosend = self.get_tosend(readings) |
459 | 60 nreadings = len(readings) |
527 | 61 yield from self.send(tosend) |
459 | 62 readings = None |
462 | 63 D("Sent updated %d readings" % nreadings) |
444 | 64 except Exception, e: |
459 | 65 EX("Error in uploader: %s" % str(e)) |
444 | 66 finally: |
67 if readings is not None: | |
68 self.server.pushfront(readings) |