关于MQTT内容发布错误
本帖最后由 榴莲山竹酥 于 2022-6-15 10:06 编辑请问下大佬 这个问题应该怎么解决
完整代码:
import paho.mqtt.client as mqtt
import time
class MqttServer:
def __init__(self,ip) -> None:
sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
sys.path.append("..")
_client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
self.ip = ip
self.client = mqtt.Client(_client_id, transport='tcp')
self.client.connect(self.ip, 1883, 60)
self.client.loop_start()
def send_message(self,topic:str,message: str):
"""
topic: 发送主题
message: 发送的消息体
"""
payload = {
"topic":eval(topic),
#"msg": eval("%s" % message),
"msg": "%s" % message,
"len":len(msg),
"send_time": "%s" % time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),
"from_ip":self.client._host,
"type":'msg',
"version":mqtt.CONNACK_REFUSED_PROTOCOL_VERSION}
self.client.publish(topic, json.dumps(payload, ensure_ascii=False))
print("------Successful send message!------")
return True
if __name__ == '__main__':
IP = 'xxx.xxx.xxx.xx'
#IP = input("输入MQTT服务器地址:")
try:
#mqttServer = MqttServer(IP)
mqttServer = IP
except ConnectionRefusedError:
print("MQTT中间件服务器未开启!")
sys.exit()
print(f"mqtt服务端初始成功\n服务器IP:{IP}\n时间:{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))}")
while 1:
try:
topic = input("发布主题:")
msg =input("发布内容:")
mqttServer.send_message(topic=topic,message= eval (msg))
print(f"topic:{topic} \n msg:{msg}")
print("------------------------------------")
except KeyboardInterrupt:
print("system exit success")
sys.exit() if __name__ == '__main__':
IP = 'xxx.xxx.xxx.xx'
#IP = input("输入MQTT服务器地址:")
try:
#mqttServer = MqttServer(IP)
mqttServer = IP#看这里!!!!!!!!!!!!!!
except ConnectionRefusedError:
print("MQTT中间件服务器未开启!")
sys.exit()
print(f"mqtt服务端初始成功\n服务器IP:{IP}\n时间:{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))}")
你看你的mqttServer是ip,是字符串 已自我解决 主函数缩进错误导致
页:
[1]