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): class Marshaller(Server):
def __init__(self): 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.red_led = Pin(11, Pin.OUT)
self.blue_led = Pin(13, Pin.OUT) self.blue_led = Pin(13, Pin.OUT)
self.green_led = Pin(20, Pin.OUT) self.green_led = Pin(20, Pin.OUT)
self.yellow_led = Pin(18, Pin.OUT) self.yellow_led = Pin(18, Pin.OUT)
self.v = Pin(27, Pin.OUT) self.distance_sensor_power = Pin(27, Pin.OUT)
self.a = ADC(2) self.distance_reading = ADC(2)
self.last_value = -1 self.last_value = -1
self.v.on()
super().__init__()
self.last_http_activation_ticks = time.ticks_ms() self.last_http_activation_ticks = time.ticks_ms()
self.http_activation_interval_in_seconds = 2 * 60 self.http_activation_interval_in_seconds = 2 * 60
self.is_http_activation = False self.is_http_activation = False
self.ntp_interval_in_seconds = 3 * 60 * 60 self.ntp_interval_in_seconds = 3 * 60 * 60
self.ntp_ticks = time.ticks_ms() 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() ntp.sync()
def work(self): def work(self):
ticks = time.ticks_ms() ticks = time.ticks_ms()
if self.is_scanning(): if self.is_active():
self.v.on() self.distance_sensor_power.on()
if util.millisecondsElapsed(ticks, self.distance_ticks) > self.distance_interval_in_milliseconds:
self.distance_ticks = ticks
self.show_color() 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 self.is_http_activation = False
else: else:
self.v.off() self.distance_sensor_power.off()
self.leds_off() self.leds_off()
super().work() super().work()
@ -57,65 +49,26 @@ class Marshaller(Server):
self.ntp_ticks = ticks self.ntp_ticks = ticks
ntp.sync() ntp.sync()
def is_scanning(self): def is_active(self):
return self.switch.value() == 0 or self.is_http_activation return self.activation_switch.value() == 0 or self.is_http_activation
def get_buffered_distance_in_inches(self): def is_activation_expired(self, ticks):
distance = self.get_distance_in_inches() return self.is_http_activation and util.secondsElapsed(ticks, self.last_http_activation_ticks) > self.http_activation_interval_in_seconds
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 show_color(self): def show_color(self):
distance_in_inches = self.get_buffered_distance_in_inches() distance_in_inches = self.get_buffered_distance_in_inches()
self.leds_off()
if distance_in_inches < 15: if distance_in_inches < 15:
self.leds_off()
self.red_led.on() self.red_led.on()
elif distance_in_inches < 20: elif distance_in_inches < 20:
self.leds_off()
self.green_led.on() self.green_led.on()
self.yellow_led.on() self.yellow_led.on()
elif distance_in_inches < 25: elif distance_in_inches < 25:
self.leds_off()
self.green_led.on() self.green_led.on()
elif distance_in_inches < 40: elif distance_in_inches < 30:
self.leds_off()
self.yellow_led.on() self.yellow_led.on()
else: else:
self.leds_off()
self.blue_led.on() self.blue_led.on()
def leds_off(self): def leds_off(self):
@ -124,8 +77,44 @@ class Marshaller(Server):
self.green_led.off() self.green_led.off()
self.yellow_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): def cleanup(self):
self.v.off() self.distance_sensor_power.off()
self.leds_off() self.leds_off()
super().cleanup() 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') 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') 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') 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') 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') serverErrorResponse = 'HTTP/1.1 500 Internal Server Error\r\n\r\n'.encode('ascii')

View File

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

View File

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