Python은 MQTT 구독 프로그램을 작성합니다.

다운로드 | 이클립스 모기

1. 다운로드:

https://mosquitto.org/files/binary/win64/mosquitto-2.0.17-install-windows-x64.exe

2. 설치:

3. conf 구성

1) 메모장을 사용하여 "C:\Program Files\mosquitto\mosquitto.conf"를 열고 c:\myapp\msquitto\mosquitto.conf.txt로 저장합니다.

listener 1883
protocol mqtt
listener 9005
protocol websockets
allow_anonymous true

log_type notice
log_type websockets
log_type warning
log_type error
log_type information

2) txt 파일의 이름을 conf로 바꿉니다.

C:\myApp\mosquitto>rename mosquitto.conf.txt mosquitto.conf

4. 서비스를 시작합니다.

"C:\Program Files\mosquitto\mosquitto.exe" -c C:\myApp\mosquitto\mosquitto.conf

MQTTX 다운로드

 5. mqtt x 클라이언트 다운로드

https://packages.emqx.net/MQTTX/v1.9.5/MQTTX-Setup-1.9.5-x64.exe

6. mqtt x 클라이언트를 설치합니다.

1) 새 연결 만들기

2) 신규 구독

3) 출판

4) 수락

Python 코드 부분:

아래 코드는 Python의 wxPython 라이브러리와 paho-mqtt 라이브러리를 사용하여 간단한 MQTT 구독자 애플리케이션을 생성하는 예입니다. 코드에 대한 자세한 설명은 다음과 같습니다.

C:\pythoncode\new\mqtt.py

1. wx 및 paho.mqtt.client 모듈을 가져옵니다.

import wx
import paho.mqtt.client as mqtt


GUI 인터페이스를 생성하기 위해 wx 모듈을 여기로 가져오고, paho.mqtt.client 모듈을 사용하여 MQTT 클라이언트 기능을 구현합니다.

2. MQTTSubscriber 클래스를 생성하고 이를 wx.Frame 클래스에서 상속합니다.

class MQTTSubscriber(wx.Frame):


이 클래스는 MQTT 구독자 애플리케이션의 기본 창을 나타냅니다.

3. 클래스 생성자 `__init__`을 정의합니다.

def __init__(self):
    wx.Frame.__init__(self, None, title="MQTT Subscriber", size=(400, 300))
    self.panel = wx.Panel(self)


생성자는 지정된 제목과 크기를 가진 wx.Frame 창을 생성하고 창에 다른 GUI 요소를 배치하기 위한 wx.Panel 패널을 생성합니다.

4. IP 주소, 포트 번호, 클라이언트 ID를 입력하기 위한 라벨과 텍스트 상자를 만듭니다.

wx.StaticText(self.panel, label="IP Address:", pos=(20, 20))
self.ip_text = wx.TextCtrl(self.panel, pos=(120, 20), size=(240, -1))


이 코드는 MQTT 브로커 서버의 IP 주소를 입력하기 위한 정적 텍스트 레이블과 텍스트 상자를 생성합니다.

마찬가지로 포트 번호와 클라이언트 ID에 대한 입력 레이블과 텍스트 상자는 `wx.StaticText` 및 `wx.TextCtrl`을 사용하여 생성됩니다.

5. 테마 선택을 위한 드롭다운 상자를 만듭니다.

wx.StaticText(self.panel, label="Topic:", pos=(20, 110))
self.topic_choice = wx.Choice(self.panel, pos=(120, 110), size=(240, -1))
self.topic_choice.Append("test/A")
self.topic_choice.Append("test/B")


이 코드는 구독할 MQTT 주제를 선택하기 위한 정적 텍스트 레이블과 드롭다운 상자(선택 사항)를 생성합니다. 드롭다운 상자에 "test/A" 및 "test/B"라는 두 가지 옵션이 추가되었습니다.

6. MQTT 메시지를 수신하기 위한 버튼을 생성합니다.

self.receive_button = wx.Button(self.panel, label="Receive", pos=(160, 140))
self.receive_button.Bind(wx.EVT_BUTTON, self.on_receive)


이 코드는 MQTT 메시지 수신 작업을 트리거하는 버튼을 생성합니다. 버튼의 라벨은 "Receive"이고 버튼의 클릭 이벤트는 `self.on_receive` 메소드에 바인딩됩니다.

7. 수신된 메시지를 표시하는 여러 줄의 텍스트 상자를 만듭니다.

wx.StaticText(self.panel, label="Received Messages:", pos=(20, 180))
self.message_text = wx.TextCtrl(self.panel, pos=(20, 200), size=(360, 80), style=wx.TE_READONLY|wx.TE_MULTILINE)


이 코드는 수신된 MQTT 메시지를 표시하기 위한 정적 텍스트 레이블과 여러 줄의 텍스트 상자(TextCtrl)를 생성합니다. 텍스트 상자는 읽기 전용이며 여러 줄의 텍스트를 표시할 수 있습니다. 8. 'on_receive' 메서드를 정의합니다.

