@@ -21,6 +21,9 @@ class BTHome:
2121 0x40 # Currently hardcoded as: no encryption, regular updates, version 2
2222 )
2323
24+ # Advertising size limit
25+ _ADVERT_PAYLOAD_MAX_BYTES = 31 # [^3]
26+
2427 debug = False
2528
2629 # Device name used in BLE advertisements.
@@ -293,7 +296,7 @@ class BTHome:
293296 window = False
294297
295298 def __init__ (self , local_name = "BTHome" , debug = False ):
296- local_name = local_name [:10 ] # Truncate to fit [^3 ]
299+ local_name = local_name [:10 ] # Truncate to fit [^4 ]
297300 self ._local_name = local_name
298301 self .debug = debug
299302
@@ -310,7 +313,7 @@ def packet_id(self):
310313 # Technically, the functions below could be static methods, but @staticmethod
311314 # on a dictionary of functions only works with Python >3.10, and MicroPython
312315 # is based on 3.4. Also, __func__ and __get()__ workarounds throw errors in
313- # MicroPython. [^4 ]
316+ # MicroPython. [^5 ]
314317
315318 # Binary flag (true/false, on/off)
316319 def _pack_binary (self , object_id , value ):
@@ -481,6 +484,9 @@ def pack_advertisement(self, *args):
481484 advertisement_bytes += self ._pack_service_data (* args )
482485 if self .debug :
483486 print ("BLE Advertisement:" , advertisement_bytes .hex ().upper ())
487+ print ("Advertisement Len:" , len (advertisement_bytes ))
488+ if len (advertisement_bytes ) > BTHome ._ADVERT_PAYLOAD_MAX_BYTES :
489+ raise ValueError ("BLE advertisement exceeds max length" )
484490 return advertisement_bytes
485491
486492
@@ -502,5 +508,6 @@ def demo():
502508
503509# [^1]: https://community.silabs.com/s/article/kba-bt-0201-bluetooth-advertising-data-basics
504510# [^2]: https://bthome.io/images/License_Statement_-_BTHOME.pdf
505- # [^3]: https://community.st.com/t5/stm32-mcus-wireless/ble-name-advertising/m-p/254711/highlight/true#M10645
506- # [^4]: https://stackoverflow.com/questions/41921255/staticmethod-object-is-not-callable
511+ # [^3]: https://github.com/orgs/micropython/discussions/12701
512+ # [^4]: https://community.st.com/t5/stm32-mcus-wireless/ble-name-advertising/m-p/254711/highlight/true#M10645
513+ # [^5]: https://stackoverflow.com/questions/41921255/staticmethod-object-is-not-callable
0 commit comments