2023年1月8日 星期日

Python MQTT + MQTT Broker + Node-Red

 






import paho.mqtt.client as mqtt

from datetime import datetime

# 當地端程式連線伺服器得到回應時,要做的動作

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

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


    # 將訂閱主題寫在on_connet中

    # 如果我們失去連線或重新連線時 

    # 地端程式將會重新訂閱

    #client.subscribe("alex9ufo/MQTT/Test")


    client.subscribe([("alex9ufo/Weather/Taichung/message1",1),("alex9ufo/Weather/Taichung/message2",1),("alex9ufo/Weather/Taichung/message3",0),("alex9ufo/Weather/Taichung/message4",0)])


# 當接收到從伺服器發送的訊息時要進行的動作

def on_message(client, userdata, msg):

    # 轉換編碼utf-8才看得懂中文

    now = datetime.now()

    current_time = now.strftime("%H:%M:%S")

    print("Current Time =", current_time)

    

    print(msg.topic+" "+ msg.payload.decode('utf-8'))

    print("\n")

# 連線設定

# 初始化地端程式

client = mqtt.Client()


# 設定連線的動作

client.on_connect = on_connect


# 設定接收訊息的動作

client.on_message = on_message


# 設定登入帳號密碼

client.username_pw_set("alex9ufo","alex9981")


# 設定連線資訊(IP, Port, 連線時間)

client.connect("broker.mqtt-dashboard.com", 1883, 60)


# 開始連線,執行設定的動作和處理重新連線問題

# 也可以手動使用其他loop函式來進行連接

client.loop_forever()


====================================================================

Connected with result code 0

Current Time = 20:38:48

alex9ufo/Weather/Taichung/message1 多雲山區局部短暫雨,稍有寒意至舒適,請適時做好保暖



Current Time = 20:38:48

alex9ufo/Weather/Taichung/message2 臺中地區今天(8日)晴時多雲;臺中公園及一中商圈氣溫16.3~25.8℃,梧棲氣溫15.6~19.5℃。



Current Time = 20:38:48

alex9ufo/Weather/Taichung/message3 臺中市明天(9日)受華南雲雨區東移影響,為多雲的天氣,山區有局部短暫雨,晚起平地亦有零星短暫雨;氣溫18-23℃,稍有寒意至舒適,請適時做好保暖。易有局部霧或低雲影響能見度,請注意。



Current Time = 20:38:48

alex9ufo/Weather/Taichung/message4 明天(9日)臺中沿海地區平均風力4至5陣風7級,船隻或沿岸活動,請注意安全。




