鸭'先觉 2022-03-10 21:35 采纳率: 100%
浏览 330
已结题

python编写蓝牙传输程序的数据接收问题

你好,目前大四(机械专业),毕设做一款显示实时数据的软件(蓝牙传输,python编写)。
现在可以连接目标蓝牙(如图Connection successful. Now ready to get the data)
不知道现在是接下来该如何接收数据并显示,能不能点拨我一下👀,不胜感激。

我的代码(无报错):
import datetime
import time
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-E"
target_address = "98:DA:10:00:CB:0C"
BluetoothConnection().connect_target_device(target_name=target_name, target_address=target_address)

img

  • 写回答

1条回答 默认 最新

  • Flashang_sg 2022-03-11 11:30
    关注

    有没有参考别人做的 demo?
    小程序蓝牙与设备传输数据-demo
    https://blog.csdn.net/qq_35084280/article/details/107201480

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 3月20日
  • 已采纳回答 3月12日
  • 创建了问题 3月10日

悬赏问题

  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果