Clean up code

This commit is contained in:
Mike Cifelli 2023-10-27 17:39:58 -04:00
parent a0f8027923
commit 838efe083e
Signed by: mike
GPG Key ID: 6B08C6BE47D08E4C
4 changed files with 61 additions and 67 deletions

115
main.py
View File

@ -13,43 +13,35 @@ from net.config import config
class Marshaller(Server):
def __init__(self):
self.switch = Pin(8, Pin.IN, Pin.PULL_UP)
self.activation_switch = Pin(8, Pin.IN, Pin.PULL_UP)
self.red_led = Pin(11, Pin.OUT)
self.blue_led = Pin(13, Pin.OUT)
self.green_led = Pin(20, Pin.OUT)
self.yellow_led = Pin(18, Pin.OUT)
self.v = Pin(27, Pin.OUT)
self.a = ADC(2)
self.distance_sensor_power = Pin(27, Pin.OUT)
self.distance_reading = ADC(2)
self.last_value = -1
self.v.on()
super().__init__()
self.last_http_activation_ticks = time.ticks_ms()
self.http_activation_interval_in_seconds = 2 * 60
self.is_http_activation = False
self.ntp_interval_in_seconds = 3 * 60 * 60
self.ntp_ticks = time.ticks_ms()
self.distance_interval_in_milliseconds = 50
self.distance_ticks = time.ticks_ms()
self.isWaterPresent = False
super().__init__()
ntp.sync()
def work(self):
ticks = time.ticks_ms()
if self.is_scanning():
self.v.on()
if util.millisecondsElapsed(ticks, self.distance_ticks) > self.distance_interval_in_milliseconds:
self.distance_ticks = ticks
if self.is_active():
self.distance_sensor_power.on()
self.show_color()
if self.is_http_activation and util.secondsElapsed(ticks, self.last_http_activation_ticks) > self.http_activation_interval_in_seconds:
if self.is_activation_expired(ticks):
logging.info('deactivating')
self.is_http_activation = False
else:
self.v.off()
self.distance_sensor_power.off()
self.leds_off()
super().work()
@ -57,65 +49,26 @@ class Marshaller(Server):
self.ntp_ticks = ticks
ntp.sync()
def is_scanning(self):
return self.switch.value() == 0 or self.is_http_activation
def is_active(self):
return self.activation_switch.value() == 0 or self.is_http_activation
def get_buffered_distance_in_inches(self):
distance = self.get_distance_in_inches()
if abs(distance - self.last_value) > 0.25:
self.last_value = distance
return distance
return self.last_value
# TODO - don't convert distances to inches, convert thresholds in the opposite direction
def get_distance_in_inches(self):
return self.a.read_u16() / 65535 * 1024 * 5 * 0.03937008
def handlePath(self, path):
if (path == 'on'):
return self.http_activation()
return self.getPathData(path)
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}',
hostname=config['hostname'],
datetime=util.datetime(),
is_active=self.is_scanning()
)
def http_activation(self):
self.is_http_activation = True
self.last_http_activation_ticks = time.ticks_ms()
# todo - no content status
return ""
def is_activation_expired(self, ticks):
return self.is_http_activation and util.secondsElapsed(ticks, self.last_http_activation_ticks) > self.http_activation_interval_in_seconds
def show_color(self):
distance_in_inches = self.get_buffered_distance_in_inches()
self.leds_off()
if distance_in_inches < 15:
self.leds_off()
self.red_led.on()
elif distance_in_inches < 20:
self.leds_off()
self.green_led.on()
self.yellow_led.on()
elif distance_in_inches < 25:
self.leds_off()
self.green_led.on()
elif distance_in_inches < 40:
self.leds_off()
elif distance_in_inches < 30:
self.yellow_led.on()
else:
self.leds_off()
self.blue_led.on()
def leds_off(self):
@ -124,8 +77,44 @@ class Marshaller(Server):
self.green_led.off()
self.yellow_led.off()
def get_buffered_distance_in_inches(self):
distance = self.get_distance_in_inches()
if abs(distance - self.last_value) > 0.25:
self.last_value = distance
return self.last_value
def get_distance_in_inches(self):
return self.distance_reading.read_u16() / 65535 * 1024 * 5 * 0.03937008
def handlePath(self, path):
if (path == 'on'):
logging.info('activated via http')
return self.http_activation()
return self.get_path_data(path)
def get_path_data(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}',
hostname=config['hostname'],
datetime=util.datetime(),
is_active=self.is_active()
)
def http_activation(self):
self.is_http_activation = True
self.last_http_activation_ticks = time.ticks_ms()
return ''
def cleanup(self):
self.v.off()
self.distance_sensor_power.off()
self.leds_off()
super().cleanup()

View File

@ -2,5 +2,6 @@ okResponse = 'HTTP/1.1 200 OK\r\ncontent-type: text/html\r\n\r\n'.encode('ascii'
okTextResponse = 'HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\n\r\n'.encode('ascii')
okJsonResponse = 'HTTP/1.1 200 OK\r\ncontent-type: application/json\r\n\r\n'.encode('ascii')
okIconResponse = 'HTTP/1.1 200 OK\r\ncontent-type: image/x-icon\r\n\r\n'.encode('ascii')
noContentResponse = 'HTTP/1.1 204 No Content\r\n\r\n'.encode('ascii')
notFoundResponse = 'HTTP/1.1 404 Not Found\r\n\r\n'.encode('ascii')
serverErrorResponse = 'HTTP/1.1 500 Internal Server Error\r\n\r\n'.encode('ascii')

View File

@ -50,7 +50,7 @@ class Server:
return addr
def serve(self):
evts = self.poller.poll(500)
evts = self.poller.poll(10)
for sock, _evt in evts:
try:
@ -74,20 +74,22 @@ class Server:
if method == 'GET':
response = self.handlePath(path.strip('/'))
conn.write(self.getPathContentType(path))
conn.write(self.getContentType(path, response))
conn.write(response)
else:
conn.write(http.notFoundResponse)
except OSError:
conn.write(http.notFoundResponse)
def getPathContentType(self, path):
def getContentType(self, path, response):
if path.endswith('.txt'):
return http.okTextResponse
elif path.endswith('.json'):
return http.okJsonResponse
elif path.endswith('.ico'):
return http.okIconResponse
elif response == '':
return http.noContentResponse
return http.okResponse

View File

@ -3,6 +3,7 @@ import rp2
import time
from . import logging
from .config import config
from .config import secrets
@ -21,6 +22,7 @@ def connect():
def connectToWifi():
rp2.country('US')
network.hostname(config['hostname'])
wlan = network.WLAN(network.STA_IF)
wlan.active(True)