Skip to content

Commit 2f9e9a9

Browse files
Create main.py
1 parent ffadeb8 commit 2f9e9a9

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

main.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Example of how to use BTHome beacons with aioble in MicroPython
2+
# Some parts are ESP32 specific, but most code is portable.
3+
4+
from machine import deepsleep, unique_id
5+
from binascii import hexlify
6+
import asyncio
7+
import aioble
8+
import bthome
9+
10+
BLE_ADV_INTERVAL_uS = 250000
11+
AWAKE_TIME_SECS = 60 # How long to spend advertising and servicing clients.
12+
SLEEP_TIME_SECS = 120 # How long to spend in deep sleep.
13+
14+
base_mac = unique_id() # WiFi MAC
15+
bluetooth_mac = bytearray(base_mac)
16+
bluetooth_mac[5] += 2 # ESP32 Bluetooth MAC is always WiFi MAC + 2
17+
18+
bthome.device_name = "DIY-sensor"
19+
print(bthome.device_name)
20+
print(hexlify(bluetooth_mac, ':').decode().upper())
21+
22+
async def read_sensor():
23+
bthome.temperature = 25
24+
bthome.humidity = 50.55
25+
print(f"BTHome flags: {bthome._ADVERT_FLAGS.hex().upper()}")
26+
print(f"Device name: {bthome._pack_device_name().hex().upper()}")
27+
print(f"Temperature data: {bthome._pack_temperature(bthome.TEMPERATURE_SINT16).hex().upper()}")
28+
print(f"Humidity data: {bthome._pack_humidity(bthome.HUMIDITY_UINT16).hex().upper()}")
29+
print(f"BTHome advertisement: {bthome.pack_advertisement(bthome.TEMPERATURE_SINT16, bthome.HUMIDITY_UINT16).hex().upper()}")
30+
await asyncio.sleep(AWAKE_TIME_SECS)
31+
print("Going to sleep.")
32+
deepsleep(SLEEP_TIME_SECS * 1000) # Helps mitigate sensor self-heating.
33+
34+
async def communicate_readings():
35+
print("Advertising availability of data.")
36+
while True:
37+
async with await aioble.advertise(
38+
BLE_ADV_INTERVAL_uS,
39+
adv_data = bthome.pack_advertisement(bthome.TEMPERATURE_SINT16, bthome.HUMIDITY_UINT16)
40+
) as connection:
41+
print("Client connect:", connection.device)
42+
await connection.disconnected(timeout_ms=None)
43+
print("Client disconnect.")
44+
45+
46+
async def main():
47+
task1 = asyncio.create_task(read_sensor())
48+
task2 = asyncio.create_task(communicate_readings())
49+
await asyncio.gather(task1, task2)
50+
51+
asyncio.run(main())

0 commit comments

Comments
 (0)