### Advertiser Example Source: https://github.com/thecellule/python-bleson/wiki/Bleson-API---(DRAFT) This example demonstrates how to start advertising a custom advertisement with a specified device name. ```python from signal import pause from bleson import AdapterManager from bleson import Advertisement from bleson.roles import Advertiser adapter = AdapterManager.get_adapter() # defaults to first found HCI device advertiser = Advertiser(adapter) advertiser.advertisement = Advertisement(device_name="bleson") advertiser.start() pause() ``` -------------------------------- ### Run Bleson CLI Observer Tool Source: https://context7.com/thecellule/python-bleson/llms.txt Provides examples of how to use the Bleson command-line interface to start a BLE observer, with options for default or custom scan durations. ```bash # Observe for the default duration python3 -m bleson --observer # Pass a custom scan duration (seconds) where supported python3 -m bleson --observer 30 ``` -------------------------------- ### Install and Run Bleson Observer CLI Source: https://context7.com/thecellule/python-bleson/llms.txt Install the Bleson library using pip and run the observer CLI for a quick smoke-test to observe nearby BLE advertisements. ```bash pip3 install bleson # Quick smoke-test: observe nearby BLE advertisements for 10 seconds python3 -m bleson --observer ``` -------------------------------- ### Beacon Example (Conceptual Subclass) Source: https://github.com/thecellule/python-bleson/wiki/Bleson-API---(DRAFT) This is a conceptual example showing how a beacon class could subclass Advertiser for simpler user code. ```python advertiser = Eddystone('www.bleson.com', adapter) advertiser.start() ``` -------------------------------- ### Install and Run Bleson Observer Source: https://github.com/thecellule/python-bleson/blob/master/README.rst Installs the bleson package using pip3 and then runs the bleson module in observer mode. May require sudo for pip3 installation unless using a virtual environment or --user option. 'python' might be 'python3' on some platforms. ```bash pip3 install bleson python3 -m bleson --observer ``` -------------------------------- ### Observer/Scanning Example Source: https://github.com/thecellule/python-bleson/wiki/Bleson-API---(DRAFT) Use this snippet to observe and scan for Bluetooth devices. It prints the device address and RSSI, and details from the advertisement. ```python from signal import pause from bleson import AdapterManager from bleson.roles import Observer adapter = AdapterManager.get_adapter() # default to first found HCI device observer = Observer(adapter) def advertisement_update(device): print(device.addr) # instance of 'BDAddress' print(device.rssi) # int advertisement = device.advertisement # instance of 'Advertisement' print(advertisement.device_name) print(advertisement.tx_power) print(advertisement.manufacturer_data) observer.on_scan_response = advertisement_update observer.start() pause() ``` -------------------------------- ### Build Docs and Run Doctests Source: https://github.com/thecellule/python-bleson/blob/master/docs/development.md Builds the documentation and executes embedded doctests to verify code examples. ```console python3 setup.py doctest ``` -------------------------------- ### Install Bleson on Linux Source: https://github.com/thecellule/python-bleson/blob/master/docs/installing.md Use pip3 to install the Bleson library on Linux systems. Ensure you are using Python 3. ```bash sudo pip3 install bleson ``` -------------------------------- ### Install Bleson on macOS Source: https://github.com/thecellule/python-bleson/blob/master/docs/installing.md Install Bleson using pip3 on macOS. You might need sudo if not using Homebrew. ```bash $ pip3 install bleson ``` -------------------------------- ### Start an Eddystone Beacon Source: https://github.com/thecellule/python-bleson/blob/master/docs/cli_tools.md Initiate an Eddystone beacon advertising a specified URL. Ensure the URL is valid. ```console python3 -m bleson --beacon --url http://www.google.com/ ``` -------------------------------- ### Install Bleson on Windows 10 Source: https://github.com/thecellule/python-bleson/blob/master/docs/installing.md Install Bleson using pip on Windows 10. Ensure pip version is 9.0 or newer for precompiled native components. ```bash $ pip install bleson ``` -------------------------------- ### Beacon Example with Raw Data Source: https://github.com/thecellule/python-bleson/wiki/Bleson-API---(DRAFT) Use this snippet to advertise raw advertising data, such as that generated by third-party helpers like Eddystone. ```python from signal import pause from bleson import AdapterManager from bleson import Advertisement from bleson.roles import Advertiser from some.helper import Eddystone ADV_RAW_DATA = Eddystone('www.bleson.com').advertising_data() adapter = AdapterManager.get_adapter() # defaults to first found HCI device advertiser = Advertiser(adapter) advertiser.advertisement = Advertisement(data=ADV_RAW_DATA) advertiser.start() pause() ``` -------------------------------- ### Create and Use UUID16 Source: https://context7.com/thecellule/python-bleson/llms.txt Illustrates the creation of a UUID16 object from an integer or a byte representation, and shows how to compare them and get their byte representation. ```python from bleson.core.types import UUID16 u1 = UUID16(0x180d) # Heart Rate Service u2 = UUID16([0x0d, 0x18]) # same UUID from little-endian bytes u3 = UUID16(bytearray([0x0d, 0x18])) print(u1) # UUID16(0x180d) print(u1 == u2) # True print(bytes(u1).hex()) # '0d18' — little-endian wire bytes print(len(u1)) # 2 ``` -------------------------------- ### Get Default BLE Adapter using get_provider Source: https://context7.com/thecellule/python-bleson/llms.txt Auto-detect the current platform and retrieve the default BLE adapter. The stub provider can be forced for testing purposes using an environment variable. ```python from bleson import get_provider # Auto-detect platform and get the default adapter adapter = get_provider().get_adapter() print(adapter) # e.g. # Force the stub (no-hardware) provider for testing import os os.environ["BLESON_PROVIDER"] = "stub" from bleson.providers import get_provider as gp stub_adapter = gp().get_adapter() ``` -------------------------------- ### Scan for Bluetooth LE Devices Source: https://github.com/thecellule/python-bleson/blob/master/docs/cli_tools.md Use this command to scan for nearby Bluetooth LE devices and view advertising reports. No additional setup is required. ```console python3 -m bleson --observer ``` -------------------------------- ### Build Documentation Source: https://github.com/thecellule/python-bleson/blob/master/docs/development.md Use this command to build the project's documentation. ```console python3 setup.py doc ``` -------------------------------- ### Build and Inspect BLE Advertisements Source: https://context7.com/thecellule/python-bleson/llms.txt Demonstrates creating an outgoing BLE advertisement with various fields and inspecting a received advertisement. Includes setting name, transmit power, UUIDs, and manufacturer data. ```python from bleson.core.types import Advertisement, BDAddress, UUID16, UUID128 # Build an outgoing advertisement adv = Advertisement() adv.name = "MySensor" adv.tx_pwr_lvl = 0 adv.uuid16s = [UUID16(0x180f)] # Battery Service adv.uuid128s = [UUID128('00001530-1212-efde-1523-785feabcd123')] adv.mfg_data = bytearray([0x4c, 0x00, 0x02, 0x15]) # iBeacon prefix # Inspect a received advertisement print(adv) # Advertisement(flags=0x06, name='MySensor', txpower=0, # uuid16s=[UUID16(0x180f)], uuid128s=[UUID128('00001530-...')], # rssi=None, mfg_data=bytearray(b'L\x00\x02\x15')) # Raw-data form (Linux HCI payload passthrough) raw_adv = Advertisement(raw_data=bytearray([0x02, 0x01, 0x1a, 0x03, 0x03, 0xaa, 0xfe])) ``` -------------------------------- ### Update Development Tools Source: https://github.com/thecellule/python-bleson/blob/master/docs/development.md Ensure your pip, setuptools, and wheel are up-to-date before proceeding with development. ```console pip3 install --upgrade pip setuptools wheel twine ``` -------------------------------- ### Observer Source: https://context7.com/thecellule/python-bleson/llms.txt Wraps the platform adapter's scanning functionality and delivers received Advertisement objects to a callback. Supports explicit start/stop and the context-manager protocol. ```APIDOC ## Observer ### Description `Observer` wraps the platform adapter's scanning functionality and delivers received `Advertisement` objects to a callback. It supports both explicit `start()`/`stop()` lifecycle calls and the Python context-manager (`with`) protocol for automatic cleanup. ### Usage ```python from time import sleep from bleson import get_provider, Observer def on_advertisement(advertisement): # advertisement is an Advertisement value object print(f"[{advertisement.address}] name={advertisement.name!r} " f"rssi={advertisement.rssi} uuid16s={advertisement.uuid16s}") adapter = get_provider().get_adapter() # Explicit start/stop observer = Observer(adapter) observer.on_advertising_data = on_advertisement observer.start() sleep(10) observer.stop() # Context-manager form (callback passed in constructor) with Observer(adapter, on_advertisement): sleep(10) # Expected output (sample): # [BDAddress('AA:BB:CC:DD:EE:FF')] name='MyDevice' rssi=-72 uuid16s=[UUID16(0x180d)] ``` ``` -------------------------------- ### get_provider() / get_default_adapter() Source: https://context7.com/thecellule/python-bleson/llms.txt Auto-detects the current platform and returns a singleton provider or the default BLE adapter. ```APIDOC ## get_provider() / get_default_adapter() ### Description `get_provider()` auto-detects the current platform (Linux, macOS, Windows, or the `BLESON_PROVIDER=stub` environment override) and returns a singleton provider. `get_default_adapter()` is a convenience wrapper that returns the first BLE adapter from the provider. ### Usage ```python from bleson import get_provider # Auto-detect platform and get the default adapter adapter = get_provider().get_adapter() print(adapter) # e.g. # Force the stub (no-hardware) provider for testing import os os.environ["BLESON_PROVIDER"] = "stub" from bleson.providers import get_provider as gp stub_adapter = gp().get_adapter() ``` ``` -------------------------------- ### Run Test Suite Source: https://github.com/thecellule/python-bleson/blob/master/docs/development.md Executes the project's test suite to ensure code quality and functionality. ```console python3 setup.py test ``` -------------------------------- ### Create and Normalize BDAddress Source: https://context7.com/thecellule/python-bleson/llms.txt Shows how to create a BDAddress object from various input formats like strings or byte lists, and demonstrates its normalization to an uppercase colon-separated string. ```python from bleson.core.types import BDAddress # From string addr1 = BDAddress('12:34:56:78:90:AB') print(addr1) # BDAddress('12:34:56:78:90:AB') # From little-endian byte list (as received over HCI) addr2 = BDAddress([0xab, 0x90, 0x78, 0x56, 0x34, 0x12]) print(addr2) # BDAddress('12:34:56:78:90:AB') print(addr1 == addr2) # True — equality is value-based print(hash(addr1)) # stable integer hash, safe for dict/set keys ``` -------------------------------- ### BLE Advertisement Observation with Observer Source: https://context7.com/thecellule/python-bleson/llms.txt Use the Observer class to wrap an adapter's scanning functionality and deliver received Advertisement objects to a callback. Supports explicit start/stop calls and the Python context-manager protocol for automatic cleanup. ```python from time import sleep from bleson import get_provider, Observer def on_advertisement(advertisement): # advertisement is an Advertisement value object print(f"[{advertisement.address}] name={advertisement.name!r} " f"rssi={advertisement.rssi} uuid16s={advertisement.uuid16s}") adapter = get_provider().get_adapter() # Explicit start/stop observer = Observer(adapter) observer.on_advertising_data = on_advertisement observer.start() sleep(10) observer.stop() # Context-manager form (callback passed in constructor) with Observer(adapter, on_advertisement): sleep(10) # Expected output (sample): # [BDAddress('AA:BB:CC:DD:EE:FF')] name='MyDevice' rssi=-72 uuid16s=[UUID16(0x180d)] ``` -------------------------------- ### Create and Use UUID128 Source: https://context7.com/thecellule/python-bleson/llms.txt Demonstrates creating UUID128 objects, including promoting a 16-bit UUID to the base 128-bit form and parsing from little-endian byte lists. ```python from bleson.core.types import UUID128 # Promote a 16-bit UUID to Bluetooth base 128-bit form u1 = UUID128(0x1234) print(u1) # UUID128('00001234-0000-1000-8000-00805f9b34fb') # From little-endian byte list (as received over HCI) u2 = UUID128([0x23,0xD1,0xBC,0xEA,0x5F,0x78,0x23,0x15, 0xDE,0xEF,0x12,0x12,0x30,0x15,0x00,0x00]) print(u2) # UUID128('00001530-1212-efde-1523-785feabcd123') print(bytes(u2).hex()) # reversed bytes (little-endian wire format) print(len(u2)) # 16 ``` -------------------------------- ### Grant Bluetooth LE Permissions on Linux Source: https://github.com/thecellule/python-bleson/blob/master/docs/installing.md Set capabilities for the Python 3 binary to allow running scripts without root privileges for Bluetooth LE access. ```bash sudo setcap cap_net_raw,cap_net_admin+eip $(eval readlink -f `which python3`) ``` -------------------------------- ### CLI Observer Tool Source: https://context7.com/thecellule/python-bleson/llms.txt Bleson provides a command-line interface tool for observing BLE advertisements. It can be run with default or custom scan durations. ```APIDOC ## CLI Observer Tool Bleson ships a `__main__` module exposing a command-line BLE scanner. ```bash # Observe for the default duration python3 -m bleson --observer # Pass a custom scan duration (seconds) where supported python3 -m bleson --observer 30 ``` ``` -------------------------------- ### BLE Advertisement Broadcasting with Advertiser Source: https://context7.com/thecellule/python-bleson/llms.txt Use the Advertiser class to broadcast a BLE Advertisement payload. Supports start/stop and context-manager usage. On Linux, it emits the full HCI advertisement; on macOS, the OS may adjust the payload. ```python from time import sleep from bleson import get_provider, Advertiser, Advertisement, UUID16 from bleson import LE_GENERAL_DISCOVERABLE, BREDR_NOT_SUPPORTED adapter = get_provider().get_adapter() # Simple name-only advertisement advertisement = Advertisement(name="bleson") with Advertiser(adapter, advertisement): sleep(10) # Advanced: Heart-rate monitor with service UUIDs and flags adv = Advertisement() adv.name = "Heart Rate" adv.flags = LE_GENERAL_DISCOVERABLE | BREDR_NOT_SUPPORTED adv.uuid16s = [UUID16(0x180a), UUID16(0x180d)] # Device Info + Heart Rate advertiser = Advertiser(adapter) advertiser.advertisement = adv advertiser.start() sleep(10) advertiser.stop() ``` -------------------------------- ### Advertiser Source: https://context7.com/thecellule/python-bleson/llms.txt Broadcasts a BLE Advertisement payload. Supports start/stop and the context-manager protocol. ```APIDOC ## Advertiser ### Description `Advertiser` broadcasts a BLE `Advertisement` payload. On Linux it emits the full HCI advertisement; on macOS the OS may adjust the actual payload. Supports `start()`/`stop()` and the context-manager protocol. ### Usage ```python from time import sleep from bleson import get_provider, Advertiser, Advertisement, UUID16 from bleson import LE_GENERAL_DISCOVERABLE, BREDR_NOT_SUPPORTED adapter = get_provider().get_adapter() # Simple name-only advertisement advertisement = Advertisement(name="bleson") with Advertiser(adapter, advertisement): sleep(10) # Advanced: Heart-rate monitor with service UUIDs and flags adv = Advertisement() adv.name = "Heart Rate" adv.flags = LE_GENERAL_DISCOVERABLE | BREDR_NOT_SUPPORTED adv.uuid16s = [UUID16(0x180a), UUID16(0x180d)] # Device Info + Heart Rate advertiser = Advertiser(adapter) advertiser.advertisement = adv advertiser.start() sleep(10) advertiser.stop() ``` ``` -------------------------------- ### Stop Bluetooth Service on Linux Source: https://github.com/thecellule/python-bleson/blob/master/docs/installing.md Recommended step for Bleson usage on Linux to avoid conflicts with the HCI socket interface. This command stops the Bluetooth service. ```bash sudo service bluetooth stop ``` -------------------------------- ### Tag Release Source: https://github.com/thecellule/python-bleson/blob/master/docs/development.md Generates a Git tag for the release after merging changes and updating the version. ```console python3 setup.py tag ``` -------------------------------- ### Adjust Bleson Logging Level Source: https://context7.com/thecellule/python-bleson/llms.txt Shows how to dynamically change the Bleson logger's verbosity using `set_level()`. It demonstrates enabling debug output and restoring the previous level. ```python from bleson.logger import set_level, DEBUG, INFO from bleson import get_provider, Observer from time import sleep # Enable debug output previous = set_level(DEBUG) with Observer(get_provider().get_adapter(), lambda adv: print(adv)): sleep(5) # Restore original level set_level(previous) ``` -------------------------------- ### Advertisement Source: https://context7.com/thecellule/python-bleson/llms.txt The Advertisement object represents BLE advertisement data. It can be used to build outgoing advertisements or to parse incoming ones. It includes fields for name, transmit power level, UUIDs, and manufacturer-specific data. ```APIDOC ## Advertisement `Advertisement` is the central BLE value object carrying all advertisement fields. It is used both when building outgoing advertisements (Advertiser) and when receiving incoming ones (Observer callback). ```python from bleson.core.types import Advertisement, BDAddress, UUID16, UUID128 # Build an outgoing advertisement adv = Advertisement() adv.name = "MySensor" adv.tx_pwr_lvl = 0 adv.uuid16s = [UUID16(0x180f)] # Battery Service adv.uuid128s = [UUID128('00001530-1212-efde-1523-785feabcd123')] adv.mfg_data = bytearray([0x4c, 0x00, 0x02, 0x15]) # iBeacon prefix # Inspect a received advertisement print(adv) # Advertisement(flags=0x06, name='MySensor', txpower=0, # uuid16s=[UUID16(0x180f)], uuid128s=[UUID128('00001530-...')], # rssi=None, mfg_data=bytearray(b'L\x00\x02\x15')) # Raw-data form (Linux HCI payload passthrough) raw_adv = Advertisement(raw_data=bytearray([0x02, 0x01, 0x1a, 0x03, 0x03, 0xaa, 0xfe])) ``` ``` -------------------------------- ### EddystoneBeacon Source: https://context7.com/thecellule/python-bleson/llms.txt Extends Advertiser with Physical Web / Eddystone-URL support, encoding a URL into the standard Eddystone advertisement format. Supports context-manager usage. ```APIDOC ## EddystoneBeacon ### Description `EddystoneBeacon` extends `Advertiser` with Physical Web / Eddystone-URL support, encoding a URL into the standard Eddystone advertisement format. Supports context-manager usage. The encoded URL must be ≤ 18 bytes after scheme/extension compression. ### Usage ```python from time import sleep from bleson import get_provider, EddystoneBeacon adapter = get_provider().get_adapter() # Context-manager form with EddystoneBeacon(adapter, 'https://www.bluetooth.com/'): sleep(10) # Explicit form with error handling try: beacon = EddystoneBeacon(adapter) beacon.url = 'https://www.bluetooth.com/' # setter encodes immediately beacon.start() sleep(10) except ValueError as e: print(f"URL too long to encode: {e}") except KeyboardInterrupt: pass finally: beacon.stop() # EddystoneBeacon.encode_url classmethod can be used standalone: encoded = EddystoneBeacon.encode_url('https://www.bluetooth.com/') print(encoded) # [3, 1, 0] (scheme index + compressed path) ``` ``` -------------------------------- ### Eddystone-URL Beacon Broadcasting Source: https://context7.com/thecellule/python-bleson/llms.txt Extend Advertiser with Physical Web / Eddystone-URL support, encoding a URL into the standard Eddystone advertisement format. Supports context-manager usage. The encoded URL must be ≤ 18 bytes after scheme/extension compression. ```python from time import sleep from bleson import get_provider, EddystoneBeacon adapter = get_provider().get_adapter() # Context-manager form with EddystoneBeacon(adapter, 'https://www.bluetooth.com/'): sleep(10) # Explicit form with error handling try: beacon = EddystoneBeacon(adapter) beacon.url = 'https://www.bluetooth.com/' # setter encodes immediately beacon.start() sleep(10) except ValueError as e: print(f"URL too long to encode: {e}") except KeyboardInterrupt: pass finally: beacon.stop() # EddystoneBeacon.encode_url classmethod can be used standalone: encoded = EddystoneBeacon.encode_url('https://www.bluetooth.com/') print(encoded) # [3, 1, 0] (scheme index + compressed path) ``` -------------------------------- ### set_level() — Logging Source: https://context7.com/thecellule/python-bleson/llms.txt `set_level()` adjusts the Bleson logger verbosity at runtime. It returns the previous level, allowing it to be restored after a noisy section. ```APIDOC ## set_level() — Logging `set_level()` adjusts the Bleson logger verbosity at runtime. It returns the previous level so it can be restored after a noisy section. ```python from bleson.logger import set_level, DEBUG, INFO from bleson import get_provider, Observer from time import sleep # Enable debug output previous = set_level(DEBUG) with Observer(get_provider().get_adapter(), lambda adv: print(adv)): sleep(5) # Restore original level set_level(previous) ``` ``` -------------------------------- ### UUID16 Source: https://context7.com/thecellule/python-bleson/llms.txt `UUID16` represents a 16-bit Bluetooth UUID. It accepts various input types and provides methods to convert to bytes and check length. ```APIDOC ## UUID16 `UUID16` represents a 16-bit Bluetooth UUID, accepting int, list, tuple, bytes, or bytearray in little-endian byte order. ```python from bleson.core.types import UUID16 u1 = UUID16(0x180d) # Heart Rate Service u2 = UUID16([0x0d, 0x18]) # same UUID from little-endian bytes u3 = UUID16(bytearray([0x0d, 0x18])) print(u1) # UUID16(0x180d) print(u1 == u2) # True print(bytes(u1).hex()) # '0d18' — little-endian wire bytes print(len(u1)) # 2 ``` ``` -------------------------------- ### BDAddress Source: https://context7.com/thecellule/python-bleson/llms.txt `BDAddress` represents a 48-bit Bluetooth Device Address. It normalizes various input formats (string, bytes, bytearray) into a consistent uppercase colon-separated string. ```APIDOC ## BDAddress `BDAddress` represents a 48-bit Bluetooth Device Address, accepting string, list, tuple, bytes, or bytearray input and normalising to uppercase colon-separated string form. ```python from bleson.core.types import BDAddress # From string addr1 = BDAddress('12:34:56:78:90:AB') print(addr1) # BDAddress('12:34:56:78:90:AB') # From little-endian byte list (as received over HCI) addr2 = BDAddress([0xab, 0x90, 0x78, 0x56, 0x34, 0x12]) print(addr2) # BDAddress('12:34:56:78:90:AB') print(addr1 == addr2) # True — equality is value-based print(hash(addr1)) # stable integer hash, safe for dict/set keys ``` ``` -------------------------------- ### UUID128 Source: https://context7.com/thecellule/python-bleson/llms.txt `UUID128` represents a 128-bit Bluetooth UUID. It supports promotion from 16-bit UUIDs and various input formats, including little-endian byte arrays. ```APIDOC ## UUID128 `UUID128` represents a 128-bit Bluetooth UUID, accepting int (Bluetooth base UUID promotion), string, list, tuple, bytes, or bytearray. ```python from bleson.core.types import UUID128 # Promote a 16-bit UUID to Bluetooth base 128-bit form u1 = UUID128(0x1234) print(u1) # UUID128('00001234-0000-1000-8000-00805f9b34fb') # From little-endian byte list (as received over HCI) u2 = UUID128([0x23,0xD1,0xBC,0xEA,0x5F,0x78,0x23,0x15, 0xDE,0xEF,0x12,0x12,0x30,0x15,0x00,0x00]) print(u2) # UUID128('00001530-1212-efde-1523-785feabcd123') print(bytes(u2).hex()) # reversed bytes (little-endian wire format) print(len(u2)) # 16 ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.