MQTTX + Claude 3.7 Sonnet: Intelligent Code Generation for MQTT Testing
This example will demonstrate how to report the temperature and humidity data collected by the DHT11 sensor to the MQTT service in the cloud through the MQTT protocol and the NodeMCU based on ESP8266 , and show how the application subscribes to and processes the data. The reason why mqtt protocol is used in this article is that it is lightweight and energy-saving, which is very suitable for the use scenarios of the Internet of things. At present, all major public cloud providers have basically opened IOT hub services based on MQTT protocol. For example, the IOT Core of AWS and the IOT Hub of Azure can easily access these data to these public cloud services through MQTT protocol.
The overall architecture of this example is as follows:

NodeMCU board x 1: NodeMCU is an open source IoT platform. It includes firmware which runs on the ESP8266 Wi-Fi SoC, and hardware which is based on the ESP-12 module. The term "NodeMCU" by default refers to the firmware rather than the development kits . The firmware uses the Lua scripting language.
DHT11 temperature / humidity sensor x 1: DHT11 digital temperature and humidity sensor is a composite sensor with calibrated digital signal output
Breadboard x 1
Several jumper wires
Please refer to the following screenshot for Connection Graph

Download and install CH340G USB driver
Install ESP8266 module
Install PubSubClient library (by Nick O'Leary)
Sketch -> Include Library -> Manage Libraries... -> Type PubSub in Search field -> Install
After the data is successfully collected through NodeMCU, it needs to be sent to the MQTT cloud service in the cloud. This article uses the MQTT cloud service provided by EMQX. Readers can also choose other MQTT cloud services according to their own circumstances, such as Azure IoT Hub or AWS IoT Core. Each cloud service needs to provide different authentication methods when accessing. Therefore, when connecting to the MQTT service in the cloud via NodeMCU, it is required to set the connection method according to the security requirements of the target cloud service. For the sake of simplicity, this article uses a non-secure connection method. In a formal production environment, a connection with a secure authentication method must be set.
Click EMQX Cloud registration address to register
After registration, click EMQX Cloud to apply for a free trial of 15-day deployment

View the broker connection address

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
#define DHTPIN D4 // what pin we're connected to
#define wifi_ssid "xxxxx"
#define wifi_password "xxxxx"
#define mqtt_server "broker-internet-facing-f1429d8cb54ca4a7.elb.us-east-1.amazonaws.com" // MQTT Cloud address
#define humidity_topic "humidity"
#define temperature_topic "temperature"
#define DHTTYPE DHT11 // DHT 11
WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
dht.begin();
}
void setup_wifi() {
delay(10);
WiFi.begin(wifi_ssid, wifi_password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("nodeMcuDHT11")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
bool checkBound(float newValue, float prevValue, float maxDiff) {
return newValue < prevValue - maxDiff || newValue > prevValue + maxDiff;
}
long lastMsg = 0;
float temp = 0.0;
float hum = 0.0;
float diff = 1.0;
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 30000) {
// Wait a few seconds between measurements
lastMsg = now;
float newTemp = dht.readTemperature();
float newHum = dht.readHumidity();
if (checkBound(newTemp, temp, diff)) {
temp = newTemp;
Serial.print("New temperature:");
Serial.println(String(temp).c_str());
client.publish(temperature_topic, String(temp).c_str(), true);
}
if (checkBound(newHum, hum, diff)) {
hum = newHum;
Serial.print("New humidity:");
Serial.println(String(hum).c_str());
client.publish(humidity_topic, String(hum).c_str(), true);
}
}
}Follow these steps to edit the code to suit your own Wi-Fi and MQTT settings
Wi-Fi Setting
#define wifi_ssid ""
#define wifi_password ""Broker server setting
#define mqtt_server "broker-internet-facing-f1429d8cb54ca4a7.elb.us-east-1.amazonaws.com"Arduion configuration

Code upload
Connect the NodeMCU to the PC via USB and select the 115200 port in the Arduion IDE. Use the upload button to compile the sketch and upload it to the device.
Open Arduino monitor window to view data reporting.

MQTT client receives messages
Use MQTT Websocket Toolkit to test the reported message
MQTT Websocket Toolkit is a recently open sourced MQTT (WebSocket) test tool from EMQ, which supports online access (tools.emqx.io). We can easily verify whether the NodeMCU reports MQTT messages.
1.Create an MQTT connection

2.Subscribe to topics and receive test messages

Use Python MQTT client to view reported messages
from paho.mqtt import client as mqtt
def on_connect(client, userdata, flags, rc):
# connect mqtt broker
client.subscribe([("temperature", 0), ("humidity", 0)])
def on_message(client, userdata, msg):
# sub dht11 temperature/humidity data
print(f"{msg.topic}: {msg.payload.decode()}")
def run():
client = mqtt.Client()
# Edit MQTT Cloud address
client.connect("broker-internet-facing-f1429d8cb54ca4a7.elb.us-east-1.amazonaws.com", 1883)
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()
if __name__ == '__main__':
run()Screenshot of Python script running:

Troubleshooting: In order to perform troubleshooting, connecte the USB adapter to the PC and select the port of USB-TTL adapter in the Arduino IDE. Open the Serial Monitor to view the debug information generated by the serial output
So far, it has completed the simple process of collecting data from NodeMCU, uploading it to the MQTT cloud service provided by EMQ, and processing the data by the back-end program written by Python. However, in actual production applications, higher requirements will be required, for example,
More secure connection method
Real-time processing of IoT data
Persistence of data
Larger scale connection
EMQ Enterprise Edition and its Cloud service have provide good solution to solve the above problems. Readers can refer to related links for more information.
In order to achieve high data security (avoid uploading to the cloud), reduce business processing delays, and reduce data transmission costs, edge computing can be considered in the solution. Azure IoT Edge and AWS's Greengrass provide solutions at the edge. EMQ also provides an open sourced ultra-lightweight edge IoT edge streaming analytics solution Kuiper. Readers can refer to this Article for more detailed information.
This article takes a common IoT usage scenario as an example and describes how to use edge computing to achieve fast, low-cost and efficient processing of business.
In various IoT projects, such as intelligent building projects, it is necessary to collect and analyze building data (such as elevators, gas, water and electricity). One solution is to connect all devices directly to the IoT platform in the cloud, similar to Azure IoT Hub or AWS IoT Hub. The problem with this solution is:
Long data processing delay: it takes a long time to return data to the device after Internet transmission and cloud processing
Data transmission and storage cost: bandwidth is required for Internet transmission. For large-scale Iot projects, the bandwidth will be considerable
Data security: some data of the Iot will be very sensitive, and there will be risks if all data are transmitted through the Iot.
In order to solve the above problems, the industry has proposed a solution for edge computing. The core of edge computing lies in the proximity processing of data to avoid unnecessary delays, costs and security issues.
Suppose there is an existing set of devices. Each device in the group has an id that sends data to the corresponding topic on the MQTT message server via the MQTT protocol. The design of the topic is as follows, where {device_id} is the id of the device.
devices/{device_id}/messagesThe data format sent by each device is JSON, and the temperature and humidity data collected by the sensor are sent.
{"temperature": 30, "humidity" : 20 }
Now we need to analyze the data in real time, and ask for the following requirements: Calculate the average value (t_av) every 10 seconds for each device's temperature data, and record the maximum value within 10 seconds (t_max), minimum value (t_min) and number of data strips (t_count), and these four results are saved after the calculation is completed. The following is the sample result data:
[
{"device_id" : "1", "t_av" : 25, "t_max" : 45, "t_min" : 5, "t_count" : 2 }, { "device_id" : "2", "t_av" : 25, "t_max" : 45, "t_min" : 5, "t_count" : 2 }, ... ]
As shown in the figure below, the edge analysis / streaming data processing method is adopted. At the edge, we adopt the EMQ X approach, and finally output the calculation results to the IOT hub of AWS.

