windows -python3.7-pybluez蓝牙通信记录

window添加pybluez需要手动下载一些文件。
共计3步。请耐心~
2步配置完成,最后一部测试

**

1. 第一步,直接添加pybluez库

pip install pybluez==0.22
  • 如果出现报错:SDK——则需要安装VC编译器。想简单点的话,直接安装VS2019即可

  • 另外一个可能出现的报错就是(我忘记截图了):——需要手动更改一下文件名,即:

  • 在系统盘目录:C:\Program Files (x86)\Microsoft SDKs\Windows 下,有个文件夹(我的是v10.0A),更名为 v7.0A或者v6.0A即可(建议复制备份一下更妥)*
    windows -python3.7-pybluez蓝牙通信记录_第1张图片

2. 第二步,下载pybluez的依赖文件

解压到相应环境目录之后,在目录中运行 Windows PowerShell。(具体方法见之前一个博客提到的方式:https://blog.csdn.net/tjb132/article/details/108704457)
输入命令:python setup.py install
一般情况下是没有问题的,但是有的电脑可能出现文件。比如,我台式电脑就可以,笔记本就死活有问题

pybluez的依赖资源见博客最后链接!
windows -python3.7-pybluez蓝牙通信记录_第2张图片

3. 第三步,调试

简单点,直接公开代码吧!
import bluetooth
from bluetooth.btcommon import BluetoothError
import time

class DeviceConnector:
    TARGET_NAME =  "WIN-QK4S2AFOFSN" ##  "BIAO10214"
    TARGET_ADDRESS = None
    TARGET_PORT = 1
    SOCKET = None

    def __init__(self):
        pass

    def getConnectionInstance(self):
        self.deviceDiscovery()
        if(DeviceConnector.TARGET_ADDRESS is not None):
            print('Device found!')
            self.connect_bluetooth_addr()
            return DeviceConnector.SOCKET
        else:
            print('Could not find target bluetooth device nearby')

    def deviceDiscovery(self):
        tries=0
        try:
            nearby_devices = bluetooth.discover_devices(lookup_names = True, duration=5)
            while nearby_devices.__len__() == 0 and tries < 3:   #多次
                nearby_devices = bluetooth.discover_devices(lookup_names = True, duration=5)  ##查找。名称可见
                tries += 1
                time.sleep (2)
                print ('couldn\'t connect! trying again...')
            for bdaddr, name in nearby_devices:
                print(bdaddr,name)
            for bdaddr, name in nearby_devices:
                if bdaddr and name == DeviceConnector.TARGET_NAME:  ##查找目标
                    DeviceConnector.TARGET_ADDRESS = bdaddr
                    # DeviceConnector.TARGET_NAME = name
        except BluetoothError as e:
            print ('bluetooth is off')

    def connect_bluetooth_addr(self):
        for i in range(1,5):
            time.sleep(1)
            sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)  #服务器协议选择
            try:
                sock.connect((DeviceConnector.TARGET_ADDRESS, 4)) # DeviceConnector.TARGET_PORT #连接目标
                sock.setblocking(False)  #阻塞
                data = '12345'
                sock.send( data.encode('utf-8') )
                DeviceConnector.SOCKET = sock
                print('it has connected a device successfully')
                return
            except BluetoothError as e:
                print('Could not connect to the device')
                DeviceConnector.SOCKET.close()
        return None

    def createService(self,way=bluetooth.RFCOMM):
        server_sock = bluetooth.BluetoothSocket(way)  ## bluetooth.L2CAP     ## RFCOMM    ##
        server_sock.bind(('', 4))
        server_sock.listen(2)   #监听
        print('开始监听....................')
        while True:
            client_sock, address = server_sock.accept()  # 接受请求
            print("Accepted connection from ", address)
            while True:
                data = client_sock.recv(5)#等待接受数据。 数据长度为1(这个根据自己的情况任意改,只有接受够这么多长度的数据,才会结束这个语句)
                if not data:
                    break
                client_sock.send(data) # 数据返回
                print("received [%s]" % data.decode('utf-8') )
            client_sock.close()  #连接关闭
            server_sock.close()

bluez = DeviceConnector()
# bluez.getConnectionInstance()
bluez.createService()


最后值得一提的是,蓝牙通信跟网络socket通信相似,或者说基本一样。。。但是,如果用电脑跟手机配对的话就会比较麻烦。目前我还没有做出来!手机的配对不仅需要一个connect来激活主动连接,还需要相应的动态随机码。有经验的朋友欢迎留言指点我一下,谢谢啦~

最后:致谢 官方: https://github.com/pybluez/pybluez/blob/master/docs/install.rst

依赖的资源文件下载位置如图:
windows -python3.7-pybluez蓝牙通信记录_第3张图片

你可能感兴趣的:(嵌入式,python,socket,程序人生)