aquifer/main.py

92 lines
2.4 KiB
Python
Raw Normal View History

2023-02-07 08:49:20 -05:00
import json
import time
2023-02-07 11:22:31 -05:00
from machine import I2C
2023-02-07 08:53:04 -05:00
from net import AdafruitIO
from net import logging
from net import ntp
from net import Server
from net import templates
from net import util
2023-02-07 11:22:31 -05:00
from sensors import MCP9808
from sensors import WaterSensor
2023-02-07 08:49:20 -05:00
2023-02-07 11:23:31 -05:00
class SensorServer(Server):
2023-02-07 08:49:20 -05:00
def __init__(self):
super().__init__()
2023-02-07 11:22:31 -05:00
self.waterSensor = WaterSensor(0)
self.mcp = MCP9808(I2C(0))
2023-02-07 08:49:20 -05:00
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 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()
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}',
2023-02-07 11:22:31 -05:00
datetime=util.datetime(),
2023-02-07 12:52:52 -05:00
temperature=self.temperatureTextValue(),
2023-02-07 11:22:31 -05:00
waterStatus=self.waterTextValue(),
waterClass=self.waterCssClass()
2023-02-07 08:49:20 -05:00
)
def getReading(self):
2023-02-07 11:22:31 -05:00
return {
'timestamp': util.datetimeISO8601(),
'readings': self.getState()
}
2023-02-07 08:49:20 -05:00
def getState(self):
2023-02-07 11:22:31 -05:00
return {
'is-water-present': self.waterSensor.isWaterPresent(),
'temperature': self.mcp.get_temp()
}
2023-02-07 12:52:52 -05:00
def temperatureTextValue(self):
2023-02-07 11:22:31 -05:00
return round(self.mcp.get_temp(), 2)
2023-02-07 08:49:20 -05:00
2023-02-07 11:22:31 -05:00
def waterTextValue(self):
return 'Present' if self.waterSensor.isWaterPresent() else 'Absent'
2023-02-07 08:49:20 -05:00
2023-02-07 11:22:31 -05:00
def waterCssClass(self):
return 'water-present' if self.waterSensor.isWaterPresent() else 'water-absent'
2023-02-07 08:49:20 -05:00
def main():
logging.log_file = 'www/log.txt'
2023-02-07 11:23:31 -05:00
SensorServer().run()
2023-02-07 08:49:20 -05:00
if __name__ == '__main__':
main()