This program automatically synchronizes the time on BTHome-compatible Bluetooth Low Energy (BLE) THB2 firmware flashed devices.
It continuously scans for devices that advertise the BTHome service UUID (0xFCD2) and ensures their
internal clocks are synchronized with the host computer's time.
This script could be executed by a scheduled cron job for instance
to rectify the time drift of the devices.
Key Features:
- Discovers BTHome devices using service UUID 0xFCD2
- Automatically connects and syncs time when drift exceeds 3 seconds
- Supports multiple devices with concurrent processing
- Implements retry mechanism for failed connections
- Prevents excessive reconnections with 60-second cooldown
- Includes timeout protection for unresponsive devices
Technical Implementation:
1. Device Discovery:
- Uses BleakScanner with a detection callback
- Filters devices by BTHome service UUID (0xFCD2)
- Checks both service UUIDs and service data
2. Connection Process:
- Establishes BLE connection with 30-second timeout
- Discovers services and sets up notifications
- Uses characteristic 0xFFF4 for time sync commands
3. Time Synchronization:
- Reads current device time via command 0x33
- Compares with system time accounting for timezone
- Updates device time if difference exceeds 3 seconds
- Uses command 0x23 to set new time value
4. Error Handling:
- Implements connection retries (max 2 attempts)
- Includes timeout protection for all BLE operations
- Gracefully handles disconnections and exceptions
Usage:
Run the script directly to start the auto time sync service:
python auto_time_sync.py
The program will continuously scan for and process BTHome devices, logging all operations
and any errors that occur. Use Ctrl+C to gracefully stop the service.