如何存储MQTT Mosquitto将事件发布到MySQL中?

时间:2017-06-21 22:16:04

标签: mysql mqtt mosquitto

我已经连接了一个与我的mosquitto MQTT服务器(RPi)通信的设备,并将发布发送到指定的主题。我现在要做的是将MQTT服务器上发布的消息存储到MySQL数据库中。我知道MySQL是如何工作的,但我不知道如何收听这些传入的出版物。我正在寻找一种在后台运行的轻量级解决方案。关于库的任何指针或想法都非常受欢迎。

2 个答案:

答案 0 :(得分:1)

如果您熟悉Python,Paho MQTT library很简单,资源很少,并且与Mosquitto接口良好。要使用它,只需订阅主题并设置回调以使用peewee将有效负载传递给MySQL,如this answer.所示在后台运行脚本并将其调用好!

答案 1 :(得分:1)

最近几天我做了类似的事情:

  • 使用pywws实时收集气象站数据
  • 使用pywws.service.mqtt发布到mqtt-Broker
  • NAS上的
  • python-script 收集数据并写入MariaDB
#!/usr/bin/python -u

import mysql.connector as mariadb
import paho.mqtt.client as mqtt
import ssl

mariadb_connection = mariadb.connect(user='USER', password='PW', database='MYDB')
cursor = mariadb_connection.cursor()

# MQTT Settings 
MQTT_Broker = "192.XXX.XXX.XXX"
MQTT_Port = 8883
Keep_Alive_Interval = 60
MQTT_Topic = "/weather/pywws/#"

# Subscribe
def on_connect(client, userdata, flags, rc):
  mqttc.subscribe(MQTT_Topic, 0)

def on_message(mosq, obj, msg):
  # Prepare Data, separate columns and values
  msg_clear = msg.payload.translate(None, '{}""').split(", ")
  msg_dict =    {}
  for i in range(0, len(msg_clear)):
    msg_dict[msg_clear[i].split(": ")[0]] = msg_clear[i].split(": ")[1]

  # Prepare dynamic sql-statement
  placeholders = ', '.join(['%s'] * len(msg_dict))
  columns = ', '.join(msg_dict.keys())
  sql = "INSERT INTO pws ( %s ) VALUES ( %s )" % (columns, placeholders)

  # Save Data into DB Table
  try:
      cursor.execute(sql, msg_dict.values())
  except mariadb.Error as error:
      print("Error: {}".format(error))
  mariadb_connection.commit()

def on_subscribe(mosq, obj, mid, granted_qos):
  pass

mqttc = mqtt.Client()

# Assign event callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe

# Connect
mqttc.tls_set(ca_certs="ca.crt", tls_version=ssl.PROTOCOL_TLSv1_2)
mqttc.connect(MQTT_Broker, int(MQTT_Port), int(Keep_Alive_Interval))

# Continue the network loop & close db-connection
mqttc.loop_forever()
mariadb_connection.close()