1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
/*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at https://mozilla.org/MPL/2.0/.
*/
#include <stdbool.h>
#include <stdint.h>
#include <poll.h>
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/net/socket.h>
#include <zephyr/net/mqtt.h>
#include <zephyr/net/net_ip.h>
LOG_MODULE_REGISTER(mqtt);
#define MQTT_STACK_SIZE 500
#define MQTT_PRIO K_PRIO_PREEMPT(8)
static uint8_t rx_buffer[256];
static uint8_t tx_buffer[256];
static struct mqtt_client client_ctx;
static struct sockaddr_storage broker;
static struct zsock_pollfd fds[1];
static bool connected = false;
void mqtt_evt_handler(struct mqtt_client *client, const struct mqtt_evt *evt) {
switch (evt->type) {
case MQTT_EVT_CONNACK:
LOG_INF("Connected to MQTT broker");
connected = true;
break;
default:
LOG_ERR("Unhandled MQTT event %d", evt->type);
}
}
static void mqtt_thread_function(void *ptr1, void *ptr2, void *ptr3) {
LOG_INF("Starting MQTT thread");
struct sockaddr_in6 *broker6 = (struct sockaddr_in6 *)&broker;
broker6->sin6_family = AF_INET6;
broker6->sin6_port = htons(1883);
int rc = zsock_inet_pton(AF_INET6, "2001:db8::36", &broker6->sin6_addr);
if (rc != 1) {
LOG_ERR("Failed to convert IPv6 address (%d)", rc);
} else {
LOG_INF("Converted IPv6 address successfully");
}
mqtt_client_init(&client_ctx);
/* MQTT client configuration */
client_ctx.broker = &broker;
client_ctx.evt_cb = mqtt_evt_handler;
client_ctx.client_id.utf8 = (uint8_t *)"zephyr_mqtt_client";
client_ctx.client_id.size = sizeof("zephyr_mqtt_client") - 1;
client_ctx.password = NULL;
client_ctx.user_name = NULL;
client_ctx.protocol_version = MQTT_VERSION_3_1_1;
client_ctx.transport.type = MQTT_TRANSPORT_NON_SECURE;
/* MQTT buffers configuration */
client_ctx.rx_buf = rx_buffer;
client_ctx.rx_buf_size = sizeof(rx_buffer);
client_ctx.tx_buf = tx_buffer;
client_ctx.tx_buf_size = sizeof(tx_buffer);
rc = mqtt_connect(&client_ctx);
if (rc != 0) {
LOG_ERR("Failed to connect (%d)", rc);
return;
}
fds[0].fd = client_ctx.transport.tcp.sock;
fds[0].events = ZSOCK_POLLIN;
zsock_poll(fds, 1, 5000);
mqtt_input(&client_ctx);
if (!connected) {
mqtt_abort(&client_ctx);
}
}
K_THREAD_DEFINE(mqtt_thread, MQTT_STACK_SIZE,
mqtt_thread_function, NULL, NULL, NULL,
MQTT_PRIO, 0, 0);
|