This page refers to version 1.12. You might want to use the current stable version instead.

Getting started with Eclipse Hono using Apache Kafka

This guide will walk you through an interactive example usage scenario of Eclipse Hono. You will learn how devices can use Hono’s protocol adapters to publish telemetry data and events using both HTTP and/or MQTT. You will also see how downstream applications can consume this data via an Apache Kafkaâ„¢ broker using Hono’s north bound API regardless of the communication protocols used by the devices.

Prerequisites for the Getting started Guide

This guide requires several tools to be installed on your computer. During the course of this guide, the devices publishing data will be represented by means of running some command line tools for posting HTTP requests and for publishing MQTT packets.

Curl HTTP Command Line Client

The curl command is used in this guide for registering devices with Hono and for simulating a device publishing data using HTTP. On most *nix like systems curl will probably already be installed. Otherwise, please refer to the Curl project page for installation instructions.

Mosquitto MQTT Command Line Client

The mosquitto_pub command is used in this guide for simulating a device publishing data using the MQTT protocol. Please refer to the Mosquitto project page for installation instructions, if you do not have it installed already.

NB The installation of the Mosquitto command line client is optional. If you do not install it then you will not be able to simulate an MQTT based device but otherwise will be able to get the same results described in this guide.

Hono Command Line Client

The Hono command line client is used in this guide for simulating an application that consumes telemetry data and events published by devices. The client is available from Hono’s download page. Note that running the command line client requires a Java 11 runtime environment being installed locally.

Hono Sandbox

The most important prerequisite is, of course, a Hono instance that you can work with.

The most straightforward option to use for this guide is the Hono Sandbox which is running on infrastructure provided by the Eclipse Foundation and which is publicly accessible from the internet.

Using the Sandbox, there is no need to set up your own Hono instance locally. However, it requires several non-standard ports being accessible from your computer which may not be the case, e.g. if you are behind a firewall restricting internet access to a few standard ports only.

You can verify if you can access the relevant ports of the Sandbox by running the following command and comparing the output:

curl -sIX GET http://hono.eclipseprojects.io:28080/v1/tenants/DEFAULT_TENANT

If you get output like this

HTTP/1.1 200 OK
etag: 89d40d26-5956-4cc6-b978-b15fda5d1823
content-type: application/json; charset=utf-8
content-length: 260

you can use the Sandbox. Run the following commands to set some environment variables which will be used during the guide

export REGISTRY_IP=hono.eclipseprojects.io
export HTTP_ADAPTER_IP=hono.eclipseprojects.io
export MQTT_ADAPTER_IP=hono.eclipseprojects.io

and then proceed to the Overview of Hono Components.

However, if the curl command yielded different output, you will need to set up Hono locally as described in the next section.

For interacting with the Device Registry of the Hono Sandbox (e.g. for creating tenants, devices), you can also use the testing functionality integrated in the Device Registry Management API documentation.

Setting up a local Hono Instance

In case you cannot access the Hono Sandbox as described above, you will need to set up an instance of Hono running on your local computer. For evaluation purposes a single node Minikube cluster is sufficient to deploy Hono to.

  1. Please refer to the installation instructions for setting up a local Minikube cluster, then
  2. follow the instructions in the README of Hono’s Helm chart in the Eclipse IoT Packages chart repository in order to install Hono with a small Kafka instance to your local Minikube cluster.

Once Hono has been deployed to your local cluster, run the following commands to set some environment variables which will be used during the guide

export REGISTRY_IP=$(kubectl get service eclipse-hono-service-device-registry-ext --output="jsonpath={.status.loadBalancer.ingress[0]['hostname','ip']}" -n hono)
export HTTP_ADAPTER_IP=$(kubectl get service eclipse-hono-adapter-http-vertx --output="jsonpath={.status.loadBalancer.ingress[0]['hostname','ip']}" -n hono)
export MQTT_ADAPTER_IP=$(kubectl get service eclipse-hono-adapter-mqtt-vertx --output="jsonpath={.status.loadBalancer.ingress[0]['hostname','ip']}" -n hono)

Verify the last step with

echo $REGISTRY_IP

If this does not print an IP address, check that minikube tunnel is running.

Secure Connections to Kafka

By default, the Kafka broker deployed with the Helm chart is configured to accept client connections only with Transport Layer Security (TLS) enabled. While the Hono components, like protocol adapters, are already deployed with a matching configuration of the Kafka clients they use, external connections, like Hono’s example application, need to be provided with configuration that enables TLS and a truststore file containing the broker certificate. The following guide assumes that for a local deployment in a Minikube cluster TLS is enabled on the Kafka broker.

NB The instructions below disable hostname verification (by setting the Kafka config property ssl.endpoint.identification.algorithm to an empty string) because the external IP in the Minikube cluster is dynamic and not included in the certificate. Don’t disable hostname verification in productive setups!

Overview of Hono Components

Hono consists of a set of microservices which are deployed as Docker containers. The diagram below provides an overview of the containers that are part of the example deployment of Hono on the Sandbox or a local Minikube cluster.

The Docker containers representing the services of the example Hono deployment with Kafka

Components of the example Hono deployment with Kafka

  • Hono Instance
    • An HTTP Adapter instance that exposes Hono’s Telemetry and Event APIs as URI resources.
    • An MQTT Adapter instance that exposes Hono’s Telemetry and Event APIs as a generic MQTT topic hierarchy.
    • An AMQP Adapter instance that exposes Hono’s Telemetry and Event APIs as a set of AMQP 1.0 addresses.
    • A Command Router instance that receives Command & Control messages and forwards them to protocol adapters.
    • A Device Registry instance that manages registration information and issues device registration assertions to protocol adapters.
    • An Auth Server instance that authenticates Hono components and issues tokens asserting identity and authorities.
  • Kafka Cluster
    • An Apache Kafka broker instance that downstream applications connect to in order to consume telemetry data and events from devices and to send Command & Control messages to devices.
    • An Apache Zookeeper instance that is required by the Kafka cluster.
  • Monitoring Infrastructure
    • A Prometheus instance for storing metrics data from services and protocol adapters.
    • A Grafana instance providing a dash board visualizing the collected metrics data.

In the example scenario used in the remainder of this guide, the devices will connect to the HTTP and MQTT adapters in order to publish telemetry data and events. The devices will be authenticated using information stored in the Device Registry. The data is then forwarded downstream to the example application via the Kafka cluster.

Registering Devices

When a device tries to connect to one of Hono’s protocol adapters, the protocol adapter first tries to authenticate the device using information kept in the Device Registry. The information maintained in the registry includes the tenant (a logical scope) that the device belongs to, the device’s unique identity within the tenant and the credentials used by the device for authentication.

Before a device can connect to Hono and publish any data, the corresponding information needs to be added to the Device Registry.

Creating a new Tenant

Register a tenant that is configured for Kafka based messaging using Hono’s Device Registry’s management HTTP API (a random tenant identifier will be generated):

curl -i -X POST -H "content-type: application/json" http://$REGISTRY_IP:28080/v1/tenants --data-binary '{
  "ext": {
    "messaging-type": "kafka"
  }
}'

HTTP/1.1 201 Created
etag: becc93d7-ab0f-48ec-ad26-debdf339cbf4
location: /v1/tenants/85f63e23-1b78-4156-8500-debcbd1a8d35
content-type: application/json; charset=utf-8
content-length: 45

{"id":"85f63e23-1b78-4156-8500-debcbd1a8d35"}
Random tenant ID value

You will receive a randomly generated tenantId value. It will probably be different than the value given in this example. Make sure to export it to an environment variable to make the following steps easier:

export MY_TENANT=85f63e23-1b78-4156-8500-debcbd1a8d35

Adding a Device to the Tenant

Register a device using Hono’s Device Registry’s management HTTP API (a random device identifier will be assigned):

curl -i -X POST http://$REGISTRY_IP:28080/v1/devices/$MY_TENANT

HTTP/1.1 201 Created
etag: 68eab243-3df9-457d-a0ab-b702e57c0c17
location: /v1/devices/85f63e23-1b78-4156-8500-debcbd1a8d35/4412abe2-f219-4099-ae14-b446604ae9c6
content-type: application/json; charset=utf-8
content-length: 45

{"id":"4412abe2-f219-4099-ae14-b446604ae9c6"}
Random device ID value

You will receive a randomly generated deviceId value. It will probably be different than the value given in this example. Make sure to export it to an environment variable to make the following steps easier:

export MY_DEVICE=4412abe2-f219-4099-ae14-b446604ae9c6

Setting a Password for the Device

Choose a (random) password and register it using Hono’s Device Registry’s management HTTP API (replace my-pwd with your password):

export MY_PWD=my-pwd
curl -i -X PUT -H "content-type: application/json" --data-binary '[{
  "type": "hashed-password",
  "auth-id": "'$MY_DEVICE'",
  "secrets": [{
      "pwd-plain": "'$MY_PWD'"
  }]
}]' http://$REGISTRY_IP:28080/v1/credentials/$MY_TENANT/$MY_DEVICE

HTTP/1.1 204 Updated
etag: cf91fd4d-7111-4e8a-af68-c703993a8be1
Content-Length: 0

Starting the example Application

The telemetry data produced by devices is usually consumed by downstream applications that use it to implement their corresponding business functionality. In this guide we will use the Hono command line client to simulate such an application. The client will connect to the Kafka cluster that provides Hono’s north bound Kafka based Telemetry and Event APIs, subscribe to all telemetry and event messages and log the messages to the console.

Open a new terminal window to run the client from the command line.

If you are using the Sandbox server (make sure to replace my-tenant with your tenant identifier):

# in directory where the hono-cli-*-exec.jar file has been downloaded to
export MY_TENANT=my-tenant
java -jar hono-cli-*-exec.jar --spring.profiles.active=receiver,kafka,sandbox --tenant.id=$MY_TENANT

Otherwise, if you are using a local Minikube cluster, first save the trust store file of the Kafka broker to your file system with the following command (adapt the value of environment variable KAFKA_TRUSTSTORE_PATH to the location that the trust store should be saved to):

export KAFKA_TRUSTSTORE_PATH=/tmp/truststore.pem
kubectl get secrets eclipse-hono-kafka-certs --template="{{index .data \"ca.crt\" | base64decode}}" -n hono > $KAFKA_TRUSTSTORE_PATH

Then set the following environment variables and start the client (make sure to replace my-tenant with your tenant identifier):

# in directory where the hono-cli-*-exec.jar file has been downloaded to
export MY_TENANT=my-tenant
export KAFKA_IP=$(kubectl get service eclipse-hono-kafka-0-external --output="jsonpath={.status.loadBalancer.ingress[0]['hostname','ip']}" -n hono)
export KAFKA_PORT=$(kubectl get service eclipse-hono-kafka-0-external --output="jsonpath={.spec.ports[?(@.name=='tcp-kafka')].port}" -n hono)
java -jar hono-cli-*-exec.jar --hono.kafka.commonClientConfig.bootstrap.servers=$KAFKA_IP:$KAFKA_PORT --hono.kafka.commonClientConfig.ssl.truststore.location=$KAFKA_TRUSTSTORE_PATH --hono.kafka.commonClientConfig.ssl.truststore.type=PEM --spring.profiles.active=receiver,kafka,local --tenant.id=$MY_TENANT

Note that the profiles sandbox respectively local enable default configurations for TLS and the authentication of an existing example Kafka user.

Publishing Telemetry Data to the HTTP Adapter

Now that the downstream application is running, devices can start publishing telemetry data and events using Hono’s protocol adapters. First, you will simulate a device publishing data to Hono using the HTTP protocol. Go back to the original terminal and run:

curl -i -u $MY_DEVICE@$MY_TENANT:$MY_PWD -H 'Content-Type: application/json' --data-binary '{"temp": 5}' http://$HTTP_ADAPTER_IP:8080/telemetry

