]> vault307.fbx.one Git - ir_remote.git/blob - primitives/switch.py
infrared remote
[ir_remote.git] / primitives / switch.py
1 # switch.py
2
3 # Copyright (c) 2018-2022 Peter Hinch
4 # Released under the MIT License (MIT) - see LICENSE file
5
6 import uasyncio as asyncio
7 import utime as time
8 from . import launch
9
10 class Switch:
11 debounce_ms = 50
12 def __init__(self, pin):
13 self.pin = pin # Should be initialised for input with pullup
14 self._open_func = False
15 self._close_func = False
16 self.switchstate = self.pin.value() # Get initial state
17 self._run = asyncio.create_task(self.switchcheck()) # Thread runs forever
18
19 def open_func(self, func, args=()):
20 if func is None:
21 self.open = asyncio.Event()
22 self._open_func = self.open.set if func is None else func
23 self._open_args = args
24
25 def close_func(self, func, args=()):
26 if func is None:
27 self.close = asyncio.Event()
28 self._close_func = self.close.set if func is None else func
29 self._close_args = args
30
31 # Return current state of switch (0 = pressed)
32 def __call__(self):
33 return self.switchstate
34
35 async def switchcheck(self):
36 while True:
37 state = self.pin.value()
38 if state != self.switchstate:
39 # State has changed: act on it now.
40 self.switchstate = state
41 if state == 0 and self._close_func:
42 launch(self._close_func, self._close_args)
43 elif state == 1 and self._open_func:
44 launch(self._open_func, self._open_args)
45 # Ignore further state changes until switch has settled
46 await asyncio.sleep_ms(Switch.debounce_ms)
47
48 def deinit(self):
49 self._run.cancel()