aquifer/networking/adafruit_io.py

69 lines
1.8 KiB
Python

import urequests
from . import logging
from .config import config
from .config import secrets
class AdafruitIO:
def __init__(self):
self.nickname = config['adafruit_io_nickname']
self.headers = {
'x-aio-key': secrets['adafruit_io_key'],
'content-type': 'application/json'
}
group = config['adafruit_io_group']
username = secrets['adafruit_io_username']
self.url = f'https://io.adafruit.com/api/v2/{username}/groups/{group}/data'
def upload(self, reading):
result = urequests.post(
self.url,
json=self.createPayload(reading),
headers=self.headers
)
try:
if result.status_code != 200:
self.logError(result)
return False
return True
finally:
result.close()
def createPayload(self, reading):
payload = {
'created_at': reading['timestamp'],
'feeds': []
}
for key, value in reading['readings'].items():
payload['feeds'].append({
'key': f'{self.nickname}-{key}',
'value': str(value)
})
return payload
def logError(self, result):
reason = 'unknown'
error_message = self.getErrorMessage(result)
if result.status_code == 429:
reason = 'rate limited'
elif result.status_code == 422 and error_message.find('data created_at may not be in the future') == 0:
reason = 'future reading'
else:
reason = f'{result.status_code} - {result.reason.decode("utf-8")}'
logging.debug(f'upload issue: {reason} - "{error_message}"')
def getErrorMessage(self, result):
try:
return result.json()['error']
except (TypeError, KeyError):
return ''