Created
March 19, 2023 20:30
-
-
Save franklindyer/4fc504901621b962d0dc88392bdaee88 to your computer and use it in GitHub Desktop.
Simple python script using bluetooth to periodically log your phone's battery level from another device.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
from bleak import BleakClient, BleakScanner | |
import time | |
from datetime import datetime | |
import sys | |
print("Bluetooth battery monitoring script launched.") | |
args = sys.argv | |
if len(args) < 3: | |
print("Usage: python3.9 battery_tracker.py [NAME OF DEVICE] [PATH TO LOGFILE]") | |
exit(1) | |
PHONE_NAME = args[1] | |
LOGFILE = args[2] | |
async def main(): | |
iphone_dev = False; | |
## Discover my device, given its name | |
while iphone_dev == False: | |
async with BleakScanner() as scanner: | |
devices = await scanner.discover(timeout=30.0) | |
for d in devices: | |
if d.name == PHONE_NAME: | |
iphone_dev = d; | |
break | |
print("Scan timed out, trying again.") | |
print(iphone_dev) | |
async with BleakClient(iphone_dev.address) as client: | |
await client.connect() | |
phone_services = client.services | |
battery_char = phone_services.get_characteristic(26) | |
while True: | |
battery_level = int.from_bytes(await client.read_gatt_char(battery_char), byteorder='big') | |
with open(LOGFILE, "a") as f: | |
f.write(str(datetime.now()) + " " + str(battery_level) + "\n") | |
print("Battery logged: " + str(datetime.now())) | |
time.sleep(30) | |
await client.disconnect() | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment