Using MQTT Server For IoT

Introduction

 
In this article, I will discuss the MQTT server and how to implement the Python MQTT server.
 

Key Terms

 

1. Publisher-Subscriber Architecture 

 
It is a messaging infrastructure in which publishers transmit messages without recognizing the subscribers themselves through a central broker. These messages may be written about a particular issue and can be heard by subscribers without recognizing the publisher itself, just the subject matter.
 
Publisher is the individual that sends data on a "topic" to a broker. The subscriber is the person that listens to data from a broker on a certain topic. Data are released for a given topic in a publisher/subscriber architecture, and subscribers may subscribe to this topic to access the data.
 

2. FFMPEG (Fast Forward MPEG)

 
Audio and video applications which can help transform or transmit. FFmpeg programme is used as a site server, which then can be consulted in the web browser using a node server.
 

3. Flask

 
It is a frame useful for web creation and another viable video streaming alternative to a web browser.
 

3. Node Server

 
It is a node.js webserver that can accommodate HTTP requests or serve a web page for web browser display.
 

4. MQTT 

 
MQTT or MQ Telemetry Transport. The MQ here came from a message queue from an old IBM product line called IBM MQ. While there are no queues on the MQTT itself, in the case of unencrypted communication, it uses usually 1883 and 8883 for encrypted communication.
 
Because of its lightweight nature, MQTT is a publisher-subscriber protocol frequently used for IoT computers. paho-mqtt is a common way to work in Python with MQTT. The MQTT protocol covers two topics: an agent and a client. An MQTT broker is a server while the clients are the computers connected. The device/client is designated the publisher and when the process is reversed the process is called the subscribe, whether it wishes to forward data to a server or broker.
 
If a client connection is interrupted, the broker buffers messages and pushes them out until they are back inline. If the connection from the publisher to the broker is terminated without warning, the broker is free to close the connection and send a cached message with an editor instruction to subscribers.
 
MQTT is split into four phases: connect, authenticate, correspondence, and terminate. A client begins to create a TCP / IP connection to the broker using either a regular port or a custom port specified by the operators of the broker. It is necessary to realize when establishing the link that a server can continue a peculiar session when a customer identity has been reused.
 
MQTT is regarded as a lightweight protocol because all the message has a limited footprint of code. A fixed header (2 bytes), optional variable header, a payload of message limiting to 256 MB of content, and a service quality level are all features in each message.
 
To install paho-mqtt,
  1. pip install paho-mqtt  
or with Vittual enviornment 
  1. virtualenv paho-mqtt  
  2. source paho-mqtt/bin/activate  
  3. pip install paho-mqtt  
Using GitHub repository
  1. git clone https://github.com/eclipse/paho.mqtt.python   
The library used for performing client specific operations is 'paho.mqtt.client'.
 

PAHO-MQTT 

 
There are more functions than I am discussing, you can find the details here
  1. client (client_id="", clean_session=True, userdata=None, protocol=MQTTv311, transport="tcp")
     
    It is the client library class constructor.
    • client_id is the special client id string used when connecting to the broker. Client is randomly generated if client_id is zero length or None.
    • clean_session: If the value is True, when this client is detached, the broker deletes all information about this client. If the value is False, then the client will hold subscription information and queued messages.
    • userdata: it is the data that is transferred to callbacks as a user-data parameter.
    • protocol: It is the version of the MQTT protocol to use for this client. The value can be MQTTv31 or MQTTv311
    • transport: It is set to "websockets" to send MQTT over WebSockets. 
    1. client=mqtt.client()  
  2. reinitialise (client_id="", clean_session=True, userdata=None)
     
    It resets the client to its initial state as it has been recently established.
    1. client.reinitialise()  
  3. connect (host, port=1883, keepalive=60, bind_address="")
     
    This function is used to connect the client to a broker. It is a blocking function.
    • bind_address is the IP of a local network interface to bind this client to, assuming multiple interfaces exist
    • host is the hostname or IP address of the remote broker
    • port is the server host network port to which to connect. The default is 1883, which can be used to connect without encryption. You can set 8883 if you connect with SSL / TLS
    • keepalive is the maximum period in seconds allowed between communication with the broker.
    1. client.connect("mqtt.eclipse.org")  
  4. connect_Async(host, port=1883, keepalive=60, bind_address="")
     
    In conjunction with loop_start(), the above function is used to connect non-blockingly. Before loop_start() is called, the connexion will not complete.
     
  5. reconnect()
     
    This functionality is used to reconnect to a broker with the previosly provided information.
    1. reconnect()  
  6. disconnect()
     
    This feature helps the broker to be cleanly disconnected. (We do not see a message received by the broker when we use disconnect).
     
  7. publish(topic, paylaod=None, qos=0, return=False)
     
    This approach requires a message to be submitted to the broker and then to any client who subscribes for related topics from the broker.
    • topic is the topic that the message should be published on
    • payload is the actual message to send. If not specified a zero-length message will be used.
    • qos is the quality of service level to use
    • if the value of retain is set to True then the message will be set as "last known good" or retained message for the topic
    It returns:
    • rc means to reset the publishing
    • mid means the message ID
    • wait_for_publish() is used to block until the message is published
    • is_published() is used to return if the message is published or not
       
  8. subscribe(topic, qos=0)
     
    Use this option to subscribe to one or more topics for the client.
    1. subscribe("my/topic",2)  # 1  
    2.   
    3. subscribe(("my/topic",2))  # 2  
    4.   
    5. subscribe([("my/topic",0), ("another/topic",2)])  # 3   
  9. unsubscribe()
     
    This feature helps you to unsubscribe from one or more topics.
  10.  
  11. Callback
     
    Following is a list of callback method provided by the Python MQTT API.
    • callback(connect)
    • callback(reconnect)
    • callback(disconnect)
    • callback(publish)
    • callback(subscribe)
    • callback(unsubscribe)
       
  12. Network Loop
     
    Following is a list of loop mechanisms provided by the Python MQTT API
    • LOOP()
    • LOOP_START() or LOOP_STOP()
    • LOOP_FOREVER()

Implementation Python MQTT API 

 
To import MQTT
  1. import paho.mqtt.client as client  
To set the server environment variables
  1. # to declate the hostname    
  2. HOSTNAME=socket.gethostname()    
  3.   
  4. # to declare the IP address    
  5. IPADDRESS=socket.gethostname(HOSTNAME)    
  6.   
  7. # to declare MQTT hostname    
  8. MQTT_HOST = IPADDRESS    
  9.   
  10. # to declare the HOST port for communication    
  11. MQTT_PORT=3001    
  12.   
  13. # to declare the duration for which connection need to be up    
  14. MQTT_KEEPALIVE_INTERVAL=60    
To establish a connection
  1. client=client()  
  2. client.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)  
To send class name and speed to MQTT server
  1. client.publish("class", json.dumps({"class_name":class_names}))  
  2. client.publish("speedometer",json.dumps({"speed":speed}))  
Some of you may be thinking how I have decided what to send. I have just taken demo values.
 
json.dumps() is used to submit JSON as the topic to publish.
 
To disconnect the MQTT server
  1. client.disconnect()  

Conclusion 

 
In the above article, we learned about the MQTT server and Intel OpenVINO to process the video.