modbus_MediaPipe/MQTT_to_PLC.py

51 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# pip install paho-mqtt
import json
import time
from paho.mqtt import client as mqtt
BROKER_HOST = "169.254.11.130"
BROKER_PORT = 1886
TOPIC = "topic_plc_and_py_for_AXIS"
# 建議測試用 QoS=1retain=False
QOS = 1
RETAIN = False
def main():
client = mqtt.Client(client_id="py_pub_plc_test", protocol=mqtt.MQTTv311)
# 若 Broker 有帳密、TLS 在這裡設定(目前不需要)
# client.username_pw_set("user", "pass")
# client.tls_set(ca_certs="ca.pem") # 若是 TLS
client.connect(BROKER_HOST, BROKER_PORT, keepalive=60)
client.loop_start()
time.sleep(0.3) # 等連線建立
# ---- 第一組: ----
payload_forward = {
"Move_Forward": False, # BOOL
"Move_Forward_Velocity": 6.2 # REAL (float)
}
msg1 = json.dumps(payload_forward, ensure_ascii=False)
r1 = client.publish(TOPIC, msg1, qos=QOS, retain=RETAIN)
r1.wait_for_publish()
time.sleep(3)#第二顆馬達等等再開啟
# ---- 第二組: ----
payload_updown = {
"Move_UPDown": False, # BOOL
"Move_UPDown_Velocity": 5.1 # REAL (float)
}
msg2 = json.dumps(payload_updown, ensure_ascii=False)
r2 = client.publish(TOPIC, msg2, qos=QOS, retain=RETAIN)
r2.wait_for_publish()
time.sleep(0.3)
client.loop_stop()
client.disconnect()
if __name__ == "__main__":
main()