From 7620db8abbf90f0a673ae7c96babf18b96f281ac Mon Sep 17 00:00:00 2001 From: "Adrian A. Baumann" Date: Sat, 28 May 2022 12:46:31 +0200 Subject: [PATCH] Coding style enforced --- Device.py | 81 ++++++++++++++++++++++---------------- aabiot/DoubleReset.py | 57 ++++++++++++++------------- aabiot/LED.py | 90 ++++++++++++++++++++++++++++++------------- aabiot/__init__.py | 2 - aabiot/wiegand.py | 24 +++++++----- boot.py | 11 ++++-- main.py | 43 +++++++++++++-------- netstop.py | 14 ++++--- 8 files changed, 197 insertions(+), 125 deletions(-) diff --git a/Device.py b/Device.py index 80bd9b0..d9bb73a 100644 --- a/Device.py +++ b/Device.py @@ -4,83 +4,98 @@ 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() # Hardware Setup, e.g. Garage Door Remote -Button={} +Button = {} for name in settings["buttons"].keys(): - Button[name]=Pin(settings["buttons"][name]["pin"],Pin.OUT) + Button[name] = Pin(settings["buttons"][name]["pin"], Pin.OUT) 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(''' + await response.send( + """

Garage Door Remote

- \n''') + \n""" + ) -@app.route('/reset') + +@app.route("/reset") async def index(request, response): await response.start_html() - await response.send(''' + await response.send( + """

RESETTING...

- \n''') + \n""" + ) reset() -@app.route('/button/') -async def button(request, response,nr): + +@app.route("/button/") +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'])) - #Send response + 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('

Hi George!

Button number %s pushed for %s seconds. Go back.\n'%(nr,settings['buttons'][str(nr)]['delay'])) + await response.send( + '

Hi George!

