-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcatflap_magnet.py
44 lines (31 loc) · 1.04 KB
/
catflap_magnet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import requests, os, logging, sys
from gpiozero import DigitalInputDevice
from signal import pause
from dotenv import load_dotenv
load_dotenv(override=True)
def activate():
state = get_value_from_env("ACTIVATED_STATE")
send_command(state)
def deactivate():
state = get_value_from_env("DEACTIVATED_STATE")
send_command(state)
def get_value_from_env(key):
value = os.getenv(key)
if not value:
logging.error(f"key '{key}' not found in env, process terminated")
sys.exit(1)
return value
def send_command(state):
openhab_thing_url = get_value_from_env("OPENHAB_THING_STATE_URL")
data = state
headers = {'Content-type': 'text/plain'}
try:
response = requests.put(openhab_thing_url, data=data, headers=headers)
logging.debug(f"send command with state '{state}'")
except:
logging.warning("request failed")
pin = get_value_from_env("MAGNET_PIN")
magnet = DigitalInputDevice(pin, pull_up=True)
magnet.when_activated = activate
magnet.when_deactivated = deactivate
pause()