python 连接蓝牙设备

原始内容

# %%
from binascii import hexlify
import struct
from bluepy.btle import Scanner, DefaultDelegate,UUID, Peripheral # %%
class ScanDelegate(DefaultDelegate):
def __init__(self):
DefaultDelegate.__init__(self) def handleDiscovery(self, dev, isNewDev, isNewData):
if isNewDev:
print("Discovered device", dev.addr)
print("device", dev.addr)
elif isNewData:
print("Received new data from", dev.addr) class NotifyDelegate(DefaultDelegate):
# Constructor (run once on startup).
def __init__(self, params):
DefaultDelegate.__init__(self) # func is caled on notifications
def handleNotification(self, cHandle, data):
print("Notification from Handle: 0x" + format(cHandle,'02X') )
print(hexlify(data)) # %%
scanner = Scanner().withDelegate(ScanDelegate())
devices = scanner.scan(10.0)
creyond_devices = []
for dev in devices:
print("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi))
for (adtype, desc, value) in dev.getScanData():
if value == "CreYond":
creyond_devices.append(dev)
print(" %s = %s" % (desc, value)) print(creyond_devices)
# %% get services
# the first device name CreYond
# c_device = creyond_devices[0] # c_device = "40:D6:3C:2F:F2:52" # 小蓝牙
c_device = "9O:A5:25:C8:93:D5" # 大蓝牙
p_device = Peripheral(c_device)
p_device.withDelegate(NotifyDelegate(p_device))
services = p_device.getServices() # displays all services
for service in services:
print(service)
# %% get specified service
#service_uuid = UUID("uuid service") # 小蓝牙
service_uuid = UUID("uuid service") # 大蓝牙
c_service = p_device.getServiceByUUID(service_uuid)
print(c_service) # %%
characteristics = c_service.getCharacteristics()
# displays all characteristics
for char in characteristics:
print(char)
# %%
notify_char = characteristics[0] print("我是notify_char :" + str(characteristics[0])) #%%
hEcg=notify_char.getHandle()
for descriptor in p_device.getDescriptors(hEcg,c_service.hndEnd):
if (descriptor.uuid==0x2902):
print(f'Client Characteristic Configuration found at handle 0x{format(descriptor.handle,"02X")}')
print(descriptor.handle)
hEcgCCC=descriptor.handle print("hEcgCCC:" + str(hEcgCCC))
p_device.writeCharacteristic(hEcgCCC,bytes([1, 0])) #%%
# tmp_data=p_device.readCharacteristic(0x11)
# # tmp_data=p_device.readCharacteristic(0x11)
# print(tmp_data)
# %%
while True:
if p_device.waitForNotifications(1.0):
# handleNotification() was called
continue print("Waiting... Waited more than one sec for notification") # %%
p_device.disconnect() # %%

优化成demo 做成web api的模式 (uuid是蓝牙的service 一个 service 下可以有多个 特征 可以订阅特征也可以向特征中写心跳)

# %%
from binascii import hexlify
import struct
import json
import datetime
from bluepy.btle import Scanner, DefaultDelegate,UUID, Peripheral
from flask import Flask, render_template, request, jsonify
import logging
from kafka import KafkaProducer
import time
from threading import Thread
import binascii
import threading logger = logging.getLogger('werkzeug') # grabs underlying WSGI logger
handler = logging.FileHandler('test.log') # creates handler for the log file
logger.addHandler(handler) #创建Flask对象app并初始化
app = Flask(__name__) # 设备全局
x_device = None #小蓝牙
d_device = None #大蓝牙
xt_device = None #大蓝牙 心跳
d_characteristics = None # 大蓝牙特征
notify_char_d = None # 大蓝牙通道
lock = threading.Lock() #ScanDelegate 类用来打印在线设备
class ScanDelegate(DefaultDelegate):
try:
def __init__(self):
DefaultDelegate.__init__(self)
def handleDiscovery(self, dev, isNewDev, isNewData):
if isNewDev:
logger.info("Discovered device", dev.addr)
print("Discovered device", dev.addr)
elif isNewData:
print("Received new data from", dev.addr)
logger.info("Received new data from", dev.addr)
except Exception as ex:
logger.info(str(ex)) class NotifyDelegate_x(DefaultDelegate):
def __init__(self, params):
DefaultDelegate.__init__(self) def handleNotification(self, cHandle, data):
print(hexlify(data))
producer = KafkaProducer(value_serializer=lambda v: json.dumps(v).encode('utf-8'),bootstrap_servers='xxxx:9092')
for x in range(0,2):
time.sleep(0.1) # 每隔0.1秒发送一行数据
databody = {
'messageType':'smallBluetooth',
'body': str(hexlify(data)),
'time': str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')),
}
producer.send('BluetoothMessageType', databody) class NotifyDelegate_d(DefaultDelegate):
def __init__(self, params):
DefaultDelegate.__init__(self) def handleNotification(self, cHandle, data):
print(hexlify(data))
producer = KafkaProducer(value_serializer=lambda v: json.dumps(v).encode('utf-8'),bootstrap_servers='xxxx:9092')
for x in range(0,2):
time.sleep(0.1) # 每隔0.1秒发送一行数据
databody = {
'messageType':'bigBluetooth',
'body': str(hexlify(data)),
'time': str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')),
}
producer.send('BluetoothMessageType', databody) # %% route
#默认界面
@app.route('/')
def index():
logger.info("hello python")
return {'code':200,'message':"hello python",'data':None} @app.route("/getdevicelist",methods=["GET"])
def getdevicelist():
try:
devicesListData = []
scanner = Scanner().withDelegate(ScanDelegate())
devices = scanner.scan(10.0)
for dev in devices:
result = {}
# logger.info("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi))
result["deviceAddr"] = dev.addr
result["deviceAddrType"] = dev.addrType
result["deviceRssi"] = dev.rssi
devicesListData.append(result)
return {'code':200,'message':"ok",'data':devicesListData}
except Exception as ex:
logger.info(str(ex))
return {'code':500,'message':"ok",'data':str(ex)} # 连接小蓝牙
@app.route("/connectionSmallBluetooth",methods=["GET"])
def connectionSmallBluetooth():
try:
adder = ""
if request.method == "GET":
adder = request.args.get("adder")
if len(adder) == 0:
adder = "u0:e6:3s:2F:H2:52"
print(adder)
obj = MyThreading(runSmallBluetooth, adder)
obj.start()
print("主线程结束")
return {'code':200,'message':"ok",'data':None}
except Exception as ex:
logger.info(str(ex)) # 连接大蓝牙
@app.route("/connectionBigBluetooth",methods=["GET"])
def connectionBigBluetooth():
try:
if request.method == "GET":
adder = request.args.get("adder")
if len(adder) == 0:
adder = "9C:l5:25:r8:93:75"
print(adder)
# obj = MyThreading_d(runBigBluetooth, adder)
obj = MyThreading(RunBigBlue.runBigBluetooth_xt, adder)
obj.start()
print("主线程结束") # 开启心跳 return {'code':200,'message':"ok",'data':None}
except Exception as ex:
logger.info(str(ex)) # 关闭 大/小 蓝牙
@app.route("/closeBluetooth",methods=["GET"])
def close():
try:
if request.method == "GET":
type = request.args.get("type")
if len(type) == 0:
return {'code':500,'message':"no",'data':None} if type == "1" :
xt_device.disconnect() if type == "2" :
d_device.disconnect() return {'code':200,'message':"ok",'data':None}
except Exception as ex:
logger.info(str(ex))
return {'code':500,'message':"ok",'data':str(ex)} class MyThreading(Thread): def __init__(self, func, arg):
super(MyThreading,self).__init__()
self.func = func
self.arg = arg def run(self):
self.func(self.arg) # run 小蓝牙
def runSmallBluetooth(args):
try:
print("收到前端传递的参数为:" + args)
logger.info("收到前端传递的参数为:" + args)
global x_device
x_device = Peripheral(args)
# 添加委托类
x_device.withDelegate(NotifyDelegate_x(x_device)) logger.info("准备开始连接小蓝牙:uuid")
service_uuid = UUID("uuid") # 小蓝牙
c_service = x_device.getServiceByUUID(service_uuid)
# 获取所有特征
characteristics = c_service.getCharacteristics() notify_char = characteristics[0]
logger.info("使用特征" , notify_char) hEcg=notify_char.getHandle()
for descriptor in x_device.getDescriptors(hEcg,c_service.hndEnd):
if (descriptor.uuid==0x2902):
print(f'Client Characteristic Configuration found at handle 0x{format(descriptor.handle,"02X")}')
logger.info(f'Client Characteristic Configuration found at handle 0x{format(descriptor.handle,"02X")}')
hEcgCCC=descriptor.handle
x_device.writeCharacteristic(hEcgCCC,bytes([1, 0])) tmp_data=x_device.readCharacteristic(0x11)
logger.info("tmp_data :", tmp_data) while True:
if x_device.waitForNotifications(1.0):
continue
print("Waiting... Waited more than one sec for notification")
except Exception as ex:
logger.info(str(ex))
print(str(ex)) # run 大蓝牙
def runBigBluetooth(args):
try:
logger.info("大蓝牙收到前端传递的参数为:" + args)
global d_device
d_device = Peripheral(args)
# 添加委托类
d_device.withDelegate(NotifyDelegate_d(d_device)) logger.info("准备开始连接大蓝牙:uuid")
service_uuid = UUID("uuid") # 大蓝牙
c_service = d_device.getServiceByUUID(service_uuid) # 获取所有特征
global d_characteristics
d_characteristics = c_service.getCharacteristics()
notify_char = d_characteristics[0]
# logger.info("使用特征" , str(notify_char)) hEcg=notify_char.getHandle()
for descriptor in d_device.getDescriptors(hEcg,c_service.hndEnd):
if (descriptor.uuid==0x2902):
print(f'Client Characteristic Configuration found at handle 0x{format(descriptor.handle,"02X")}')
logger.info(f'Client Characteristic Configuration found at handle 0x{format(descriptor.handle,"02X")}')
hEcgCCC=descriptor.handle
d_device.writeCharacteristic(hEcgCCC,bytes([1, 0])) # 发送心跳
logger.info("开始发送心跳")
print("开始发送心跳")
obj = MyThreading(BigBluetooth_xt, 1)
obj.start() while True:
time.sleep(1)
if d_device.waitForNotifications(1.0):
continue
print("Waiting... Waited more than one sec for notification") except Exception as ex:
logger.info(str(ex))
print(str(ex)) class RunBigBlue:
# 定义构造器
def __init__(self, account_no, balance):
# 封装账户编号、账户余额的两个成员变量
self.account_no = account_no
self._balance = balance
self.lock = threading.RLock() # 大蓝牙心跳
def runBigBluetooth_xt(args):
try:
logger.info("大蓝牙收到前端传递的参数为:" + args)
global xt_device
xt_device = Peripheral(args)
# 添加委托类
xt_device.withDelegate(NotifyDelegate_d(xt_device))
c_service = xt_device.getServiceByUUID(UUID("uuid")) characteristics = c_service.getCharacteristics()
print(str(characteristics[0]))
print(str(characteristics[1]))
global notify_char_d
notify_char_d = characteristics[1] obj = MyThreading(BigBluetooth_xt, 1)
obj.start() # 开始接收数据
xt_device.writeCharacteristic(15,bytes([1, 0])) while True:
with lock:
if xt_device.waitForNotifications(1.0):
continue
print("Waiting... Waited more than one sec for notification") except Exception as ex:
logger.info(str(ex))
print(str(ex)) def printHello():
print ("xt")
with lock:
# notify = d_characteristics[1]
data = binascii.unhexlify("F500AA")
notify_char_d.write(data, withResponse=True) def loop_func(func, second):
# 每隔second秒执行func函数
while True:
func()
time.sleep(second) def BigBluetooth_xt(args):
loop_func(printHello, 3) #定义app在6580端口运行
app.run(host="0.0.0.0", port="6580", debug=True)
# %%

继续更新 由于现实环境中 存在蓝牙掉线的情况  可以把服务做成自动拉起挂掉的蓝牙设备 上代码

from binascii import hexlify
from bluepy.btle import Scanner, DefaultDelegate,UUID, Peripheral
from kafka import KafkaProducer
import logging
from threading import Thread
import time
import datetime
import binascii
import json
import pymysql
import threading
# import numpy as np logger = logging.getLogger('werkzeug') # grabs underlying WSGI logger
handler = logging.FileHandler('test.log') # creates handler for the log file
logger.addHandler(handler) notify_char_d = None d_device_bool = False
x_device_bool = False # 小蓝牙
class MyThreading_x(Thread):
def __init__(self, func, arg):
super(MyThreading_x,self).__init__()
self.func = func
self.arg = arg
def run(self):
self.func(self.arg) class MyThreading_d(Thread):
def __init__(self, func, arg):
super(MyThreading_d,self).__init__()
self.func = func
self.arg = arg
def run(self):
self.func(self.arg) class MyThreading(Thread):
def __init__(self, func, arg):
super(MyThreading,self).__init__()
self.func = func
self.arg = arg
def run(self):
self.func(self.arg) #ScanDelegate 类用来打印在线设备
class ScanDelegate(DefaultDelegate):
try:
def __init__(self):
DefaultDelegate.__init__(self)
def handleDiscovery(self, dev, isNewDev, isNewData):
if isNewDev:
pass
# logger.info("Discovered device", dev.addr)
elif isNewData:
pass
# logger.info("Received new data from", dev.addr)
except Exception as ex:
logger.info(str(ex)) # # 小蓝牙发送消息
class NotifyDelegate_x(DefaultDelegate):
def __init__(self, params):
DefaultDelegate.__init__(self)
def handleNotification(self, cHandle, data):
print(bytes.decode(hexlify(data)))
time.sleep(0.001) # 每隔0.1秒发送一行数据
databody = {
'messageType':'smallBluetooth',
'body': bytes.decode(hexlify(data)),
'time': str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')),
}
producer.send('bluetoothMessage', databody) # 大蓝牙发送消息
class NotifyDelegate_d(DefaultDelegate):
def __init__(self, params):
DefaultDelegate.__init__(self) def handleNotification(self, cHandle, data):
with lock:
print(bytes.decode(hexlify(data)))
time.sleep(0.001) # 每隔0.1秒发送一行数据
databody = {
'messageType':'主题',
'body': bytes.decode(hexlify(data)),
'time': str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')),
}
producer.send('bluetoothMessage', databody) # 小蓝牙
def runSmallBluetooth(args):
# try:
print("进入小蓝牙:")
print(args)
print("进入小蓝牙")
x_device = Peripheral("40:D6:3C:2F:F2:52")
# 添加委托类
x_device.withDelegate(NotifyDelegate_x(x_device))
print("已连接")
print("准备开始连接小蓝牙:0000fff0-0000-1000-8000-00805f9b3488")
service_uuid = UUID("xxxxx") # 小蓝牙
c_service = x_device.getServiceByUUID(service_uuid)
# 获取所有特征
characteristics = c_service.getCharacteristics() notify_char = characteristics[0]
logger.info("使用特征" , notify_char) hEcg=notify_char.getHandle()
for descriptor in x_device.getDescriptors(hEcg,c_service.hndEnd):
if (descriptor.uuid==0x2902):
print(f'Client Characteristic Configuration found at handle 0x{format(descriptor.handle,"02X")}')
logger.info(f'Client Characteristic Configuration found at handle 0x{format(descriptor.handle,"02X")}')
hEcgCCC=descriptor.handle
x_device.writeCharacteristic(hEcgCCC,bytes([1, 0])) with lock:
tmp_data=x_device.readCharacteristic(0x11)
logger.info("tmp_data :", tmp_data) while True:
#with lock:
if x_device.waitForNotifications(1.0):
continue
print("Waiting... Waited more than one sec for notification") class RunBigBlue:
# 定义构造器
def __init__(self, account_no, balance):
# 封装账户编号、账户余额的两个成员变量
self.account_no = account_no
self._balance = balance
# self.lock = threading.RLock() # 大蓝牙心跳
def runBigBluetooth_xt(args):
# try:
print("进入大蓝牙" + args)
global xt_device
xt_device = Peripheral(args)
# 添加委托类
xt_device.withDelegate(NotifyDelegate_d(xt_device))
print("已连接")
c_service = xt_device.getServiceByUUID(UUID("xxxx--xxx-xxx-xxxx")) characteristics = c_service.getCharacteristics()
# print(str(characteristics[0]))
# print(str(characteristics[1]))
global notify_char_d
notify_char_d = characteristics[1] # 开始接收数据
with lock:
xt_device.writeCharacteristic(15,bytes([1, 0])) global d_device_bool
d_device_bool = True # 这里注释了好像无伤大雅 虽然会报错
while True:
with lock:
if xt_device.waitForNotifications(1.0):
continue
print("Waiting... Waited more than one sec for notification") def BigBluetooth_xt(args):
while True:
time.sleep(2)
global notify_char_d
print ("进入xt")
try:
if notify_char_d != None:
print("xt")
data = binascii.unhexlify("F500AA")
with lock:
notify_char_d.write(data, withResponse=True)
else:
print("xt特征为null")
except Exception as e:
print(e) # 主业务逻辑
#if __name__ == '__main__':
x1 , d1 ,xt = True,True,True
obj , obj01 ,obj02,connection,cur,notify_char_d= None, None ,None ,None ,None,None
connection = pymysql.connect(host = '',
user = '',
password = '',
db = '',port =)
cur = connection.cursor()
cur.execute('SELECT * FROM BlueEntity ')
data = cur.fetchall()
print("data")
print(data)
print(len(data))
if len(data) == 0:
cur.execute("INSERT INTO `BlueEntity` (`BlueName`, `BlueNO`, `IsOnline`, `Address`, `Alias`, `BluetoothType`) VALUES ('大型激光气体遥测仪', '000002', b'1', '9C:A5:25:C8:93:D5', '大激光气体遥测仪', 2);")
cur.execute("INSERT INTO `BlueEntity` (`BlueName`, `BlueNO`, `IsOnline`, `Address`, `Alias`, `BluetoothType`) VALUES ('小型激光气体探测仪', '000001', b'1', '40:D6:3C:2F:F2:52', '小型激光气体探测仪', 1);")
connection.commit()
else:
isadd01 = False
for i in range(0, len(data)):
if data[i][4] == "40:D6:3C:2F:F2:52":
isadd01 = True if isadd01 == False:
connection.begin()
cur.execute("INSERT INTO `BlueEntity` (`BlueName`, `BlueNO`, `IsOnline`, `Address`, `Alias`, `BluetoothType`) VALUES ('探测仪', '000001', b'1', '40:D6:3C:2F:F2:52', '探测仪', 1);")
connection.commit()
else:
print("40:D6:3C:2F:F2:52 存在")
isadd02 = False
for i in range(0, len(data)):
if data[i][4] == "9C:A5:25:C8:93:D5":
isadd02 = True if isadd02 == False:
connection.begin()
cur.execute("INSERT INTO `BlueEntity` (`BlueName`, `BlueNO`, `IsOnline`, `Address`, `Alias`, `BluetoothType`) VALUES ('遥测仪', '000002', b'1', '9C:A5:25:C8:93:D5', '遥测仪', 2);")
connection.commit()
else:
print("9C:A5:25:C8:93:D5 存在") print("数据已创建")
producer = KafkaProducer(value_serializer=lambda v: json.dumps(v).encode('utf-8'),bootstrap_servers='host')
print("kafka已连接")
cur.close()
connection.close()
# # 主方法
while True:
time.sleep(5)
print("每5s执行一次")
lock = threading.RLock() # 小蓝牙 第一次
if x1 == True:
print("小蓝牙第一次初始化数据")
obj = MyThreading_x(runSmallBluetooth, "40:D6:3C:2F:F2:52")
obj.start()
x1 = False if d1 == True:
print("大蓝牙第一次初始化数据")
obj01 = MyThreading_d(RunBigBlue.runBigBluetooth_xt, "9C:A5:25:C8:93:D5")
obj01.start()
d1 = False if xt == True:
print("心跳第一次初始化数据")
obj02 = MyThreading(BigBluetooth_xt, 1)
obj02.start()
xt = False # 小蓝牙 死一次后
if obj is not None and not obj.is_alive():
print("小蓝牙程序死了一次后进行再次扫描")
obj = MyThreading_x(runSmallBluetooth, "40:D6:3C:2F:F2:52")
obj.start() # 大蓝牙 死一次后
if obj01 is not None and not obj01.is_alive():
print("大蓝牙程序死了一次后进行再次扫描")
obj01 = MyThreading_d(RunBigBlue.runBigBluetooth_xt, "9C:A5:25:C8:93:D5")
obj01.start() # scanner = Scanner().withDelegate(ScanDelegate())
# devices = scanner.scan(10.0)

优化  缩短了时间和使用api方式调用

from binascii import hexlify
from bluepy.btle import Scanner, DefaultDelegate,UUID, Peripheral
from kafka import KafkaProducer
import logging
from threading import Thread
import time
import datetime
import binascii
import json
import pymysql
import threading
import requests
# import numpy as np logger = logging.getLogger('werkzeug') # grabs underlying WSGI logger
handler = logging.FileHandler('test.log') # creates handler for the log file
logger.addHandler(handler) notify_char_d = None d_device_bool = False
x_device_bool = False x1 , d1 ,xt = True,True,True
obj , obj01 ,obj02,connection,cur,notify_char_d= None, None ,None ,None ,None,None # 小蓝牙
class MyThreading_x(Thread):
def __init__(self, func, arg):
super(MyThreading_x,self).__init__()
self.func = func
self.arg = arg
def run(self):
self.func(self.arg) class MyThreading_d(Thread):
def __init__(self, func, arg):
super(MyThreading_d,self).__init__()
self.func = func
self.arg = arg
def run(self):
self.func(self.arg) class MyThreading(Thread):
def __init__(self, func, arg):
super(MyThreading,self).__init__()
self.func = func
self.arg = arg
def run(self):
self.func(self.arg) #ScanDelegate 类用来打印在线设备
class ScanDelegate(DefaultDelegate):
try:
def __init__(self):
DefaultDelegate.__init__(self)
def handleDiscovery(self, dev, isNewDev, isNewData):
if isNewDev:
pass
# logger.info("Discovered device", dev.addr)
elif isNewData:
pass
# logger.info("Received new data from", dev.addr)
except Exception as ex:
logger.info(str(ex)) # # 小蓝牙发送消息
class NotifyDelegate_x(DefaultDelegate):
def __init__(self, params):
DefaultDelegate.__init__(self)
def handleNotification(self, cHandle, data):
print(bytes.decode(hexlify(data)))
time.sleep(0.001) # 每隔0.1秒发送一行数据
databody = {
'messageType':'smallBluetooth',
'body': bytes.decode(hexlify(data)),
'time': str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')),
}
producer.send('bluetoothMessage', databody) # 大蓝牙发送消息
class NotifyDelegate_d(DefaultDelegate):
def __init__(self, params):
DefaultDelegate.__init__(self) def handleNotification(self, cHandle, data):
with lock:
print(bytes.decode(hexlify(data)))
time.sleep(0.001) # 每隔0.1秒发送一行数据
databody = {
'messageType':'bigBluetooth',
'body': bytes.decode(hexlify(data)),
'time': str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')),
}
producer.send('bluetoothMessage', databody) # 小蓝牙
def runSmallBluetooth(args):
# try:
print("进入小蓝牙:")
print(args)
print("进入小蓝牙")
x_device = Peripheral("40:D6:3C:2F:F2:52")
# 添加委托类
x_device.withDelegate(NotifyDelegate_x(x_device))
print("已连接")
print("准备开始连接小蓝牙:0000fff0-0000-1000-8000-00805f9b34cb")
service_uuid = UUID("0000fff0-0000-1000-8000-00805f9b34fb") # 小蓝牙
c_service = x_device.getServiceByUUID(service_uuid) # 修改数据库状态
SendGet('40:D6:3C:2F:F2:52',True) # 获取所有特征
characteristics = c_service.getCharacteristics() notify_char = characteristics[0]
logger.info("使用特征" , notify_char) hEcg=notify_char.getHandle()
for descriptor in x_device.getDescriptors(hEcg,c_service.hndEnd):
if (descriptor.uuid==0x2902):
print(f'Client Characteristic Configuration found at handle 0x{format(descriptor.handle,"02X")}')
logger.info(f'Client Characteristic Configuration found at handle 0x{format(descriptor.handle,"02X")}')
hEcgCCC=descriptor.handle
x_device.writeCharacteristic(hEcgCCC,bytes([1, 0])) with lock:
tmp_data=x_device.readCharacteristic(0x11)
logger.info("tmp_data :", tmp_data) while True:
#with lock:
if x_device.waitForNotifications(1.0):
continue
print("Waiting... Waited more than one sec for notification") class RunBigBlue:
# 定义构造器
def __init__(self, account_no, balance):
# 封装账户编号、账户余额的两个成员变量
self.account_no = account_no
self._balance = balance
# self.lock = threading.RLock() # 大蓝牙心跳
def runBigBluetooth_xt(args):
# try:
print("进入大蓝牙" + args)
global xt_device
xt_device = Peripheral(args)
# 添加委托类
xt_device.withDelegate(NotifyDelegate_d(xt_device))
print("已连接")
c_service = xt_device.getServiceByUUID(UUID("0003CDD0-0000-1000-8000-00805F9B01f1")) # 修改数据库状态
SendGet('9C:A5:25:C8:93:D5',True) characteristics = c_service.getCharacteristics()
# print(str(characteristics[0]))
# print(str(characteristics[1]))
global notify_char_d
notify_char_d = characteristics[1] # 开始接收数据
with lock:
xt_device.writeCharacteristic(15,bytes([1, 0])) global d_device_bool
d_device_bool = True # 这里注释了好像无伤大雅 虽然会报错
while True:
with lock:
if xt_device.waitForNotifications(1.0):
continue
print("Waiting... Waited more than one sec for notification") def BigBluetooth_xt(args):
while True:
time.sleep(2)
global notify_char_d
print ("进入xt")
try:
if notify_char_d != None:
print("xt")
data = binascii.unhexlify("F500AA")
with lock:
notify_char_d.write(data, withResponse=True)
else:
print("xt特征为null")
except Exception as e:
print(e) def SendGet(address,isonline):
# url,注意参数我们通过&和键值对的形式放在了 url 中
url = 'http://xxxxx/api/xxxx?addres='+address+'&isonline='+ str(isonline)
print(url)
r = requests.get(url)
print(r.json()) # 主业务逻辑
#if __name__ == '__main__': connection = pymysql.connect(host = 'xxxxx',
user = 'xxxxx',
password = 'xxxxxx',
db = 'xxxxx',port = xxxx)
cur = connection.cursor()
cur.execute('SELECT * FROM BlueEntity ')
data = cur.fetchall()
print("data")
print(data)
print(len(data))
if len(data) == 0:
cur.execute("INSERT INTO `BlueEntity` (`BlueName`, `BlueNO`, `IsOnline`, `Address`, `Alias`, `BluetoothType`) VALUES ('大型激光气体遥测仪', '000002', b'1', '9C:A5:25:C8:93:D5', '大激光气体遥测仪', 2);")
cur.execute("INSERT INTO `BlueEntity` (`BlueName`, `BlueNO`, `IsOnline`, `Address`, `Alias`, `BluetoothType`) VALUES ('小型激光气体探测仪', '000001', b'1', '40:D6:3C:2F:F2:52', '小型激光气体探测仪', 1);")
connection.commit()
else:
isadd01 = False
for i in range(0, len(data)):
if data[i][4] == "40:D6:3C:2F:F1:52":
isadd01 = True if isadd01 == False:
connection.begin()
cur.execute("INSERT INTO `BlueEntity` (`BlueName`, `BlueNO`, `IsOnline`, `Address`, `Alias`, `BluetoothType`) VALUES ('小型激光气体探测仪', '000001', b'1', '40:D6:3C:2F:F2:52', '小型激光气体探测仪', 1);")
connection.commit()
else:
print("40:D6:3C:1F:F2:52 存在")
isadd02 = False
for i in range(0, len(data)):
if data[i][4] == "9C:A5:25:C8:93:f5":
isadd02 = True if isadd02 == False:
connection.begin()
cur.execute("INSERT INTO `BlueEntity` (`BlueName`, `BlueNO`, `IsOnline`, `Address`, `Alias`, `BluetoothType`) VALUES ('大型激光气体遥测仪', '000002', b'1', '9C:A5:25:C8:93:D5', '激光气体遥测仪', 2);")
connection.commit()
else:
print("9C:A5:25:C8:93:s5 存在") print("数据已创建")
producer = KafkaProducer(value_serializer=lambda v: json.dumps(v).encode('utf-8'),bootstrap_servers='xxxxxxx:xxxx')
print("kafka已连接")
cur.close()
connection.close() # # 主方法
while True:
time.sleep(0.5)
print("每500ms执行一次")
lock = threading.RLock() # 小蓝牙 第一次
if x1 == True:
print("小蓝牙第一次初始化数据")
obj = MyThreading_x(runSmallBluetooth, "40:D6:3C:2F:F2:52")
obj.start()
x1 = False if d1 == True:
print("大蓝牙第一次初始化数据")
obj01 = MyThreading_d(RunBigBlue.runBigBluetooth_xt, "9C:A5:25:C8:93:D5")
obj01.start()
d1 = False if xt == True:
print("心跳第一次初始化数据")
obj02 = MyThreading(BigBluetooth_xt, 1)
obj02.start()
xt = False # 小蓝牙 死一次后
if obj is not None and not obj.is_alive():
SendGet('40:D6:3C:2F:F3:52',False)
print("小蓝牙程序死了一次后进行再次扫描")
obj = MyThreading_x(runSmallBluetooth, '40:D6:3C:2F:F2:52')
obj.start() # 大蓝牙 死一次后
if obj01 is not None and not obj01.is_alive():
SendGet('9C:A5:25:C8:94:D5',False)
print("大蓝牙程序死了一次后进行再次扫描")
obj01 = MyThreading_d(RunBigBlue.runBigBluetooth_xt, '9C:A5:25:C8:93:D5')
obj01.start()

再以容器的方式部署

FROM python:3.6.9

WORKDIR /code/

ADD ./ /code/

RUN pip install -r requirements.txt
RUN pip install pymysql
RUN pip install bluepy CMD ["python3", "./app/blue.py"]

再把容器run起来 前面几个命令是尝试 后面才是run起来的命令

docker run -d  --net=host  --restart=always --name pyblue--privileged=true IMAGE pyblue

docker run -d --restart=always --name pyblue pyblue --net=host   --restart=always --privileged=true

docker run -d --restart=always --name pyblue pyblue --restart=always --privileged=true

docker run -d --restart=always --net=host  -v /app/blue.py:/app/blue.py  --name pyblue pyblue

docker run -d --restart=always --net=host --name pyblue pyblue

docker run -itd --restart=always --net=host  --name pyblue pyblue

python 连接蓝牙设备并接收数据的更多相关文章

  1. 安卓Socket连接实现连接实现发送接收数据,openwrt wifi转串口连接单片机实现控制

    安卓Socket连接实现连接实现发送接收数据,openwrt wifi转串口连接单片机实现控制 socket 连接采用流的方式进行发送接收数据,采用thread线程的方式. 什么是线程?  详细代码介 ...

  2. Unary模式下客户端从开始连接到发送接收数据的主要流程

    (原创)C/C/1.25.0-dev grpc-c/8.0.0, 使用的例子是自带的例子GreeterClient grpc Unary模式下客户端从开始连接到发送数据的主要流程 graph TD; ...

  3. python连接mysql数据库读取数据

    #-*- coding:utf-8 -*- #Author:'Lmc' #DATE: 2019/4/28/0028 上午 11:22:47 #FileName:test.PY import pymys ...

  4. Python连接MySQL数据库获取数据绘制柱状图

    一.Python通过pymysql包获取MySQL数据库中的数据(没有对应包的可以通过pip install pymysql 安装对应的包) import matplotlib.pyplot as p ...

  5. python连接mysql并插入数据(自用)

    #coding=utf-8 import MySQLdb db = MySQLdb.connect("IP","用户名","密码",&quo ...

  6. python3.4连接和读取oracle数据表

    想用python连接Oracle并查询数据表,就写了个Demo.参考了以下网址. Python学习之 cx_Oracle学习记录 一 http://my.oschina.net/bxxfighting ...

  7. Python连接Mysql数据库_20160928

    python版本 2.7.1,python 连接mysql需要安装MYSQLdb模块 安装方法一种是cmd pip命令安装 pip install MySQLdb 一种是网上下载python MYSQ ...

  8. 手把手教你Android手机与BLE终端通信--连接,发送和接收数据

    假设你还没有看上一篇 手把手教你Android手机与BLE终端通信--搜索,你就先看看吧,由于这一篇要接着讲搜索到蓝牙后的连接.和连接后的发送和接收数据. 评论里有非常多人问假设一条信息特别长,怎么不 ...

  9. python网络编程调用recv函数完整接收数据的三种方法

    最近在使用python进行网络编程开发一个通用的tcpclient测试小工具.在使用socket进行网络编程中,如何判定对端发送一条报文是否接收完成,是进行socket网络开发必须要考虑的一个问题.这 ...

  10. 【初学python】使用python连接mysql数据查询结果并显示

    因为测试工作经常需要与后台数据库进行数据比较和统计,所以采用python编写连接数据库脚本方便测试,提高工作效率,脚本如下(python连接mysql需要引入第三方库MySQLdb,百度下载安装) # ...

随机推荐

  1. 使用layui时遇到的问题以及解决文章链接

    1.斜线表头效果 2.表格嵌套使用 3.layui数据表格跨行自动合并 4.layui表格数据变更的处理方式 5.layer弹窗动态添加KindEditor编辑器 6.layer弹出层自动调节位置 7 ...

  2. Linux下的zip和tar压缩解压缩命令详解

    一.zip压缩工具 zip的压缩包在windows和linux中都比较常用,它可以压缩目录和文件,压缩时录时,需要指定目录下的文件.zip后面先跟目标文件名,即压缩后得自定义压缩包名,然后跟要压缩的文 ...

  3. 攻防世界Web篇——PHP2

    可以从index.phps中找到网站源码 从源码中得出,要满足admin!=$_GET[id],urldecode($_GET[id]) == admin,两个条件才能得到flag 所以就将admin ...

  4. MFC中利用CFileDialog选择文件并读取文件所遇到的问题和解决方法

    在用MFC编写一个上位机时,需要实现选择和读取一个二进制文件,本来以为很简单的但是在实现过程中遇到很多问题,所幸都一一解决,这里做一下记录. 首先在实现文件选择,在界面上设置一个按钮,并在点击事件函数 ...

  5. shell_Day02

    虽然差了不少天,但的确是第......一天 history 查看历史命令记录 !命令序号 查看命令并执行 -c 清空 关于命令历史的文件 关于命令历史的变量(环境变量) 命令补全 tab:制表符 \t ...

  6. JS中Promise

    Promise的作用: Promise是异步微任务,解决了异步多层嵌套回调的问题,让代码的可读性更高,更容易维护. Promise如何使用: Promise是ES6提供的一个构造函数,可以使用Prom ...

  7. Office 2016 未授权

    用于管理 Office 批量激活的工具 https://docs.microsoft.com/zh-cn/DeployOffice/vlactivation/tools-to-manage-volum ...

  8. 20200926--矩阵转置(奥赛一本通P95 8 多维数组)

    输入一个n行m列的矩阵A,输出它的转置(看下面说明) 输入:第1行包含两个整数n和m(1<=n<=100,1<=m<=100),表示矩阵A的行数和列数.接下来n行,每行m个整数 ...

  9. UEC++学习(1)

    第三章 流程控制 第一节 C++和蓝图循环 ForLoop蓝图节点相当于C++中的for循环,ForeLoopWithBreak节点相当于for循环体中加了break语句,当触发某个条件时直接结束. ...

  10. PTA1004 成绩排名 (20 分)

    PTA1004 成绩排名 读入 n(>0)名学生的姓名.学号.成绩,分别输出成绩最高和成绩最低学生的姓名和学号. 输入格式: 每个测试输入包含 1 个测试用例,格式为 第 1 行:正整数 n 第 ...