overhaul ble.py, move all async calls there
This commit is contained in:
1 parent
87cd24234a
commit
0d975a15a8
8 files changed
+712
-135
No files matched your search
+28
-30
@@ -4,6 +4,7 @@ import time
|
||||
import redis
|
||||
import pickle
|
||||
import os
|
||||
import subprocess
|
||||
from datetime import datetime, timezone
|
||||
from zoneinfo import ZoneInfo # Python 3.9+
|
||||
from bleak import BleakScanner, BleakClient
|
||||
@@ -11,7 +12,7 @@ from typing import Set, Iterable
|
||||
from config import *
|
||||
from sensors import *
|
||||
from ble import *
|
||||
from ble_redis import *
|
||||
|
||||
|
||||
# In-memory cache + thread-safe lock
|
||||
_mac_cache: Set[str] = set()
|
||||
@@ -78,24 +79,8 @@ def update_redis(data):
|
||||
print(json.dumps(data, indent=2))
|
||||
return True
|
||||
|
||||
# this function filters MACs
|
||||
def _is_match(mac: str, name: str) -> bool:
|
||||
"""Return True if the MAC starts with the configured prefix and is correct model."""
|
||||
if name == "LYWSD03MMC":
|
||||
return mac.upper().startswith(MAC_PREFIX.upper())
|
||||
|
||||
# this function scans for MACs
|
||||
async def _scan_once() -> Iterable[str]:
|
||||
"""Do one scan cycle and return the matching MACs."""
|
||||
devices = await BleakScanner.discover(timeout=5.0) # 5s scan
|
||||
return [dev.address for dev in devices if _is_match(dev.address, dev.name)]
|
||||
|
||||
# this very important function updates the MAC cache and the sensor objects
|
||||
def update_cache() -> None:
|
||||
"""
|
||||
Called by the scheduler (in a separate thread). It runs a tiny
|
||||
asyncio event loop to call the Bleak scan, then updates the cache.
|
||||
"""
|
||||
# Run the async scan in a fresh loop; Bleak requires this.
|
||||
# Gets the MACs
|
||||
print("")
|
||||
@@ -122,19 +107,18 @@ def update_cache() -> None:
|
||||
update_redis(get_sensor_details())
|
||||
save_state()
|
||||
|
||||
# this helper function scans for MACs
|
||||
def scan_macs():
|
||||
print("Scanning for MACs:")
|
||||
new_macs = asyncio.run(_scan_once())
|
||||
with _lock:
|
||||
for new_mac in new_macs:
|
||||
print(f"{new_mac}")
|
||||
new_sensor = Sensor(name=f"{new_mac}")
|
||||
if new_mac not in set(_mac_cache):
|
||||
_sensors_cache.append(new_sensor)
|
||||
_mac_cache.update(new_macs)
|
||||
print(f"Found {len(new_macs)} new MACs, total {len(_mac_cache)} MACs in cache.")
|
||||
return new_macs
|
||||
#def scan_macs():
|
||||
# print("Scanning for MACs:")
|
||||
# new_macs = asyncio.run(_scan_once())
|
||||
# with _lock:
|
||||
# for new_mac in new_macs:
|
||||
# print(f"{new_mac}")
|
||||
# new_sensor = Sensor(name=f"{new_mac}")
|
||||
# if new_mac not in set(_mac_cache):
|
||||
# _sensors_cache.append(new_sensor)
|
||||
# _mac_cache.update(new_macs)
|
||||
# print(f"Found {len(new_macs)} new MACs, total {len(_mac_cache)} MACs in cache.")
|
||||
# return new_macs
|
||||
|
||||
# return just the MACs
|
||||
def get_cache_snapshot() -> Set[str]:
|
||||
@@ -188,3 +172,17 @@ def ts_to_pst_string(ts_str):
|
||||
utc_dt = datetime.fromtimestamp(ts_str, tz=timezone.utc)
|
||||
pacific_dt = utc_dt.astimezone(ZoneInfo("America/Los_Angeles"))
|
||||
return pacific_dt.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
# subroutine to run a command, return stdout as array unless zero_only then return [0]
|
||||
def run_command(cmd, zero_only=False, use_shell=True, req_check = True):
|
||||
# Run the command and capture the output
|
||||
result = subprocess.run(cmd, shell=use_shell, check=req_check, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
# Decode the byte output to a string
|
||||
output = result.stdout.decode('utf-8')
|
||||
# Split the output into lines and store it in an array
|
||||
output_lines = [line for line in output.split('\n') if line]
|
||||
# Return result
|
||||
try:
|
||||
return output_lines[0] if zero_only else output_lines
|
||||
except:
|
||||
return output_lines
|
||||
Reference in new issue
Block a user