-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathmain.py
89 lines (69 loc) · 2.52 KB
/
main.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import json
import logging
import signal
import sys
from pyhap.accessory_driver import AccessoryDriver
from accessory import Lock
from repository import Repository
from service import Service
from util.bfclf import BroadcastFrameContactlessFrontend
# By default, this file is located in the same folder as the project
CONFIGURATION_FILE_PATH = "configuration.json"
def load_configuration(path=CONFIGURATION_FILE_PATH) -> dict:
return json.load(open(path, "r+"))
def configure_logging(config: dict):
log = logging.getLogger()
formatter = logging.Formatter(
"[%(asctime)s] [%(levelname)8s] %(module)-18s:%(lineno)-4d %(message)s"
)
hdlr = logging.StreamHandler(sys.stdout)
log.setLevel(config.get("level", logging.INFO))
hdlr.setFormatter(formatter)
log.addHandler(hdlr)
return log
def configure_hap_accessory(config: dict, homekey_service=None):
driver = AccessoryDriver(port=config["port"], persist_file=config["persist"])
accessory = Lock(
driver,
"NFC Lock",
service=homekey_service,
lock_state_at_startup=int(config.get("default") != "unlocked")
)
driver.add_accessory(accessory=accessory)
return driver, accessory
def configure_nfc_device(config: dict):
clf = BroadcastFrameContactlessFrontend(
path=config.get("path", None) or f"tty:{config.get('port')}:{config.get('driver')}",
broadcast_enabled=config.get("broadcast", True),
)
return clf
def configure_homekey_service(config: dict, nfc_device, repository=None):
service = Service(
nfc_device,
repository=repository or Repository(config["persist"]),
express=config.get("express", True),
finish=config.get("finish"),
flow=config.get("flow"),
# Poll no more than ~6 times a second by default
throttle_polling=float(config.get("throttle_polling") or 0.15),
)
return service
def main():
config = load_configuration()
log = configure_logging(config["logging"])
nfc_device = configure_nfc_device(config["nfc"])
homekey_service = configure_homekey_service(config["homekey"], nfc_device)
hap_driver, _ = configure_hap_accessory(config["hap"], homekey_service)
for s in (signal.SIGINT, signal.SIGTERM):
signal.signal(
s,
lambda *_: (
log.info(f"SIGNAL {s}"),
homekey_service.stop(),
hap_driver.stop(),
),
)
homekey_service.start()
hap_driver.start()
if __name__ == "__main__":
main()