我正在尝试用Raspberry pi创建一些东西,如果执行一项操作,我会向CloudMQTT发送一条MQTT消息,以便谁在听此消息知道该怎么做。
一个例子是: 用户1按下按钮RBP知道了此信息,然后向MQMQTT发送MQTT消息,另一个RBP检测到用户1按下了按钮,因此用户2知道何时按下按钮。
我所做的是:
import paho.mqtt.client as mqtt
def on_connect(client, userData, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe("MyInstanceName/topic")
def on_message(client,userdata,msg):
print(msg.topic+ " "+ str(msg.payload))
if(msg.payload == "button"):
print("something")
if(msg.payload == "button2"):
print("something")
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set("user","password")
client.connect("m21.cloudmqtt.com",port,60)
client.loop_forever()
我创建了两个Users and ACL
,因为我只需要2个用户,所以我创建了一个主题为User1的用户,并且还可以为User2读/写
我不知道该怎么做,因为我有这个:
import paho.mqtt.publish as publish
publish.single("MyInstanceName/topic","button",hostname="m21.cloudmqtt.com")
publish.single("MyInstanceName/topic","button2",hostname="m21.cloudmqtt.com")
print("Done")
但是我遇到了这个错误:
Traceback (most recent call last):
File "mqtt_publisher.py", line 3, in <module>
publish.single("MyInstanceName/topic","button",hostname="m21.cloudmqtt.com")
File "/Library/Python/2.7/site-packages/paho/mqtt/publish.py", line 223, in single
protocol, transport)
File "/Library/Python/2.7/site-packages/paho/mqtt/publish.py", line 159, in multiple
client.connect(hostname, port, keepalive)
File "/Library/Python/2.7/site-packages/paho/mqtt/client.py", line 839, in connect
return self.reconnect()
File "/Library/Python/2.7/site-packages/paho/mqtt/client.py", line 962, in reconnect
sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 575, in create_connection
raise err
socket.error: [Errno 61] Connection refused
现在所有代码都是硬编码的,但是当我将按钮连接到RBP中时,如何检测到该按钮单击呢?我仍然可以使用Python吗?
答案 0 :(得分:0)
如果您查看publish.single
函数的doc,您会看到它可以使用名为auth
的参数,该参数包含用于连接代理的用户名/密码
身份验证
包含客户端身份验证参数的字典:
auth = {“用户名”:””,“密码”:“”}
用户名是必需的,密码是可选的,如果没有,则默认为无 没有提供。
默认为无,表示不使用身份验证。