]>
vault307.fbx.one Git - ir_remote.git/blob - primitives/switch.py
3 # Copyright (c) 2018-2022 Peter Hinch
4 # Released under the MIT License (MIT) - see LICENSE file
6 import uasyncio
as asyncio
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
19 def open_func(self
, func
, args
=()):
21 self
.open = asyncio
.Event()
22 self
._open
_func
= self
.open.set if func
is None else func
23 self
._open
_args
= args
25 def close_func(self
, func
, args
=()):
27 self
.close
= asyncio
.Event()
28 self
._close
_func
= self
.close
.set if func
is None else func
29 self
._close
_args
= args
31 # Return current state of switch (0 = pressed)
33 return self
.switchstate
35 async def switchcheck(self
):
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
)