我是物联网的新手,我的大学有一个代码练习。我不知道如何连接此脚本,以便连接到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)
创建
Client
实例时需要添加括号它说unbound这一事实表明您没有创建实例。相反,
self.client
只是Client
类本身的另一个名称相关问题 更多 >
编程相关推荐