Skip to content

Commit

Permalink
Rewrite schedule_lock function to be time based rather than counter…
Browse files Browse the repository at this point in the history
… based
  • Loading branch information
North101 committed Jul 1, 2024
1 parent 43e746b commit 39f56fb
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions access-front-door/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,7 @@ def __init__(self):
self.led = Pin(2, Pin.OUT) # Pin 2 is the built-in LED
self.setup_server()

# Tracks locks / unlocks so that we only actually lock when
# the value is 0
self.lock_queue = 0
self.unlocked_until = 0

def setup_server(self):
self.server = server.Phew()
Expand All @@ -79,17 +77,22 @@ async def index(self, request: Request):
duration = self.parse_duration(params.get("duration"))
unlock_duration = max(min(duration, 30), 1)

self.lock_queue += 1
self.unlock()

asyncio.create_task(self.schedule_lock(unlock_duration))
asyncio.create_task(self.schedule_lock(unlock_duration * 1000))
return 'OK'

async def schedule_lock(self, duration: int):
await asyncio.sleep(duration)
async def schedule_lock(self, duration_ms: int):
until_ms = time.ticks_add(time.ticks_ms(), duration_ms)
# if until_ms - self.unlocked_until is a negative number then
# until_ms is lower than the current value, so we exit early
if time.ticks_diff(until_ms, self.unlocked_until) < 0:
return

self.unlocked_until = until_ms
await asyncio.sleep_ms(duration_ms)

self.lock_queue -= 1
if self.lock_queue == 0:
# check that self.unlocked_until hasn't been updated
if self.unlocked_until == until_ms:
self.lock()

def lock(self):
Expand Down

0 comments on commit 39f56fb

Please sign in to comment.