HTTP/1.1 202 Accepted
Content-Length: 0

If you have started the downstream application as described above, you should now see the telemetry message being logged to the application’s console in the other terminal. The output should look something like this:

13:36:49.169 [vert.x-eventloop-thread-0] INFO  org.eclipse.hono.cli.app.Receiver - received telemetry message [device: my-device, content-type: application/json]: {"temp": 5}
13:36:49.170 [vert.x-eventloop-thread-0] INFO  org.eclipse.hono.cli.app.Receiver - ... with properties: {orig_adapter=hono-http, qos=0, device_id=my-device, importance=high, uber-trace-id=6fd25dfcc1904fa1:95b598b9325f7ea3:a2ab14cbc5032ec9:0, content-type=application/json, orig_address=/telemetry}

You can publish more data simply by re-running the curl command above with arbitrary payload.

The HTTP Adapter also supports publishing telemetry messages using at least once delivery semantics. For information on how that works and additional examples for interacting with Hono via HTTP, please refer to the HTTP Adapter’s User Guide.

Publishing Events to the HTTP Adapter

In a similar way you can upload events:

curl -i -u $MY_DEVICE@$MY_TENANT:$MY_PWD -H 'Content-Type: application/json' --data-binary '{"alarm": "fire"}' http://$HTTP_ADAPTER_IP:8080/event

HTTP/1.1 202 Accepted
Content-Length: 0

Again, you should see the event being logged to the console of the downstream application.

Publishing Telemetry Data to the MQTT Adapter

Devices can also publish data to Hono using the MQTT protocol. If you have installed the mosquitto_pub command line client, you can run the following command to publish arbitrary telemetry data to Hono’s MQTT adapter using QoS 0:

mosquitto_pub -h $MQTT_ADAPTER_IP -u $MY_DEVICE@$MY_TENANT -P $MY_PWD -t telemetry -m '{"temp": 5}'

Again, you should now see the telemetry message being logged to console of the downstream application.

The MQTT Adapter also supports publishing telemetry messages using QoS 1. For information on how that works and additional examples for interacting with Hono via MQTT, please refer to the MQTT Adapter’s User Guide.

Publishing Events to the MQTT Adapter

In a similar way you can upload events:

mosquitto_pub -h $MQTT_ADAPTER_IP -u $MY_DEVICE@$MY_TENANT -P $MY_PWD -t event -q 1 -m '{"alarm": "fire"}'

Again, you should now see the telemetry message being logged to console of the downstream application.

Congratulations

You have successfully connected a device to Hono and published sensor data for consumption by an application connected to Hono’s north bound API. The application consumed messages from the Kafka cluster regardless of the transport protocol used by the device to publish the data.

What to try next?

  • Continue with the next sections to learn how applications can send commands to devices by means of the Command & Control API for Kafka.
  • Take a look at some of the metrics collected by Hono’s components by opening the Hono dashboard. On the Sandbox server the dashboard is available at https://hono.eclipseprojects.io:3000. When running a local Minikube cluster, please refer to Opening the Dashboard for instructions.
  • Check out the User Guides to explore more options for devices to connect to Hono using different transport protocols.
  • Learn more about the managing tenants, devices and credentials using the Device Registry’s HTTP API.

Advanced: Sending Commands to a Device

The following example will guide you through an advanced feature of Hono. You will see how an application can send a command to a device and receive a response with the result of processing the command on the device. The communication direction here is exactly the other way round than with telemetry and events.

The following assumes that the steps in the Prerequisites for the Getting started Guide and Registering Devices sections above have been completed. To simulate the device, you can use the Mosquitto tools again while the Hono Command Line Client simulates the application as before.

Receiving a Command

With the mosquitto_sub command you simulate an MQTT device that receives a command. Create a subscription to the command topic in the terminal for the simulated device (don’t forget to set the environment variables MQTT_ADAPTER_IP, MY_TENANT and MY_DEVICE)

mosquitto_sub -v -h $MQTT_ADAPTER_IP -u $MY_DEVICE@$MY_TENANT -P $MY_PWD -t command///req/#

Now that the device is waiting to receive commands, the application can start sending them. Start the Command Line Client in the terminal for the application side. If you are using the Sandbox server (don’t forget to set the environment variables MY_TENANT and MY_DEVICE):

# in directory where the hono-cli-*-exec.jar file has been downloaded to
java -jar hono-cli-*-exec.jar --spring.profiles.active=command,kafka,sandbox --tenant.id=$MY_TENANT --device.id=$MY_DEVICE

Otherwise, if you are using a local Minikube cluster (don’t forget to set the environment variables KAFKA_IP, KAFKA_PORT, KAFKA_TRUSTSTORE_PATH, MY_TENANT and MY_DEVICE):

# in directory where the hono-cli-*-exec.jar file has been downloaded to
java -jar hono-cli-*-exec.jar --hono.kafka.commonClientConfig.bootstrap.servers=$KAFKA_IP:$KAFKA_PORT --hono.kafka.commonClientConfig.ssl.truststore.location=$KAFKA_TRUSTSTORE_PATH --spring.profiles.active=command,kafka,local --tenant.id=$MY_TENANT --device.id=$MY_DEVICE

Note that this time the profile command is activated instead of receiver, which enables a different mode of the Command Line Client.

The client will prompt you to enter the command’s name, the payload to send and the payload’s content type. The example below illustrates how a one-way command to set the volume with a JSON payload is sent to the device.

>>>>>>>>> Enter name of command for device [<DeviceId>] in tenant [<TenantId>] (prefix with 'ow:' to send one-way command):
ow:setVolume
>>>>>>>>> Enter command payload:
{"level": 50}
>>>>>>>>> Enter content type:
application/json

INFO  org.eclipse.hono.cli.app.Commander - Command sent to device

In the terminal for the simulated device you should see the received command as follows

command///req//setVolume {"level": 50}

Sending a Response to a Command

Now that you have sent a one-way command to the device, you may get to know request/response commands where the device sends a response to the application. A request/response command received from an application contains an identifier that is unique to each new command. The device must include this identifier in its response so that the application can correctly correlate the response with the request.

If you send a request/response command like this

>>>>>>>>> Enter name of command for device [<DeviceId>] in tenant [<TenantId>] (prefix with 'ow:' to send one-way command):
setBrightness
>>>>>>>>> Enter command payload:
{"brightness": 87}
>>>>>>>>> Enter content type:
application/json

INFO  org.eclipse.hono.cli.app.Commander - Command sent to device... [waiting for response for max. 60 seconds]

the application will wait up to 60 seconds for the device’s response.

In the terminal for the simulated device you should see the received command that looks like this

command///req/10117f669c12-09ef-416d-88c1-1787f894856d/setBrightness {"brightness": 87}

The element between req and setBrightness is the request identifier that must be included in the response.

You can cancel the command mosquitto_sub in the terminal of the device (press the key combination Ctrl + C) to reuse the configuration with the environment variables for sending the response. The following example shows how an answer can be sent with MQTT. Note that the actual identifier from the received command must be used.

export REQ_ID=10117f669c12-09ef-416d-88c1-1787f894856d
mosquitto_pub -h $MQTT_ADAPTER_IP -u $MY_DEVICE@$MY_TENANT -P $MY_PWD -t command///res/$REQ_ID/200 -m '{"success": true}'

The 200 at the end of the topic is an HTTP status code that reports the result of processing the command to the application.

If the Command Line Client has successfully received the response in time, it will print it to the console. This looks like this:

INFO  org.eclipse.hono.cli.app.Commander - Received Command response: {"success": true}

If the 60 seconds have already expired, an error message is logged. In this case you can send a new command or restart the Command Line Client with a higher timeout (append --command.timeoutInSeconds=120).

Congratulations. Now you have successfully sent commands to a device and responded to them. For more information on Command & Control refer to Commands using HTTP and Commands using MQTT. The Command and Control Concepts page contains sequence diagrams that explain this in more detail.