39 lines
1.2 KiB
Python
39 lines
1.2 KiB
Python
import time
|
|
import json
|
|
from paho.mqtt import client as mqtt
|
|
|
|
def pub_to_plc(BROKER_HOST, BROKER_PORT, TOPIC, QOS, RETAIN):
|
|
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": True, # BOOL
|
|
"Move_Forward_Velocity": 1.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": True, # BOOL
|
|
"Move_UPDown_Velocity": 55.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()
|