树莓派(ZeroW或4B)(原生蓝牙)BLE低功耗蓝牙python示例(Peripheral 从机模式、GATT Server)

从机模式:例如微信小程序上蓝牙搜索树莓派蓝牙服务,配对连接。然后访问树莓派蓝牙提供的服务。

一、安装python库

pip3 install dbus-python
pip3 install bluezero

二、例子代码一(cpu_temperature.py)

import logging
import random

from bluezero import async_tools, adapter, peripheral

CPU_TMP_SRVC = '12341000-1234-1234-1234-123456789abc'
# https://www.bluetooth.com/specifications/assigned-numbers/
# Bluetooth SIG adopted UUID for Temperature characteristic
CPU_TMP_CHRC = '2A6E'
# Bluetooth SIG adopted UUID for Characteristic Presentation Format
CPU_FMT_DSCP = '2904'

def read_value():
    cpu_value = random.randrange(3200, 5310, 10) / 100
    return list(int(cpu_value * 100).to_bytes(2, byteorder='little', signed=True))

def update_value(characteristic):
    new_value = read_value()
    characteristic.set_value(new_value)
    return characteristic.is_notifying

def notify_callback(notifying, characteristic):
    if notifying:
        async_tools.add_timer_seconds(2, update_value, characteristic)

def main(adapter_address):
    logger = logging.getLogger('localGATT')
    logger.setLevel(logging.DEBUG)

    print('CPU temperature is {}\u00B0C'.format(
        int.from_bytes(read_value(), byteorder='little', signed=True)/100))

    cpu_monitor = peripheral.Peripheral(
    	adapter_address,
        local_name='CPU Monitor',
        appearance=1344)
    
    cpu_monitor.add_service(
    	srv_id=1, uuid=CPU_TMP_SRVC, primary=True)
    
    cpu_monitor.add_characteristic(
    	srv_id=1, chr_id=1, uuid=CPU_TMP_CHRC,
        value=[], notifying=False,
        flags=['read', 'notify'],
        read_callback=read_value,
        write_callback=None,
        notify_callback=notify_callback
        )
    
    cpu_monitor.add_descriptor(
    	srv_id=1, chr_id=1, dsc_id=1, uuid=CPU_FMT_DSCP,
        value=[0x0E, 0xFE, 0x2F, 0x27, 0x01, 0x00, 0x00],
        flags=['read'])
    
    # Publish peripheral and start event loop
    cpu_monitor.publish()

if __name__ == '__main__':
    # Get the default adapter address and pass it to main
    main(list(adapter.Adapter.available())[0].address)

三、例子代码二(ble_uart.py)

from gi.repository import GLib
from bluezero import adapter, peripheral, device

class UARTDevice:
    def __init__(self, adapter_address):
        UART_SERVICE      = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
        RX_CHARACTERISTIC = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E'
        TX_CHARACTERISTIC = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E'
    
        ble_uart = peripheral.Peripheral(
            adapter_address, 
            local_name='BLE UART V1'
            )

        ble_uart.add_service(srv_id=1, uuid = UART_SERVICE, primary = True)
    
        ble_uart.add_characteristic(
            srv_id = 1, chr_id = 1, uuid = RX_CHARACTERISTIC,
            value=[], notifying=False,
            flags=['write', 'write-without-response'],
            write_callback  = self.uart_write,
            read_callback   = None,
            notify_callback = None
            )

        ble_uart.add_characteristic(
            srv_id = 1, chr_id = 2, uuid = TX_CHARACTERISTIC,
            value=[], notifying=False,
            flags=['notify'],
            notify_callback = self.uart_notify,
            read_callback   = None,
            write_callback  = None
            )
    
        ble_uart.on_connect    = self.on_connect
        ble_uart.on_disconnect = self.on_disconnect    

        self.ble_uart = ble_uart
        self.tx_obj = None

    def publish(self):
        self.ble_uart.publish()

    def on_connect(self, ble_device: device.Device):
        print("Connected to " + str(ble_device.address))

    def on_disconnect(self, adapter_address, device_address):
        print("Disconnected from " + device_address)

    def uart_notify(self, notifying, characteristic):
        if notifying:
            self.tx_obj = characteristic
        else:
            self.tx_obj = None

    def update_tx(self, value):
        if self.tx_obj:
            print("Sending")
            self.tx_obj.set_value(value)

    def uart_write(self, value, options):
        print('raw bytes:', value)
        print('With options:', options)
        print('Text value:', bytes(value).decode('utf-8'))
        self.update_tx(value)
    
if __name__ == '__main__':
    adapter_address = list(adapter.Adapter.available())[0].address
    ud = UARTDevice(adapter_address)
    ud.publish()

你可能感兴趣的:(树莓派,Python,python,蓝牙,物联网)