首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >智能插件IoT

智能插件IoT
EN

Stack Overflow用户
提问于 2020-10-10 21:38:14
回答 1查看 139关注 0票数 0

我是一个全新的IoT新手,我有一个我大学的代码练习。我不知道如何连接这个脚本才能连接到MQTT并无错误地运行。

如何连接MQTT?脚本如下:

代码语言:javascript
复制
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)

我得到了以下错误:

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2020-10-10 21:41:07

代码语言:javascript
复制
   def _establish_mqtt_connection(self):
        self.client = mqtt.Client()

您需要在创建Client实例时添加括号。

TypeError:必须使用客户端实例作为第一个参数调用未绑定的方法connect() (改为获取字符串实例)

它显示unbound这一事实表明您没有创建实例。相反,self.client只是Client类本身的另一个名称。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64294056

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档