EMQ X Edge can access devices with various protocol types, such as MQTT, CoAP, LwM2M, etc.. Therefore, users do not need to care about protocol adaptation; it is also lightweight and suitable for deployment on edge devices.
EMQ X Kuiper is a SQL-based lightweight edge streaming data analysis engine released by EMQ. The installation package is only about 7MB, which is very suitable for running on the edge device side.
AWS IoT Hub provides a comprehensive approach of device access and data analysis, which is used for the result data access in the cloud and the result data analysis required by the application.
At the time of this writing this article, the latest version of EMQ X Edge is 4.0, and users can install and launch EMQ X Edge via Docker.
# docker pull emqx/emqx-edge
# docker run -d --name emqx -p 1883:1883 emqx/emqx-edge:latest
# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a348e3ac150c emqx/emqx-edge:latest "/usr/bin/docker-entr" 3 seconds ago Up 2 seconds 4369/tcp, 5369/tcp, 6369/tcp, 8080/tcp, 8083-8084/tcp, 8883/tcp, 11883/tcp, 0.0.0.0:1883->1883/tcp, 18083/tcp emqxThe user can use the telnet command to determine whether the startup is successful, as shown below.
# telnet localhost 1883
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.Install and start Kuiper
Click here to download the latest version of Kuiper and unzip it. At the time of this writing this article, the latest version of Kuiper is 0.0.3.
# unzip kuiper-linux-amd64-0.0.3.zip
# cd kuiper
# bin/server
Serving Kuiper server on port 20498If it does not start, check the log file log/stream.log
Kuiper provides a command to manage streams and rules. Users can check which subcommands and helps are available by typing bin/cli in the command line window. The cli command is connected to the local Kuiper server by default. The cli command can also be connected to other Kuiper servers. Users can modify the connected Kuiper server in the etc/client.yaml configuration file. Users who want to know more about the command line can refer to here.
Create a stream definition: The purpose of creating a stream is to define the format of the data sent to the stream, which is similar to defining the structure of a table in a relational database. All supported data types in Kuiper can be found in here.
# cd kuiperThe above statement creates a stream definition called demo in Kuiper, which contains two fields, temperature and humidity. The data source is the subscribed topicdevices/+/messages to MQTT. Please note that the wildcard + is used here to subscribe to messages from different devices. The MQTT server address corresponding to the data source is in the configuration file etc/mqtt_source.yaml, which can be configured according to the server address. Configure the servers project as shown below.
#Global MQTT configurationsdefault: qos: 1 sharedsubscription: true servers: [tcp://127.0.0.1:1883]
The user can type the describe subcommand on the command line to check the stream definition just created.
# bin/cli describe stream demotemperature float humidity bigint FORMAT: JSON DATASOURCE: devices/+/messages
Kuiper uses SQL to implement business logic. The average, maximum, minimum, and number of temperatures are counted every 10 seconds and grouped according to the device ID. The implemented SQL is shown below.
SELECT avg(temperature) AS t_av, max(temperature) AS t_max, min(temperature) AS t_min, COUNT(*) As t_count, split_value(mqtt(topic), "/", 1) AS device_id FROM demo GROUP BY device_id, TUMBLINGWINDOW(ss, 10)The SQL here uses four aggregate functions to count the correlation values over a 10-second window period.
avg: average
max: maximum
min: minimum
count: Count
Two basic functions are also used.
mqtt: The information of the MQTT protocol is taken out from the message, and mqtt (topic) is the name of the topic of the currently obtained message.
split_value: This function splits the first argument with the second argument, and then the third argument specifies the subscript to get the split value. So the function split_value("devices/001/messages", "/", 1)call returns 001
GROUP BY is followed by the grouped fields, which are the calculated field device_id; and the time window TUMBLINGWINDOW(ss, 10). The time window means that a batch of statistics data is generated every 10 seconds.
Before we write the rules, we need to debug the rules. Kuiper provides debugging tools for SQL, which makes it very convenient for users to debug SQL.
Go to the Kuiper installation directory and run bin/cli query
Enter the previously prepared SQL statement at the appeared command line prompt.
# bin/cli query
Connecting to 127.0.0.1:20498
kuiper > SELECT avg(temperature) AS t_av, max(temperature) AS t_max, min(temperature) AS t_min, COUNT(*) As t_count, split_value(mqtt(topic), "/", 1) AS device_id FROM demo GROUP BY device_id, TUMBLINGWINDOW(ss, 10)
query is submit successfully.
kuiper >In the log file ``log/stream.log``, we can see that a temporary rule named ``internal-kuiper_query_rule`` has been created.
...
time="2019-11-12T11:56:10+08:00" level=info msg="The connection to server tcp://10.211.55.6:1883 was established successfully" rule=internal-kuiper_query_rule
time="2019-11-12T11:56:10+08:00" level=info msg="Successfully subscribe to topic devices/+/messages" rule=internal-kuiper_query_ruleIt is worth noting that this rule named ``internal-kuiper_query_rule`` is created by ``query``, and the server will check if the ``query`` client is online every 5 seconds, if ``query `` The client finds that there is no response for more than 10 seconds (such as being closed), then the internally created ``internal-kuiper_query_rule`` rule will be automatically deleted. After that, the following information will be printed in the log file.
...
time="2019-11-12T12:04:08+08:00" level=info msg="The client seems no longer fetch the query result, stop the query now."
time="2019-11-12T12:04:08+08:00" level=info msg="stop the query."
time="2019-11-12T12:04:08+08:00" level=info msg="unary operator project cancelling...." rule=internal-kuiper_query_rule
...Send test data
Send the following test data to EMQ X Edge via any test tool. The writer used JMeter's MQTT plugin during the test because JMeter can make some flexible automatic data generation, business logic control, and a large number of devices simulations and so on. Users can also use other clients such as mosquitto to simulate directly.
Topic: devices/$device_id/messages, where $device_id is the first column in the data below
Message: {"temperature": $temperature, "humidity" : $humidity}, where $temperature and $humidity are the second and third columns in the data below
#device_id, temperature, humidity
1,20,30
2,31,40
1,35,50
2,20,30
1,80,90
2,45,20
1,10,90
2,12,30
1,65,35
2,55,32We can see that after sending the simulation data, two groups of data are printed in two 10-second time windows in the ``query`` client command line. The number of results output here is related to the frequency at which the user sends data. If Kuiper receives all the data in one time window, only one result is printed.
kuiper > [{"device_id":"1","t_av":45,"t_count":3,"t_max":80,"t_min":20},{"device_id":"2","t_av":25.5,"t_count":2,"t_max":31,"t_min":20}]
[{"device_id":"2","t_av":37.333333333333336,"t_count":3,"t_max":55,"t_min":12},{"device_id":"1","t_av":37.5,"t_count":2,"t_max":65,"t_min":10}]After debugging the SQL, users start configuring the rules file and send the resulting data to the remote AWS IoT Hub via Kuiper's MQTT Sink. In AWS IoT Hub, users need to create the following content first.
Device: The device is a gateway for edge data analysis, and it installs Kuiper. After the data is processed in gateway, the result will be sent to AWS IoT. Here the name is demo, please refer to below.

Device certification and private key: To ensure the security, the devices of AWS are using certification to connect. AWS provides following 3 files when creating devices. Now the certification and private key will be used.
Certification: Similar to d3807d9fa5-certificate.pem
Private key: Similar to d3807d9fa5-private.pem.key
Public key: Similar to d3807d9fa5-public.pem.key
Refer to AWS device creation document for more detailed information.
Write a Kuiper rules file
A rule file is a text file that describes the logic of business processing (the SQL statement that has been debugged before) and the configuration of the sink (the destination of the message processing result). Most of the information about connecting to the AWS IoT has been described in the previous section. The analysis result produced by Kuiper will be sent to devices/result topic of created device.
{"sql": "SELECT avg(temperature) AS t_av, max(temperature) AS t_max, min(temperature) AS t_min, COUNT(*) As t_count, split_value(mqtt(topic), "/", 1) AS device_id FROM demo GROUP BY device_id, TUMBLINGWINDOW(ss, 10)", "actions": [ { "log": {} }, { "mqtt": { "server": "ssl://xyz-ats.iot.us-east-1.amazonaws.com:8883", "topic": "devices/result", "qos": 1, "clientId": "demo_001", "certificationPath": "/var/aws/d3807d9fa5-certificate.pem", "privateKeyPath": "/var/aws/d3807d9fa5-private.pem.key" } } ] }
Create rules via the Kuiper command line
# bin/cli create rule rule1 -f rule1.txtConnecting to 127.0.0.1:20498 Creating a new rule from file rule1.txt. Rule rule1 was created.
We can view the running connection status of the rule in the log file. If the configuration items are correct, we should see that the connection to the Azure IoT Hub is established successfully.
......time="2019-11-13T17:41:19+08:00" level=info msg="The connection to server tcp://10.211.55.6:1883 was established successfully" rule=rule1 time="2019-11-13T17:41:19+08:00" level=info msg="Successfully subscribe to topic devices/+/messages" rule=rule1 time="2019-11-13T17:41:20+08:00" level=info msg="The connection to server ssl://xyz-ats.iot.us-east-1.amazonaws.com:8883 was established successfully" rule=rule1 ......
Topic devices/result is subscribed through MQTT client tool provided by AWS IoT. Then send simulation device data to local EMQ X Edge. After processing by Kuiper, the result is sent to AWS IoT. Refer to below, it received 2 batch of data (the 1st batch is collapsed).

User can use AWS Iot Rule to saving the result to Amazon DynamoDB or other storage services, and applications display result to end-user by reading data saving in DynamoDB. Refer to Amazon DynamoDB Document for more detailed information。
Through this article, readers can understand that the EMQ X solution at the edge can be used to develop a system based on edge data analysis very quickly and flexibly, achieving low data latency, low cost and safe processing.
AWS IoT also provides Edge solution named Greengrass, comparing to AWS Greengrass, Kuiper is more lightweight, and SQL based business implementation is also more simple. AWS Greengrass provides Lambada based programming model, supplied different language runtime to develop Edge analytics applications, and publish the result to AWS IoT. Kuiper lacks of flexibility when processing complex business logics. Greengrass is better than Kuiper at this point. Finally, Kuiper is more flexible to integrate with other 3rd party IoT Hubs, while Greengrass mostly can be only work with AWS IoT Hub.
If you are interested in learning more about edge streaming data analysis, please refer to Kuiper Open Source Project.

As an important open source relational databases, PostgreSQL claims to be the most advanced open source database in the world. Compared to other open source relational databases such as MySQL, PostgreSQL is a completely community-driven open source project, maintained by more than 1,000 contributors worldwide. PostgreSQL provides a single full-featured version, that is unlike MySQL which offers multiple different versions for community, business, and enterprise. PostgreSQL is based on a free BSD / MIT license, and organizations can use, copy, modify, and redistribute its code with a copyright notice.
PostgreSQL has many features, and has more support in the field of GIS. Its "lock-free" feature is very prominent, supports function and condition indexes, and has a mature clustering solution. PostgreSQL also has powerful SQL programming capabilities such as statistical functions and statistical syntax support. With the Timescaledb plugin, PostgreSQL can be transformed into a full-featured time-series database Timescaledb.
Under this scenario, it is required to store the messages that meet the conditions under the topic specified by EMQ X to the PostgreSQL database. In order to facilitate subsequent analysis and retrieval, the message content needs to be split and stored.
The data reported by the client in this scenario is as follows:
Topic:testtopic
Payload:
{"msg":"Hello, World!"}Create a tutorial database with a username of postgres and a password of password:
$ docker pull postgres
$ docker run --rm --name postgres -p 5432:5432 -e POSTGRES_PASSWORD=password -d postgres:latest
$ docker exec -it postgres psql -U postgres
> CREATE database tutorial;
> \c tutorialCreate t_mqtt_msg table:
CREATE TABLE t_mqtt_msg (
id SERIAL primary key,
msgid character varying(64),
sender character varying(64),
topic character varying(255),
qos integer,
retain integer,
payload text,
arrived timestamp without time zone
);Open EMQ X Dashboard, enter the Resources page of the left menu, click the New button, select the PostgreSQL resource type and complete the related configuration for resource creation.

