-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbtproxy_test_client.py
More file actions
64 lines (52 loc) · 2.07 KB
/
btproxy_test_client.py
File metadata and controls
64 lines (52 loc) · 2.07 KB
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
import aioesphomeapi
import argparse
import asyncio
import pprint
import contextlib
from aioesphomeapi.api_pb2 import BluetoothLEAdvertisementResponse, BluetoothLERawAdvertisementsResponse
from aioesphomeapi.core import InvalidAuthAPIError, APIConnectionError
pp = pprint.PrettyPrinter(indent=2, width=100)
async def main(hostname, password):
api = aioesphomeapi.APIClient(hostname, 6053, password)
def handle_ble_adv(msg: BluetoothLEAdvertisementResponse):
pp.pprint(msg)
def handle_raw_ble_adv(msg: BluetoothLERawAdvertisementsResponse):
for adv in msg.advertisements:
pp.pprint(adv)
try:
await api.connect(login=True)
except InvalidAuthAPIError:
print("ERROR: Invalid password!")
return
except APIConnectionError as e:
print(f"ERROR: Failed to connect to {hostname}: {e}")
return
print(f"Connected to {hostname}")
print("API Version:", api.api_version)
print("Listening for BLE advertisements...\n")
unsubscribe = None
try:
# unsubscribe = api.subscribe_bluetooth_le_raw_advertisements(handle_raw_ble_adv)
unsubscribe = api.subscribe_bluetooth_le_advertisements(handle_ble_adv)
if not unsubscribe:
print("ERROR: Subscription failed — device busy?")
return
print("Subscribed successfully.")
while True:
await asyncio.sleep(1)
except (KeyboardInterrupt, asyncio.CancelledError):
print("Stopping...")
except Exception as e:
print(f"ERROR during run: {e}")
finally:
if unsubscribe:
print("Unsubscribing...")
with contextlib.suppress(Exception):
unsubscribe()
print("Done.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="ESPHome Bluetooth Proxy passive monitor (subscribe API)")
parser.add_argument("hostname", help="ESPHome BTProxy hostname")
parser.add_argument("--password", default="", help="API password")
args = parser.parse_args()
asyncio.run(main(args.hostname, args.password))