본문 바로가기
  • "하나씩 기록하다보면 누군가에게 도움이 되지 않을까"
IT/Python

[Python] MQTT 통신

by raVineL 2021. 2. 2.
728x90

- MQTT통신

 * QT에서 프로그램 세팅(IP, PORT, TOPIC 등) 후 시작 누르면 QThread사용해서 MQTT 통신 진행

**** QT 안쓰면 QThread 부분을 그냥 파이썬 기본 Thread로 변경하여 사용가능

 

* main.py

# ... 생략

self.Comm = QThread_MQTT.Comm(parent=self, flag=flag2)
self.Comm.Comm_ThreadEvent.connect(self.Log_Event) # 쓰레드 이벤트 헨들러 -> 데이터 전송
self.Comm.start()
self.Comm.isRunning = True

@pyqtSlot(str)
def Log_Event(self, n):
       now= datetime.datetime.now()
       texts = str(now) + " : " + n
       self.Log_Edit_2.append(texts)
       
       
# ... 생략

* QThread_MQTT.py

import main
from main import *
import socket
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5.QtCore import *
from PyQt5 import QtCore, QtGui, QtWidgets, uic
import numpy as np
import serial
import glob
import time
import threading
import binascii
import paho.mqtt.client as mqtt
import datetime
import numpy as np
from ConfVariables import *
import ConfVariables as cvs


client_pub = mqtt.Client()
client_sub = mqtt.Client()
t_pub = None
t_sub = None


class Comm(QThread):
    Comm_ThreadEvent = QtCore.pyqtSignal(str) # 데이터 전달 타입 str이고 
	# 클래스.Comm_ThreadEvent(변수명).emit(str(xxx)) 형식으로 데이터 전달 가능

    def __init__(self, parent=None, flag=1):
        super().__init__()
        self.main = parent
        self.isRunning = True
        self.flag = flag

    def stop(self):
        self.stopped = True
        self.MQTT_SUB.isRunning = False
        self.MQTT_PUB.isRunning = False
        self.isRunning = False
        self.MQTT_SUB.stop()
        self.MQTT_PUB.stop()
        self.MQTT_SUB = None
        self.MQTT_PUB = None

    def run(self):
        self.isRunning = True
        self.MQTT_SUB = t_subscribe(parent=self)
        self.MQTT_PUB = t_publish(parent=self)
        self.MQTT_SUB.start()
        self.MQTT_PUB.start()
        self.MQTT_SUB.isRunning = True
        self.MQTT_PUB.isRunning = True

class t_publish(QThread):

    def __init__(self, parent=None):
        super().__init__()
        self.main = parent
        self.isRunning = True

        client_pub.on_connect = on_connect
        client_pub.on_disconnect = on_pubdisconnect
        client_pub.on_publish = on_publish

    def stop(self):
        self.stopped = True
        self.isRunning = False
        #client_pub.loop_stop()
        client_pub.disconnect()

    def run(self):
        client_pub.connect(MQTT_IP, int(MQTT_PORT))
        client_pub.loop_start()

    def sendPub(self, topic, text):
        self.topic = topic
        self.text = text
        client_pub.publish(self.topic, self.text)

class t_subscribe(QThread):
    def __init__(self, parent=None):
        super().__init__()
        client_sub.on_connect = on_connect
        client_sub.on_disconnect = on_subdisconnect
        client_sub.on_subscribe = on_subscribe
        client_sub.on_message = on_message

    def run(self):
        self.isRunning = True
        client_sub.connect(MQTT_IP, int(MQTT_PORT))
        client_sub.subscribe(MQTT_TOPIC, 1)
        client_sub.loop_forever()

    def stop(self):
        self.isRunning = False
        #client_sub.loop_stop()
        client_sub.disconnect()


def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("connected OK")

    else:
        print("Bad Connection Returned code = ", rc)


def on_pubdisconnect(client, userdata, flags, rc=0):
    print(str(rc))
    if (rc != 0):
        print("UNEXPECTED MQTT PUB DISCONNECTION")
        t_pub.start()


def on_subdisconnect(client, userdata, flags, rc=0):
    print(str(rc))
    if (rc != 0):
        print("UNEXPECTED MQTT SUB DISCONNECTION")


def on_publish(client, userdata, mid):
    print("In on_pub callback mid= ", mid)


def on_subscribe(client, userdata, mid, granted_qos):
    print("subscribed: ", str(mid), " " + str(granted_qos))


def on_message(client, userdata, msg):
    receiveMsg = str(msg.payload.decode("utf-8"))
    print(receiveMsg)
728x90

댓글