Create a rule
Enter the Rules page on the left menu and click the New button to create a rule. Here we choose to trigger event of message.publish, which means when EMQ X receives the message of PUBLISH , the rule is triggered for data processing.
After the trigger event is selected, we can see optional fields and sample SQL on the interface:

The rules engine uses SQL statements to filter and process data. Here we need data such as msgid, topic, payload, and we want to match messages from all topics. Therefore, we only need to delete the WHERE clause based on the default SQL. In the end, we get the following SQL:
SELECT
*
FROM
"message.publish"With the SQL test feature, we can quickly confirm whether the SQL statement we just filled out can achieve our purpose. First we fill in the payload and other data for test as follows:

After clicking the Test button, we get the following data output:
{
"client_id": "c_emqx",
"event": "message.publish",
"id": "589A429E9572FB44B0000057C0001",
"node": "[email protected]",
"payload": "{\"msg\":\"Hello, World!\"}",
"peername": "127.0.0.1:50891",
"qos": 1,
"retain": 0,
"timestamp": 1564037750692,
"topic": "testtopic",
"username": "u_emqx"
}The test output contains all the required data and we can proceed to the next steps.
After the SQL condition input and output are correct, we continue to add corresponding actions, configure to write SQL statements, and store the filtered results in PostgreSQL.
Click the Add button in the response action, select the action of Save Data to PostgreSQL , select the PostgreSQL resource you just created and fill in the SQL template as follows:
insert into t_mqtt_msg(msgid, topic, qos, retain, payload, arrived) values (${id}, ${topic}, ${qos}, ${retain}, ${payload}, to_timestamp(${timestamp}::double precision /1000)) returning id
Finally, click the New button to complete the rule creation.

We have successfully created a rule that contains a processing action. The expected outcome of the action is as follows:
When the client reports a message, the message will hit SQL and the number of hits in the rule list will increase by 1;
A piece of data will be added to the t_mqtt_msg table of the PostgreSQLtutorial database. The data content is consistent with the message content.
Switch to the Tools -> Websocket page, use any information client to connect to EMQ X. After the connection is successful, send the following message in the message card:
Topic:testtopic
Payload:

Click the Send button. After sending successfully, we can see that the number of hits of the current rule has changed to 1.
Then check PostgreSQL to see if the new data point was added successfully:

So far, we have used the rule engine to implement business development to store messages to a PostgreSQL database.
OpenTSDB is an extensible distributed time series database, whose bottom layer relies on HBase and makes full use of the distributed column storage feature of HBase to support millions of reads and writes per second.
Facing large-scale rapid growth of loT sensor acquisition, transaction records and other data, time series data accumulates very quickly. The time series database processes this large-scale data by improving efficiency, and it brings performance improvements, including higher Ingest Rates, faster large-scale queries (Although it supports more queries than other relational databases), and better data compression.
This article will describe how to store related EMQ X MQTT messages through OpenTSDB by practical examples in the system CentOS 7.2.
Readers can refer to the OpenTSDB documentation or Docker to download and install the OpenTSDB server. This article uses OpenTSDB 2.4.0.
If users use RPM method to install EMQ X, the OpenTSDB related configuration files is located in /etc/emqx/plugins/emqx_backend_opentsdb.conf. The OpenTSDB plugin only supports message storage considering the function location.
Configure the connection address, connection pool size and batch strategies
## OpenTSDB Server connected address
backend.opentsdb.pool1.server = 127.0.0.1:4242
## Connection pool size
backend.opentsdb.pool1.pool_size = 8
## Max batch size of put
backend.opentsdb.pool1.max_batch_size = 20
## Store all information through the topic filter
backend.opentsdb.hook.message.publish.1 = {"topic": "#", "action": {"function": "on_message_publish"}, "pool": "pool1"}OpenTSDB Backend message storage rule parameters:
Set the topic which needs to store information through the topic filter, and distinguish the pool parameter between multiple data sources:
## Store Publish Message
backend.opentsdb.hook.message.publish.1 = {"topic": "#", "action": {"function": "on_message_publish"}, "pool": "pool1"}Enable this plugin:
./bin/emqx_ctl plugins load emqx_backend_opentsdbBecause the MQTT Message can not be written directly to OpenTSDB, OpenTSDB backend provides the emqx_backend_opentsdb.tmpl template file to convert the MQTT Message to DataPoint that can be written to OpenTSDB.
The message template function requires EMQ X to be restarted to apply the changes.
The tmpl file is located in data/templates/emqx_backend_opentsdb_example.tmpl. Using the json format, users can define different Template for different Topic, which is similar to:
{
"sample": {
"measurement": "$topic",
"tags": {
"host": ["$payload", "data", "$0", "host"],
"region": ["$payload", "data", "$0", "region"],
"qos": "$qos",
"from": "$from"
},
"value": ["$payload", "data", "$0", "temp"],
"timestamp": "$timestamp"
}
}Among them, measurement and fields are required to be filled, and tags and timestamp are optional. Supports to extract variables with the name key by placeholders such as $key. The supported variables are as follows:
qos: Message QoS
form: Publisher information
topic: Published topic
timestamp
Payload.*: Any variable in the JSON message body, such as { "data": [{ "temp": 1 }] }. Use ["$payload", "data", "temp"] to extract 1.
This example sets the template as follows:
{
"sample": {
"measurement": "$topic",
"tags": {
"host": ["$payload", "data", "$0", "host"],
"region": ["$payload", "data", "$0", "region"],
"qos": "$qos",
"from": "$from"
},
"value": ["$payload", "data", "$0", "temp"],
"timestamp": "$timestamp"
}
}When the MQTT message with the Topic "sample" has the following Payload:
{
"data": [
{
"temp": 1,
"host": "serverA",
"region": "hangzhou"
},
{
"temp": 2,
"host": "serverB",
"region": "ningbo"
}
]
}Backend will convert the MQTT Message to:
[
{
"measurement": "sample",
"tags": {
"from": "mqttjs_ebcc36079a",
"host": "serverA",
"qos": "0",
"region": "hangzhou"
},
"value": "1",
"timestamp": "1560743513626681000"
},
{
"measurement": "sample",
"tags": {
"from": "mqttjs_ebcc36079a",
"host": "serverB",
"qos": "0",
"region": "ningbo"
},
"value": "2",
"timestamp": "1560743513626681000"
}
]In the EMQ X management console WebSocket page, publish the message in the above format to the topic sample, the message will be parsed and stored in the measurement corresponding to the OpenTSDB udp database.
Readers can extend related applications by using OpenTSDB, after understanding the data structure stored in OpenTSDB and learning how to use the message template to configure the written message field format.
Although the publish-subscribe model fully decouples the publisher of the message from the subscriber, there is also an implicit problem that the subscriber cannot actively request the message from the publisher, and when the subscriber receives the message depends entirely on the publisher. This is inconvenient in some scenarios. For example, when a device periodically publishes its own GPS coordinates, it may take a few seconds for a subscriber to receive data from initiation of a subscription for the first time, or it may take ten minutes or more, which is not friendly. Therefore, MQTT introduces the retained message.

