Skip to content

Instantly share code, notes, and snippets.

@sourceperl
Last active January 8, 2025 18:25
Show Gist options
  • Save sourceperl/aeae8945cab249938f344bf45f76f8a4 to your computer and use it in GitHub Desktop.
Save sourceperl/aeae8945cab249938f344bf45f76f8a4 to your computer and use it in GitHub Desktop.
micropython aioble basic peripheral (service environmental_sensing with temperature characteristic)
import uasyncio as aio
import aioble
from bluetooth import UUID
import random
import struct
# org.bluetooth.service.environmental_sensing
_ENV_SENSE_UUID = UUID(0x181A)
# org.bluetooth.characteristic.temperature
_ENV_SENSE_TEMP_UUID = UUID(0x2A6E)
# org.bluetooth.characteristic.gap.appearance.xml
_ADV_APPEARANCE_GENERIC_THERMOMETER = 768
# Register GATT server
temp_service = aioble.Service(_ENV_SENSE_UUID)
temp_characteristic = aioble.Characteristic(temp_service, _ENV_SENSE_TEMP_UUID, read=True, notify=True)
aioble.register_services(temp_service)
# periodically polling a hardware sensor
async def sensor_task():
while True:
t = 25.5 + random.uniform(-0.5, 0.5)
t_encode = struct.pack('<h', int(t * 100))
temp_characteristic.write(t_encode, send_update=True)
await aio.sleep_ms(1_000)
# wait for connections (don't advertise while a central is connected)
async def peripheral_task():
while True:
connection = await aioble.advertise(interval_us=250_000, name='mpy-temp',
services=[_ENV_SENSE_UUID], appearance=_ADV_APPEARANCE_GENERIC_THERMOMETER)
print('Connection from', connection.device)
await connection.disconnected(timeout_ms=None)
print('end of connection')
# create asyncio task and run it
loop = aio.get_event_loop()
loop.create_task(sensor_task())
loop.create_task(peripheral_task())
loop.run_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment