MQTT#using Python Library as a Subscriber and Publisher

Here is a tutorial to explain how to implement the MQTT Client by using Python.

I will build the broker with raspberry-pi3.

Install Broker

Some Useful Link while using Raspberry

Raspberrypi#Using VNC Viewer
RaspberryPI#Set the static ip without starting the OS
RaspberryPI#Enable the SSH Interface without start the OS

Here is the tutorial to build a broker in the raspberry pi/ubuntu.

MQTT#Broker Setup

If the connection is refused:

MQTT#Connection is refuesd solution

Install Python Library

pip install paho-mqtt

https://www.eclipse.org/paho/index.php?page=clients/python/index.php

https://www.eclipse.org/paho/index.php?page=clients/python/docs/index.php

Main Functions used

connect()

connect(host, port=1883, keepalive=60, bind_address=””)

connect() function connects the client to a broker. Here are the arguments:

  • host
    • the hostname or IP address of the broker
  • port
    • the network port of the server host to connect to. Defaults to 1883.
  • keepalive
    • maximum period in seconds allowed between communications with the broker. 
  • bind_address
    • the IP address of a local network interface to bind this client to, assuming multiple interfaces exist
  • Callback
    • The callback function when the client receives a CONNACK message from the broker.

disconnect()

disconnect()

Disconnect from the broker cleanly. 

publish()

publish(topic, payload=None, qos=0, retain=False)

Sent a message to the broker with topics. 

It takes the following arguments:

  • topic
    • the topic that the message should be published on
  • payload
    • the actual message to send
  • qos
    • quality of service level to use
  • retain
    • True, the message will be set as the “last known good”/retained message for the topic.

Returns a MQTTMessageInfo with:

  • rc
    • the result of the publishing. 
      • MQTT_ERR_SUCCESS to indicate success,
      • MQTT_ERR_NO_CONN if the client is not currently connected
      • MQTT_ERR_QUEUE_SIZE when max_queued_messages_set is used
  • mid 
    • the message ID for the publish request. 
  • wait_for_publish() 
    • block until the message is published. 
  • is_published 
    • True if the message has been published. 

Callback (publish)

When the message has been sent to the broker an on_publish() callback will be generated.

subscribe()

subscribe(topic, qos=0)

Subscribe the client to one or more topics.

  • topic
    • a string specifying the subscription topic to subscribe to.
  • qos
    • quality of service level for the subscription. Defaults to 0.

Callback (subscribe)

When the broker has acknowledged the subscription, an on_subscribe() callback will be generated.

Callbacks

on_connect()

on_connect(client, userdata, flags, rc)

Called when the broker responds to our connection request.

  • client
    • the client instance for this callback
  • userdata
    • the private user data as set in Client() or user_data_set()
  • flags
    • response flags sent by the broker0
  • rc
    • the connection result

on_message()

on_message(client, userdata, message)

Called when a message has been received on a topic.

  • client
    • the client instance for this callback
  • userdata
    • the private user data as set in Client() or user_data_set()
  • message
    • an instance of MQTTMessage. This is a class with members topic, payload, qos, retain.

on_publish()

on_publish(client, userdata, mid)

Called when a message that was to be sent using the publish() call has completed 

on_subscribe()

on_subscribe(client, userdata, mid, granted_qos)

Called when the broker responds to a subscribe request. 


Implement a Subscriber

Here is a sample code to implement a Subscriber to subscribe to a Topic with ‘RoboDK/Station/#’.

import paho.mqtt.client as mqtt
import time

def on_connect(client,userdata,flag,rc):
    print(‘Connected with result code ‘+str(rc))
    client.subscribe(‘RoboDK/Station/#’)

def on_disconnect(client,userdata,rc):
    if rc !=0:
        print(‘Something Wrong..’)

def on_message(client,userdata,msg):
    print(str(msg.payload)+’,’+msg.topic+’,’+str(msg.qos))
   
   
BROCKER_URL=’192.168.1.50′
BROCKET_PORT=1883
   
client=mqtt.Client()
client.on_connect=on_connect
client.on_disconnect=on_disconnect
client.on_message=on_message

client.connect(BROCKER_URL,BROCKET_PORT,60)
count=0

while True:
    client.loop_forever()
client.disconnect()


Implement a Publisher

Here is a sample code to implement a Publisher to Publish to a Topic with ‘RoboDK/Station/st1/Example’.

import paho.mqtt.client as mqtt
import time

def on_connect(client,userdata,flag,rc):
    print(‘Connected with result code ‘+str(rc))
    client.subscribe(‘RoboDK/Station/s1/Lamp/Red’)

def on_disconnect(client,userdata,rc):
    if rc !=0:
        print(‘Something Wrong..’)

def on_publish(client,userdata,mid):
    print(‘publish: {0}’.format(mid))
   
BROCKER_URL=’192.168.1.50′
BROCKET_PORT=1883
   
client=mqtt.Client()
client.on_connect=on_connect
client.on_disconnect=on_disconnect
client.on_publish=on_publish

client.connect(BROCKER_URL,BROCKET_PORT,60)
count=0

while count<100:
    ret=client.publish(‘RoboDK/Station/st1/Example’,str(count))
    count=count+1
    time.sleep(0.1)
client.disconnect()

Result

Run the Publisher script and the message should be published to the broker.

Let’s use Teraterm to access the raspberry pi, and directly use this command to create a new subscriber.

mosquitto_sub -d -t RoboDK/Station/st1/#

The result is output from the Terminal.

If you run the subscriber script, you can see the message from another Publisher.

Footer_Basic

Please Support some devices for my blog

Amazon Gift List

Find ME

Twitter:@3threes2
Email:soup01threes*gmail.com (* to @)
YoutubeChannel:https://www.youtube.com/channel/UCQ3CHGAIXZAbeOC_9mjQiWQ

シェアする

  • このエントリーをはてなブックマークに追加

フォローする