├── LICENSE ├── README.md ├── live-demo-kafka-connect-iot-mqtt-connector.adoc ├── pictures ├── Apache_Kafka_Connect_MQTT_Broker_Mosquitto_Integration.png └── MQTT_Apache_Kafka_Integration_Confluent_Proxy_Connect.png └── sensor_generator.sh /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apache Kafka + Kafka Connect + MQTT Connector + Sensor Data 2 | 3 | This demo shows an Internet of Things (IoT) integration example using Apache Kafka + Kafka Connect + MQTT Connector + Sensor Data. 4 | 5 | This project does not include any source code as Kafka Connect allows integration with data sources and sinks just with configuration. 6 | 7 | Example configuration and step-by-step guide can be found below. If you want to find more details about Kafka + MQTT integration, take a look at my slides from Kafka Summit 2018 in San Francisco: [IoT Integration with MQTT and Apache Kafka](https://www.slideshare.net/KaiWaehner/iot-integration-with-mqtt-and-apache-kafka). The video recording is available on the website of Kafka Summit for free: [Kafka MQTT Integration - Video Recording](https://www.confluent.io/kafka-summit-sf18/processing-iot-data-from-end-to-end). 8 | 9 | ## Architecture: Sensor Data via MQTT Broker and Kafka Connect MQTT Connector to Kafka Cluster 10 | 11 | This project focuses on the integration of MQTT sensor data into Kafka via MQTT Broker and Kafka Connect for further processing: 12 | 13 | ![](pictures/Apache_Kafka_Connect_MQTT_Broker_Mosquitto_Integration.png) 14 | 15 | As alternative to using Kafka Connect, you can also leverage Confluent MQTT Proxy to integrate IoT data from IoT devices directly withou the need for a MQTT Broker. See [Deep Learning UDF for KSQL for Streaming Anomaly Detection of MQTT IoT Sensor Data](https://github.com/kaiwaehner/ksql-udf-deep-learning-mqtt-iot) for an example and source code. 16 | 17 | If you want to see the other part (integration with sink applications like Elasticsearch / Grafana), please take a look at the project "[KSQL for streaming IoT data](https://github.com/kaiwaehner/ksql-fork-with-deep-learning-function)", which shows how to realize the integration with ElasticSearch via Kafka Connect. 18 | 19 | ## Live Demo Video - MQTT with Kafka Connect and MQTT Proxy 20 | 21 | If you want to see Apache Kafka / MQTT integration in a video, please check out the following 15min recording showing a demo my two Github examples: 22 | 23 | [![Apache Kafka + MQTT Integration](pictures/MQTT_Apache_Kafka_Integration_Confluent_Proxy_Connect.png)](https://www.youtube.com/watch?v=L38-6ilGeKE) 24 | 25 | ## Kafka Connect Configuration (No Source Code Needed!) 26 | 27 | Here is the full configuration for the MQTT Connector for Kafka Connect's Standalone mode, which we use with Confluent CLI for a local setup: 28 | 29 | name=MqttSourceConnector1 30 | connector.class=io.confluent.connect.mqtt.MqttSourceConnector 31 | tasks.max=1 32 | mqtt.server.uri=< Required Configuration > 33 | mqtt.topics=< Required Configuration > 34 | 35 | For distributed mode, you can use the same configuration with REST API: 36 | 37 | curl -s -X POST -H 'Content-Type: application/json' http://localhost:8083/connectors -d '{ 38 | "name" : "< Required Configuration >", 39 | "config" : { 40 | "connector.class" : "io.confluent.connect.mqtt.MqttSourceConnector", 41 | "tasks.max" : "1", 42 | "mqtt.server.uri" : "< Required Configuration >", 43 | "mqtt.topics" : "< Required Configuration >", 44 | "kafka.topics" : "< Required Configuration >" 45 | } 46 | }' 47 | 48 | The documentation explains the [differences between standalone and distributed Kafka Connect mode](https://docs.confluent.io/current/connect/concepts.html#connect-concepts). In short: Standalone mode is the simplest mode, where a single process is responsible for executing all connectors and tasks. Distributed mode is used in most production scenarios and provides scalability and automatic fault tolerance for Kafka Connect. You can also use distributed mode for local development leveraging its advantages like a REST API even if you just have one single Connect instance (and you can scale it later easily without complex changes). We will use distributed mode in this project therefore. 49 | 50 | Confluent documentation contains more details about installing and using [Confluent's MQTT Connector](https://docs.confluent.io/current/connect/kafka-connect-mqtt). 51 | 52 | ## How to run it? 53 | 54 | ### Requirements 55 | 56 | - Java 8 57 | - [Confluent Platform 5.0+](https://www.confluent.io/download/) (Confluent Enterprise if you want to use the Confluent MQTT Proxy, Confluent Open Source if you just want to run the KSQL UDF and send data via kafkacat instead of MQTT) 58 | - MQTT Client and Broker (this demo uses [Mosquitto](https://mosquitto.org/download/)) 59 | - [Confluent MQTT Connector](https://www.confluent.io/connector/kafka-connect-mqtt/) (a Kafka Connect based connector to send and receive MQTT messages) - Very easy installation via Confluent Hub, just one command: 60 | 61 | confluent-hub install confluentinc/kafka-connect-mqtt:1.2.3 62 | 63 | - Optional: [MQTT.fx](https://mqttfx.jensd.de/) (a nice, simple UI to test MQTT pub/sub; not required - just makes life more comfortable) 64 | 65 | The code is developed and tested on Mac and Linux operating systems. As Kafka does not support and work well on Windows, this is not tested at all. 66 | 67 | ### Step-by-step demo 68 | 69 | Follow these steps to [configure the MQTT Connector, start all components, generate MQTT sensor data and consume it from a Kafka consumer](https://github.com/kaiwaehner/kafka-connect-iot-mqtt-connector-example/blob/master/live-demo-kafka-connect-iot-mqtt-connector.adoc). -------------------------------------------------------------------------------- /live-demo-kafka-connect-iot-mqtt-connector.adoc: -------------------------------------------------------------------------------- 1 | = Apache Kafka / Kafka Connect / MQTT / Mosquitto Live Demo 2 | 3 | Kai Waehner 4 | 22 Jul 2019 5 | 6 | This script assumes that all components (Zookeeper, Kafka, Connect, MQTT Broker) use default values. 7 | 8 | Please note that Confluent CLI changed with Confluent Platform 5.3+: 'confluent local start' 9 | Confluent Platform 5.2 and earlier: 'confluent start'. This guide is tested with Confluent Platform 5.4.0. 10 | 11 | == Starting backend services 12 | 13 | Start the MQTT Broker and test publish / subscribe with 'dummy' topic: 14 | 15 | [source,bash] 16 | ---- 17 | brew services start mosquitto 18 | mosquitto_sub -h 127.0.0.1 -t dummy 19 | mosquitto_pub -h 127.0.0.1 -t dummy -m "Hello world" 20 | ---- 21 | 22 | _Make sure to have Confluent folder on PATH. Otherwise, go to `$CONFLUENT_INSTALL/bin` to execute commands these commands._ 23 | 24 | Start Kafka Connect and dependencies (Kafka, Zookeeper, Schema Registry): 25 | 26 | [source,bash] 27 | ---- 28 | confluent local start connect 29 | ---- 30 | 31 | == Create and deploy MQTT Connector Instance 32 | 33 | We use Kafka Connect in distributed mode via REST call (only possible when Connect is running). This is highly recommend as you can do this for one single node (like in this example, but also deploy a distributed Connect cluster). 34 | 35 | Important: If you copy&paste the below curl command, make sure that you copy it "plaintext only". Otherwise, it might not work. On my Mac, I copy the command to a text editor first and from there to the command line to execute it. 36 | 37 | curl -s -X POST -H 'Content-Type: application/json' http://localhost:8083/connectors -d '{ 38 | "name" : "mqtt-source", 39 | "config" : { 40 | "connector.class" : "io.confluent.connect.mqtt.MqttSourceConnector", 41 | "tasks.max" : "1", 42 | "mqtt.server.uri" : "tcp://127.0.0.1:1883", 43 | "mqtt.topics" : "temperature", 44 | "kafka.topic" : "mqtt.temperature", 45 | "confluent.topic.bootstrap.servers": "localhost:9092", 46 | "confluent.topic.replication.factor": "1", 47 | "confluent.license":"" 48 | } 49 | }' 50 | 51 | Please note that "distributed mode" can also be used for one single Connect instance like when using Confluent CLI. You could also use standalone mode (see more details at the end of the file). 52 | 53 | == Check Status of Connector 54 | Check if connector is loaded and status is 'RUNNING': 55 | 56 | [source,bash] 57 | ---- 58 | // REST 59 | curl -s "http://localhost:8083/connectors" 60 | curl -s "http://localhost:8083/connectors/mqtt-source/status" 61 | curl -s -X DELETE localhost:8083/connectors/mqtt-source 62 | 63 | // Confluent CLI 64 | confluent local status connectors 65 | confluent local status mqtt-source 66 | ---- 67 | 68 | Next, create a Kafka Topic for consuming the MQTT messages via the MQTT Connector (needs to be the same as in the Connector Config): 69 | 70 | [source,bash] 71 | ---- 72 | kafka-topics --create --bootstrap-server localhost:9092 --replication-factor 1 --partitions 1 --topic mqtt.temperature 73 | ---- 74 | 75 | 76 | == Starting Client services (Kafka Consumer and MQTT Publisher) 77 | 78 | Use a CLI tool such as `mosquitto_sub` from the shell prompt to consume from MQTT topic (to ensure the MQTT infrastructure works): 79 | 80 | [source,bash] 81 | ---- 82 | $ mosquitto_sub -h 127.0.0.1 -t temperature 83 | 99999,4.193955593608823 84 | 99999,5.363750640274894 85 | 99999,7.292092517069437 86 | [...] 87 | ---- 88 | 89 | Use a CLI tool such as `kafka-console-consumer` from the shell prompt to consume from Kafka topic: 90 | 91 | [source,bash] 92 | ---- 93 | $ kafka-console-consumer --bootstrap-server localhost:9092 --topic mqtt.temperature --property print.key=true --from-beginning 94 | 99999,4.193955593608823 95 | 99999,5.363750640274894 96 | 99999,7.292092517069437 97 | [...] 98 | ---- 99 | 100 | Send a MQTT message to the MQTT Broker, using `mosquitto_pub`: 101 | 102 | [source,bash] 103 | ---- 104 | mosquitto_pub -h 127.0.0.1 -p 1883 -t temperature -q 2 -m "99999,2.10#" 105 | 106 | // Send fraud messages. These are routed to a different Kafka Topic if you used the Connector config with the SMT above. 107 | mosquitto_pub -h 127.0.0.1 -p 1883 -t temperature -q 2 -m "fraud" 108 | 109 | mosquitto_pub -h 127.0.0.1 -p 1883 -t temperature -q 2 -m "99999,2.10# 2.13# 2.19# 2.28# 2.44# 2.62# 2.80# 3.04# 3.36# 3.69# 3.97# 4.24# 4.53#4.80# 5.02# 5.21# 5.40# 5.57# 5.71# 5.79# 5.86# 5.92# 5.98# 6.02# 6.06# 6.08# 6.14# 6.18# 6.22# 6.27#6.32# 6.35# 6.38# 6.45# 6.49# 6.53# 6.57# 6.64# 6.70# 6.73# 6.78# 6.83# 6.88# 6.92# 6.94# 6.98# 7.01#7.03# 7.05# 7.06# 7.07# 7.08# 7.06# 7.04# 7.03# 6.99# 6.94# 6.88# 6.83# 6.77# 6.69# 6.60# 6.53# 6.45#6.36# 6.27# 6.19# 6.11# 6.03# 5.94# 5.88# 5.81# 5.75# 5.68# 5.62# 5.61# 5.54# 5.49# 5.45# 5.42# 5.38#5.34# 5.31# 5.30# 5.29# 5.26# 5.23# 5.23# 5.22# 5.20# 5.19# 5.18# 5.19# 5.17# 5.15# 5.14# 5.17# 5.16#5.15# 5.15# 5.15# 5.14# 5.14# 5.14# 5.15# 5.14# 5.14# 5.13# 5.15# 5.15# 5.15# 5.14# 5.16# 5.15# 5.15#5.14# 5.14# 5.15# 5.15# 5.14# 5.13# 5.14# 5.14# 5.11# 5.12# 5.12# 5.12# 5.09# 5.09# 5.09# 5.10# 5.08# 5.08# 5.08# 5.08# 5.06# 5.05# 5.06# 5.07# 5.05# 5.03# 5.03# 5.04# 5.03# 5.01# 5.01# 5.02# 5.01# 5.01#5.00# 5.00# 5.02# 5.01# 4.98# 5.00# 5.00# 5.00# 4.99# 5.00# 5.01# 5.02# 5.01# 5.03# 5.03# 5.02# 5.02#5.04# 5.04# 5.04# 5.02# 5.02# 5.01# 4.99# 4.98# 4.96# 4.96# 4.96# 4.94# 4.93# 4.93# 4.93# 4.93# 4.93# 5.02# 5.27# 5.80# 5.94# 5.58# 5.39# 5.32# 5.25# 5.21# 5.13# 4.97# 4.71# 4.39# 4.05# 3.69# 3.32# 3.05#2.99# 2.74# 2.61# 2.47# 2.35# 2.26# 2.20# 2.15# 2.10# 2.08" 110 | ---- 111 | 112 | Now run a script to generate and publish a continuous stream of MQTT messages: 113 | 114 | [source,bash] 115 | ---- 116 | ./sensor_generator.sh 117 | ---- 118 | 119 | == Stop services and destroy test data 120 | 121 | Stop the sensor_generator script with Control-C. 122 | 123 | Stop the Kafka and MQTT consumers with Control-C. 124 | 125 | Finally, stop the backend services: 126 | 127 | [source,bash] 128 | ---- 129 | brew services stop mosquitto 130 | confluent local destroy 131 | ---- 132 | 133 | == Errors? Problems? 134 | Here are some helpful commands if you have problems starting mosquitto or finding out if it is running and on which port: 135 | 136 | === Find the system process and port of MQTT Broker 137 | 138 | [source,bash] 139 | ---- 140 | // If brew does not work (or you are not on Mac): 141 | // Start Mosquitto 142 | /usr/local/sbin/mosquitto 143 | 144 | // Start Moquitto (being in PATH) with a specific config file 145 | mosquitto -c /usr/local/etc/mosquitto/mosquitto.conf 146 | 147 | // Mosquitto Broker running? => Find process: 148 | ps -ef | grep mosquitto 149 | 150 | // Which port? 151 | lsof -n -P -i4|grep LISTEN 152 | ---- 153 | 154 | === Change log level of Kafka Connect 155 | Logging is a worker-level configuration, so there's no way to set it per connector instance. 156 | To adjust the log levels you modify the `connect-log4j.properties` file and restart your worker. 157 | 158 | Default log level is ERROR. You can change to INFO or DEBUG. 159 | 160 | [source,bash] 161 | ---- 162 | vi /Users/kai.waehner/confluent-5.1.0/etc/kafka/connect-log4j.properties 163 | // => Change log level 164 | 165 | // Restart Kafka Connect worker 166 | confluent local stop connect 167 | confluent local start connect 168 | 169 | // Check the Connect log: 170 | confluent local log kafka 171 | ---- 172 | 173 | 174 | 175 | == Configuration of Standalone Mode via Properties File 176 | 177 | As alternative to a HTTP call, you could also configure a property file for standalone mode. However, as REST can also be used for one single instance (in distributed mode), I always use this option to configure Kafka Connect. But here is some more information about using a property file instead of HTTP to configure Connect (in standalone mode). 178 | 179 | Configure MQTT Connector properties file (for Kafka Connect standalone mode) `/Users/kai.waehner/confluent-5.0.0/share/confluent-hub-components/confluentinc-kafka-connect-mqtt/etc/source-anonymous.properties` with your values for 180 | 181 | - MQTT Broker URL 182 | - MQTT Topic(s) to consume from (comma-separated list) 183 | - Kafka Topic Mapping (prefix) 184 | 185 | For example, if you want to consume the MQTT topics `temperature` and `humidity`, and you want the Kafka topics to be `mqtt.temperature` and `mqtt.humidity`, then do 186 | 187 | [source,bash] 188 | ---- 189 | "mqtt.topics" : "temperature,humidity", 190 | "kafka.topics" : "mqtt.temperature" 191 | ---- 192 | 193 | This needs to be done before you start Kafka Connect. Example: 194 | 195 | [source,bash] 196 | ---- 197 | name=mqtt-source 198 | tasks.max=1 199 | connector.class=io.confluent.connect.mqtt.MqttSourceConnector 200 | mqtt.server.uri=tcp://127.0.0.1:32790 201 | mqtt.topics=temperature 202 | kafka.topics=mqtt.temperature 203 | ---- 204 | -------------------------------------------------------------------------------- /pictures/Apache_Kafka_Connect_MQTT_Broker_Mosquitto_Integration.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaiwaehner/kafka-connect-iot-mqtt-connector-example/99b82b50f3e16303fc6c082b986a40768ac18b9b/pictures/Apache_Kafka_Connect_MQTT_Broker_Mosquitto_Integration.png -------------------------------------------------------------------------------- /pictures/MQTT_Apache_Kafka_Integration_Confluent_Proxy_Connect.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaiwaehner/kafka-connect-iot-mqtt-connector-example/99b82b50f3e16303fc6c082b986a40768ac18b9b/pictures/MQTT_Apache_Kafka_Integration_Confluent_Proxy_Connect.png -------------------------------------------------------------------------------- /sensor_generator.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | #Log levels 4 | OFF=0 5 | FATAL=100 6 | ERROR=200 7 | WARN=300 8 | INFO=400 9 | DEBUG=500 10 | 11 | #Sensor value range 12 | MINVAL=2 13 | MAXVAL=8 14 | DECVAL=2 15 | EVENTID=99999 16 | 17 | #Measurement array 18 | ASIZE=210 19 | ADELIM="#" 20 | initVal="" 21 | msgSize=0 22 | msgArr="" 23 | arrLen=0 24 | msgNr=0 25 | 26 | #MQTT Client command 27 | PUBEXE="mosquitto_pub" 28 | HOST="0.0.0.0" 29 | PORT=1883 30 | TOPIC="temperature" 31 | QOS=2 32 | 33 | #Set log level for the script 34 | LOGLEVEL=$INFO 35 | 36 | log() 37 | { # This function will log the input message to STDOUT if the log level for the message is lower or equal to the log level set for the script 38 | local logMessage=$1 39 | local msgLevel=$2 40 | 41 | if [ $LOGLEVEL -ge $msgLevel ] 42 | then 43 | echo -e $logMessage 44 | fi 45 | } 46 | 47 | initialVal() 48 | { # This function initialises a sensor value for the signal we want to generate 49 | 50 | local initBase=-1 51 | local initFract=0 52 | local decMod=$((10**$DECVAL)) 53 | log "Modulus divisor value for decimal generation is: $decMod" $DEBUG 54 | 55 | until [ $initBase -ge $MINVAL ] && [ $initBase -lt $MAXVAL ] 56 | do 57 | initBase=$((RANDOM % $MAXVAL)) 58 | log "Ïnitial generated sensor base value is: $initBase" $DEBUG 59 | done 60 | 61 | initFract=$(($RANDOM % $decMod)) 62 | 63 | # Prepend 0's for fractions with a shorter length then the nr of defined decimails0 64 | while [ ${#initFract} -lt $DECVAL ] 65 | do 66 | initFract=0${initFract} 67 | log "Random generated number was smaller than 100, appending it with zeros. Current number value is $initFract" $DEBUG 68 | done 69 | 70 | initVal="${initBase}.${initFract}" 71 | log "Ïnitial generated sensor value is: $initVal" $DEBUG 72 | return 0 73 | } 74 | 75 | genInterval() 76 | { # This function will generate an increasing or decreasing interval of sensor reading values, based on its input parameters of startReading, intervalSize and intervalDirection 77 | 78 | local sensReading="`echo $1 | cut -f 1 -d '.'``echo $1 | cut -f 2 -d '.'`" 79 | log "Last sensor reading value: $sensReading" $DEBUG 80 | local intSize=$2 81 | log "Interval size: $intSize" $DEBUG 82 | local intDirection=$3 83 | local incrDiv=0 84 | local readIncr=-1 85 | local newReading 86 | local intArr="" 87 | local i=0 88 | 89 | while [ $i -lt $intSize ] 90 | do 91 | # Generate an reading value increment size (choice between 1/100th or 1/10th multple) 92 | incrDiv=$((10**$(($(($RANDOM % 2))+1)))) 93 | log "Increment divisor: $incrDiv" $DEBUG 94 | 95 | # Generate reading value increment 96 | readIncr=$(($RANDOM % $incrDiv)) 97 | 98 | if [ $intDirection -eq 0 ] 99 | then 100 | readIncr=$(($readIncr * -1)) 101 | fi 102 | log "Reading increment is : $readIncr" $DEBUG 103 | 104 | #Calculate new reading 105 | sensReading=$(($sensReading + $readIncr)) 106 | log "New generated reading number in interval is: $sensReading" $DEBUG 107 | 108 | newReading="`echo $sensReading | cut -c 1`.`echo $sensReading|cut -c 2-3`" 109 | log "New generated reading value in interval is: $newReading" $DEBUG 110 | 111 | # Swap the interval direction in case we've crossed a boundary value 112 | if [ $intDirection -eq 0 ] && [ $sensReading -le $(($MINVAL * 100)) ] 113 | then 114 | intDirection=1 115 | elif [ $intDirection -eq 1 ] && [ $sensReading -ge $(($MAXVAL * 100)) ] 116 | then 117 | intDirection=0 118 | fi 119 | 120 | intArr="${intArr}${newReading}${ADELIM} " 121 | log "Current sensor readings interval array: $intArr" $DEBUG 122 | i=$(($i+1)) 123 | done 124 | msgArr=${msgArr}${intArr} 125 | msgSize=$(($msgSize + $intSize)) 126 | return 0 127 | } 128 | 129 | 130 | randomTemp() 131 | { # This function will generate a random temperature value between 0 and 10 and two decimals precision 132 | 133 | local temp="" 134 | # Generate random number 135 | local rNum=$RANDOM 136 | log "Random generated number : $rNum" $DEBUG 137 | 138 | # Append 0's for random numbers smaller than 100 139 | while [ ${#rNum} -lt 3 ] 140 | do 141 | rNum=${rNum}0 142 | log "Random generated number was smaller than 100, appending it with zeros. Current number value is $rNum" $DEBUG 143 | done 144 | 145 | # Construct random temperature value from first 3 digits of random number 146 | temp="`echo $rNum|cut -c 1`.`echo $rNum|cut -c 2-3`" 147 | log "Random generated temperature value of $temp" $DEBUG 148 | 149 | return $temp 150 | } 151 | 152 | # We are not in the main program. Let's first initialize a first measurement value 153 | initialVal 154 | 155 | if [ $? -eq 0 ] 156 | then 157 | log "initialVal function returned initial sensor value : $initVal" $DEBUG 158 | 159 | # Now we will start the endless loop to generate sensorvalues in ranges 160 | while true; 161 | do 162 | if [ $msgSize -eq 0 ] 163 | then 164 | #initialise a new message array 165 | msgNr=$(($msgNr + 1)) 166 | msgArr="${EVENTID}," 167 | fi 168 | 169 | # Now lets generate sensor value ranges that increase or decrease from the current sensor value 170 | rangeLength=$(($(($RANDOM % 10))+1)) # a value between 1 and 10 171 | if [ $ASIZE -lt $(($msgSize + $rangeLength)) ] 172 | then 173 | rangeLength=$(($ASIZE - $msgSize)) 174 | fi 175 | log "Length for the interval is: $rangeLength" $DEBUG 176 | 177 | rangeDir=$((RANDOM % 2)) # 0 is decreasing interval and 1 is an increasing interval 178 | log "Direction for the interval is: $rangeDir" $DEBUG 179 | 180 | genInterval $initVal $rangeLength $rangeDir 181 | 182 | if [ $? -eq 0 ] 183 | then 184 | arrLen=${#msgArr} 185 | log "Current measurements array for next message to sent is: $msgArr" $DEBUG 186 | if [ $msgSize -eq $ASIZE ] 187 | then 188 | # We need to prepare the message for sending, by removing the last two characters (delimter) 189 | msgArr=`echo $msgArr | cut -c 1-$(($arrLen - 2))` 190 | # log "${PUBEXE} -h ${HOST} -p ${PORT} -t ${TOPIC} -q ${QOS} -m \"${msgArr}\"" $DEBUG 191 | $(${PUBEXE} -h ${HOST} -p ${PORT} -t ${TOPIC} -q ${QOS} -m "${msgArr}") 192 | 193 | if [ $? -eq 0 ] 194 | then 195 | log "New message published, nr: $msgNr" $INFO 196 | msgSize=0 197 | 198 | log "Current message measurement array has a length of : $arrLen" $DEBUG 199 | initVal=`echo $msgArr | cut -c $(($arrLen - 5))-$(($arrLen))` 200 | log "New start measurement value for next message is : $initVal" $DEBUG 201 | fi 202 | else 203 | # We need take the last measurement from the interval and set it as the initialisation value for the next interval 204 | log "Current message measurement array has a length of : $arrLen" $DEBUG 205 | initVal=`echo $msgArr | cut -c $(($arrLen - 5))-$(($arrLen - 2))` 206 | log "New start measurement value for next interval is : $initVal" $DEBUG 207 | fi 208 | fi 209 | done 210 | fi 211 | --------------------------------------------------------------------------------