When the server receives a PUBLISH packet with a Retain flag of 1, it will conduct the following operations:
If there are subscribers matching this topic name, it will forward them in normal logic and clear the Retain flag before forwarding. The Retain flag in the MQTT v3.1.1 protocol must be cleared, and a Retain As Publish field is added in the subscription option of MQTT v5.0 protocol. The client itself indicates whether the server needs to clear the Retain flag before forwarding.
If Payload is not empty, it will store this application message and replace it if a retained message already exists under this topic. If Payload is empty, the server will not store this application message and clear the retained messages that already exist under this topic.
Whenever a subscriber establishes a subscription, the server will check if there is a retained message that matches the subscription, and if the retained message exists, it immediately forwards it to the subscriber. When a retained message is forwarded to the subscriber in this case, its Retain flag must remain at 1. Compared to MQTT v3.1.1, it makes a more detailed division of whether to send a retained message when the subscription is established in MQTT v5.0 , and provides a Retain Handling field in the subscription option. For example, some clients may only want to receive a retained message when they subscribe for the first time, or they may not want to receive a retained message when the subscription is established, which can be adjusted by the Retain Handling option.
Although retained message is stored in the server, it is not part of the session. That is to say, even if the session that published the retained message is terminated, the retained message will not be deleted. There are only two ways to delete a retained message:
As mentioned earlier, the client sends a retained message with a Payload empty to a topic, and the server deletes the retained message under this topic.
The message expiration interval attribute is also applicable in the retained message. If the client sets this attribute, the retained message will be deleted after the storage expiration time is dued.
With retained messages, new subscribers can get the most recent status immediately, without waiting for unpredictable times, which is very important in many scenarios.
Date: 2019/11/22
The Kuiper team would like to announce the release of Kuiper 0.0.3
Kuiper 0.0.3 is available for download.
Kuiper is a SQL based lightweight IoT analytics/streaming software running at resource constrained edge devices. This release includes several new features and bug fixes.
Website: https://www.emqx.io/products/kuiper
Github Repository: https://github.com/emqx/kuiper
Refactor the code to support Kuiper Sink and Source extension.
Enhanced MQTT Sink to support AWS IoT and Azure IoT Hub. User can directly publish result to any MQTT IoT Hub by configuring Sink.
Enhanced MQTT Source to support secured settings. User can specifiy username, password, certifications and private key information for MQTT source.
HAVING clause support
Added Chinese document, and renamed XStream to Kuiper in all of documents.
Build improvement
Added build version number in command line tools
Updated Makefile, and now supports automatically build for all platforms
If having any problems for Kuiper, feel free to contact us through [email protected]
When the client disconnects, a will message is sent to the relevant subscriber. Will Messages will be sent when:
I / O error or network failure occurred on the server;
The client loses contact during a defined heartbeat period;
The client closes the network connection before sending offline packets;
The server closes the network connection before receiving the offline packet.
Will messages are usually specified when the client is connected. As shown below, it is set during the connection by calling the setWill method of theMqttConnectOptions instance. Any client who subscribes to the topic below will receive the will message.
//method1
MqttConnectOptions.setWill(MqttTopic topic, byte[] payload, int qos, boolean retained)
//method2
MqttConnectOptions.setWill(java.lang.String topic, byte[] payload, int qos, boolean retained)When client A connects, the will message is set to "offline" and client B subscribes to this will topic. When A disconnects abnormally, client B will receive this will message of "offline" to know that client A is offline.
Connect Flag packet field
| Bit | 7 | 6 | 5 | 4 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|
| User Name Flag | Password Flag | Will Retain | Will QoS | Will Flag | Clean Start | Reserved | |
| byte 8 | X | X | X | X | X | X | X |
The will message is not sent after the client calls the disconnect method normally.
In short, it is the last will (also known as the Testament) that the client has defined in advance and left when it is disconnected abnormally. This will is a topic and a corresponding message pre-defined by the client, which is attached to the variable packet header of CONNECT. In case of abnormal connection of the client, the server actively publishes this message.
When the bit of Will Flag is 1, Will QoS and Will Retain will be read. At this time, the specific contents of Will Topic and Will Message will appear in the message body, otherwise the Will QoS and Will Retain will be ignored.
When the Will Flag bit is 0, Will Qos and Will Retain are invalid.
Here is an example of Will Message:
Sub side ClientID = sub predefined will message:
clientid = alive subscribes to the will topic at 192.168.1.1 (EMQ server)
Abnormally disconnect the sub end from the server end (EMQ server), and the pub end receives the will message.
Here's how to use Retained messages with Will messages.
The will message of client A is set to "offline", and the topic of the will is set to A/status that is the same as the topic of a normal sending status;
When client A is connected, send the "Online" Retained message to the topic A/status. When other clients subscribe to the topicA/status, they obtain the Retained message as "online";
When client A disconnects abnormally, the system automatically sends an "offline" message to the topic A/status. Other clients that subscribe to this topic will immediately receive an" offline "message; if the will message is set Retained, and when a new client subscribing to the A/status topic comes online, the message obtained is“ offline ”.
Security is a challenge for almost all projects, especially for IoT projects. Since the widespread of IoT application, there have been too many security incidents in the IoT industry.
As the factual standard for IoT communication protocols, MQTT maintains a high level of security and provides a multi-level security design:
Transport layer: MQTT is based on TCP / IP protocol, and SSL/TLS is used for encrypted transmission on the transport layer:
SSL/TLS is used to encrypt communication data to prevent middleman attacks;
The client certificate is used as device identity certificate to verify the validity of the device.
Application layer :MQTT's security features are used for protection:
MQTT protocol supports user name and password for client identity verification;
MQTT Broker implements access control for topics (Topic ACL).
MQTT Safety specifications are fully supported by EMQ, and the built-in safety functions can be used out-of-the-box without programming, which can quickly eliminate security risks in projects. This series will focus on various levels of safety specifications, and introduce how to enable relevant functions through the configuration of EMQ X to finally achieve the corresponding safety protection.
emqx_auth_mysql is an MQTT authentication/access control plug-in based on the MySQL database. It realizes connection authentication and access control of the terminal by checking whether the username and password accessed by each terminal are consistent with the information stored in the user-specified MySQL database. Its functional logic is as follows:

In this article, only the authentication function is introduced. ACL function will be introduced in the following article.
When the device is connected, EMQ X will execute the query statement according to the configuration and compare whether the value of the password field in the query result is the same as the value of current requesting client's password with salt processing and encryption. The verification process is as follows:
There must be password and salt fields in the query result set. You can use the AS syntax setting such as SELECT *,pwd as password FROM mqtt_user
Salt can be specified for each client in the database. EMQ X generates a ciphertext based on the client's incoming password and the salt information returned through SQL.
If the result set is empty or the comparison results are not equal, the authentication fails
You can use any client you like to create the corresponding database. The command-line client of MySQL is used here. Open the MySQL console, as shown below, create an authentication database named emqx, and switch to the emqx database.
mysql> create database emqx;
Query OK, 1 row affected (0.00 sec)
mysql> use emqx;
Database changedThe suggested table structure is as follows, where:
username is the user name specified when the client connects
password_hash is the ciphertext encrypted with salt
salt is an encrypted string
is_superuser means whether it is a super user, which is used to control the ACL. The default is 0; when set to 1, it is a super user, which can skip the ACL check
The data table fields do not need to be completely consistent with the following. They can be set according to business needs and specified through the
auth_queryconfiguration item in theemqx_auth_mysql.confconfiguration file.
CREATE TABLE `mqtt_user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(100) DEFAULT NULL,
`password_hash` varchar(255) DEFAULT NULL,
`salt` varchar(40) DEFAULT NULL,
`is_superuser` tinyint(1) DEFAULT 0,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `mqtt_username` (`username`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;After the creation is successful, the table structure is as follows:
mysql> desc mqtt_user;
+---------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+------------------+------+-----+---------+----------------+
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| username | varchar(100) | YES | UNI | NULL | |
| password_hash | varchar(255) | YES | | NULL | |
| salt | varchar(40) | YES | | NULL | |
| is_superuser | tinyint(1) | YES | | 0 | |
| created | datetime | YES | | NULL | |
+---------------+------------------+------+-----+---------+----------------+
6 rows in set (0.01 sec)In this article, the password of sample data is test_password and the encrypted salt is secret. That is, the password used by the client for connection is test_password.
In the configuration file auth.mysql.password_hash of EMQ X, salt is just an identifier, which indicates the concatenation relationship between salt and the plaintext of the password.
If auth.mysql.password_hash = md5,salt is used, then the MD5 algorithm is used by EMQ X to encrypt test_passwordsecret string
If auth.mysql.password_hash = salt,md5 is used, then the MD5 algorithm is used by EMQ X to encrypt secrettest_password string
In this article, the first configuration method is used, inserting the obtained MD5 ciphertext into the table mqtt_user. Readers can use online MD5 tool or write a program to encode the password.
MD5("test_passwordsecret") -> a904b2d1d2b2f73de384955022964595mysql> INSERT INTO mqtt_user(username,password_hash,salt) VALUES('test_username', 'a904b2d1d2b2f73de384955022964595', 'secret');
Query OK, 1 row affected (0.00 sec)
mysql> select * from mqtt_user;
+----+----------------+----------------------------------+--------+--------------+---------+
| id | username | password_hash | salt | is_superuser | created |
+----+----------------+----------------------------------+--------+--------------+---------+
| 3 | test_username1 | a904b2d1d2b2f73de384955022964595 | secret | 0 | NULL |
+----+----------------+----------------------------------+--------+--------------+---------+
1 row in set (0.00 sec)Modify etc/plugins/emqx_auth_mysql.conf. The effective configuration after the modification is shown below. The remaining ACL related configuration items can be commented:
## Change to the server address where the actual mysql is located
auth.mysql.server = localhost:3306
## Change to the emqx database created above
auth.mysql.database = emqx
## Connection authentication query
auth.mysql.auth_query = SELECT password_hash AS password, salt FROM mqtt_user WHERE username = '%u'
## Encryption Algorithm plain | md5 | sha | sha256 | bcrypt
## Salt encryption algorithm
auth.mysql.password_hash = md5,salt
## No salt encryption algorithm, just write the algorithm name
# auth.mysql.password_hash = md5After the modification, use Dashboard or the command line to restart the plug in to apply the configuration. The command line for restarting example is as follows:
emqx_ctl plugins reload emqx_auth_mysqlEMQ X enabled anonymous authentication by default. Once the authentication function is enabled, the device can connect normally even when the database does not query the data, and the connection will be refused only when the data is queried and the password is incorrect.
Open the etc/emqx.conf configuration file and disable anonymous authentication:
## Value: true | false
allow_anonymous = falseRestart emqx to complete the configuration application.
Once ready, only devices that have passed authentication verification can successfully connect to EMQ X:
Connect with the correct username and password, subscribe to the topic, and the connection will succeed:
$ mosquitto_sub -p 1883 -u test_username -P test_password -t 'topic' -d
Client mosqsub|5228-wivwiv-mac sending CONNECT
Client mosqsub|5228-wivwiv-mac received CONNACK
Client mosqsub|5228-wivwiv-mac sending SUBSCRIBE (Mid: 1, Topic: topic, QoS: 0)
Client mosqsub|4119-zh
ouzibode received SUBACK
Subscribed (mid: 1): 02. Connect with the wrong username or password, subscribe to the topic, and the connection will fail:
$ mosquitto_sub -p 1883 -u test_username -P test_password -t 'topic' -d
Client mosqsub/61879-wivwiv-ma sending CONNECT
Client mosqsub/61879-wivwiv-ma received CONNACK
Connection Refused: not authorised.After understanding the principle of EMQ X MySQL authentication, readers can use MySQL to expand related applications. Welcome to the EMQ X security series, and this series will explain the security issues related to EMQ X and IoT to help you build an IoT project with high-level security.
Cassandra is an open source distributed database system from Apache that supports linear extension, high availability without losing the original read and write performance. At present, it is widely used in the back-end services of large enterprises, such as Netflix, Apple and so on, which have deployed thousands of nodes.
Installation Reference of Cassandra:http://cassandra.apache.org/doc/latest/getting_started/installing.html
By configuring the rules engine, EMQ X stores messages that meet certain criteria under a given topic into the Cassandra database. The message flow diagram is as follows:

among them:
PUB/SUB: Publish and subscribe processing logic for EMQ X.
Rule: IoT message rules that extract, filter, and transform data in message packet.
Action: An action for specific execution. For example, store into databases, write Kafka, etc.
To illustrate the use of rule engine in Cassandra database, we take the example of ``storing the vehicle state with engine speed over 8000 in Cassandra`'.
Assume that vehicle status information is reported as follows:
Report topic: cmd/state/:id, the id of the topic represents the vehicle client ID
Message body:
Create a database
Create a emqx_rule_engine_output tablespace to store message data:
CREATE KEYSPACE emqx_rule_engine_output WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} AND durable_writes = true;Create a data table
According to the scenario requirements, create the data table use_statistics structure and field annotations as follows:
USE emqx_rule_engine_output;
CREATE TABLE use_statistics (
msgid text,
client_id text,
speed double,
tachometer int,
ts int,
PRIMARY KEY (msgid)
);Confirm the existence of the data table after successful creation:
root@cqlsh:emqx_rule_engine_output> use emqx_rule_engine_output ;
root@cqlsh:emqx_rule_engine_output> desc use_statistics ;
CREATE TABLE emqx_rule_engine_output.use_statistics (
msgid text PRIMARY KEY,
client_id text,
speed double,
tachometer int,
ts int
) WITH bloom_filter_fp_chance = 0.01
AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}
AND comment = ''
AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4'}
AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
AND crc_check_chance = 1.0
AND dclocal_read_repair_chance = 0.1
AND default_time_to_live = 0
AND gc_grace_seconds = 864000
AND max_index_interval = 2048
AND memtable_flush_period_in_ms = 0
AND min_index_interval = 128
AND read_repair_chance = 0.0
AND speculative_retry = '99PERCENTILE';Create a resource
Open the EMQ X Dashboard, go to the Resources page of the left menu, click the New button, select the Cassandra resource type to create:

The network environment of the nodes in the EMQ X cluster may be different. After the resources are created successfully, click the **Status button ** in the list to check the connection status of each node. If the resources on the node are unavailable, check whether the configuration is correct and the network connectivity is correct, and click the Reconnect button to manually reconnect.

Create a rule
Go to the Rules page on the left menu and click the New button to create the rule. Select the trigger event message release, which is triggered when the message is published for data processing.
After selecting the trigger event, we can see the optional fields and sample SQL on the interface:

Screen the required fields
The rule engine uses SQL statements to process rule conditions. In this business, we need to select all the fields in payload separately, use the payload.<fieldName> format to select, and also also need ``topic,qos, id` information in message context. The current SQL is as follows:
SELECT
payload.id as client_id, payload.speed as speed,
payload.tachometer as tachometer,
payload.ts as ts, id
FROM
"message.publish"
WHERE
topic =~ 't/#'Establish screening criteria
Conditional screening using the SQL statement WHERE clause, in which we need to define two conditions:
Only cmd/state/:id topics are processed, and topic is filtered by using the topic wildcard = ~':topic = cmd/state/+'.
Only tachometer > 8000 messages are processed, and tachometer is filtered with comparator: payload. tachometer > 8000
Combine the previous step to get the following SQL:
SELECT
payload.id as client_id, payload.speed as speed,
payload.tachometer as tachometer,
payload.ts as ts,
id
FROM
"message.publish"
WHERE
topic =~ 'cmd/state/+'
AND payload.tachometer > 8000Output testing is done by using the SQL test function
With the SQL test function, we can view the current data output processed by SQL in real time. This function requires us to specify the simulated raw data such as payload.
The payload data is as follows, note to change the tachometer value to satisfy the SQL condition:
{
"id": "NXP-058659730253-963945118132721-22",
"speed": 32.12,
"direction": 198.33212,
"tachometer": 9001,
"dynamical": 8.93,
"location": {
"lng": 116.296011,
"lat": 40.005091
},
"ts": 1563268202
}Click the SQL Test toggle button, change topic and payload to the information in the scenario, and click the Test button to view the data output:

The test output data is:
{
"client_id": "NXP-058659730253-963945118132721-22",
"id": "589A429E9572FB44B0000057C0001",
"speed": 32.12,
"tachometer": 9001,
"ts": 1563268202
}The test output is as expected and we can proceed to the next step.
Add a response action and store the message to Cassandra
After the input and output of SQL condition is correct, we continue to add the corresponding action, configure to write SQL statement, and store the screening result in Cassandra.
Click the Add button in the response action, select the Save data to Cassandra action, select the resource just selected, we populate the SQL statement with the ${fieldName} syntax, insert the data into the database, and finally click the New button to complete the rule creation.
The SQL configuration of the action is as follows:
INSERT INTO use_statistics (msgid, client_id, speed, tachometer, ts) VALUES (${id}, ${client_id}, ${speed}, ${tachometer}, ${ts});
Expected results
We successfully created a rule that contains a processing action, and the expected result of action is as follows:
The device reports the message to the cmd/state/:id topic. When the value of tachometer in the message exceeds 8000, it will hit SQL. The number of hits in the rule list is increased by 1;
A data is added to the use_statistics table of the Cassandra emqx_rule_engine_output database, the value is the same as the current message.
Test with the Websocket tool in Dashboard
Switch to the Tools => Websocket page and use any information client to connect to EMQ X. After the connection is successful, the message card sends the following message:
Topic: cmd/state/NXP-058659730253-963945118132721-22
Message body:
{
"id": "NXP-058659730253-963945118132721-22",
"speed": 32.12,
"direction": 198.33212,
"tachometer": 8081,
"dynamical": 8.93,
"location": {
"lng": 116.296011,
"lat": 40.005091
},
"ts": 1563268202
}
Click the Send button. At this time, the value of tachometer in the message body satisfies the condition of tachometer > 8000 set above. The current rule has been hit and the statistic value plus one.
View the data table records in the Cassandra command line to get the following data:

So far, we have implemented a business development to store messages to the Cassandra database through the rules engine.
For more information, please visit our official website emqx.io or follow our open source project github.com/emqx/emqx. Please visit Official Documentation for detailed documentation.
Amazon DynamoDB is a fully hosted NoSQL database service that supports key values and document data structures.
Amazon DynamoDB is provided by Amazon as part of the AWS cloud portfolio, delivering fast, predictable performance and seamless scaling.
Amazon DynamoDB Service Address:
https://aws.amazon.com/dynamodb/
In this scenario, messages that meet the criteria under the EMQ X specified topic are required to be stored in the DynamoDB database. In order to facilitate subsequent analysis and retrieval, the message content needs to be split and stored.
In this scenario, the message reported by the device is as follows:
Reported topic: cmd/state/:id, the topic id represents the vehicle client ID
Message body:
{
"id": "NXP-058659730253-963945118132721-22", // Client ID
"speed": 32.12, // Vehicle speed
"direction": 198.33212, // Driving direction
"tachometer": 3211, // Engine speed, that is required to be stored when the value is greater than 8000
"dynamical": 8.93, // Instantaneous fuel consumption
"location": { // GPS latitude and longitude data
"lng": 116.296011,
"lat": 40.005091
},
"ts": 1563268202 // Reported time
}When the reported data of engine speed value is greater than `8000', the current information is stored for subsequent analysis of the user's vehicle usage.
Define DynamoDB data table
According to the scenario requirements, define the data table use_statistics structure as follows:
use_statistics.json
{
"TableName": "use_statistics",
"KeySchema": [
{ "AttributeName": "client_id", "KeyType": "HASH" },
{ "AttributeName": "id", "KeyType": "RANGE" }
],
"AttributeDefinitions": [
{ "AttributeName": "client_id", "AttributeType": "S" },
{ "AttributeName": "id", "AttributeType": "S" }
],
"ProvisionedThroughput": {
"ReadCapacityUnits": 5,
"WriteCapacityUnits": 5
}
}Create DynamoDB data table
Create use_statistics data table with the aws cli command:
$ aws dynamodb create-table --cli-input-json file://use_statistics.json --endpoint-url http://localhost:8000
{
"TableDescription": {
"AttributeDefinitions": [
{
"AttributeName": "client_id",
"AttributeType": "S"
},
{
"AttributeName": "id",
"AttributeType": "S"
}
],
"TableName": "use_statistics",
"KeySchema": [
{
"AttributeName": "client_id",
"KeyType": "HASH"
},
{
"AttributeName": "id",
"KeyType": "RANGE"
}
],
"TableStatus": "ACTIVE",
"CreationDateTime": 1563765603.777,
"ProvisionedThroughput": {
"LastIncreaseDateTime": 0.0,
"LastDecreaseDateTime": 0.0,
"NumberOfDecreasesToday": 0,
"ReadCapacityUnits": 5,
"WriteCapacityUnits": 5
},
"TableSizeBytes": 0,
"ItemCount": 0,
"TableArn": "arn:aws:dynamodb:ddblocal:000000000000:table/use_statistics",
"BillingModeSummary": {
"BillingMode": "PROVISIONED",
"LastUpdateToPayPerRequestDateTime": 0.0
}
}
}Confirm the existence of the data table through the aws cli command after the successful creation:
$ aws dynamodb list-tables --region us-west-2 --endpoint-url http://127.0.0.1:8000
{
"TableNames": [
"use_statistics"
]
}Create resource
Open EMQ X Dashboard, go to the Resources page on the left menu, click the New button, type DynamoDB server information for resource creation.

The network environment of the nodes in the EMQ X cluster may be different. After the resources are created successfully, click the Status button in the list to check the connection status of each node. If the resources on the node are unavailable, check whether the configuration is correct and the network connectivity is correct, and click the Reconnect button to manually reconnect.

Create rules
Go to the left menu of rules page, click new button to create rules. Select trigger event of message publishing to trigger this rule for data processing when the message is published.
After selecting the trigger event, we can see the optional field and sample SQL in the interface:

