Coding style enforced

This commit is contained in:
2022-05-28 12:46:31 +02:00
parent 4a5c844510
commit 7620db8abb
8 changed files with 197 additions and 125 deletions

View File

@@ -4,7 +4,7 @@ from machine import reset
from time import sleep
import json
settings=json.loads(''.join(open('settings.json').readlines()))
settings = json.loads("".join(open("settings.json").readlines()))
# Create web server application
app = tinyweb.webserver()
@@ -16,55 +16,70 @@ for name in settings["buttons"].keys():
Button[name].off()
# Index page
@app.route('/')
@app.route("/")
async def index(request, response):
# Start HTTP response with content-type text/html
await response.start_html()
# Send actual HTML page, in this example with three buttons
await response.send('''<html><head>
await response.send(
"""<html><head>
<style>.button { display: inline-block; border-radius: 4px; background-color: #00001e; border: none; color: #FFFFFF; text-align: center; font-size: 28px; padding: 20px; width: 200px; transition: all 0.5s; cursor: pointer; margin: 5px;}</style>
</head><body><h1>Garage Door Remote</h1>
<a href="button/1"><button class="button">1</button></a>
<a href="button/2"><button class="button">2</button></a>
<a href="button/3"><button class="button">3</button></a>
</html>\n''')
</html>\n"""
)
@app.route('/reset')
@app.route("/reset")
async def index(request, response):
await response.start_html()
await response.send('''<html><head>
await response.send(
"""<html><head>
<style>.button { display: inline-block; border-radius: 4px; background-color: #00001e; border: none; color: #FFFFFF; text-align: center; font-size: 28px; padding: 20px; width: 200px; transition: all 0.5s; cursor: pointer; margin: 5px;}</style>
</head><body><h1>RESETTING...</h1>
</html>\n''')
</html>\n"""
)
reset()
@app.route('/button/<nr>')
@app.route("/button/<nr>")
async def button(request, response, nr):
# Start HTTP response with content-type text/html
# Machine control
Button[nr].on()
sleep(settings['buttons'][nr]['delay'])
sleep(settings["buttons"][nr]["delay"])
Button[str(nr)].off()
# Debug string
print ('button %s (Pin %s) pressed for %s seconds'%(nr,Button[nr],settings['buttons'][nr]['delay']))
print(
"button %s (Pin %s) pressed for %s seconds"
% (nr, Button[nr], settings["buttons"][nr]["delay"])
)
# Send response
await response.start_html()
await response.send('<html><head><meta http-equiv="refresh" content="0;url=/" /></head><body><h1>Hi George!</h1>Button number %s pushed for %s seconds. <a href="/">Go back.</a></html>\n'%(nr,settings['buttons'][str(nr)]['delay']))
await response.send(
'<html><head><meta http-equiv="refresh" content="0;url=/" /></head><body><h1>Hi George!</h1>Button number %s pushed for %s seconds. <a href="/">Go back.</a></html>\n'
% (nr, settings["buttons"][str(nr)]["delay"])
)
def Write_Settings():
File=open('settings.json','w')
File = open("settings.json", "w")
File.write(json.dumps(settings))
File.close()
# @app.route('/config',save_headers=[])
class config():
class config:
def get(self, data):
SanitizedSettings = settings.copy()
if 'password' in SanitizedSettings:
SanitizedSettings['password']='*not displayed*'
if 'AP-password' in SanitizedSettings:
SanitizedSettings['AP-password']='*not displayed*'
if "password" in SanitizedSettings:
SanitizedSettings["password"] = "*not displayed*"
if "AP-password" in SanitizedSettings:
SanitizedSettings["AP-password"] = "*not displayed*"
return SanitizedSettings
def post(self, data):
print(data)
for Setting in data.keys():
@@ -83,4 +98,4 @@ class config():
def run():
print("running app")
app.add_resource(config, "/config")
app.run(host='0.0.0.0', port=80)
app.run(host="0.0.0.0", port=80)

View File

@@ -1,6 +1,7 @@
from time import sleep
import os
def DoubleReset(Time=5, File="doublereset.txt"):
"""Use this at the beginning of the file.
DoubleReset(Time=5,File="doublereset.txt")
@@ -25,5 +26,3 @@ def DoubleReset(Time=5,File="doublereset.txt"):
sleep(Time)
os.remove(File)
return False

View File

@@ -1,11 +1,14 @@
from machine import Pin
from time import sleep
class LED:
"""Define a LED on a defined pin"""
def __init__(self, LEDPin=2):
self.LEDPin = Pin(LEDPin, Pin.OUT)
print("New LED defined on Pin %s" % LEDPin)
def Blink(self, number, timeon=0.2, timeoff=0.2):
"""Blinks the LED (number) times, (timeon) and (timeoff) are self explanatory"""
for x in range(number):
@@ -29,21 +32,54 @@ class LED:
SpaceInLetter = 0.1 * Speed
SpaceBetweenLetters = 0.3 * Speed
Space = 0.7 * Speed
alphabet={' ':' ','a':'.-','b':'-...','c':'-.-.','d':'-..','e':'.','f':'..-.','g':'--.',
'h':'....','i':'..','j':'.---','k':'-.-','l':'.-..','m':'--','n':'-.','o':'---',
'p':'.--.','q':'--.-','r':'.-.','s':'...','t':'-','u':'..-','v':'...-','w':'.--',
'x':'-..-','y':'-.--','z':'--..','1':'.----','2':'..---','3':'...--','4':'....-',
'5':'.....','6':'-....','7':'--...','8':'---..','9':'----.','0':'-----',
'.':'.-.-.-',}
alphabet = {
" ": " ",
"a": ".-",
"b": "-...",
"c": "-.-.",
"d": "-..",
"e": ".",
"f": "..-.",
"g": "--.",
"h": "....",
"i": "..",
"j": ".---",
"k": "-.-",
"l": ".-..",
"m": "--",
"n": "-.",
"o": "---",
"p": ".--.",
"q": "--.-",
"r": ".-.",
"s": "...",
"t": "-",
"u": "..-",
"v": "...-",
"w": ".--",
"x": "-..-",
"y": "-.--",
"z": "--..",
"1": ".----",
"2": "..---",
"3": "...--",
"4": "....-",
"5": ".....",
"6": "-....",
"7": "--...",
"8": "---..",
"9": "----.",
"0": "-----",
".": ".-.-.-",
}
print("morsing %s" % text)
for c in text:
for m in alphabet[c.lower()]:
if m == '.':
if m == ".":
self.Pulse(Dot, Speed)
if m == '-':
if m == "-":
self.Pulse(Dash, Speed)
if m == ' ':
if m == " ":
sleep(Space)
sleep(SpaceBetweenLetters)

View File

@@ -2,5 +2,3 @@ from aabiot.LED import LED
from aabiot.DoubleReset import DoubleReset
print("AABIOT v0.1 imported")

View File

@@ -13,6 +13,7 @@ FACILITY_MASK = 0b1111111100000000000000000 # 8 ones
# Max pulse interval: 2ms
# pulse width: 50us
class Wiegand:
def __init__(self, pin0, pin1, callback):
"""
@@ -35,8 +36,11 @@ class Wiegand:
self.timer.init(period=50, mode=Timer.PERIODIC, callback=self._cardcheck)
self.cards_read = 0
def _on_pin0(self, newstate): self._on_pin(0, newstate)
def _on_pin1(self, newstate): self._on_pin(1, newstate)
def _on_pin0(self, newstate):
self._on_pin(0, newstate)
def _on_pin1(self, newstate):
self._on_pin(1, newstate)
def _on_pin(self, is_one, newstate):
now = utime.ticks_ms()
@@ -46,7 +50,8 @@ class Wiegand:
self.last_bit_read = now
self.next_card <<= 1
if is_one: self.next_card |= 1
if is_one:
self.next_card |= 1
self._bits += 1
def get_card(self):
@@ -61,7 +66,8 @@ class Wiegand:
return (self.last_card & FACILITY_MASK) >> 17
def _cardcheck(self, t):
if self.last_bit_read is None: return
if self.last_bit_read is None:
return
now = utime.ticks_ms()
if now - self.last_bit_read > 50:
# too slow - new start!

View File

@@ -1,9 +1,12 @@
# This file is executed on every boot (including wake-boot from deepsleep)
import esp
# esp.osdebug(None)
import uos, machine
# uos.dupterm(None, 1) # disable REPL on UART(0)
import gc
# import webrepl
# webrepl.start()
gc.collect()

27
main.py
View File

@@ -11,15 +11,17 @@ if aabiot.DoubleReset():
AP()
# import settings
settings=json.loads(''.join(open('settings.json').readlines()))
settings = json.loads("".join(open("settings.json").readlines()))
LED = aabiot.LED.LED()
def netstop():
n = network.WLAN(network.STA_IF)
n.active(False)
n = network.WLAN(network.AP_IF)
n.active(False)
def STA():
"""Connects Board as Client to WiFi-Network. LED.Blinks 5 times short if successful and then displays the IP address in morse code"""
sta = network.WLAN(network.STA_IF)
@@ -27,31 +29,40 @@ def STA():
LED.Blink(5)
return True
sta.active(True)
if ('NetMask') in settings and 'DNS' in settings and 'Gateway' in settings and 'IP' in settings:
if (
("NetMask") in settings
and "DNS" in settings
and "Gateway" in settings
and "IP" in settings
):
print("Static configuration active")
sta.ifconfig((settings["IP"],settings["NetMask"],settings["Gateway"],settings["DNS"]))
sta.ifconfig(
(settings["IP"], settings["NetMask"], settings["Gateway"], settings["DNS"])
)
else:
print("DHCP active")
sta.connect(settings['ssid'],settings['password'])
sta.connect(settings["ssid"], settings["password"])
timeout = 0
while timeout < 30:
if sta.isconnected():
LED.Morse('ip %s'%sta.ifconfig()[0],1)
LED.Morse("ip %s" % sta.ifconfig()[0], 1)
return True
else:
LED.Blink(1,.05,.95)
LED.Blink(1, 0.05, 0.95)
timeout += 1
print("Time waiting: %s sec" % timeout)
sta.active(False)
return False
def AP():
"""Provides Access point with settings in settings.json. LED blinks 'AP' in morse code on success"""
ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid=settings['AP-ssid'],password=settings['AP-password'])
ap.config(essid=settings["AP-ssid"], password=settings["AP-password"])
print("AP configured")
LED.Morse ('AP')
LED.Morse("AP")
netstop()
if STA() != True:

View File

@@ -1,5 +1,9 @@
import network
n = network.WLAN(network.STA_IF)
n.active(False)
n = network.WLAN(network.AP_IF)
n.active(False)