Python - MQTT Konfigurasi Dasar

December 18, 2018

Library yang digunakan untuk MQTT pada python adalah paho-mqtt. Silahkan kunjungi situs resminya di untuk informasi lebih lanjut
pip install paho-mqtt

Setelah library berhasil diinstall, langkah selanjutnya adalah mencoba konfigurasi dasar paho-mqtt

  • Buat sebuah project folder baru
  • Buka menggunakan visual studio code atau code editor lainnya
  • Buat sebuah file python beri nama
  • copy dan paste program dibawah ini
import paho.mqtt.client as mqtt

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("/sensor") # topic you want to subscribe

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload)) # displaying the data on console

client = mqtt.Client()
client.username_pw_set("/train:trainsensor", password="12345") #vhost username & password
client.on_connect = on_connect
client.on_message = on_message

client.connect("", 1883, 60) # your mqtt host and port

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.

  • Jalankan programnya menggunakan perintah python
  • Publish data ke topic /sensor menggunakan MQTT-Box

1 comment:

Powered by Blogger.