Screen the required fields
Rule engine uses SQL statements to process rule conditions. In this business, we need to select all the fields in payload separately, use the payload.fieldName format to select, and also need the topic context information oftopic, qos, id. The current SQL is as follows:
SELECT
payload.id as client_id, payload.speed as speed,
payload.tachometer as tachometer,
payload.ts as ts, id
FROM
"message.publish"
WHERE
topic =~ 't/#'Establish screening conditions
Conditional screening is done by using the SQL statement WHERE clause, in which we need to define two conditions:
Only handle cmd/state/:id topic, use the topic wildcard =~ to screen topic: `topic =~ 'cmd/state/+'
Only process tachometer > 8000 messages, use the comparator to screen tachometer: payload.tachometer > 8000
Combine the previous step to get the SQL as follows:
SELECT
payload.id as client_id, payload.speed as speed,
payload.tachometer as tachometer,
payload.ts as ts,
id
FROM
"message.publish"
WHERE
topic =~ 'cmd/state/+'
AND payload.tachometer > 8000Output test is done with the SQL test function
With the SQL test function, we can view the current SQL processed data output in real time. This function requires us to specify the simulated raw data such as payload.
The payload data is as follows, note to change the tachometer value to satisfy the SQL condition:
{
"id": "NXP-058659730253-963945118132721-22",
"speed": 32.12,
"direction": 198.33212,
"tachometer": 9001,
"dynamical": 8.93,
"location": {
"lng": 116.296011,
"lat": 40.005091
},
"ts": 1563268202
}Click the SQL Test toggle button, change topic and payload to be the information in the scenario, and click the Test button to view the data output:

The test output data is:
{
"client_id": "NXP-058659730253-963945118132721-22",
"id": "589A429E9572FB44B0000057C0001",
"speed": 32.12,
"tachometer": 9001,
"ts": 1563268202
}The test output is as expected and we can proceed to the next step.
Add a response action and store the message to DynamoDB
After the input and output of SQL condition is correct, we continue to add the corresponding action, configure to write SQL statement, and store the screening result in DynamoDB.
Click the Add button in the response action, select the Save data to DynamoDB action, select the resource just selected, fill the DynamoDB table name, Hash Key, and Range Key.

Expected result
We successfully created a rule that contains a processing action, and expected result of the action is as follows:
When the device reports a message to the cmd/state/:id topic, it will hit SQL when the value of tachometer in the message exceeds 8000, and the number of hit in the rule list is increased by 1;
A piece of data will be added to the 'use_statistics' table in DynamoDB with the same value as the current message.
Test with the Websocket tool in Dashboard
Switch to tools -> Websocket page, connect to EMQ X with any client, and send the following message to message card after successful connection:
Topic: cmd/state/NXP-058659730253-963945118132721-22
Message body:
{
"id": "NXP-058659730253-963945118132721-22",
"speed": 32.12,
"direction": 198.33212,
"tachometer": 9001,
"dynamical": 8.93,
"location": {
"lng": 116.296011,
"lat": 40.005091
},
"ts": 1563268202
}
Click the Send button. After sending successfully, the statistic of hit under current rule is 1.
View the data table records with the aws cli command to get the following data:

So far, we have implemented the business development of using the rules engine to store messages to DynamoDB.
OpenTSDB is an extensible distributed time series Database database, whose bottom layer relies on HBase and makes full use of HBase's features of distributed column storage to support millions of reads and writes per second.
Facing large-scale and rapid growth of IoT sensor acquisition, transaction records and other data, time series data accumulates very quickly. The time series database processes this large-scale data by improving efficiency and brings performance improvements, including higher Ingest Rates, faster large-scale queries, and better data compression.
Readers can refer to the official OpenTSDB document (http://opentsdb.net) or Docker (https://hub.docker.com/r/petergrace/opentsdb-docker/) to download and install the OpenTSDB server. This article uses OpenTSDB 2.4.0 .
In this scenario, it is required to store the messages that meet the conditions under the topic specified by EMQ X to the OpenTSDB database. In order to facilitate subsequent analysis and retrieval, the message content needs to be split and stored.
The data reported by the client in this scenario is as follows:
Topic:stat/cpu
Payload:
Start OpenTSDB Server and open port 4242.
$ docker pull petergrace/opentsdb-docker
$ docker run -d --name opentsdb -p 4242:4242 petergrace/opentsdb-dockerOpen EMQ X Dashboard, enter the Resources page on the left menu, click the New button, select the OpenTSDB resource type and complete the related configuration to create the resources.

Enter the Rules page on the left menu and click the New button to create a rule. Here we choose message.publish as the trigger event. When EMQ X receives the PUBLISH message, the rule is triggered for data processing.
After the trigger event is selected, we can see optional fields and sample SQL on the interface:

The rules engine uses SQL statements to filter and process data. For example, in the scenario mentioned above, when we need to extract the fields in payload , it can be achieved by payload. <FieldName>. At the same time, we only want to deal with the topic stat / cpu, so we can use the topic wildcard= ~in the WHERE clause to filter the topic:topic = ~ 'stat / cpu', and finally we get the following SQL:
SELECT
payload.metric as metric, payload.tags as tags, payload.value as value
FROM
"message.publish"
WHERE
topic =~ 'stat/cpu'With the SQL test feature, we can quickly confirm whether the SQL statement we just filled out can achieve our purpose. We firstly fill in the payload and other data for testing as follows:

Then click the Test button, we get the following data output:
{
"metric": "cpu",
"tags": {
"host": "serverA"
},
"value": 12
}The test output is as expected and we can proceed to the next step.
After the SQL condition input and output are correct, we continue to add corresponding actions, configure to write SQL statements, and store the filtered results in OpenTSDB.
Click the Add button in the response action, select the action of Save Data to OpenTSDB, select the OpenTSDB resource just created and complete the remaining parameter settings. Several parameters that OpenTSDB requires for operation are:
Details. Whether OpenTSDB Server is required to return data points and reasons for failure. The default is false.
Summary information. Whether OpenTSDB Server is required to return data points to store the number of successes and failures. The default is true.
Maximum number of batches processing. How many Data Points the driver is allowed to read from the queue at one time to merge into one HTTP request when the message request is frequent . It is a performance optimization parameter. The default value is 20.
Whether to call synchronously. Configures whether OpenTSDB Server waits for all data to be written before returning results. The default is false.
Synchronous call timeout. The maximum time that the OpenTSDB Server waits for data to be written. The default is 0, that means times out never happens.
Here we all use the default configuration, click the New button to complete the rule creation.

We have successfully created a rule that contains a processing action. The expected effect of the action is as follows:
When the client reports a message to the topic stat / cpu, the message will hit SQL and the number of hits in the rule list will increase by 1;
A piece of data will be added to the OpenTSDB Server, and the data content is consistent with the message content.
Switch to the Tools -> Websocket page, use any information client to connect to EMQ X. After the connection is successful, send the following message in the Message card:
Topic:stat/cpu
Payload:

Click the Send button. After sending successfully, we can see that the number of hits of the current rule has changed to 1.
Then, send a query request to OpenTSDB through Postman. When we get the following response, it means the new data point has been added successfully:

So far, we have implemented business development to store messages to the OpenTSDB database through the rule engine.
Date: 2020/3/23
The Kuiper team would like to announce the release of Kuiper 0.2.1.
Kuiper 0.2.1 now is available for download.
EMQ X Kuiper is an edge lightweight IoT data analytics / streaming software implemented by Golang, and it can be run at all kinds of resource constrained edge devices. One goal of Kuiper is to migrate the cloud streaming software frameworks (such as Apache Spark,Apache Storm and Apache Flink) to edge side. Kuiper references these cloud streaming frameworks, and also considered special requirement of edge analytics, and introduced rule engine, which is based on Source, SQL (business logic) and Sink, rule engine is used for developing streaming applications at edge side.

This release includes several new features and bug fixes.
Website: https://www.emqx.io/products/kuiper
Github Repository: https://github.com/emqx/kuiper
The initial version of Kuiper & EdgeX integration work was just completed, users can start to try it. In the coming EdgeX Geneva release, Kuiper 0.3.0 or 0.4.0 will be released with EdgeX officially.
EdgeX integration
EdgeX source support, now Kuiper can consume data from EdgeX Message Bus directly. You can refer to tutorial doc for learning how to use Kuiper to analyze data from EdgeX.
EdgeX sink support, the analysis result can be published to EdgeX Message Bus directly.
Schemaless stream definition
FVT test schenarios enhancements
Added 4 EdgeX testcases
Added testcases for Docker image
Fixed several problems of Github Actions
If having any problems for Kuiper, feel free to contact us through [[email protected]](
MQTT X is a cross-platform MQTT 5.0 desktop test client provided by the world's leading open source IoT middleware provider EMQ , which supports macOS, Linux, Windows. The user interface of MQTT X simplifies the operation logic of the page with the pattern of chatting software. Users can quickly create multiple simultaneous-online MQTT clients to test the connection/publish/subscribe functions of MQTT/TCP, MQTT/TLS, MQTT/WebSocket and other MQTT protocol features.
MQTT X website: https://mqttx.app
MQTT X v1.3.0 download link: https://github.com/emqx/MQTTX/releases/tag/v1.3.0

Support MQTT over WebSockets


The format conversion of Payload is supported


The height of the input box can be adjusted freely
In the previous version, the height of the input box was fixed, and the Payload content that the user could see when using it was limited. If too much content was sent, the operation of input and editing in the input box could not be performed well. After optimization, users can place the mouse on the top of the input box, and when the arrow appears, drag the mouse to freely adjust the height of the input box to facilitate better processing of the Payload content.

Fuzzy query for the Topic is supported
In the previous version, only precise search for the Topic is supported, and only messages under the same Topic were searched. Currently, fuzzy query is supported, which can search and filter a wider range of Topic messages. We will continue to optimize the function of distinguishing and displaying messages by Topic, and it is coming soon.
In the pop-up box for adding Topic, the Enter key can be used as a shortcut to quickly add subscriptions.
MQTT maximum reconnection is added in settings
When the connection is successful and the top panel is automatically folded, you can click the red button on the top bar to quickly disconnect
Certificate selection is optimized , which supports to select more certificate format files.
This project is completely open sourced. If you have any questions during use, you can go to GitHub to submit your questions and opinions, or Fork our MQTT X project, and submit the revised PR to us. We will carefully review and respond shortly.
Non-relational databases (NoSQL) are used for the storage of very large-scale data, such as Google or Facebook, which collects trillions of bits of data per day for their users. These types of data storage do not require a fixed pattern and can be scaled horizontally without redundant operations.
MongoDB is a product between relational database and non-relational database. Among non-relational databases, MongoDB has the most abundant functions and most resembles relational database. MongoDB is written in C++ and is an open source database system based on distributed file storage. MongoDB is designed to provide a scalable, high-performance data storage solution for data storage. It can easily add more nodes under high load to ensure service performance.
MongoDB stores data as a document, and the data structure consists of key => value pairs. MongoDB documents are similar to JSON objects. Field values can contain other documents, arrays, and document arrays.
MongoDB download address:https://www.mongodb.com/download-center/community
This scenario requires that messages satisfying certain conditions under the EMQ X specified topic to be stored in the MongoDB database. In order to facilitate subsequent analysis and retrieval, message content needs to be split and stored.
In this scenario, The information reported by the device is as follows:
Reported topic: cmd/state/:id, the topic id represents the vehicle client ID
Message body:
{
"id": "NXP-058659730253-963945118132721-22", // Client identification
"speed": 32.12, // Cehicle speed
"direction": 198.33212, // Driving direction
"tachometer": 3211, // Engine speed, than is required to be stored when the value is greater than 8000
"dynamical": 8.93, // Instantaneous fuel consumption
"location": { // GPS latitude and longitude data
"lng": 116.296011,
"lat": 40.005091
},
"ts": 1563268202 // Time for reporting
}When the reported data of engine speed value is greater than 8000, the current information is stored for subsequent analysis of the user's vehicle usage.
Create administrative users
At first, log in to MongoDB with an account that has permissions to create users, and add users to emqx_rule_engine_output:
> use emqx_rule_engine_output;
> db.createUser({user: "root", pwd: "public", roles: [{role: "readWrite", db: "emqx_rule_engine_output"}]});Create data table
Log in with the new user and create the data set use_statistics:
$ mongo 127.0.0.1/emqx_rule_engine_output -uroot -ppublic
> db.createCollection("use_statistics"); Confirm the existence of the data table after successful creation:
> show collections
use_statisticsCreate resource
Open the EMQ X Dashboard, go to the Resources page on the left menu, click the New button, select the MongoDB resource type to create:

The network environment of the nodes in the EMQ X cluster may be different. After the resources are created successfully, click the **Status button ** in the list to check the resource connection status of each node . If the resources on the node are unavailable, check whether the configuration is correct and the network connectivity is correct, and click the Reconnect button to manually reconnect.

Create rules
Go to the Rules page on the left menu and click the New button to create the rule. Select the trigger event message publish, which is triggered when the message is published for data processing.
After selecting the trigger event, we can see the optional fields and sample SQL on the interface:

Filter the required fields
The rule engine uses SQL statements to process rule conditions. In this business, we need to select all the fields in payload separately, use the payload.<fieldName> format to select, and also need the information of topic, qos, id in topic context. The current SQL is as follows:
SELECT
payload.id as client_id, payload.speed as speed,
payload.tachometer as tachometer,
payload.ts as ts, id
FROM
"message.publish"
WHERE
topic =~ 't/#'Establish filtering criteria
Using the SQL statement WHERE clause for conditional filtering, in which we need to define two conditions:
Only handle cmd/state/:id topic, use the theme wildcard =~ to filter topic: `topic =~ 'cmd/state/+'
Only handle tachometer > 8000 messages, use the comparator to filter tachometer: payload.tachometer > 8000
Combine the previous step to get the SQL as follows:
SELECT
payload.id as client_id, payload.speed as speed,
payload.tachometer as tachometer,
payload.ts as ts,
id
FROM
"message.publish"
WHERE
topic =~ 'cmd/state/+'
AND payload.tachometer > 8000Use SQL test capabilities for output testing
With the SQL test function, we can check the current SQL processed data output in real time. This function requires us to specify the simulated raw data such as payload.
The payload data is as follows, note to change the tachometer value to satisfy the SQL condition:
{
"id": "NXP-058659730253-963945118132721-22",
"speed": 32.12,
"direction": 198.33212,
"tachometer": 9001,
"dynamical": 8.93,
"location": {
"lng": 116.296011,
"lat": 40.005091
},
"ts": 1563268202
}Click the SQL Test switch button, change topic and payload as the information in the scenario, and click the Test button to check the data output:

