aquifer/main.py

89 lines
2.3 KiB
Python

import json
import time
from machine import Pin
from networking import AdafruitIO
from networking import logging
from networking import ntp
from networking import Server
from networking import templates
from networking import util
class LedServer(Server):
def __init__(self):
super().__init__()
self.led = Pin('LED', Pin.OUT)
self.aio = AdafruitIO()
self.ntp_interval_in_seconds = 60 * 60
self.aio_interval_in_seconds = 60 * 5
self.ntp_ticks = time.ticks_ms()
self.aio_ticks = time.ticks_ms()
ntp.sync()
def cleanup(self):
super().cleanup()
self.led.off()
def work(self):
super().work()
ticks = time.ticks_ms()
if util.secondsElapsed(ticks, self.ntp_ticks) > self.ntp_interval_in_seconds:
self.ntp_ticks = ticks
ntp.sync()
if util.secondsElapsed(ticks, self.aio_ticks) > self.aio_interval_in_seconds:
self.aio_ticks = ticks
self.aio.upload(self.getReading())
def handlePath(self, path):
if path == 'index.json':
return self.getJsonData()
elif path == 'light/on':
self.led.on()
return self.getJsonData()
elif path == 'light/off':
self.led.off()
return self.getJsonData()
return self.getPathData(path)
def getJsonData(self):
return json.dumps(self.getState())
def getPathData(self, path):
if path.endswith('.txt') or path.endswith('.ico'):
with open(f'www/{path}', 'rb') as f:
return f.read()
return templates.render(
f'www/{path or self.default_path}',
ledStatus=self.ledTextValue(),
ledClass=self.ledCssClass(),
datetime=util.datetime()
)
def getReading(self):
return {'timestamp': util.datetimeISO8601(), 'readings': self.getState()}
def getState(self):
return {'is-led-on': bool(self.led.value())}
def ledTextValue(self):
return 'ON' if self.led.value() else 'OFF'
def ledCssClass(self):
return 'led-on' if self.led.value() else 'led-off'
def main():
logging.log_file = 'www/log.txt'
LedServer().run()
if __name__ == '__main__':
main()