2022年 11月 13日

python操作蓝牙

一、介绍

二、安装
pip install pybluez
在这里插入图片描述
三、函数介绍
socket
1、

四、代码示例

import bluetooth

def get_locol_address():
    print("本机蓝牙MAC地址:",bluetooth.read_local_bdaddr())
    
def find_buletooth(target_name):
    nearby_devices = bluetooth.discover_devices()
    target_address = None
    
    for bdaddr in nearby_devices:
        if target_name == bluetooth.lookup_name( bdaddr ):
            target_address = bdaddr
        break

    if target_address is not None:
        print("found target bluetooth device with address ", target_address)
        return 1
    else:
        print("could not find target bluetooth device nearby")
        return 0
    
def san_bluetooth():
    nearby_devices = bluetooth.discover_devices(lookup_names=True)
    for addr, name in nearby_devices:
        print(" %s - %s" % (addr, name))

    services = bluetooth.find_service(address=addr)
    for svc in services:
        print("Service Name: %s" % svc["name"])
        print(" Host: %s" % svc["host"])
        print(" Description: %s" % svc["description"])
        print(" Provided By: %s" % svc["provider"])
        print(" Protocol: %s" % svc["protocol"])
        print(" channel/PSM: %s" % svc["port"])
        print(" svc classes: %s "% svc["service-classes"])
        print(" profiles: %s "% svc["profiles"])
        print(" service id: %s "% svc["service-id"])
        print("")
    return
        
def socket_client(bd_addr, port):
    sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
    sock.connect((bd_addr, port))
    sock.send("hello!!")
    sock.close()
    return

#find_buletooth("GZSOAIY")
#san_bluetooth()
#socket_client("41:42:C5:BF:2C:32", 1)
get_locol_address()
#bluetooth.bt.connect("41:42:C5:BF:2C:32", 1)


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

五、结果
在这里插入图片描述