The test output data is:
{
"client_id": "NXP-058659730253-963945118132721-22",
"id": "589A429E9572FB44B0000057C0001",
"speed": 32.12,
"tachometer": 9001,
"ts": 1563268202
}The test output is as expected and we can proceed to the next step.
Add response action, store the message to MongoDB
When the input and output of SQL condition is correct, we continue to add response actions, configure to write SQL statement, and store the filtered results in MongoDB.
Click the Add button in the response action, select the Save data to MongoDB action, select the resource just selected, we fill the action statement with the ${fieldName} syntax, insert the data into the database, and finally Click the New button to complete the rule creation.
Collection is configured as: use_statistics
Selector is configured as:
msgid=${id}, client_id=${client_id}, speed=${speed}, tachometer=${tachometer}, ts=${ts}
Expected result
We successfully created a rule that contains a processing action, and the expected result of action is as follows:
When the device reports a message to the cmd/state/:id topic, it will hit SQL when the value of tachometer in the message exceeds 8000, and the number of hits in the rule list is increased by 1;
The use_statistics table in MongoDB emqx_rule_engine_output database will be added with a piece of data, and the value is consistent with the current message.
Test with the Websocket tool in Dashboard
Switch to the Tools => Websocket page and use any information client to connect to EMQ X. After the connection is successful, the sends the following message with the message card:
Topic: md/state/NXP-058659730253-963945118132721-22
Message body:
{
"id": "NXP-058659730253-963945118132721-22",
"speed": 32.12,
"direction": 198.33212,
"tachometer": 8081,
"dynamical": 8.93,
"location": {
"lng": 116.296011,
"lat": 40.005091
},
"ts": 1563268202
}
Click the Send button. At this time, the value of tachometer in the message body satisfies the condition of tachometer > 8000 set above , and the hit statistic value of current rule is increased by one.
Check the data table records in the MongoDB command line to get the following data:

So far, we have implemented a business development using the rules engine to store messages to the MongoDB database.
In various types of IoT projects, the messages generated by devices not only affect devices, but also need to be used by business systems to implement functions such as security audits, traffic accounting, data statistics, and notification triggers, which are easily completed through the following prototype systems:

In this prototype, multiple data channels need to be maintained on EMQ X for each business link to obtain message data from EMQ x according to their own needs. The problems with this solution are:
Each business needs to establish a data channel with EMQ X. The establishment and maintenance of data channels requires additional resource overhead, and the speed of data synchronization seriously affects EMQ X high-speed message exchange;
As business grows, every new business link needs to involve changes in the entire system;
Because the processing speed and timing of each link are different, some services will be blocked when there is a large amount of messages, which will further lead to serious consequences such as data loss and reduced system stability.
The above problems are highly consistent with the problems encountered in current Internet applications, which is that data integration and data synchronization issues between multiple business systems. In Internet applications, message queues are generally integrated to perform operations such as peak clipping, current limiting, and queue processing to decouple data from services. With the help of RabbitMQ, Kafka, RocketMQ, Pulsar and other message and stream middleware bridging functions provided by EMQ X, IoT projects can also use this model to solve the above problems.
This article uses common IoT usage scenarios as an example to introduce how to use EMQ X message middleware and open source flow processing platform Kafka to process massive message data of the Internet of Things, store massive data streams in a highly reliable and fault-tolerant manner and ensure the order of data streams to store message data and effectively provide message data to multiple business links at the same time.
Suppose there is now an intelligent door lock project, all the door locks will report the door lock information every 1 minute or any time when the door lock status changes, such as on / off, and the MQTT topic is reported as follows (QoS = 1):
devices/{client_id}/stateThe format of data sent by each device is JSON, including data such as door lock power, unlocking status, operation result, etc. The content is as follows:
{
"process_id": "7802441525528958",
"action": "unlock",
"battery": 83.4,
"lock_state": 1,
"version": 1.1,
"client_id": "10083618796833171"
}Each door lock subscribes to a unique topic. As a remote unlocking command, MQTT topics are issued as follows (QoS = 1):
devices/{client_id}/commandThe data issued includes unlocking instruction, message encryption verification information, etc.
{
"process_id": "7802441525528958",
"action": "unlock",
"nonce_str": "u7u4p0n8",
"ts": 1574744434,
"sign": "e9f5af7deaa28563"
}The upstream and downstream message data need to be used by the following three business links:
Message notification: Notify the unlocking status to the notification method (mobile phone message, email) bound by the door lock user;
Status monitoring: Analyze and process the status information reported when the door is locked. If the power or status is abnormal, an alarm must be triggered to notify the user;
Security audit: Analyze the uplink and downlink message data, record the user's unlocking behavior, and prevent attacks such as tampering and replay of downlink instructions.
In this solution, EMQ X will uniformly bridge the messages of the above topics to Kafka for usage by business systems, and decouple the business systems from EMQ X.
client_id is the ID of the door lock, which is the MQTT client ID used to connect the door lock to EMQ X.
Kafka is an open source stream processing platform developed by the Apache Software Foundation, written in Scala and Java. The goal of the project is to provide a unified, high-throughput, low-latency platform for processing real-time data.
kafka has the following characteristics:
High throughput: Throughput up to hundreds of thousands and high concurrency, supporting thousands of clients to read and write at the same time;
Low latency: The minimum latency is only a few milliseconds, making it easy to build real-time streaming applications;
Data reliability: The message data is stored safely and distributed in a fault-tolerant cluster, processed in strict accordance with the queue order, and provides message transaction support to ensure data integrity and consumption reliability;
Cluster fault tolerance: n-1 nodes are allowed to fail in multi node replica
Scalability: Support cluster dynamic expansion.
In this solution, Kafka is integrated to provide a message queue and a message bus for message passing between the EMQ X message server and the application. The producer (EMQ X) only adds data to the end of the queue, and each consumer (business link) reads the data in turn and processes it on its own. This architecture considers performance and data reliability, and effectively reduces system complexity and increases system expansion. The prototype of the solution is as follows:

