aquifer/net/adafruit_io.py

66 lines
1.7 KiB
Python
Raw Normal View History

2023-02-07 08:49:20 -05:00
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):
2023-02-08 08:30:26 -05:00
result = self.uploadReading(reading)
2023-02-07 08:49:20 -05:00
try:
if result.status_code != 200:
self.logError(result)
return False
return True
finally:
result.close()
2023-02-08 08:30:26 -05:00
def uploadReading(self, reading):
return urequests.post(
self.url,
json=self.createPayload(reading),
headers=self.headers
)
2023-02-07 08:49:20 -05:00
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):
2023-02-08 08:30:26 -05:00
status = result.status_code
reason = result.reason.decode("utf-8")
2023-02-07 08:49:20 -05:00
error_message = self.getErrorMessage(result)
2023-02-08 08:30:26 -05:00
logging.debug(f'Adafruit IO upload issue: {status} {reason} - "{error_message}"')
2023-02-07 08:49:20 -05:00
def getErrorMessage(self, result):
try:
return result.json()['error']
except (TypeError, KeyError):
return ''