기타 (Other)

[python] MQTT 예제

Kim MyeongOk 2024. 9. 22. 19:31

 

■ python 패키지 설치

! pip install paho-mqtt

 

 

■ subscribe 예제

import paho.mqtt.client as mqtt


def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("connected OK")
    else:
        print("Bad connection Returned code=", rc)


def on_disconnect(client, userdata, flags, rc=0):
    print(str(rc))


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


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


# 새로운 클라이언트 생성
client = mqtt.Client()
# 콜백 함수 설정 on_connect(브로커에 접속), on_disconnect(브로커에 접속중료), on_subscribe(topic 구독),
# on_message(발행된 메세지가 들어왔을 때)
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_subscribe = on_subscribe
client.on_message = on_message
# 로컬 아닌, 원격 mqtt broker에 연결
# address : broker.hivemq.com
# port: 1883 에 연결
client.connect('broker.hivemq.com', 1883)
# test/hello 라는 topic 구독
client.subscribe('test/hello', 1)
client.loop_forever()

 

 

■ publisher 예제

import paho.mqtt.client as mqtt
import json


def on_connect(client, userdata, flags, rc):
    # 연결이 성공적으로 된다면 완료 메세지 출력
    if rc == 0:
        print("completely connected")
    else:
        print("Bad connection Returned code=", rc)

# 연결이 끊기면 출력
def on_disconnect(client, userdata, flags, rc=0):
    print(str(rc))


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


# 새로운 클라이언트 생성
client = mqtt.Client()
# 콜백 함수 설정 on_connect(브로커에 접속), on_disconnect(브로커에 접속중료), on_publish(메세지 발행)
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_publish = on_publish
# 로컬 아닌, 원격 mqtt broker에 연결
# address : broker.hivemq.com
# port: 1883 에 연결
client.connect('broker.hivemq.com', 1883)
client.loop_start()
# 'test/hello' 라는 topic 으로 메세지 발행
client.publish('test/hello', "Hello", 1)
client.loop_stop()
# 연결 종료
client.disconnect()

 

 

'기타 (Other)' 카테고리의 다른 글

아파치 카프카  (0) 2025.01.21
[python] pandas  (4) 2025.01.09
[python] decorator 예제  (0) 2024.12.07
[python] logging  (0) 2024.12.07
[python] Flask 기본 통신 예제  (0) 2024.11.09