MQTTLens를 통해 게시를 테스트하면 작동합니다. 그러나 버튼을 누르면 "on_publish"가 트리거되지만 상대방의 on_message에서는 아무것도 수신되지 않습니다. 트리거되지 않습니다. 동일한 스크립트를 실행하는 두 개의 Raspberry Pi가 있으며 유일한 차이점은 브로커 IP이며 주제가 반대입니다.
import RPi.GPIO as io
import os
import json
from time import sleep
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
############### MQTT section ##################
Broker = "192.168.1.10"
rcv_topic = "home/groundfloor/livingroom/lights/lightx" # receive messages on this topic
snd_topic = "home/groundfloor/kitchen/lights/lightx" # send messages to this topic
def on_connect(mqttc, obj, flags, rc):
print("rc: "+str(rc))
mqttc.subscribe(rcv_topic) #receving/subscriber
#when receving a message:
def on_message(mqttc, obj, msg):
print("sub") #this is not being executed on button push, but it is when I publish through the MQTTLens
print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
try:
p = msg.payload.decode("utf-8")
print("decoded payload: " + p)
x = json.loads(p)
set_leds(leds, tuple(x['leds'])) #set leds to received value
return
except Exception as e:
print(e)
# callback functie voor publish event
def on_publish(mqttc, obj, mid):
print("pub")
return
mqttc = mqtt.Client()
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
mqttc.connect(Broker, 1883, 60) #last could be a port too
mqttc.loop_start() #client.loop_forever()
############### led&button section ##################
def init_leds(leds):
io.setup(leds, io.OUT)
def set_leds(leds, states):
print("leds and states: " + str(leds) + " " + str(states))
io.output(leds, states)
def snd_msg(led):
dataToSend=json.dumps({"leds":[led1State,led2State]})
print("data: " + dataToSend)
mqttc.publish(snd_topic, dataToSend)
io.add_event_detect(btn1,io.FALLING,callback=lambda *a: snd_msg(1),bouncetime=500)
############### main ##################
def main():
try:
while True:
init_leds(leds)
except KeyboardInterrupt:
pass
finally:
io.cleanup()
#toplevel script
#below will only execute if ran directly - above is always accessible
if __name__ == '__main__':
main()
내 문제와 직접 관련된 코드 부분 만 포함하고 일부를 더 짧게 변경했습니다. 그러나 더 많은 코드가 필요한 경우 언제든지 제공 할 수 있습니다.
나는 이것이이 질문 의 중복 일 수 있음을 알고 있지만 이미 답변에서 내 코드를 도출하려고 시도했으며 내가 잘못하지 않는 한 내 문제를 해결하지 못하는 것 같습니다.
두 개의 서로 다른 IP에 게시 및 구독중인 것 같습니다. 메시지를 받으려면 TOPIC_TEST (가정) 주제에 IP 192.168.1.10 (이는 브로커 IP라고 가정)에 게시하고 동일한 주제 TOPIC_TEST에 IP 192.168.1.10에 등록해야합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다