[{"id":"1b9a2627e036e730","type":"inject","z":"ebc6fb2c201ca0ea","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"120","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":360,"y":160,"wires":[["cc2a6b321cec93a3"]]},{"id":"cc2a6b321cec93a3","type":"http request","z":"ebc6fb2c201ca0ea","name":"temp request","method":"GET","ret":"txt","paytoqs":"ignore","url":"https://opendata.cwb.gov.tw/fileapi/v1/opendataapi/F-C0032-021?Authorization=rdec-key-123-45678-011121314&format=JSON","tls":"","persist":false,"proxy":"","insecureHTTPParser":false,"authType":"","senderr":false,"headers":[],"x":510,"y":140,"wires":[["ad9f5263762da64f"]]},{"id":"ad9f5263762da64f","type":"json","z":"ebc6fb2c201ca0ea","name":"","property":"payload","action":"","pretty":false,"x":650,"y":140,"wires":[["f5683033a7df808a","6a2f558bbed319e9","afbbc26f6835ee22"]]},{"id":"6a2f558bbed319e9","type":"debug","z":"ebc6fb2c201ca0ea","name":"debug 44","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":820,"y":180,"wires":[]},{"id":"f5683033a7df808a","type":"debug","z":"ebc6fb2c201ca0ea","name":"debug 45","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload.cwbopendata.dataset.parameterSet.parameter[0]","targetType":"msg","statusVal":"","statusType":"auto","x":820,"y":120,"wires":[]},{"id":"afbbc26f6835ee22","type":"function","z":"ebc6fb2c201ca0ea","name":"set global temp","func":"\nflow.set(\"temp\",msg.payload);\nvar rawdata = flow.get(\"temp\");\n\nvar number=rawdata.cwbopendata.dataset.parameterSet.parameter.length;\nvar records_array=[];\nvar i;\nfor (i=0; i<number;i++)\n{\n    records_array[i]==rawdata.cwbopendata.dataset.parameterSet.parameter[i].parameterValue;\n}\n\nrecords_array[0]=rawdata.cwbopendata.dataset.parameterSet.parameter[0].parameterValue\nrecords_array[1]=rawdata.cwbopendata.dataset.parameterSet.parameter[1].parameterValue\nrecords_array[2]=rawdata.cwbopendata.dataset.parameterSet.parameter[2].parameterValue\nrecords_array[3]=rawdata.cwbopendata.dataset.parameterSet.parameter[3].parameterValue\nrecords_array[4]=number\n\nmsg.payload=records_array;\nflow.set(\"RECORDS\",records_array);\n\nreturn msg;\n\n//flow.set('YourVariable', value);    // to store a variable (YourVariable)\n//var x = flow.get('YourVariable'); //to retrieve a variable (YourVariable)","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":440,"y":280,"wires":[["018f88dfa3cc6e7f","966795f8090cf4d8","fa2558e8e749e204","b18e70921f1c197c","7410e63eb2a1143f","74797cb671ca79f0","2c14c9ec574464a1"]]},{"id":"018f88dfa3cc6e7f","type":"debug","z":"ebc6fb2c201ca0ea","name":"debug 46","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":660,"y":240,"wires":[]},{"id":"966795f8090cf4d8","type":"debug","z":"ebc6fb2c201ca0ea","name":"debug 47","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload[0]","targetType":"msg","statusVal":"","statusType":"auto","x":640,"y":540,"wires":[]},{"id":"40deed17204dc24e","type":"ui_button","z":"ebc6fb2c201ca0ea","name":"取得台中市天氣(等待約30秒以上 或 按壓 )","group":"f0166794.33066","order":2,"width":0,"height":0,"passthru":false,"label":"取得台中市天氣(等待約30秒以上 或 按壓 )","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"","payloadType":"str","topic":"topic","topicType":"msg","x":240,"y":100,"wires":[["cc2a6b321cec93a3"]]},{"id":"fa2558e8e749e204","type":"ui_text","z":"ebc6fb2c201ca0ea","group":"f0166794.33066","order":3,"width":0,"height":0,"name":"","label":"","format":"{{msg.payload[0]}}","layout":"row-left","className":"","x":650,"y":280,"wires":[]},{"id":"b18e70921f1c197c","type":"ui_text","z":"ebc6fb2c201ca0ea","group":"f0166794.33066","order":3,"width":0,"height":0,"name":"","label":"","format":"{{msg.payload[1]}}","layout":"row-left","className":"","x":650,"y":320,"wires":[]},{"id":"7410e63eb2a1143f","type":"ui_text","z":"ebc6fb2c201ca0ea","group":"f0166794.33066","order":3,"width":0,"height":0,"name":"","label":"","format":"{{msg.payload[2]}}","layout":"row-left","className":"","x":650,"y":360,"wires":[]},{"id":"74797cb671ca79f0","type":"ui_text","z":"ebc6fb2c201ca0ea","group":"f0166794.33066","order":3,"width":0,"height":0,"name":"","label":"","format":"{{msg.payload[3]}}","layout":"row-left","className":"","x":650,"y":400,"wires":[]},{"id":"7456af09ebe801b6","type":"mqtt out","z":"ebc6fb2c201ca0ea","name":"message1","topic":"alex9ufo/Weather/Taichung/message1","qos":"1","retain":"","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"841df58d.ee5e98","x":1070,"y":280,"wires":[]},{"id":"731820ce047b01f9","type":"mqtt out","z":"ebc6fb2c201ca0ea","name":"message2","topic":"alex9ufo/Weather/Taichung/message2","qos":"1","retain":"","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"841df58d.ee5e98","x":1070,"y":320,"wires":[]},{"id":"5fb73ae9c3e144bd","type":"mqtt out","z":"ebc6fb2c201ca0ea","name":"message3","topic":"alex9ufo/Weather/Taichung/message3","qos":"1","retain":"","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"841df58d.ee5e98","x":1070,"y":360,"wires":[]},{"id":"366971812d936c3f","type":"mqtt out","z":"ebc6fb2c201ca0ea","name":"message4","topic":"alex9ufo/Weather/Taichung/message4","qos":"1","retain":"","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"841df58d.ee5e98","x":1070,"y":400,"wires":[]},{"id":"2c14c9ec574464a1","type":"link out","z":"ebc6fb2c201ca0ea","name":"link out 4","mode":"link","links":["cb17779ed2d4d72b"],"x":615,"y":440,"wires":[]},{"id":"cb17779ed2d4d72b","type":"link in","z":"ebc6fb2c201ca0ea","name":"link in 6","links":["2c14c9ec574464a1"],"x":775,"y":340,"wires":[["6cbaf6c3a13a6cdc","41cc6541887fb6b0","cd042e01a64256e4","fde8b1d5c254221a"]]},{"id":"6cbaf6c3a13a6cdc","type":"function","z":"ebc6fb2c201ca0ea","name":"function 9","func":"msg.payload=msg.payload[0]\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":900,"y":280,"wires":[["7456af09ebe801b6"]]},{"id":"41cc6541887fb6b0","type":"function","z":"ebc6fb2c201ca0ea","name":"function 10","func":"msg.payload=msg.payload[1]\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":910,"y":320,"wires":[["731820ce047b01f9"]]},{"id":"cd042e01a64256e4","type":"function","z":"ebc6fb2c201ca0ea","name":"function 11","func":"msg.payload=msg.payload[2]\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":910,"y":360,"wires":[["5fb73ae9c3e144bd"]]},{"id":"fde8b1d5c254221a","type":"function","z":"ebc6fb2c201ca0ea","name":"function 12","func":"msg.payload=msg.payload[3]\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":910,"y":400,"wires":[["366971812d936c3f"]]},{"id":"f0166794.33066","type":"ui_group","name":"Weather_taichung","tab":"e01b6f.a9d07c9","order":2,"disp":true,"width":10,"collapse":true,"className":""},{"id":"841df58d.ee5e98","type":"mqtt-broker","name":"","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":false,"keepalive":"15","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"e01b6f.a9d07c9","type":"ui_tab","name":"Home","icon":"dashboard","disabled":false,"hidden":false}]

沒有留言:

張貼留言

Messaging API作為替代方案

  LINE超好用功能要沒了!LINE Notify明年3月底終止服務,有什麼替代方案? LINE Notify將於2025年3月31日結束服務,官方建議改用Messaging API作為替代方案。 //CHANNEL_ACCESS_TOKEN = 'Messaging ...