import json
import paho.mqtt.client as mqtt
import pymysql
import time
HOST = "mqtt域名"
PORT = mqtt端口号
KEEPALIVE = 60
topic = 'MPU6050'
client_id = "pyMQsub-003"
rawdata = {}
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
#主题订阅
client.subscribe(topic)
# 订阅遗言主题 W/topic = 来自被监控的客户端的遗言主题名
client.subscribe("W/topic")
def on_message(client, userdata, msg):
global rawdata
rawdata = msg.payload.decode()
print(msg.topic,":", rawdata)
sqlsave()
def sqlsave():
data = json.loads(rawdata)
cursor = dbconn.cursor()
#SQL语句
query = "INSERT INTO 表名 (accel_x, accel_y, accel_z, gyro_x, gyro_y, gyro_z) \
VALUES ('%s','%s','%s','%s','%s','%s')"\
%(data['Ax'], data['Ay'], data['Az'], data['Gx'], data['Gy'], data['Gz'])
cursor.execute(query)
dbconn.commit()
client = mqtt.Client(client_id=client_id, clean_session=None)
print('连接mqtt服务器成功')
dbconn = pymysql.connect(host='数据库域名',
port=数据库端口, user='用户名',
password='数据登录密码',
database='数据库名',
charset='utf8')
print('数据库连接成功')
client.on_connect = on_connect
client.on_message = on_message
# client.username_pw_set(username,password) #如果MQTT broker不要求身份认证可以注释本语句 必须要在connect前调用
client.connect(HOST, PORT, KEEPALIVE) # 阻塞式, 循环往复,一直处理网络数据,断开重连
client.loop_forever()
mpu6050数据,mqtt订阅实时存mysql数据库
最新推荐文章于 2023-11-28 13:19:10 发布