我是一个全新的IoT新手,我有一个我大学的代码练习。我不知道如何连接这个脚本才能连接到MQTT并无错误地运行。
如何连接MQTT?脚本如下:
import paho.mqtt.client as mqtt
import ssl
import os
import sys
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
from threading import Timer
from datetime import datetime
class IoTExample:
def __init__(self):
self._establish_mqtt_connection()
def start(self):
self.client.loop_forever()
def disconnect(self, args=None):
self.client.disconnect()
def _establish_mqtt_connection(self):
self.client = mqtt.Client
self.client.on_log = self._on_log
client.username_pw_set('iotlesson', 'YGK0tx5pbtkK2WkCBvJlJWCg')
self.client.connect('phoenix.medialab.ntua.gr', 8883)
client.subscribe('hscnl/hscnl02/state/ZWaveNode005_Switch/state')
self.client.publish('hscnl/hscnl02/sendcommand/ZWaveNode005_Switch', 'ON')
self.client.loop_forever()
def _on_connect(self, client, userdata, flags, rc):
self.client.on_connect = self._on_connect
def _on_message(self, client, userdata, msg):
self.client.on_message = self.on_message
print(msg.topic+' '+str(msg.payload))
def _on_log(self, client, userdata, level, buf):
self.client.on_log = self._on_log
print('log: ', buf)
try:
iot_example = IoTExample()
iot_example.start()
except KeyboardInterrupt:
print('Interrupted')
try:
iot_example.disconnect()
sys.exit(0)
except SystemExit:
os._exit(0)我得到了以下错误:
python /home/mina/paho.mqtt.python/iot_example.py
Traceback (most recent call last):
File "/home/mina/paho.mqtt.python/iot_example.py", line 41, in <module>
iot_example = IoTExample()
File "/home/mina/paho.mqtt.python/iot_example.py", line 13, in __init__
self._establish_mqtt_connection()
File "/home/mina/paho.mqtt.python/iot_example.py", line 24, in _establish_mqtt_connection
self.client.connect('phoenix.medialab.ntua.gr', 8883)
TypeError: unbound method connect() must be called with Client instance as first argument (got str instance instead)发布于 2020-10-10 21:41:07
def _establish_mqtt_connection(self):
self.client = mqtt.Client()您需要在创建Client实例时添加括号。
TypeError:必须使用客户端实例作为第一个参数调用未绑定的方法connect() (改为获取字符串实例)
它显示unbound这一事实表明您没有创建实例。相反,self.client只是Client类本身的另一个名称。
https://stackoverflow.com/questions/64294056
复制相似问题