mqtt paho python

subscribe data from broker emqx.io
 avatar
Eunbiline98
python
2 months ago
1.1 kB
9
Indexable
Never
import paho.mqtt.client as mqtt
import json

# Fungsi yang dipanggil saat koneksi ke broker berhasil dibuat
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("xxxx/xxxx/xxxx")  # topic mqtt

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))
    
    try:
        data = json.loads(msg.payload.decode())
        tegangan = data["tegangan"]
        arus = data["arus"]
        print("Tegangan:", tegangan)
        print("Arus:", arus)
    except json.JSONDecodeError as err:
        print("Error dalam menguraikan pesan JSON:", err)
        
# Config broker MQTT
broker_address = "broker.emqx.io"
broker_port = 8083
use_tls = False  # Jika menggunakan TLS, ubah menjadi True
client = mqtt.Client(transport="websockets") 

# Rules subscribe
client.on_connect = on_connect
client.on_message = on_message

# Koneksi ke broker MQTT
if use_tls:
    client.tls_set()
client.connect(broker_address, broker_port, 60)

# Looping message
client.loop_forever()
Leave a Comment