python 连接蓝牙设备并接收数据
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 连接蓝牙设备并接收数据的更多相关文章
- 安卓Socket连接实现连接实现发送接收数据,openwrt wifi转串口连接单片机实现控制
安卓Socket连接实现连接实现发送接收数据,openwrt wifi转串口连接单片机实现控制 socket 连接采用流的方式进行发送接收数据,采用thread线程的方式. 什么是线程? 详细代码介 ...
- Unary模式下客户端从开始连接到发送接收数据的主要流程
(原创)C/C/1.25.0-dev grpc-c/8.0.0, 使用的例子是自带的例子GreeterClient grpc Unary模式下客户端从开始连接到发送数据的主要流程 graph TD; ...
- python连接mysql数据库读取数据
#-*- coding:utf-8 -*- #Author:'Lmc' #DATE: 2019/4/28/0028 上午 11:22:47 #FileName:test.PY import pymys ...
- Python连接MySQL数据库获取数据绘制柱状图
一.Python通过pymysql包获取MySQL数据库中的数据(没有对应包的可以通过pip install pymysql 安装对应的包) import matplotlib.pyplot as p ...
- python连接mysql并插入数据(自用)
#coding=utf-8 import MySQLdb db = MySQLdb.connect("IP","用户名","密码",&quo ...
- python3.4连接和读取oracle数据表
想用python连接Oracle并查询数据表,就写了个Demo.参考了以下网址. Python学习之 cx_Oracle学习记录 一 http://my.oschina.net/bxxfighting ...
- Python连接Mysql数据库_20160928
python版本 2.7.1,python 连接mysql需要安装MYSQLdb模块 安装方法一种是cmd pip命令安装 pip install MySQLdb 一种是网上下载python MYSQ ...
- 手把手教你Android手机与BLE终端通信--连接,发送和接收数据
假设你还没有看上一篇 手把手教你Android手机与BLE终端通信--搜索,你就先看看吧,由于这一篇要接着讲搜索到蓝牙后的连接.和连接后的发送和接收数据. 评论里有非常多人问假设一条信息特别长,怎么不 ...
- python网络编程调用recv函数完整接收数据的三种方法
最近在使用python进行网络编程开发一个通用的tcpclient测试小工具.在使用socket进行网络编程中,如何判定对端发送一条报文是否接收完成,是进行socket网络开发必须要考虑的一个问题.这 ...
- 【初学python】使用python连接mysql数据查询结果并显示
因为测试工作经常需要与后台数据库进行数据比较和统计,所以采用python编写连接数据库脚本方便测试,提高工作效率,脚本如下(python连接mysql需要引入第三方库MySQLdb,百度下载安装) # ...
随机推荐
- 像MIUI一样做Zabbix二次开发(2)——Zabbix与商业及开源产品的比较分析
Zabbix的特点 Zabbix是一个基于WEB界面的提供分布式系统监控的开源解决方案,通过浏览器监视,做到告警分级处理.网络访问安全可控,该开源平台在全球有广泛的用户基础,他的特点: 开放性:源代码 ...
- 记录坑:Chrome谷歌浏览器最小化和页面遮挡后JS代码不稳定
问题:用定时器 setInterval()做个滚动通知的动画,浏览器最小化时,定时器 setInterval()失效了,导致滚动条重叠了 可能原因: js代码不稳定 Chrome谷歌浏览器最小化和页面 ...
- 你对USB了解吗?--USB 协议分析之 HID 设备
1. 简述 USB HID类是USB设备的一个标准设备类,包括的设备非常多.HID类设备定义它属于人机交互操作的设备,用于控制计算机操作的一些方面,如USB鼠标.USB键盘.USB游戏操纵杆等.但HI ...
- STM32中HAL库和标准库的区别
转载自:https://www.lmonkey.com/t/RwykY8bBX STM32标准库与HAL库比较 ST为开发者提供了非常方便的开发库.到目前为止,有标准外设库(STD库).HAL库.LL ...
- Joseph Problem With Passwords In Java
问题描述: 编号为1,2,......,n的n个人(每个人的信息有编号.姓名和密码三项)按照顺时针方向围坐一圈, 每个人有且只有一个密码(正整数,密码用随机方式赋值,范围1-15).一开始任选一个正整 ...
- python下载.msg文件的附件
.msg文件,outlook邮件的一种保存方式 方式一:使用win32com库,不过要安装outlook才行 import win32com.client import os def get_atta ...
- uni-app使用阿里巴巴图标库icon详细步骤--避免踩坑
踩了很多坑~~ 最终终于找到可以使用阿里图标库的方法 简单方便 阿里巴巴图标库:https://www.iconfont.cn/home/index?spm=a313x.7781069.19989 ...
- 解决leetcode登录报错
1.安装leetcode 2.安装成功后会在拓展下面增在如下图标 点开界面如下 [] 3.点击小地球弹出如下弹窗,选择 启用中国版,可以多点击几次,防止没有选中 4.点击圈出的图标 选择第一个 5.输 ...
- NifytGUI——ListBox控件
ListBox控件的用法,创建一个xml,代码如下: <?xml version="1.0" encoding="UTF-8" standalone=&q ...
- setAttribute动态添加
btnDel.setAttribute('type', 'button'); //type="button" btnDel.setAttribute('value', '删除'); ...