Python:实现蓝牙通信

本文介绍了如何在Win10上使用Python进行蓝牙通信,包括搜索附近蓝牙设备、连接目标设备及数据读写。通过`pybluez`库实现蓝牙socket连接,并给出了详细的代码示例,帮助读者理解蓝牙通信流程。
摘要由CSDN通过智能技术生成

感谢:(1)win10安装python蓝牙依赖 Pybluez Win10系统安装教程(蓝牙通信模块pybluez,Python完美安装)_caigen001的博客-CSDN博客_pybluez

           (2)Python学习笔记之蓝牙模块通讯-Pybluez_悲丶落的博客-CSDN博客_pybluez

                    python实现蓝牙通信 - -零 - 博客园

一、蓝牙通信流程

和java版的通信流程一样(java版链接:Java:PC端作为客户端连接蓝牙设备并接收蓝牙发送的数据_乐事原味~的博客-CSDN博客_java 连接蓝牙

1、创建客户端蓝牙Sokcet
2、创建连接
3、读写数据
4、关闭

二、安装蓝牙依赖包 

参考另一篇文章:Python:安装蓝牙依赖_乐事原味~的博客-CSDN博客_python 安装bluetooth

如果安装报错,可参考“感谢”的文章。

三、代码

import datetime
import time

# win10 安装蓝牙依赖包 https://blog.csdn.net/weixin_38676276/article/details/113027104
import bluetooth


class BluetoothConnection:
    def __init__(self):
        # 是否找到到设备
        self.find = False
        # 附近蓝牙设备
        self.nearby_devices = None

    def find_nearby_devices(self):
        print("Detecting nearby Bluetooth devices...")
        # 可传参数 duration--持续时间 lookup-name=true 显示设备名
        # 大概查询10s左右
        # 循环查找次数
        loop_num = 3
        i = 0
        try:
            self.nearby_devices = bluetooth.discover_devices(lookup_names=True, duration=5)
            while self.nearby_devices.__len__() == 0 and i < loop_num:
                self.nearby_devices = bluetooth.discover_devices(lookup_names=True, duration=5)
                if self.nearby_devices.__len__() > 0:
                    break
                i = i + 1
                time.sleep(2)
                print("No Bluetooth device around here! trying again {}...".format(str(i)))
            if not self.nearby_devices:
                print("There's no Bluetooth device around here. Program stop!")
            else:
                print("{} nearby Bluetooth device(s) has(have) been found:".format(self.nearby_devices.__len__()), self.nearby_devices)  # 附近所有可连的蓝牙设备s
        except Exception as e:
            # print(traceback.format_exc())
            # 不知是不是Windows的原因,当附近没有蓝牙设备时,bluetooth.discover_devices会报错。
            print("There's no Bluetooth device around here. Program stop(2)!")

    def find_target_device(self, target_name, target_address):
        self.find_nearby_devices()
        if self.nearby_devices:
            for addr, name in self.nearby_devices:
                if target_name == name and target_address == addr:
                    print("Found target bluetooth device with address:{} name:{}".format(target_address, target_name))
                    self.find = True
                    break
            if not self.find:
                print("could not find target bluetooth device nearby. "
                      "Please turn on the Bluetooth of the target device.")

    def connect_target_device(self, target_name, target_address):
        self.find_target_device(target_name=target_name, target_address=target_address)
        if self.find:
            print("Ready to connect")
            sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
            try:
                sock.connect((target_address, 1))
                print("Connection successful. Now ready to get the data")
                data_dtr = ""
                while True:
                    data = sock.recv(1024)
                    data_dtr += data.decode()
                    if '\n' in data.decode():
                        # data_dtr[:-2] 截断"\t\n",只输出数据
                        print(datetime.datetime.now().strftime("%H:%M:%S")+"->"+data_dtr[:-2])
                        data_dtr = ""
            except Exception as e:
                print("connection fail\n", e)
                sock.close()


if __name__ == '__main__':
    target_name = "BT04-A"
    target_address = "B4:4B:0E:04:16:25"
    BluetoothConnection().connect_target_device(target_name=target_name, target_address=target_address)

四、GitHub地址

Python_bluetooth_testpython版蓝牙匹配、接收数据。. Contribute to Jcsim0/Python_bluetooth_test development by creating an account on GitHub.https://github.com/Jcsim0/Python_bluetooth_test

评论 26
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值