Cumulocity MQTT Execution With Python

Cumulocity supports both REST and MQTT to Publish and Receive data. MQTT is a Client Server publish/subscribe messaging transport protocol. It is light weight, open, simple, and designed to be easy to implement. 

This article provides the approach to use python scripts to create, send and receive data using MQTT to/from Cumulocity(Edge or Cloud). Python-MQTT approach is discussed for the following topics:

  1. MQTT Broker Connection
  2. Create Device
  3. Create Measurements
  4. Create Alarm
  5. Create Event
  6. Subscribing to Topic and Receiving Messages

Prerequisites

  1. Valid tenant, a user, and a password in order to access Cumulocity(Edge or Cloud)
  2. Install Python3 and Paho MQTT package

MQTT Broker Connection

The MQTT consists of two major elements: Broker and Clients. Clients consist of IoT devices and broker does the most important job with capabilities for both subscribing to topic and publishing messages. In this section, we will check the approach for MQTT broker connection using python. Once connected, we will be publishing different kinds of messages to Cumulocity in later sections.

Python Package: paho.mqtt.client will be used for MQTT operations. Import the package in python script as below

import paho.mqtt.client as mqttClient

To configure the connection, we need the following parameters:

  • brokerAddress = For Edge tenant, add the URL without http( example: 192.168.56.120) and for cloud version, prefix “mqtt.” Before the url(Example: mqtt.cumulocity-dev.com)
  • port = 1883
  • user =  for edge username should be like “edge/{tenantusername}” and for Cloud version, it should be like “{tenantName}/{tenantUserName}”
  • password = {tenantPassword}

With the above parameters, we can use the below sample python code to establish the MQTT broker connection

Create python file with the given parameters and python code. Execute the created python file and check for connection establishment in console as shown below

MQTT Static Template Codes

To ease the device integration, Cumulocity supports different MQTT static templates that can be used by any client without the need for creating own templates. These templates focus mostly on commonly used messages in device management.  

Some of the MQTT static template codes:

  • Create Device : 100  (Template: 100,Device Name,FragmentType)
  • Create Custom Measurement :200  (Template: 200,FragmentType,Unit,value)
  • Create Critical Alarm:301  (Template: 300, AlarmType)
  • Create Basic Event:400 (Template: 400, Event Type, text)

Create device

For Device Creation, Cumulocty Static Template Code: 100 is being used. To publish the templates in python, ‘publish’ method with Paho MQTT client object can be used

client.publish(topic, template ,qos)

Following data is required to call the publish templates:

  • Topic: s/us (for device creation, other Cumulocity codes are s/e and s/ds etc..)
  • Template: generate template with message code 100
  • Qos : 0 /1/2 (this is Optional parameter)
  • Client Id :  Any random string   (This will be used to identify the device while publishing data to device in later sections)

Sample Python Code to Publish templates:

Execute the python file by passing clinetId and templates as arguments as shown in the below picture

The newly created device can be visible in "Device Management” Page- “All Devices” tab as shown below picture

In identity tab of device details page, there is an identity created automatically to link the device to the MQTT ClientId.  This ClientId value is same as clientId given as one of the argument while running python script

Create measurements

Same approach of publishing messages discussed in above (Create Device) section, can be used here to publish measurement template with code: 200 (Other Measurement template codes: 200,201,211,212 etc)

Python file requires 2 arguments as below:

  • ClientId: Same Client Id used during device creation. This will be useful to identify the device
  • Template: Measurement template. Examples are below:
    • 200,c8y_TemperatureMeasurement,C,20 (Code, 200: Custom Measurement)
    • 210,- 87  (code 210: Signal strength measurement)
    • 211,56    (code 211: Temperature measurement)
    • 212,54    (code 212: Battery measurement) etc..

Execute the publish template python script as shown below

Created Measurements can be checked in Device details page as below:

Create Alarm:

To Create Alarm, following template codes can be used with Publish template python script

  • 301: CRITICAL
  • 302: MAJOR
  • 303: MINOR
  • 304: WARNING

Execute Publish template python script as below

Created alarms are visible in Device details page of Alarm section as shown in below screenshot

Create Events

Location Events can be created by publishing messages using location code: 401. The template '401' lets you create location events and takes latitude, langitude,altitude,accuacy and time as paramters.

Execute the publish message python script with same client Id as create device and Event Template:

In Device details page, events section, new event is added

Subscribing to Topic and Receiving Messages

So far we have used MQTT to send data from client to the server. In this section, we will check the receiving data from server to the client. To achieve this, first we need to subscribe to one or multiple responsible topics:

  • s/ds :  To subscribe to static operation templates for the device
  • s/e :  To subscribe to an error topic for debugging  purpose

To subscribe to a topic, we can use the ‘Subscribe’ method of the Paho MQTT Class object

client.subscribe(topic, qos)

Required parameters for subscription:

  • Topic: Cumulocity topic , s/ds or s/e
  • Qos: 0/1/2 (It’s an optional parameter)

To receive the messages of the subscribed topic, use the following python code:

Code to subscribe and bind the on message call back function to paho MQTT class object

Add the above changes to the Publish messages python script and execute the python file by passing the invalid template.  In the python script, client is subscribed to “s/e” , Error message is sent from Server to client when invalid template is received.

When Invalid message code 900 is sent to the server, error message “No Static template for this message Id” is received. Similarly we can subscribe to “s/ds” topic and receive the messages.

To print logs in the console for additional information, below python call back function can be used:

When python script is executed after enabling log, we get console output like below:

MQTT_PublishTemplates.py (1.22 KB)

This will be improved shortly with Generic MQTT and this: How to connect any MQTT device to Cumulocity IoT