If you are new to EMQ X, we recommend getting started with EMQ X Guide
Visit EMQ website to download the installation package suitable for your operating system. As data persistence is an enterprise function, you need to download EMQ X Enterprise Edition (you can apply for a license trial) . At the time of this writing, the latest version of EMQ X Enterprise Edition is v3.4.4. The startup steps for downloading the zip package are as follows:
## Extract the downloaded installation package
unzip emqx-ee-macosx-v3.4.4.zip
cd emqx
## Copy the license file to the EMQ X designated directory etc /. In terms of the license , you need to apply for a trial or obtain it through a purchase authorization
cp ../emqx.lic ./etc
## Launch EMQ X in console mode
./bin/emqx consoleThe configuration files needed in this article are as follows:
License file, EMQ X Enterprise License file, covered with available licenses:
etc/emqx.lic2. EMQ x Kafka message storage plug-in configuration file is used to configure Kafka connection information and data bridging topics:
etc/plugins/emqx_bridge_kafka.confFill in the plug-in configuration information as follows according to the actual deployment situation. For other configuration items, please read the configuration file carefully and make adjustments or use the default configuration directly.
## Connection address
bridge.kafka.servers = 127.0.0.1:9092
## The hooks that need to be processed are used for message transmission by QoS 1, and ACK hooks can be used
## Comment other unrelated events and messages hooks
## bridge.kafka.hook.client.connected.1 = {"topic":"client_connected"}
## bridge.kafka.hook.client.disconnected.1 = {"topic":"client_disconnected"}
## bridge.kafka.hook.session.subscribed.1 = {"filter":"#", "topic":"session_subscribed"}
## bridge.kafka.hook.session.unsubscribed.1 = {"filter":"#", "topic":"session_unsubscribed"}
## bridge.kafka.hook.message.deliver.1 = {"filter":"#", "topic":"message_deliver"}
## filter is the MQTT topic to be processed, and topoc is the Kafka topic to be written
## Register multiple Hooks for upstream and downstream message processing
## Select publish hooks for reporting instructions
bridge.kafka.hook.message.publish.1 = {"filter":"devices/+/state", "topic":"message_state"}
## Select acked hooks as issue instructions to ensure that messages arrive before they are stored
bridge.kafka.hook.message.acked.1 = {"filter":"devices/+/command", "topic":"message_command"}Kafka installation and initialization
Install Kafka through Docker, and map the data 9092 port for connection. Kafka depends on Zookeeper. The complete installation command is provided below:
## Install Zookeeper
docker run -d --name zookeeper -p 2181 -t wurstmeister/zookeeper
## Install and configure Kafka
docker run -d --name kafka --publish 9092:9092 \
--link zookeeper --env KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181 \
--env KAFKA_ADVERTISED_HOST_NAME=127.0.0.1 \
--env KAFKA_ADVERTISED_PORT=9092 \
wurstmeister/kafka:latestCreate the required topic in Kafka in advance:
## Enter Kafka Docker container
docker exec -it kafka bash
## Upstream data topic message_state
kafka-topics.sh --create --zookeeper zookeeper:2181 --replication-factor 1 --partitions 1 --topic message_state
## Downstream data topic message_command
kafka-topics.sh --create --zookeeper zookeeper:2181 --replication-factor 1 --partitions 1 --topic message_commandAt this point, you can restart EMQ X and launch the plugin to apply the above configuration:
./bin/emqx stop
./bin/emqx start
## Or use console mode for more information
./bin/emqx console
## Launch plugin
./bin/emqx_ctl plugins load emqx_bridge_kafka
## After successful startup, there will be the following prompt
Plugin load emqx_bridge_kafka loaded successfully.The detailed implementation of the three business links in this solution will not be described in detail in this article. This article only needs to ensure that messages are written to Kafka. You can use Kafka's own consumption commands to view the data in the topic:
## Enter Kafka Docker container
docker exec -it kafka bash
## Upstream data topic
kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic message_state --from-beginning
## Open another window to view the topic of downstream data
kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic message_command --from-beginningAfter the command is executed successfully, it will block and wait for the data of the topic to be consumed. We will continue the following operations.
Through the WebSocket tool in the EMQ X Management Console, you can simulate smart door lock up / downstream business data. Opens http: //127.0.0.1: 1883 by the browser to enter EMQ X management console, open Tool -> WebSocket function, enter connection information to establish MQTT connection to simulate door lock device . Client ID in the connection information is designated according to the business designation. In this article, we uses 10083618796833171.
According to business needs, you need to subscribe to the door lock exclusive downstream control topic devices / {client_id} / command, here you need to subscribe to the topicdevices / 10083618796833171 / command and set QoS = 1 :

Send unlocking command to the door lock control topic devices / {client {ID} / command. Here the data is:
Topic: devices/10083618796833171/command
QoS:1
payload:
{
"process_id": "7802441525528958",
"action": "unlock",
"nonce_str": "u7u4p0n8",
"ts": 1574744434,
"sign": "e9f5af7deaa28563"
}After successful issuing, a message can be received in the publish interface of the management console:

At the same time, the Kafka message_command topic consumer will receive one or more messages (the number of EMQ x ack hooks triggers is subject to the actual number of message clients ). The message is in JSON format. The formatted content is as follows :
{
"client_id": "10083618796833171",
"username": "",
"from": "10083618796833171",
"topic": "devices/10083618796833171/command",
"payload": "eyAgICJwcm9jZXNzX2lkIjogIjc4MDI0NDE1MjU1Mjg5NTgiLCAgICJhY3Rpb24iOiAidW5sb2NrIiwgICAibm9uY2Vfc3RyIjogInU3dTRwMG44IiwgICAidHMiOiAxNTc0NzQ0NDM0LCAgICJzaWduIjogImU5ZjVhZjdkZWFhMjg1NjMiIH0=",
"qos": 1,
"node": "[email protected]",
"ts": 1574751635845
}This message contains MQTT receiving / publishing client information and Base64 encoded Payload data:
client_id: receiving client client_id
username: accepting client username
from: Publish client client_id
topic: message publishing target topic
payload: Base64 encoded message payload
qos: message QoS
node: message processing node
ts: hooks trigger timestamps in milliseconds
Send status data to the door lock control topic devices / {client {ID} / state. The data published here is:
Topic:devices/10083618796833171/state
QoS: 1
payload:
{
"process_id": "7802441525528958",
"action": "unlock",
"battery": 83.4,
"lock_state": 1,
"version": 1.1,
"client_id": "10083618796833171"
}After successful reporting, Kafka message_state consumers will receive a message (the number of EMQ x publish hooks triggers is related to the message publishing, regardless of whether the message subject is subscribed and the number of subscriptions). The message is in JSON format, and the content is formatted as follows:
{
"client_id": "10083618796833171",
"username": "",
"topic": "devices/10083618796833171/state",
"payload": "eyAgICJwcm9jZXNzX2lkIjogIjc4MDI0NDE1MjU1Mjg5NTgiLCAgICJhY3Rpb24iOiAidW5sb2NrIiwgICAiYmF0dGVyeSI6IDgzLjQsICAgImxvY2tfc3RhdGUiOiAxLCAgICJ2ZXJzaW9uIjogMS4xLCAgICJjbGllbnRfaWQiOiAiMTAwODM2MTg3OTY4MzMxNzEiIH0=",
"qos": 1,
"node": "[email protected]",
"ts": 1574753026269
}This message only contains MQTT publishing client information and Base64 encoded Payload data:
client_id: publishing client client_id
username: publishing client username
topic: message publishing target topic
payload: Base64 encoded message payload
qos: message QoS
node: message processing node
ts: hooks trigger timestamps in milliseconds
At this point, we have successfully completed all the steps of EMQ X bridging messages to Kafka. After accessing Kafka, the business system can make business judgments based on the number of messages consumed, the client_id of the message publisher / subscriber, and the content of the message payload to achieve the required business functions.
If readers are interested in the performance of this solution, they can use the MQTT-JMeter plugin to test it. It should be noted that the reader needs to ensure that the optimizations and configurations related to EMQ cluster, Kafka cluster, Kafka consumers, and JMeter test cluster are done during the performance test process to obtain the correct and optimal performance test results under the relevant configuration.
Through this article, readers can understand the important role of EMQ X + Kafka IoT message processing solution for message communication and business processing. Using this solution, you can build a loosely coupled, high-performance, high-fault-tolerant IoT message processing platform to achieve efficient data processing safely.
The code of this article implements specific business logic, and readers can expand it according to the business prototype and system architecture provided in this paper. Because the integrated architecture in the IoT project in the message/stream processing of RabbitMQ, RocketMQ, Pulsar which has been supported by EMQ X is similar to Kafka, readers can also use this article as a reference to freely select relevant components for solution integration according to their own technology stack.