/ examples / ble_broadcastnet_expo_backoff.py
ble_broadcastnet_expo_backoff.py
 1  """This example uses the internal temperature sensor and reports the battery voltage. However, it
 2     reads the temperature more often but only reports it when it's changed by a degree since the last
 3     report. When doing a report it will actually do multiple broadcasts and wait 2 ** n readings
 4     until the next broadcast. The delay is reset every time the temp moves more than 1 degree."""
 5  
 6  import math
 7  import time
 8  import analogio
 9  import board
10  import microcontroller
11  import adafruit_ble_broadcastnet
12  
13  print("This is BroadcastNet sensor:", adafruit_ble_broadcastnet.device_address)
14  
15  battery = analogio.AnalogIn(board.VOLTAGE_MONITOR)
16  divider_ratio = 2
17  
18  last_temperature = None
19  consecutive = 1
20  while True:
21      temp = microcontroller.cpu.temperature  # pylint: disable=no-member
22      if not last_temperature or abs(temp - last_temperature) > 1:
23          consecutive = 1
24          last_temperature = temp
25      else:
26          consecutive += 1
27  
28      # Repeatedly broadcast identical values to help ensure it is picked up by the bridge. Perform
29      # exponential backoff as we get more confidence.
30      exp = int(math.log(consecutive, 2))
31      if 2 ** exp == consecutive:
32          measurement = adafruit_ble_broadcastnet.AdafruitSensorMeasurement()
33          battery_voltage = (
34              battery.value
35              / 2 ** 16
36              * divider_ratio
37              * battery.reference_voltage  # pylint: disable=no-member
38          )
39          measurement.battery_voltage = int(battery_voltage * 1000)
40          measurement.temperature = temp
41          print(measurement)
42          adafruit_ble_broadcastnet.broadcast(measurement)
43  
44      time.sleep(1)