feat: moisture and relay support

This commit is contained in:
Elias Renman
2023-05-27 00:58:56 +02:00
parent fa5a808c45
commit 6a5a76f808
2 changed files with 25 additions and 17 deletions

View File

@@ -1,4 +1,4 @@
from typing import Sized
import json
from machine import Pin, ADC
from micropython import const
@@ -11,11 +11,11 @@ relays = [
[Pin(2, mode=Pin.OUT), False]
]
moisture_sensors = const([
moisture_sensors = [
ADC(Pin(28)),
ADC(Pin(27)),
ADC(Pin(26))
])
]
min_moisture = const(0)
@@ -24,7 +24,7 @@ max_moisture = const(65535)
def read_moisture_sensors():
try:
data = map(read_moisture_sensor, moisture_sensors)
data = list(map(read_moisture_sensor, moisture_sensors))
return {
"status": "success",
"message": "Successfully read moisture sensors",
@@ -41,7 +41,7 @@ def read_moisture_sensor(sensor: ADC):
return (max_moisture-sensor.read_u16())*100/(max_moisture-min_moisture)
def assert_index(array: Sized, index: int):
def assert_index(array: list, index: int):
return not (len(array) >= index or index < 0)
@@ -65,4 +65,4 @@ def try_switch_relay(relay_index: int, value: bool):
# Then set the pin
relays[index][0].value()
return {"status": "success", "message": "Successfully turned on relay", "data": map(lambda x: x[1], relays)}
return {"status": "success", "message": "Successfully turned on relay", "data": list(map(lambda x: x[1], relays))}

View File

@@ -1,6 +1,8 @@
import socket
from config import led
from decorators import Endpoint, ServerHandler
from pin import read_moisture_sensors, try_switch_relay
import json
def initalize_app():
@@ -13,19 +15,25 @@ def initalize_app():
print('listening on', addr)
# Listen for connections
Handler(s)
try:
Handler(s)
except any as e:
print("Closing server because of crash", e)
s.close()
class Handler(ServerHandler):
@Endpoint('/light/on', 'POST')
def light_on(self):
print("led on")
led.value(1)
return {"led": "on"}
@Endpoint('/moisture/read', 'GET')
def read_moisture():
return read_moisture_sensors()
@Endpoint('/light/off', 'POST')
def light_off(self):
print("led off")
led.value(0)
return {"led": "off"}
@Endpoint('/relay/activate', 'POST')
def activate_relay(self, **kwargs):
body: dict = json.loads(str(kwargs.get('body')))
return try_switch_relay(int(body.get('relay')), True)
@Endpoint('/relay/deactivate', 'POST')
def deactivate_relay(self, **kwargs):
body: dict = json.loads(str(kwargs.get('body')))
return try_switch_relay(int(body.get('relay')), False)