Button number %s pushed for %s seconds. Go back.\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(): - 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*' + +# @app.route('/config',save_headers=[]) +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*" return SanitizedSettings + def post(self, data): - print (data) + print(data) for Setting in data.keys(): - settings[Setting]=data[Setting] - print("Setting %s to %s"%(Setting,data[Setting])) + settings[Setting] = data[Setting] + print("Setting %s to %s" % (Setting, data[Setting])) Write_Settings() return data - - def delete(self,data): + + def delete(self, data): for Setting in data.keys(): settings.pop(Setting) Write_Settings() - return data + return data def run(): - print ("running app") - app.add_resource(config,"/config") - app.run(host='0.0.0.0', port=80) + print("running app") + app.add_resource(config, "/config") + app.run(host="0.0.0.0", port=80) diff --git a/aabiot/DoubleReset.py b/aabiot/DoubleReset.py index 99054c3..0834a5b 100644 --- a/aabiot/DoubleReset.py +++ b/aabiot/DoubleReset.py @@ -1,29 +1,28 @@ -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") - Determines, if the board had two successive resets in the last seconds. - This is done by writing a file in and deleting it after seconds. - If the file is already there, the reset was doubled.""" - try: - a=open(File) - Check=a.read().strip() - a.close() - a=open(File,"w") - a.write(str(int(Check)+1)) - a.close() - sleep(Time) - os.remove(File) - return int(Check)+1 - except OSError: - pass - a=open(File,"w") - a.write("1") - a.close() - sleep(Time) - os.remove(File) - return False - - +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") + Determines, if the board had two successive resets in the last seconds. + This is done by writing a file in and deleting it after seconds. + If the file is already there, the reset was doubled.""" + try: + a = open(File) + Check = a.read().strip() + a.close() + a = open(File, "w") + a.write(str(int(Check) + 1)) + a.close() + sleep(Time) + os.remove(File) + return int(Check) + 1 + except OSError: + pass + a = open(File, "w") + a.write("1") + a.close() + sleep(Time) + os.remove(File) + return False diff --git a/aabiot/LED.py b/aabiot/LED.py index 6e64a8a..d9b3b92 100644 --- a/aabiot/LED.py +++ b/aabiot/LED.py @@ -1,49 +1,85 @@ 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): + + 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): + for x in range(number): self.LEDPin.off() sleep(timeon) self.LEDPin.on() sleep(timeoff) - def Pulse(self,seconds,Speed=1): + def Pulse(self, seconds, Speed=1): """Helper function for Morse Code""" self.LEDPin.off() sleep(seconds) self.LEDPin.on() - sleep (0.1*Speed) + sleep(0.1 * Speed) - def Morse(self,text,Speed=1): + def Morse(self, text, Speed=1): """Blinks (text) in morse code. Speed is around 60 cpm at 1 and proportional""" - Speed=1/Speed - Dot=0.1*Speed - Dash=0.3*Speed - 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':'-----', - '.':'.-.-.-',} + Speed = 1 / Speed + Dot = 0.1 * Speed + Dash = 0.3 * Speed + 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": "-----", + ".": ".-.-.-", + } - print ("morsing %s"%text) + print("morsing %s" % text) for c in text: for m in alphabet[c.lower()]: - if m == '.': - self.Pulse(Dot,Speed) - if m == '-': - self.Pulse(Dash,Speed) - if m == ' ': + if m == ".": + self.Pulse(Dot, Speed) + if m == "-": + self.Pulse(Dash, Speed) + if m == " ": sleep(Space) sleep(SpaceBetweenLetters) - diff --git a/aabiot/__init__.py b/aabiot/__init__.py index 0d57dcc..bde0cbe 100644 --- a/aabiot/__init__.py +++ b/aabiot/__init__.py @@ -2,5 +2,3 @@ from aabiot.LED import LED from aabiot.DoubleReset import DoubleReset print("AABIOT v0.1 imported") - - diff --git a/aabiot/wiegand.py b/aabiot/wiegand.py index b2fdfcd..a4d3d43 100755 --- a/aabiot/wiegand.py +++ b/aabiot/wiegand.py @@ -7,12 +7,13 @@ weigand.py - read card IDs from a wiegand card reader from machine import Pin, Timer import utime -CARD_MASK = 0b11111111111111110 # 16 ones -FACILITY_MASK = 0b1111111100000000000000000 # 8 ones +CARD_MASK = 0b11111111111111110 # 16 ones +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,22 +50,24 @@ 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): if self.last_card is None: return None - return ( self.last_card & CARD_MASK ) >> 1 - + return (self.last_card & CARD_MASK) >> 1 + def get_facility_code(self): if self.last_card is None: return None # Specific to standard 26bit wiegand - return ( self.last_card & FACILITY_MASK ) >> 17 + 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! diff --git a/boot.py b/boot.py index b288637..9a923a2 100644 --- a/boot.py +++ b/boot.py @@ -1,9 +1,12 @@ # This file is executed on every boot (including wake-boot from deepsleep) import esp -#esp.osdebug(None) + +# esp.osdebug(None) import uos, machine -#uos.dupterm(None, 1) # disable REPL on UART(0) + +# uos.dupterm(None, 1) # disable REPL on UART(0) import gc -#import webrepl -#webrepl.start() + +# import webrepl +# webrepl.start() gc.collect() diff --git a/main.py b/main.py index 5c60d68..fed8999 100644 --- a/main.py +++ b/main.py @@ -10,48 +10,59 @@ if aabiot.DoubleReset(): print("Double Reset - Starting AP") AP() -#import settings -settings=json.loads(''.join(open('settings.json').readlines())) -LED=aabiot.LED.LED() +# import settings +settings = json.loads("".join(open("settings.json").readlines())) +LED = aabiot.LED.LED() + def netstop(): - n=network.WLAN(network.STA_IF) + n = network.WLAN(network.STA_IF) n.active(False) - n=network.WLAN(network.AP_IF) + 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) + sta = network.WLAN(network.STA_IF) if sta.isconnected(): 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']) - timeout=0 + 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) + 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 = 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: diff --git a/netstop.py b/netstop.py index d3a8e33..0307aaa 100644 --- a/netstop.py +++ b/netstop.py @@ -1,5 +1,9 @@ -import network -n=network.WLAN(network.STA_IF) -n.active(False) -n=network.WLAN(network.AP_IF) -n.active(False) +import network + +n = network.WLAN(network.STA_IF) + +n.active(False) + +n = network.WLAN(network.AP_IF) + +n.active(False)