Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 09c5880

Browse files
committedJun 6, 2024·
feat(console): Added component with mqtt command
1 parent 5d69d3f commit 09c5880

22 files changed

+1223
-0
lines changed
 

‎components/console_cmd_mqtt/.cz.yaml

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
commitizen:
3+
bump_message: 'bump(console): $current_version -> $new_version'
4+
pre_bump_hooks: python ../../ci/changelog.py console_cmd_mqtt
5+
tag_format: console_cmd_mqtt-v$version
6+
version: 1.0.0
7+
version_files:
8+
- idf_component.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
idf_component_register(SRCS "console_mqtt.c"
2+
INCLUDE_DIRS "."
3+
PRIV_REQUIRES esp_netif console mqtt)
4+
5+
if(CONFIG_MQTT_CMD_AUTO_REGISTRATION)
6+
target_link_libraries(${COMPONENT_LIB} PRIVATE "-u console_cmd_mqtt_register")
7+
endif()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
menu "MQTT Configuration"
2+
3+
config MQTT_CMD_AUTO_REGISTRATION
4+
bool "Enable Console command mqtt Auto-registration"
5+
default y
6+
help
7+
Enabling this allows for the autoregistration of the wifi command.
8+
9+
config MQTT_BROKER_URL
10+
string "Broker URL or IP address"
11+
default "mqtt://mqtt.eclipseprojects.io"
12+
help
13+
URL or IP address of the broker to connect to
14+
15+
endmenu

‎components/console_cmd_mqtt/LICENSE

+201
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
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.

‎components/console_cmd_mqtt/README.md

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Console command mqtt
2+
The component provides a console where mqtt commands can be executed.
3+
4+
5+
## MQTT Configuration:
6+
1. Broker: Use menuconfig **"MQTT Configuration"** to configure the broker url.
7+
8+
9+
## API
10+
11+
### Steps to enable console in an example code:
12+
1. Add this component to your project using ```idf.py add-dependency``` command.
13+
2. In the main file of the example, add the following line:
14+
```c
15+
#include "console_mqtt.h"
16+
```
17+
3. Ensure esp-netif and NVS flash is initialized and default event loop is created in your app_main():
18+
```c
19+
ESP_ERROR_CHECK(esp_netif_init());
20+
ESP_ERROR_CHECK(esp_event_loop_create_default());
21+
```
22+
4. In your app_main() function, add the following line as the last line:
23+
```c
24+
ESP_ERROR_CHECK(console_cmd_init()); // Initialize console
25+
26+
// Register all plugin command added to your project
27+
ESP_ERROR_CHECK(console_cmd_all_register());
28+
29+
// To register only mqtt command skip calling console_cmd_all_register()
30+
ESP_ERROR_CHECK(console_cmd_mqtt_register());
31+
32+
ESP_ERROR_CHECK(console_cmd_start()); // Start console
33+
```
34+
35+
Note: Auto-registration of a specific plugin command can be disabled from menuconfig.
36+
37+
### Certificate Integration for Mutual Authentication
38+
To enhance security and enable secure communication over MQTT, we have introduced the option to set certificates within the MQTT console library. With the new `set_mqtt_certs()` function, users can now conveniently supply client and server certificates along with their respective keys.
39+
```c
40+
set_mqtt_certs(client_cert_pem_start, client_cert_pem_end, client_key_pem_start,
41+
client_key_pem_end, server_cert_pem_start, server_cert_pem_end);
42+
```
43+
This function takes client certificate, client key and server certificate allowing users to specify the necessary certificate and key data. To utilize these certificates, users need to include additional arguments when establishing MQTT connections using the library. Specifically, users should provide the `--cert`, `--key`, and `--cafile` options along with the MQTT connection command.
44+
45+
### Adding a plugin command or component:
46+
To add a plugin command or any component from IDF component manager into your project, simply include an entry within the `idf_component.yml` file.
47+
48+
For more details refer [IDF Component Manager](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/tools/idf-component-manager.html)
49+
50+
51+
## Suported command:
52+
53+
### mqtt:
54+
```
55+
mqtt [-CD] [-h <host>] [-u <username>] [-P <password>]
56+
mqtt command
57+
-C, --connect Connect to a broker
58+
-h, --host=<host> Specify the host uri to connect to
59+
-u, --username=<username> Provide a username to be used for authenticating with the broker
60+
-P, --password=<password> Provide a password to be used for authenticating with the broker
61+
, --cert Define the PEM encoded certificate for this client, if required by the server
62+
, --key Define the PEM encoded private key for this client, if required by the server
63+
, --cafile Define the PEM encoded CA certificates that are trusted
64+
-D, --disconnect Disconnect from the broker
65+
66+
mqtt_pub [-t <topic>] [-m <message>]
67+
mqtt publish command
68+
-t, --topic=<topic> Topic to Subscribe/Publish
69+
-m, --message=<message> Message to Publish
70+
71+
mqtt_sub [-U] [-t <topic>]
72+
mqtt subscribe command
73+
-t, --topic=<topic> Topic to Subscribe/Publish
74+
-U, --unsubscribe Unsubscribe from a topic
75+
```

