mtqq+mysql,Python+MQTT+MySQL实现获取边缘设备上行数据

步骤

这个是我用来看EMQ服务器里面数据的工具,MQTTX,挺好用的哦

1-10.jpg

首先,我们需要这些库,下载起来也很简单,直接百度安装即可,安装好之后import进来

2-6.jpg

3-5.jpg

以主题“weight_pub”为例

首先是进行获取MQTT的数据,函数API使用实例如下:

4-4.jpg

##MQTT操作

def MQTTWeight():

# config._init()

client_weight = mqtt.Client()

client_weight.on_connect = on_connect_weight

client_weight.on_message = on_message_weight

client_weight.connect('**.**.***.***',****, 600) # 600为keepalive的时间间隔

client_weight.subscribe('weight_pub', qos=0)

client_weight.loop_forever() # 保持连接

这个函数表示正常连接到了EMQ服务器的weight_pub主题,并且会进行回显告诉用户成功连上服务器

5-5.jpg

def on_connect_weight(client, userdata, flags, rc):

print("Connected with weight result code: " + str(rc))

接下来在on_message_weight(client, userdata, msg) 函数中处理我们获得到的数据

6-4.jpg

def on_message_weight(client, userdata, msg):

var = str(msg.payload)

if(get_value('WriteEnable') == 1):

set_value('weight',(GetWeight(var)))

if(get_value('weight') > 10):

total_data['weight'] -= 2.75

# print ( 'wei :%.2f' % total_data['weight'] ,end=':')

至此数据获取完成,接下来进行数据库记录修改操作,我已经在数据库里面建好记录了,所以只要修改对应记录里面的数据即可,python通过id寻找相应的记录。

7-4.jpg

##数据库操作

def updateHandPart():

if(get_value('heartRate') > 0):

conn = get_conn()

cur = conn.cursor()

sql = 'UPDATE bodyhealthmonitor SET heartRate=%s WHERE id = %s';

args = (get_value('heartRate'), total_data['id'])

result = cur.execute(sql,args)

total_data['heartRate'] = 0

# print(result,end=';')

sql = 'UPDATE bodyhealthmonitor SET diastolicPressure=%s WHERE id = %s';

args = (get_value('diastolicPressure'), total_data['id'])

result = cur.execute(sql,args)

total_data['diastolicPressure'] = 0

# print(result,end=';')

sql = 'UPDATE bodyhealthmonitor SET systolicPressure=%s WHERE id = %s';

args = (get_value('systolicPressure'), total_data['id'])

total_data['systolicPressure'] = 0

result = cur.execute(sql,args)

# print(result)

conn.commit()

cur.close()

conn.close()

这个函数是为了连接上数据库的

8-4.jpg

def get_conn():

conn = pymysql.connect(host='*****', port=*****, user='*****', passwd='*****', db='*****')

return conn

最后在我们的main函数里面开线程获取数据之后处理数据

9-5.jpg

#*****代表用户自己的数据

total_data = {'WriteEnable':0, 'weight': 0.00, 'diastolicPressure': 0,

'heartRate': 0, 'systolicPressure':0,

'height':0.00, 'bloodOxygen':0.00, 'BMI':0.00,

'idealWeight':0.00, 'temperature':0.00,'id':1000}

def set_value(name, value):

total_data[name] = value

def get_value(name, defValue=None):

try:

return total_data[name]

except KeyError:

return defValue

#获取体重

def GetWeight(str):

var = ''

cnt = 0

for char in str:

cnt = cnt + 1

if char >= '0' and char <= '9' or char == '.':

var += char

return float(var)

def on_connect_weight(client, userdata, flags, rc):

print("Connected with weight result code: " + str(rc))

def on_message_weight(client, userdata, msg):

var = str(msg.payload)

if(get_value('WriteEnable') == 1):

set_value('weight',(GetWeight(var)))

if(get_value('weight') > 10):

total_data['weight'] -= 2.75

# print ( 'wei :%.2f' % total_data['weight'] ,end=':')

##MQTT操作

def MQTTWeight():

# config._init()

client_weight = mqtt.Client()

client_weight.on_connect = on_connect_weight

client_weight.on_message = on_message_weight

client_weight.connect('**.**.***.***',****, 600) # 600为keepalive的时间间隔

client_weight.subscribe('weight_pub', qos=0)

client_weight.loop_forever() # 保持连接

def get_conn():

conn = pymysql.connect(host='*****', port=*****, user='*****', passwd='*****', db='*****')

return conn

##数据库操作

def updateHandPart():

if(get_value('heartRate') > 0):

conn = get_conn()

cur = conn.cursor()

sql = 'UPDATE bodyhealthmonitor SET heartRate=%s WHERE id = %s';

args = (get_value('heartRate'), total_data['id'])

result = cur.execute(sql,args)

total_data['heartRate'] = 0

# print(result,end=';')

sql = 'UPDATE bodyhealthmonitor SET diastolicPressure=%s WHERE id = %s';

args = (get_value('diastolicPressure'), total_data['id'])

result = cur.execute(sql,args)

total_data['diastolicPressure'] = 0

# print(result,end=';')

sql = 'UPDATE bodyhealthmonitor SET systolicPressure=%s WHERE id = %s';

args = (get_value('systolicPressure'), total_data['id'])

total_data['systolicPressure'] = 0

result = cur.execute(sql,args)

# print(result)

conn.commit()

cur.close()

conn.close()

if __name__ == '__main__':

try:

thread_weight = threading.Thread(target=MQTTWeight)

thread_weight.setDaemon(True)

thread_weight.start()

thread_height = threading.Thread(target=MQTTHeight)

thread_height.setDaemon(True)

thread_height.start()

thread_blood = threading.Thread(target=MQTTBoold)

thread_blood.setDaemon(True)

thread_blood.start()

var = 1

while(var == 1):

time.sleep(1)#延时1s查看数据

if(get_value('WriteEnable') == 1):

update()

total_data['WriteEnable'] = 0

else:

updateHandPart()

except KeyboardInterrupt:

stop_thread(thread_weight)

stop_thread(thread_height)

stop_thread(thread_blood)

print('end')

(づ ̄3 ̄)づ╭❤~一键三连,这次一定(๑•̀ㅂ•́)و✧

5cb954aa2c45c3a7ccf9f8b975e9e686.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值