GithubHelp home page GithubHelp logo

jcsim0 / python_bluetooth_test Goto Github PK

View Code? Open in Web Editor NEW
5.0 1.0 7.0 37 KB

python版蓝牙匹配、接收数据。

Home Page: https://blog.csdn.net/weixin_38676276/article/details/113058456

Python 100.00%

python_bluetooth_test's People

Contributors

jcsim0 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

python_bluetooth_test's Issues

连接失败 connection fail

runfile('E:/cloudComputer/bluetooth/blobgitBT.py', wdir='E:/cloudComputer/bluetooth')
Detecting nearby Bluetooth devices...
9 nearby Bluetooth device(s) has(have) been found: [('AC:76:4C:C9:66:04', ''), ('34:88:5D:A4:44:A8', 'Keyboard K380'), ('00:1B:66:BD:62:E3', 'LE-HD 450BT'), ('9C:97:89:37:A6:47', 'Mi Air 2s'), ('94:17:00:46:61:9C', 'Dear.Jim的Redmi K30 Ultra'), ('60:1D:9D:DE:EB:8C', '客厅的小米电视'), ('58:20:59:3C:F9:48', 'QCOM-BTD'), ('28:16:7F:82:41:C2', 'Redmi'), ('8C:DE:E6:F2:75:00', 'Galaxy Tab S7+')]
Found target bluetooth device with address:8C:DE:E6:F2:75:00 name:Galaxy Tab S7+
Ready to connect
connection fail

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
# sock
self.sock = 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")
        self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        try:
            self.sock.connect((target_address, 1))
            print("Connection successful. Now ready to get the data")
            data_dtr = ""
            # 以下代码根据需求更改
            while True:
                data = self.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)
            self.sock.close()

def close_target_device(self):
    print("Ready to close")
    self.sock.close()

if name == 'main':
target_name = "Galaxy Tab S7+"
target_address = "8C:DE:E6:F2:75:00"
# target_name = "BT04-A"
# target_address = "B4:4B:0E:04:16:25"
b = BluetoothConnection()
b.connect_target_device(target_name=target_name, target_address=target_address)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.