def on_receive(self, event):
    ip = self.ip_text.GetValue()
    port = int(self.port_text.GetValue())
    client_id = self.client_id_text.GetValue()
    topic = self.topic_choice.GetString(self.topic_choice.GetSelection())

    # 创建MQTT客户端并连接到代理服务器
    client = mqtt.Client(client_id)
    client.on_connect = self.on_connect
    client.on_message = self.on_message
    client.connect(ip, port)

    # 订阅主题
    client.subscribe(topic)

    # 启动MQTT消息循环
    client.loop_start()


이 메소드는 버튼 클릭 이벤트에 대한 핸들러 함수입니다. 입력 상자와 드롭다운 상자에서 IP 주소, 포트 번호, 클라이언트 ID 및 주제 값을 가져온 다음 MQTT 클라이언트를 생성하고 지정된 MQTT 브로커 서버에 연결합니다. `client.subscribe(topic)` 메서드를 호출하여 지정된 주제를 구독하고 `client.loop_start()` 메서드를 통해 MQTT 메시지 루프를 시작합니다. 9. `on_connect` 메소드와 `on_message` 메소드를 정의하십시오.

def on_connect(self, client, userdata, flags, rc):
    print("Connected with result code " + str(rc))

def on_message(self, client, userdata, msg):
    message = msg.payload.decode("utf-8")
    self.message_text.AppendText(message + "\n")


이 두 가지 메소드는 각각 MQTT 클라이언트가 성공적으로 연결되어 메시지를 수신할 때의 콜백 함수입니다. 클라이언트가 MQTT 브로커 서버에 성공적으로 연결되면 'on_connect' 메소드가 호출되어 연결 결과 코드를 출력합니다. 'on_message' 메소드는 메시지가 수신되면 호출되며, 메시지 내용을 문자열로 디코딩하고 이를 여러 줄의 텍스트 상자에 추가하여 표시합니다.

10. 애플리케이션 인스턴스를 생성하고 `if __name__ == '__main__':` 조건에서 메인 루프를 실행합니다.

app = wx.App()
frame = MQTTSubscriber()
frame.Show()
app.MainLoop()

모든 코드

import wx
import paho.mqtt.client as mqtt

class MQTTSubscriber(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="MQTT Subscriber", size=(400, 300))
        self.panel = wx.Panel(self)

        # 创建标签和文本框用于输入IP地址、端口号和客户端ID
        wx.StaticText(self.panel, label="IP Address:", pos=(20, 20))
        self.ip_text = wx.TextCtrl(self.panel, pos=(120, 20), size=(240, -1))

        wx.StaticText(self.panel, label="Port:", pos=(20, 50))
        self.port_text = wx.TextCtrl(self.panel, pos=(120, 50), size=(240, -1))

        wx.StaticText(self.panel, label="Client ID:", pos=(20, 80))
        self.client_id_text = wx.TextCtrl(self.panel, pos=(120, 80), size=(240, -1))

        # 创建下拉框用于选择主题
        wx.StaticText(self.panel, label="Topic:", pos=(20, 110))
        self.topic_choice = wx.Choice(self.panel, pos=(120, 110), size=(240, -1))
        self.topic_choice.Append("test/A")
        self.topic_choice.Append("test/B")

        # 创建按钮用于接收MQTT消息
        self.receive_button = wx.Button(self.panel, label="Receive", pos=(160, 140))
        self.receive_button.Bind(wx.EVT_BUTTON, self.on_receive)

        # 创建多行文本框用于显示接收到的消息
        wx.StaticText(self.panel, label="Received Messages:", pos=(20, 180))
        self.message_text = wx.TextCtrl(self.panel, pos=(20, 200), size=(360, 80), style=wx.TE_READONLY|wx.TE_MULTILINE)

    def on_receive(self, event):
        ip = self.ip_text.GetValue()
        port = int(self.port_text.GetValue())
        client_id = self.client_id_text.GetValue()
        topic = self.topic_choice.GetString(self.topic_choice.GetSelection())

        # 创建MQTT客户端并连接到代理服务器
        client = mqtt.Client(client_id)
        client.on_connect = self.on_connect
        client.on_message = self.on_message
        client.connect(ip, port)

        # 订阅主题
        client.subscribe(topic)

        # 启动MQTT消息循环
        client.loop_start()

    def on_connect(self, client, userdata, flags, rc):
        print("Connected with result code " + str(rc))

    def on_message(self, client, userdata, msg):
        message = msg.payload.decode("utf-8")
        self.message_text.AppendText(message + "\n")

if __name__ == '__main__':
    app = wx.App()
    frame = MQTTSubscriber()
    frame.Show()
    app.MainLoop()


이 코드는 `wx.App` 인스턴스를 생성한 다음 `MQTTSubscriber` 클래스의 `프레임` 객체를 생성합니다. 마지막으로, 창이 닫힐 때까지 애플리케이션을 계속 실행하는 `app.MainLoop()`를 호출하여 메인 루프에 진입합니다.

이 코드를 실행하면 간단한 MQTT 구독자 애플리케이션 창이 표시됩니다. 창에 MQTT 프록시 서버의 IP 주소, 포트 번호 및 클라이언트 ID를 입력하고 구독할 주제를 선택한 후 "수신" 버튼을 클릭하여 MQTT 메시지 수신을 시작하고 수신된 메시지를 창에 표시할 수 있습니다.

Supongo que te gusta

Origin blog.csdn.net/winniezhang/article/details/132641869
Recomendado
Clasificación