Skip to content

Python Example with MQTT, REST and InfluxDB

Overview

This guide covers how to access the REST-API, InfluxDB, and MQTT broker of the CMTK device using Python.

Prerequisites

  • CMTK device with Docker already setup and a working Portainer instance.

REST-API

Accessing the REST-API is possible using built-in methods of Python 3. However, it is entirely possible to use a REST library. All methods are available at 172.16.0.2:8080.

HTTP GET

This example code gathers some information about the CMTK device and prints it to the console. The general methedology will apply to all other GET operations.

import http.client

if __name__ == '__main__':

    # Parameters
    host = "172.16.0.2"
    path = "/api/yaasy/v1/device"

    try:
        # Send request
        h1 = http.client.HTTPConnection(host, port=8080, timeout=3)
        h1.request("GET", path)
        response = h1.getresponse()

        # Process response
        responseCode = response.status
        responseReason = response.reason
        responseContent = response.read()

        # Use response
        print("Response Code: " + str(responseCode))
        print("Response Reason: " + str(responseReason))
        print("Response Content: " + str(responseContent))

    except:
        print("Error accessing REST-API.")

HTTP POST

This sets an output pin of the CMTK using a POST request. The general methedology will apply to most other POST operations.

import http.client
import json

if __name__ == '__main__':

    # Parameters
    host = "172.16.0.2"
    path = "/iolink/v1/devices/master1port2/processdata/value"
    params=json.dumps({'iqValue': True})
    headers = {"content-type": "application/json"}

    try:
        # Send request
        h1 = http.client.HTTPConnection(host, port=8080, timeout=3)
        h1.request("POST", path, params, headers)
        response = h1.getresponse()

        # Process response
        responseCode = response.status
        responseContent = response.read()

        # Use response
        if responseCode != 200 and responseCode != 204:
            raise ValueError('Request not succesful. Error: ' + str(responseContent))
    except:
        println("Error accessing REST-API.")

MQTT

Accessing the REST-API is possible using the Paho library for Python 3. You can install it with the following command:

pip install paho-mqtt

The broker is available at 172.16.0.2:1883 without authentication. The following example is printing data of the sensor connected to port1 to the console.

import paho.mqtt.client as mqtt

if __name__ == '__main__':
    # Parameters
    host = "172.16.0.2"
    port = 1883

    # Message callback
    def on_message(client, userdata, msg):
        print("Topic: " + msg.topic + "\nPayload: " + str(msg.payload) + "\n")

    # Connection callback
    def on_connect(client, userdata, flags, rc):
      client.subscribe("balluff/cmtk/master1/iolink/devices/port1/data/fromdevice")

    try:
      # Connect
      client = mqtt.Client()
      client.on_connect = on_connect
      client.on_message = on_message
      client.connect(host, port, 3)

      # Loop
      client.loop_forever()

      # Disconnect
      client.disconnect()
    except:
        print("MQTT error.")

InfluxDB

Accessing InfluxDB is possible using the InfluxDB library for Python 3. You can install it with the following command:

pip install influxdb

The influxdb service is available at 172.16.0.2:8086 via ssl. If you want to verify the server certificate setup python certifi using cmtk's root CA.

from influxdb import InfluxDBClient
import traceback

if __name__ == '__main__':
    # Parameters
    host = "172.16.0.2"
    port = 8086
    query = 'SHOW QUERIES;'

    try:
        # Connect
        client = InfluxDBClient(host=host, port=port, username='cmtk',
                                password='balluff',
                                database='balluffCMTKDatabase', timeout=3,
                                ssl=True, verify_ssl=False)

        # Query
        result = client.query(query)

        # Output
        print(str(result))
    except Exception:
        print("InfluxDB error.")
        print(traceback.format_exc())

Building the container

You have to build the container by using a Dockerfile. If you named your application app.py, you may use the following example.

First create a file called requirements.txt. This contains all pip packages required for your container.

File: requirements.txt

paho-mqtt
influxdb

Next you need a Dockerfile to build your actual container.

File: Dockerfile

FROM python:3-slim

WORKDIR /usr/src/app

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY app.py ./

EXPOSE 80

CMD ["python", "/usr/src/app/app.py"]

Full example: src.zip

When developing on the device you can run the example with python3 app.py: Documentation. The alternative is to create a Dockerfile and upload the project to Portainer: Documentation.