‎components/console_cmd_mqtt/console_mqtt.c

+445
Large diffs are not rendered by default.
+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
3+
*
4+
* SPDX-License-Identifier: Apache-2.0
5+
*/
6+
7+
#pragma once
8+
9+
#include "console_simple_init.h"
10+
11+
#ifdef __cplusplus
12+
extern "C" {
13+
#endif
14+
15+
/**
16+
* @brief Registers the mqtt command.
17+
*
18+
* @return
19+
* - esp_err_t
20+
*/
21+
esp_err_t console_cmd_mqtt_register(void);
22+
23+
24+
/**
25+
* @brief Set MQTT client certificates
26+
*
27+
* This function sets the MQTT client certificates for secure communication.
28+
* The function takes the PEM(Privacy Enhanced Mail) encoded certificates and keys as arguments.
29+
*
30+
* @param client_cert_pem_start_i Pointer to the beginning of the client certificate PEM data.
31+
* @param client_cert_pem_end_i Pointer to the end of the client certificate PEM data.
32+
* @param client_key_pem_start_i Pointer to the beginning of the client key PEM data.
33+
* @param client_key_pem_end_i Pointer to the end of the client key PEM data.
34+
* @param server_cert_pem_start_i Pointer to the beginning of the server certificate PEM data.
35+
* @param server_cert_pem_end_i Pointer to the end of the server certificate PEM data.
36+
*
37+
* @return
38+
* ESP_OK on success
39+
* ESP_ERR_INVALID_ARG on invalid arguments
40+
*/
41+
esp_err_t set_mqtt_certs(const uint8_t *client_cert_pem_start_i, const uint8_t *client_cert_pem_end_i,
42+
const uint8_t *client_key_pem_start_i, const uint8_t *client_key_pem_end_i,
43+
const uint8_t *server_cert_pem_start_i, const uint8_t *server_cert_pem_end_i);
44+
45+
#ifdef __cplusplus
46+
}
47+
#endif
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# For more information about build system see
2+
# https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html
3+
# The following five lines of boilerplate have to be in your project's
4+
# CMakeLists in this exact order for cmake to work correctly
5+
cmake_minimum_required(VERSION 3.16)
6+
7+
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
8+
project(mqtt-basic)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# mqtt command
2+
3+
## Overview
4+
5+
This example demonstrates the usage of mqtt command component.
6+
To set up the example with Wi-Fi, Ethernet, or both, go to the project configuration menu (idf.py menuconfig) and choose "Example Connection Configuration." Then pick either Wi-Fi, Ethernet, or both under "Connect using.
7+
8+
### Command Usage:
9+
```
10+
esp> help
11+
help [<string>]
12+
Print the summary of all registered commands if no arguments are given,
13+
otherwise print summary of given command.
14+
<string> Name of command
15+
16+
mqtt [-CD] [-h <host>] [-u <username>] [-P <password>]
17+
mqtt command
18+
-C, --connect Connect to a broker
19+
-h, --host=<host> Specify the host uri to connect to
20+
-u, --username=<username> Provide a username to be used for authenticating with the broker
21+
-P, --password=<password> Provide a password to be used for authenticating with the broker
22+
, --cert Define the PEM encoded certificate for this client, if required by the server
23+
, --key Define the PEM encoded private key for this client, if required by the server
24+
, --cafile Define the PEM encoded CA certificates that are trusted
25+
-D, --disconnect Disconnect from the broker
26+
27+
mqtt_pub [-t <topic>] [-m <message>]
28+
mqtt publish command
29+
-t, --topic=<topic> Topic to Subscribe/Publish
30+
-m, --message=<message> Message to Publish
31+
32+
mqtt_sub [-U] [-t <topic>]
33+
mqtt subscribe command
34+
-t, --topic=<topic> Topic to Subscribe/Publish
35+
-U, --unsubscribe Unsubscribe from a topic
36+
```
37+
38+
#### Connect/Disconnect:
39+
```
40+
esp> mqtt -h mqtt://192.168.50.185 -C
41+
I (1678559) console_mqtt: broker: mqtt://192.168.50.185
42+
I (1678559) console_mqtt: MQTT_EVENT_BEFORE_CONNECT
43+
esp> I (1678849) console_mqtt: MQTT_EVENT_CONNECTED
44+
esp>
45+
esp> mqtt -D
46+
I (1691939) console_mqtt: mqtt client disconnected
47+
```
48+
49+
#### Subscribe/Unsubscribe:
50+
```
51+
esp> mqtt_sub -t test0
52+
I (897289) console_mqtt: Subscribe successful, msg_id=57425, topic=test0
53+
esp> I (897799) console_mqtt: MQTT_EVENT_SUBSCRIBED, msg_id=57425
54+
esp>
55+
esp> mqtt_sub -U -t test0
56+
I (902009) console_mqtt: Unsubscribe successful, msg_id=27663, topic=test0
57+
esp> I (902509) console_mqtt: MQTT_EVENT_UNSUBSCRIBED, msg_id=27663
58+
```
59+
60+
#### Publish:
61+
```
62+
esp> mqtt_pub -t test0 -m "Hello, Testing 123"
63+
I (999469) console_mqtt: Publish successful, msg_id=55776, topic=test0, data=Hello, Testing 123
64+
I (1000009) console_mqtt: MQTT_EVENT_PUBLISHED, msg_id=55776
65+
esp>
66+
```
67+
68+
#### Receiving Data Event:
69+
```
70+
esp> I (999999) console_mqtt: MQTT_EVENT_DATA
71+
I (999999) console_mqtt: TOPIC=test0
72+
73+
I (999999) console_mqtt: DATA=Hello, Testing 123
74+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
idf_component_register(SRCS "mqtt-basic.c"
2+
INCLUDE_DIRS ".")
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
dependencies:
2+
idf:
3+
version: ">=5.0"
4+
protocol_examples_common:
5+
path: ${IDF_PATH}/examples/common_components/protocol_examples_common
6+
console_cmd_mqtt:
7+
version: "*"
8+
override_path: '../../../'
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
3+
*
4+
* SPDX-License-Identifier: Unlicense OR CC0-1.0
5+
*/
6+
#include <stdio.h>
7+
#include "esp_netif.h"
8+
#include "nvs_flash.h"
9+
#include "esp_event.h"
10+
#include "console_mqtt.h"
11+
#include "protocol_examples_common.h"
12+
13+
14+
void app_main(void)
15+
{
16+
ESP_ERROR_CHECK(esp_netif_init());
17+
ESP_ERROR_CHECK(esp_event_loop_create_default());
18+
esp_err_t ret = nvs_flash_init(); //Initialize NVS
19+
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
20+
ESP_ERROR_CHECK(nvs_flash_erase());
21+
ret = nvs_flash_init();
22+
}
23+
ESP_ERROR_CHECK(ret);
24+
25+
/* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
26+
* Read "Establishing Wi-Fi or Ethernet Connection" section in
27+
* ${IDF_PATH}/examples/protocols/README.md for more information about this function.
28+
*/
29+
ESP_ERROR_CHECK(example_connect());
30+
31+
/* Initialize console REPL */
32+
ESP_ERROR_CHECK(console_cmd_init());
33+
34+
/* Register mqtt command */
35+
ESP_ERROR_CHECK(console_cmd_all_register());
36+
37+
// start console REPL
38+
ESP_ERROR_CHECK(console_cmd_start());
39+
40+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD
2+
# SPDX-License-Identifier: Unlicense OR CC0-1.0
3+
4+
# -*- coding: utf-8 -*-
5+
import pytest
6+
7+
8+
@pytest.mark.esp32
9+
def test_examples_mqtt_command(dut):
10+
dut.expect('esp>', timeout=30)
11+
dut.write('help mqtt')
12+
dut.expect('mqtt [-CD] [-h <host>] [-u <username>] [-P <password>]', timeout=30)
13+
pass
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# The following five lines of boilerplate have to be in your project's
2+
# CMakeLists in this exact order for cmake to work correctly
3+
cmake_minimum_required(VERSION 3.16)
4+
5+
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
6+
project(ssl_mutual_auth)
7+
8+
# Certs for mqtts://test.mosquitto.org:8884
9+
target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/client.crt" TEXT)
10+
target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/client.key" TEXT)
11+
target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/mosquitto.org.crt" TEXT)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
| Supported Targets | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C6 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 |
2+
| ----------------- | ----- | -------- | -------- | -------- | -------- | -------- | -------- | -------- |
3+
4+
# ESP-MQTT SSL Sample application (mutual authentication)
5+
6+
This example demonstrates the usage of mqtt command component.
7+
It connects to the broker test.mosquitto.org using ssl transport with client certificate and as a demonstration subscribes/unsubscribes and send a message on certain topic.
8+
(Please note that the public broker is maintained by the community so may not be always available, for details please visit http://test.mosquitto.org)
9+
10+
It uses ESP-MQTT library which implements mqtt client to connect to mqtt broker.
11+
12+
## How to use example
13+
14+
### Hardware Required
15+
16+
This example can be executed on any ESP32 board, the only required interface is WiFi and connection to internet.
17+
18+
### Configure the project
19+
20+
* Open the project configuration menu (`idf.py menuconfig`)
21+
* Configure Wi-Fi or Ethernet under "Example Connection Configuration" menu. See "Establishing Wi-Fi or Ethernet Connection" section in [examples/protocols/README.md](../../README.md) for more details.
22+
23+
* Generate your client keys and certificate
24+
25+
Navigate to the main directory
26+
27+
```
28+
cd main
29+
```
30+
31+
Generate a client key and a CSR. When you are generating the CSR, do not use the default values. At a minimum, the CSR must include the Country, Organisation and Common Name fields.
32+
33+
```
34+
openssl genrsa -out client.key
35+
openssl req -out client.csr -key client.key -new
36+
```
37+
38+
Paste the generated CSR in the [Mosquitto test certificate signer](https://test.mosquitto.org/ssl/index.php), click Submit and copy the downloaded `client.crt` in the `main` directory.
39+
40+
Please note, that the supplied files `client.crt` and `client.key` in the `main` directory are only placeholders for your client certificate and key (i.e. the example "as is" would compile but would not connect to the broker)
41+
42+
The server certificate `mosquitto.org.crt` can be downloaded in pem format from [mosquitto.org.crt](https://test.mosquitto.org/ssl/mosquitto.org.crt).
43+
44+
Note: Incase your certificate and keys file name differs, please update the root `CMakeLists.txt` file and main/`ssl_mutual_auth.c` accordingly.
45+
46+
### Build and Flash
47+
48+
Build the project and flash it to the board, then run monitor tool to view serial output:
49+
50+
```
51+
idf.py -p PORT flash monitor
52+
```
53+
54+
(To exit the serial monitor, type ``Ctrl-]``.)
55+
56+
See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.
57+
58+
59+
### Command Usage:
60+
```
61+
esp> help
62+
help [<string>]
63+
Print the summary of all registered commands if no arguments are given,
64+
otherwise print summary of given command.
65+
<string> Name of command
66+
67+
mqtt [-CD] [-h <host>] [-u <username>] [-P <password>]
68+
mqtt command
69+
-C, --connect Connect to a broker
70+
-h, --host=<host> Specify the host uri to connect to
71+
-u, --username=<username> Provide a username to be used for authenticating with the broker
72+
-P, --password=<password> Provide a password to be used for authenticating with the broker
73+
, --cert Define the PEM encoded certificate for this client, if required by the server
74+
, --key Define the PEM encoded private key for this client, if required by the server
75+
, --cafile Define the PEM encoded CA certificates that are trusted
76+
-D, --disconnect Disconnect from the broker
77+
78+
mqtt_pub [-t <topic>] [-m <message>]
79+
mqtt publish command
80+
-t, --topic=<topic> Topic to Subscribe/Publish
81+
-m, --message=<message> Message to Publish
82+
83+
mqtt_sub [-U] [-t <topic>]
84+
mqtt subscribe command
85+
-t, --topic=<topic> Topic to Subscribe/Publish
86+
-U, --unsubscribe Unsubscribe from a topic
87+
```
88+
89+
#### Connect/Disconnect:
90+
```
91+
esp> mqtt -h mqtts://test.mosquitto.org:8884 -C --cert --key --cafile
92+
I (668129) console_mqtt: broker: mqtts://test.mosquitto.org:8884
93+
I (668129) console_mqtt: MQTT_EVENT_BEFORE_CONNECT
94+
esp> I (671679) console_mqtt: MQTT_EVENT_CONNECTED
95+
esp>
96+
esp> mqtt -D
97+
I (1189949) console_mqtt: mqtt client disconnected
98+
```
99+
100+
#### Subscribe/Unsubscribe:
101+
```
102+
esp> mqtt_sub -t test0
103+
I (897289) console_mqtt: Subscribe successful, msg_id=57425, topic=test0
104+
esp> I (897799) console_mqtt: MQTT_EVENT_SUBSCRIBED, msg_id=57425
105+
esp>
106+
esp> mqtt_sub -U -t test0
107+
I (902009) console_mqtt: Unsubscribe successful, msg_id=27663, topic=test0
108+
esp> I (902509) console_mqtt: MQTT_EVENT_UNSUBSCRIBED, msg_id=27663
109+
```
110+
111+
#### Publish:
112+
```
113+
esp> mqtt_pub -t test0 -m "Hello, Testing 123"
114+
I (999469) console_mqtt: Publish successful, msg_id=55776, topic=test0, data=Hello, Testing 123
115+
I (1000009) console_mqtt: MQTT_EVENT_PUBLISHED, msg_id=55776
116+
esp>
117+
```
118+
119+
#### Receiving data event:
120+
```
121+
esp> I (999999) console_mqtt: MQTT_EVENT_DATA
122+
I (999999) console_mqtt: TOPIC=test0
123+
124+
I (999999) console_mqtt: DATA=Hello, Testing 123
125+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
idf_component_register(SRCS "ssl_mutual_auth.c"
2+
INCLUDE_DIRS ".")
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
-----BEGIN CERTIFICATE-----
2+
MIIDvDCCAqSgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBkDELMAkGA1UEBhMCR0Ix
3+
FzAVBgNVBAgMDlVuaXRlZCBLaW5nZG9tMQ4wDAYDVQQHDAVEZXJieTESMBAGA1UE
4+
CgwJTW9zcXVpdHRvMQswCQYDVQQLDAJDQTEWMBQGA1UEAwwNbW9zcXVpdHRvLm9y
5+
ZzEfMB0GCSqGSIb3DQEJARYQcm9nZXJAYXRjaG9vLm9yZzAeFw0yNDA1MDgwMTM5
6+
MzVaFw0yNDA4MDYwMTM5MzVaMIGVMQswCQYDVQQGEwJBVTERMA8GA1UECAwIVmlj
7+
dG9yaWExEjAQBgNVBAcMCU1lbGJvdXJuZTESMBAGA1UECgwJRXNwcmVzc2lmMRMw
8+
EQYDVQQLDApOZXR3b3JraW5nMQ4wDAYDVQQDDAVBYmhpazEmMCQGCSqGSIb3DQEJ
9+
ARYXYWJoaWsucm95QGVzcHJlc3NpZi5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IB
10+
DwAwggEKAoIBAQDTtaF4ilaKKq5Ff409KNblfmJkfqjXBxSWj6fneIbsGssNZopi
11+
6/CRqy0fbnr9fgHXIACdjk5HOmyStdtTHqFOAF+RIOqtjE2kAA2YJmomF9pD28Ph
12+
sDppicxi561j0rvQgWcn1bWaRQe7ZmNXxtoOrXnVlWVwcdUcBiWQ29/2K8r8wNhk
13+
m1O2qdyWsYphIdLutURbH5PkXht6HNoqXIuOTfYcXdz3QDV5Slph105Pox9lNPBg
14+
99RVV8I3DFiDDr1BElqudcSLaecYr8bxiiwjciOcCmX5MX5DccLWzwMSTjknRCEx
15+
wL2T64qnBRYsaKOTp1FwybuMDlvw3J6nbMhpAgMBAAGjGjAYMAkGA1UdEwQCMAAw
16+
CwYDVR0PBAQDAgXgMA0GCSqGSIb3DQEBCwUAA4IBAQBJs3n1mSASzav7qq+UsTza
17+
iWlsY9vio8ikhvtr1tfZyad1lTF9j2g68l5xyJMd34qY+EmSfOOAwKBZUBf36Qya
18+
wDbmOEXmpM89QtZZqG2Nm0GyQTcJ9KMDWE1b0ckt/rkRrWi5mrKbonT250YpPOrt
19+
SCe7Ah4W8kzN58VgmiMjSGKPzYXzJ8D1OmEw93NMGYsHwZ90U3QDVxd3WzHpPSwn
20+
aOOel6eAE4L7FifzoO+6wGHqJz+9LRAqOVH3BFQ5KlIyoNAzJjA6Zz7eFfIRhYKC
21+
1sOzNj04mU783sctgYrya7IzQBihjOESCdZrGMiM14LtpIkjVh3JPMe7CdLHzeYs
22+
-----END CERTIFICATE-----
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
-----BEGIN PRIVATE KEY-----
2+
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDTtaF4ilaKKq5F
3+
f409KNblfmJkfqjXBxSWj6fneIbsGssNZopi6/CRqy0fbnr9fgHXIACdjk5HOmyS
4+
tdtTHqFOAF+RIOqtjE2kAA2YJ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4BAvgrSmpIVN2KrHVokUf5CIT79sXwsVMWfoJl
21+
ZCA2Zpg/TTMglrVt5k2gkmt7JtJQZQCAhZ+E37GtUWYYfvLHcXDjUWiJAoGBALjt
22+
qlez0wnoh0Qmys/dkh3490PRzTsGXkukjH5mXBOEFL9sMMVYGIA7FtWibb7POT9m
23+
jSnRmZvGU/GskRoNbzR3enVCiTs9kBB11RlASJw6avIeSRIdkyXc4rW8XF/5OJHv
24+
suwHr/RATCRRpBx6bR/cQBPpb7dvuBDG6ATJX25tAoGBAPVOfEMFS3uAWy7TCg/v
25+
/KC0s7NqV3MyA0/P4DfbS8soYekd2BE3ISNLcwffHoIVtcIZ5ElM5CVC2opw167J
26+
jvwa2it6/nGQZqIFLtb4xYC291iL4IiTYm0v82jBWDBtw8xqN43vU2hk5EaWhpW0
27+
8GqLjexkQUVbpe9GS+AKFEbD
28+
-----END PRIVATE KEY-----
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
dependencies:
2+
idf:
3+
version: ">=5.0"
4+
protocol_examples_common:
5+
path: ${IDF_PATH}/examples/common_components/protocol_examples_common
6+
console_cmd_mqtt:
7+
version: "*"
8+
override_path: '../../../'
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
-----BEGIN CERTIFICATE-----
2+
MIIEAzCCAuugAwIBAgIUBY1hlCGvdj4NhBXkZ/uLUZNILAwwDQYJKoZIhvcNAQEL
3+
BQAwgZAxCzAJBgNVBAYTAkdCMRcwFQYDVQQIDA5Vbml0ZWQgS2luZ2RvbTEOMAwG
4+
A1UEBwwFRGVyYnkxEjAQBgNVBAoMCU1vc3F1aXR0bzELMAkGA1UECwwCQ0ExFjAU
5+
BgNVBAMMDW1vc3F1aXR0by5vcmcxHzAdBgkqhkiG9w0BCQEWEHJvZ2VyQGF0Y2hv
6+
by5vcmcwHhcNMjAwNjA5MTEwNjM5WhcNMzAwNjA3MTEwNjM5WjCBkDELMAkGA1UE
7+
BhMCR0IxFzAVBgNVB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/Cq4h/JfB7NTsezVslgkBaoU=
24+
-----END CERTIFICATE-----
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
3+
*
4+
* SPDX-License-Identifier: Unlicense OR CC0-1.0
5+
*/
6+
#include <stdio.h>
7+
#include "nvs_flash.h"
8+
#include "esp_netif.h"
9+
#include "esp_event.h"
10+
#include <netdb.h>
11+
#include "console_mqtt.h"
12+
#include "protocol_examples_common.h"
13+
14+
// Certs for mqtts://test.mosquitto.org:8884
15+
extern const uint8_t client_cert_pem_start[] asm("_binary_client_crt_start");
16+
extern const uint8_t client_cert_pem_end[] asm("_binary_client_crt_end");
17+
extern const uint8_t client_key_pem_start[] asm("_binary_client_key_start");
18+
extern const uint8_t client_key_pem_end[] asm("_binary_client_key_end");
19+
extern const uint8_t server_cert_pem_start[] asm("_binary_mosquitto_org_crt_start");
20+
extern const uint8_t server_cert_pem_end[] asm("_binary_mosquitto_org_crt_end");
21+
22+
23+
void app_main(void)
24+
{
25+
ESP_ERROR_CHECK(esp_netif_init());
26+
ESP_ERROR_CHECK(esp_event_loop_create_default());
27+
esp_err_t ret = nvs_flash_init(); //Initialize NVS
28+
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
29+
ESP_ERROR_CHECK(nvs_flash_erase());
30+
ret = nvs_flash_init();
31+
}
32+
ESP_ERROR_CHECK(ret);
33+
34+
/* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
35+
* Read "Establishing Wi-Fi or Ethernet Connection" section in
36+
* ${IDF_PATH}/examples/protocols/README.md for more information about this function.
37+
*/
38+
ESP_ERROR_CHECK(example_connect());
39+
40+
// Initialize console REPL
41+
ESP_ERROR_CHECK(console_cmd_init());
42+
ESP_ERROR_CHECK(console_cmd_all_register());
43+
44+
set_mqtt_certs(client_cert_pem_start, client_cert_pem_end, client_key_pem_start,
45+
client_key_pem_end, server_cert_pem_start, server_cert_pem_end);
46+
47+
// start console REPL
48+
ESP_ERROR_CHECK(console_cmd_start());
49+
50+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
version: 1.0.0
2+
url: https://github.com/espressif/esp-protocols/tree/master/components/console_cmd_mqtt
3+
description: The component provides a console where the 'mqtt' command can be executed.
4+
dependencies:
5+
idf:
6+
version: '>=5.0'
7+
espressif/console_simple_init:
8+
version: '>=1.1.0'
9+
override_path: '../console_simple_init'
10+
public: true

0 commit comments

Comments
 (0)
Please sign in to comment.