Skip to content

Commit

Permalink
[DISC] Timeout for discovered device trackers
Browse files Browse the repository at this point in the history
  • Loading branch information
DigiH committed Jan 13, 2024
1 parent 2fd7940 commit 591101c
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
29 changes: 29 additions & 0 deletions TheengsGateway/ble_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ def __init__(
self.stopped = False
self.clock_updates: dict[str, float] = {}
self.published_messages = 0
self.discovered_trackers: dict[str, int] = {}

def connect_mqtt(self) -> None:
"""Connect to MQTT broker."""
Expand Down Expand Up @@ -326,6 +327,27 @@ async def update_clock_times(self) -> None:
).strftime("%Y-%m-%d %H:%M:%S"),
)

def check_tracker_timeout(self) -> None:
"""Check if tracker timeout is over timeout limit."""
for address, timestamp in self.discovered_trackers.copy().items():
if (
round(time()) - timestamp >= self.configuration["tracker_timeout"]
and timestamp != 0
):
# If the timestamp is later than current time minus tracker_timeout
# Publish offline message
message = json.dumps(
{"id": address, "state": "offline", "unlocked": False}
)
self.publish(
message,
self.configuration["publish_topic"]
+ "/"
+ address.replace(":", ""),
)

self.discovered_trackers[address] = 0

async def ble_scan_loop(self) -> None:
"""Scan for BLE devices."""
scanner_kwargs = {"scanning_mode": self.configuration["scanning_mode"]}
Expand Down Expand Up @@ -375,6 +397,8 @@ async def ble_scan_loop(self) -> None:
self.configuration["ble_time_between_scans"],
)

# Check tracker timeouts
self.check_tracker_timeout()
# Update time for all clocks once a day
await self.update_clock_times()
else:
Expand Down Expand Up @@ -513,6 +537,11 @@ def publish_json(
decoded: bool, # noqa: FBT001
) -> None:
"""Publish JSON data to MQTT."""
# Update tracker last received time
if data_json["id"] in self.discovered_trackers:
self.discovered_trackers[data_json["id"]] = round(time())
logger.debug("Discovered Trackers @publish_json: %s", self.discovered_trackers)

# Remove "track" if PUBLISH_ADVDATA is 0
if not self.configuration["publish_advdata"] and "track" in data_json:
data_json.pop("track", None)
Expand Down
7 changes: 7 additions & 0 deletions TheengsGateway/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"enable_tls": 0,
"enable_websocket": 0,
"identities": {},
"tracker_timeout": 120,
"ble": 1,
}

Expand Down Expand Up @@ -215,6 +216,12 @@ def parse_args() -> argparse.Namespace:
type=int,
help="Enable (1) or disable (0) TLS (default: 0)",
)
parser.add_argument(
"-to",
"--tracker_timeout",
type=int,
help="Tracker timeout duration (seconds)",
)
parser.add_argument(
"-ts",
"--time_sync",
Expand Down
6 changes: 6 additions & 0 deletions TheengsGateway/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import json
import re
from time import time

from TheengsDecoder import getProperties

Expand Down Expand Up @@ -257,6 +258,11 @@ def publish_device_tracker(

def copy_pub_device(self, device: dict) -> dict:
"""Copy pub_device and remove "track" if publish_advdata is false."""
# Update tracker last received time
if "track" in device:
self.discovered_trackers[device["id"]] = round(time())
logger.debug("Discovered Trackers: %s", self.discovered_trackers)

pub_device_copy = device.copy()
# Remove "track" if PUBLISH_ADVDATA is 0
if not self.configuration["publish_advdata"] and "track" in pub_device_copy:
Expand Down

0 comments on commit 591101c

Please sign in to comment.