你好
目前正在學習MQTT與PYTHON串接,我先在電腦上安裝Mosquitto 啟動後
進行發布與訂閱,並將資料寫入postgresql。
單一發布與訂閱、寫入是可動作的,但是...
我新增了另一個主題test1,同時訂閱test1/test2 是可以在terminal上收到資料,但是要怎麼把test1/test2 的資料分開,寫入不同table??
請各位給方向或解決方法
更新:以程式碼替換圖片
publish code:
import paho.mqtt.client as mqtt
import random
import json
import datetime
import time
ISOTIMEFORMAT = '%m/%d %H:%M:%S'
client = mqtt.Client()
client.username_pw_set("try","xxxx")
client.connect("127.0.0.1", 1883, 60)
while True:
t0 = random.randint(0,30)
t = datetime.datetime.now().strftime(ISOTIMEFORMAT)
payload = {'Temperature' : t0 , 'Time' : t}
print (json.dumps(payload))
#要發布的主題和內容
client.publish("test", json.dumps(payload))
#新建立的topic,test1
client.publish("test", json.dumps(payload))
time.sleep(5)
subscribe code
import paho.mqtt.client as mqtt
import psycopg2
import pandas as pd
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("test")
#新訂閱test1
client.subscribe("test1")
# 以上都可以在terminal 上接收topic test1/test2的資訊,但要寫入postgresql同一個database不同table的時候,就寫不進去,在terminal上會繼續跑接收到的資訊,但在資料庫是部會有資料寫入,寫請問這部分怎麼解??
# 當接收到從伺服器發送的訊息時要進行的動作
def on_message(client, userdata, msg):
# 轉換編碼utf-8才看得懂中文
print(msg.payload.decode('utf-8'))
original = eval(msg.payload.decode('utf-8'))
try:
connection = psycopg2.connect(user="postgres", # 預設使用者
password="", # 登入密碼
host="127.0.0.1",
port="5432",
database="database_test") # 要連結的資料庫
cursor = connection.cursor()
postgreSQL_insert_Query = '''INSERT INTO mqtttest(time,temperature) VALUES (%s,%s)'''
recods_to_insert = (original['Time'], original['Temperature'])
cursor.execute(postgreSQL_insert_Query, recods_to_insert)
connection.commit()
count = cursor.rowcount
print(count, "record inserted successfully")
except (Exception, psycopg2.Error) as error:
print("Error while connecting to PostgreSQL", error)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set("try","xxxx")
client.connect("127.0.0.1", 1883, 60)
client.loop_forever()