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