簡體   English   中英

MQTT物聯網智能插件 Python

[英]MQTT IoT smart plug in Python

我是物聯網的新手,我有一個針對我大學的代碼練習。 我不知道如何連接此腳本才能連接到 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)
   def _establish_mqtt_connection(self):
        self.client = mqtt.Client()

您需要在創建Client實例時添加括號。

TypeError:未綁定方法 connect() 必須使用 Client 實例作為第一個參數調用(改為獲取 str 實例)

它說未綁定的事實表明您沒有創建實例。 相反, self.client只是Client class本身的另一個名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM