diff options
| author | Michal Hanus <mikehanus@protonmail.com> | 2025-04-14 22:04:32 +0200 |
|---|---|---|
| committer | Michal Hanus <mikehanus@protonmail.com> | 2025-04-14 22:04:32 +0200 |
| commit | 2e13c372f1419f08dab7797b244681f889dd9bcf (patch) | |
| tree | 995a31c40f13068c4135c213e938e0a2a9ed05a3 /nrfdemo/src | |
| parent | 620dfd94019f3c7e3022fa5a5fb9c9b51491062d (diff) | |
nrfdemo
Diffstat (limited to 'nrfdemo/src')
| -rw-r--r-- | nrfdemo/src/main.c | 303 | ||||
| -rw-r--r-- | nrfdemo/src/mqtt_connection.c | 365 | ||||
| -rw-r--r-- | nrfdemo/src/mqtt_connection.h | 21 |
3 files changed, 689 insertions, 0 deletions
diff --git a/nrfdemo/src/main.c b/nrfdemo/src/main.c new file mode 100644 index 0000000..68f8f3c --- /dev/null +++ b/nrfdemo/src/main.c @@ -0,0 +1,303 @@ +/* + * Copyright (c) 2018 Nordic Semiconductor ASA + * Copyright (c) 2024 Conexio Technologies, Inc + * + * SPDX-License-Identifier: LicenseRef-Nordic-5-Clause + */ + +#include <stdio.h> +#include <ncs_version.h> +#include <zephyr/kernel.h> +#include <zephyr/net/socket.h> + +#include <zephyr/logging/log.h> +#include <dk_buttons_and_leds.h> +#include <modem/nrf_modem_lib.h> +#include <modem/lte_lc.h> +/* Header file for the MQTT Library*/ +#include <zephyr/net/mqtt.h> +#include <nrf_modem_gnss.h> +#include "mqtt_connection.h" + +/* The mqtt client struct */ +static struct mqtt_client client; +/* File descriptor */ +static struct pollfd fds; + +/* Define the PVT data frame variable */ +static struct nrf_modem_gnss_pvt_data_frame pvt_data; + +/* Declare helper variables to find the TTFF */ +static int64_t gnss_start_time; +static bool first_fix = false; + +static void gnss_event_handler(int event); +static void print_fix_data(struct nrf_modem_gnss_pvt_data_frame *pvt_data); + +static K_SEM_DEFINE(lte_connected, 0, 1); + +LOG_MODULE_REGISTER(mqtt_app, LOG_LEVEL_INF); + +static void lte_handler(const struct lte_lc_evt *const evt) +{ + LOG_INF("LTE handler"); + switch (evt->type) { + case LTE_LC_EVT_NW_REG_STATUS: + if ((evt->nw_reg_status != LTE_LC_NW_REG_REGISTERED_HOME) && + (evt->nw_reg_status != LTE_LC_NW_REG_REGISTERED_ROAMING)) { + break; + } + LOG_INF("Network registration status: %s", + evt->nw_reg_status == LTE_LC_NW_REG_REGISTERED_HOME ? + "Connected - home network" : "Connected - roaming"); + k_sem_give(<e_connected); + break; + case LTE_LC_EVT_RRC_UPDATE: + LOG_INF("RRC mode: %s", evt->rrc_mode == LTE_LC_RRC_MODE_CONNECTED ? + "Connected" : "Idle"); + break; + default: + break; + } +} + +static int modem_configure(void) +{ + int err; + + LOG_INF("Initializing modem library"); + err = nrf_modem_lib_init(); + if (err) { + LOG_ERR("Failed to initialize the modem library, error: %d", err); + return err; + } + + /* lte_lc_init deprecated in >= v2.6.0 */ + #if NCS_VERSION_NUMBER < 0x20600 + err = lte_lc_init(); + if (err) { + LOG_ERR("Failed to initialize LTE link control library, error: %d", err); + return err; + } + #endif + + LOG_INF("Connecting to LTE network"); + err = lte_lc_connect_async(lte_handler); + if (err) { + LOG_ERR("Error in lte_lc_connect_async, error: %d", err); + return err; + } + + k_sem_take(<e_connected, K_FOREVER); + LOG_INF("Connected to LTE network"); + + #if 1 + + /* Activate only the GNSS stack * / + if (lte_lc_func_mode_set(LTE_LC_FUNC_MODE_ACTIVATE_GNSS) != 0) { + LOG_ERR("Failed to activate GNSS functional mode"); + return 0; + } */ + + /* Register the GNSS event handler */ + if (nrf_modem_gnss_event_handler_set(gnss_event_handler) != 0) { + LOG_ERR("Failed to set GNSS event handler"); + return 0; + } + + /* Set the GNSS fix interval and GNSS fix retry period */ + //if (nrf_modem_gnss_fix_interval_set(CONFIG_GNSS_PERIODIC_INTERVAL) != 0) { + // LOG_ERR("Failed to set GNSS fix interval"); + // return 0; + //} + + //if (nrf_modem_gnss_fix_retry_set(CONFIG_GNSS_PERIODIC_TIMEOUT) != 0) { + // LOG_ERR("Failed to set GNSS fix retry"); + // return 0; + //} + + /* Start the GNSS receiver */ + LOG_INF("Starting GNSS"); + if (nrf_modem_gnss_start() != 0) { + LOG_ERR("Failed to start GNSS"); + return 0; + } + #endif + + + // Blink LED to indicate we connected to MQTT broker + dk_set_led_on(DK_LED1); + k_msleep(2000); + dk_set_led_off(DK_LED1); + + return 0; +} + +static void button_handler(uint32_t button_state, uint32_t has_changed) +{ + switch (has_changed) { + case DK_BTN1_MSK: + /* When button 1/Mode is pressed, call data_publish() to publish a message */ + if (button_state & DK_BTN1_MSK){ + int err = data_publish(&client, MQTT_QOS_1_AT_LEAST_ONCE, + CONFIG_BUTTON_EVENT_PUBLISH_MSG, sizeof(CONFIG_BUTTON_EVENT_PUBLISH_MSG)-1); + if (err) { + LOG_INF("Failed to send message, %d", err); + return; + } + } + break; + } +} + +#if 1 +/* Define a function to log fix data in a readable format */ +static void print_fix_data(struct nrf_modem_gnss_pvt_data_frame *pvt_data) +{ + LOG_INF("Latitude: %.06f", pvt_data->latitude); + LOG_INF("Longitude: %.06f", pvt_data->longitude); + LOG_INF("Altitude: %.01f m", pvt_data->altitude); + LOG_INF("Time (UTC): %02u:%02u:%02u.%03u", + pvt_data->datetime.hour, + pvt_data->datetime.minute, + pvt_data->datetime.seconds, + pvt_data->datetime.ms); +} + + +static void gnss_event_handler(int event) +{ + int err; + + switch (event) { + /* On a PVT event, confirm if PVT data is a valid fix */ + case NRF_MODEM_GNSS_EVT_PVT: + LOG_INF("Searching..."); + /* Print satellite information */ + int num_satellites = 0; + for (int i = 0; i < 12 ; i++) { + if (pvt_data.sv[i].signal != 0) { + LOG_INF("sv: %d, cn0: %d", pvt_data.sv[i].sv, pvt_data.sv[i].cn0); + num_satellites++; + } + } + LOG_INF("Number of current satellites: %d", num_satellites); + err = nrf_modem_gnss_read(&pvt_data, sizeof(pvt_data), NRF_MODEM_GNSS_DATA_PVT); + if (err) { + LOG_ERR("nrf_modem_gnss_read failed, err %d", err); + return; + } + if (pvt_data.flags & NRF_MODEM_GNSS_PVT_FLAG_FIX_VALID) { + dk_set_led_on(DK_LED1); + print_fix_data(&pvt_data); + /* Print the time to first fix */ + if (!first_fix) { + LOG_INF("Time to first fix: %2.1lld s", (k_uptime_get() - gnss_start_time)/1000); + first_fix = true; + } + return; + } + break; + /* Log when the GNSS sleeps and wakes up */ + case NRF_MODEM_GNSS_EVT_PERIODIC_WAKEUP: + LOG_INF("GNSS has woken up"); + break; + case NRF_MODEM_GNSS_EVT_SLEEP_AFTER_FIX: + LOG_INF("GNSS enter sleep after fix"); + break; + default: + break; + } +} +#endif + +int main(void) +{ + int err; + uint32_t connect_attempt = 0; + + LOG_INF("Starting MQTT sample on %s\n", CONFIG_BOARD); + + if (dk_leds_init() != 0) { + LOG_ERR("Failed to initialize the LED library"); + } + + err = modem_configure(); + if (err) { + LOG_ERR("Failed to configure the modem"); + return 0; + } + + if (dk_buttons_init(button_handler) != 0) { + LOG_ERR("Failed to initialize the buttons library"); + } + + err = client_init(&client); + if (err) { + LOG_ERR("Failed to initialize MQTT client: %d", err); + return 0; + } + +do_connect: + if (connect_attempt++ > 0) { + LOG_INF("Reconnecting in %d seconds...", + CONFIG_MQTT_RECONNECT_DELAY_S); + k_sleep(K_SECONDS(CONFIG_MQTT_RECONNECT_DELAY_S)); + } + + LOG_INF("Connection to broker using mqtt_connect"); + err = mqtt_connect(&client); + if (err) { + LOG_ERR("Error in mqtt_connect: %d", err); + goto do_connect; + } + + err = fds_init(&client,&fds); + if (err) { + LOG_ERR("Error in fds_init: %d", err); + return 0; + } + + while (1) { + err = poll(&fds, 1, mqtt_keepalive_time_left(&client)); + if (err < 0) { + LOG_ERR("Error in poll(): %d", errno); + break; + } + + err = mqtt_live(&client); + if ((err != 0) && (err != -EAGAIN)) { + LOG_ERR("Error in mqtt_live: %d", err); + break; + } + + if ((fds.revents & POLLIN) == POLLIN) { + err = mqtt_input(&client); + if (err != 0) { + LOG_ERR("Error in mqtt_input: %d", err); + break; + } + } + + if ((fds.revents & POLLERR) == POLLERR) { + LOG_ERR("POLLERR"); + break; + } + + if ((fds.revents & POLLNVAL) == POLLNVAL) { + LOG_ERR("POLLNVAL"); + break; + } + } + + LOG_INF("Disconnecting MQTT client"); + + err = mqtt_disconnect(&client); + if (err) { + LOG_ERR("Could not disconnect MQTT client: %d", err); + } + goto do_connect; + + /* This is never reached */ + return 0; +} diff --git a/nrfdemo/src/mqtt_connection.c b/nrfdemo/src/mqtt_connection.c new file mode 100644 index 0000000..ef4e69f --- /dev/null +++ b/nrfdemo/src/mqtt_connection.c @@ -0,0 +1,365 @@ +#include <stdio.h> +#include <string.h> +#include <ncs_version.h> + +#include <zephyr/logging/log.h> +#include <zephyr/kernel.h> +#include <zephyr/net/socket.h> +#include <zephyr/net/mqtt.h> +#include <nrf_modem_at.h> + +#include <dk_buttons_and_leds.h> +#include "mqtt_connection.h" + +#if NCS_VERSION_NUMBER < 0x20600 +#include <zephyr/random/rand32.h> +#else +#include <zephyr/random/random.h> +#endif + +/* Buffers for MQTT client. */ +static uint8_t rx_buffer[CONFIG_MQTT_MESSAGE_BUFFER_SIZE]; +static uint8_t tx_buffer[CONFIG_MQTT_MESSAGE_BUFFER_SIZE]; +static uint8_t payload_buf[CONFIG_MQTT_PAYLOAD_BUFFER_SIZE]; + +/* MQTT Broker details. */ +static struct sockaddr_storage broker; + +LOG_MODULE_DECLARE(mqtt_app); + +/**@brief Function to get the payload of recived data. + */ +static int get_received_payload(struct mqtt_client *c, size_t length) +{ + int ret; + int err = 0; + + /* Return an error if the payload is larger than the payload buffer. + * Note: To allow new messages, we have to read the payload before returning. + */ + if (length > sizeof(payload_buf)) { + err = -EMSGSIZE; + } + + /* Truncate payload until it fits in the payload buffer. */ + while (length > sizeof(payload_buf)) { + ret = mqtt_read_publish_payload_blocking( + c, payload_buf, (length - sizeof(payload_buf))); + if (ret == 0) { + return -EIO; + } else if (ret < 0) { + return ret; + } + + length -= ret; + } + + ret = mqtt_readall_publish_payload(c, payload_buf, length); + if (ret) { + return ret; + } + + return err; +} + +/**@brief Function to subscribe to the configured topic + */ +/* Define the function subscribe() to subscribe to a specific topic. */ +static int subscribe(struct mqtt_client *const c) +{ + struct mqtt_topic subscribe_topic = { + .topic = { + .utf8 = CONFIG_MQTT_SUB_TOPIC, + .size = strlen(CONFIG_MQTT_SUB_TOPIC) + }, + .qos = MQTT_QOS_1_AT_LEAST_ONCE + }; + + const struct mqtt_subscription_list subscription_list = { + .list = &subscribe_topic, + .list_count = 1, + .message_id = 1234 + }; + + LOG_INF("Subscribing to: %s len %u", CONFIG_MQTT_SUB_TOPIC, + (unsigned int)strlen(CONFIG_MQTT_SUB_TOPIC)); + + return mqtt_subscribe(c, &subscription_list); +} + +/**@brief Function to print strings without null-termination + */ +static void data_print(uint8_t *prefix, uint8_t *data, size_t len) +{ + char buf[len + 1]; + + memcpy(buf, data, len); + buf[len] = 0; + LOG_INF("%s%s", (char *)prefix, (char *)buf); +} + +/**@brief Function to publish data on the configured topic + */ +/* Define the function data_publish() to publish data */ +int data_publish(struct mqtt_client *c, enum mqtt_qos qos, + uint8_t *data, size_t len) +{ + struct mqtt_publish_param param; + + param.message.topic.qos = qos; + param.message.topic.topic.utf8 = CONFIG_MQTT_PUB_TOPIC; + param.message.topic.topic.size = strlen(CONFIG_MQTT_PUB_TOPIC); + param.message.payload.data = data; + param.message.payload.len = len; + param.message_id = sys_rand32_get(); + param.dup_flag = 0; + param.retain_flag = 0; + + data_print("Publishing: ", data, len); + LOG_INF("to topic: %s len: %u", + CONFIG_MQTT_PUB_TOPIC, + (unsigned int)strlen(CONFIG_MQTT_PUB_TOPIC)); + + return mqtt_publish(c, ¶m); +} +/**@brief MQTT client event handler + */ +void mqtt_evt_handler(struct mqtt_client *const c, + const struct mqtt_evt *evt) +{ + int err; + + switch (evt->type) { + case MQTT_EVT_CONNACK: + /* Subscribe to the topic CONFIG_MQTT_SUB_TOPIC when we have a successful connection */ + if (evt->result != 0) { + LOG_ERR("MQTT connect failed: %d", evt->result); + break; + } + + LOG_INF("MQTT client connected"); + subscribe(c); + break; + + case MQTT_EVT_DISCONNECT: + LOG_INF("MQTT client disconnected: %d", evt->result); + break; + + case MQTT_EVT_PUBLISH: + /* Listen to published messages received from the broker and extract the message */ + { + /* Extract the payload */ + const struct mqtt_publish_param *p = &evt->param.publish; + //Print the length of the recived message + LOG_INF("MQTT PUBLISH result=%d len=%d", + evt->result, p->message.payload.len); + + //Extract the data of the recived message + err = get_received_payload(c, p->message.payload.len); + + //Send acknowledgment to the broker on receiving QoS1 publish message + if (p->message.topic.qos == MQTT_QOS_1_AT_LEAST_ONCE) { + const struct mqtt_puback_param ack = { + .message_id = p->message_id + }; + + /* Send acknowledgment. */ + mqtt_publish_qos1_ack(c, &ack); + } + + /* On successful extraction of data */ + if (err >= 0) { + data_print("Received: ", payload_buf, p->message.payload.len); + // Control the LED + if(strncmp(payload_buf,CONFIG_TURN_LED_ON_CMD,sizeof(CONFIG_TURN_LED_ON_CMD)-1) == 0){ + dk_set_led_on(LED_CONTROL_OVER_MQTT); + } + else if(strncmp(payload_buf,CONFIG_TURN_LED_OFF_CMD,sizeof(CONFIG_TURN_LED_OFF_CMD)-1) == 0){ + dk_set_led_off(LED_CONTROL_OVER_MQTT); + } + /* On failed extraction of data */ + // Payload buffer is smaller than the received data + } else if (err == -EMSGSIZE) { + LOG_ERR("Received payload (%d bytes) is larger than the payload buffer size (%d bytes).", + p->message.payload.len, sizeof(payload_buf)); + // Failed to extract data, disconnect + } else { + LOG_ERR("get_received_payload failed: %d", err); + LOG_INF("Disconnecting MQTT client..."); + + err = mqtt_disconnect(c); + if (err) { + LOG_ERR("Could not disconnect: %d", err); + } + } + } break; + + case MQTT_EVT_PUBACK: + if (evt->result != 0) { + LOG_ERR("MQTT PUBACK error: %d", evt->result); + break; + } + + LOG_INF("PUBACK packet id: %u", evt->param.puback.message_id); + break; + + case MQTT_EVT_SUBACK: + if (evt->result != 0) { + LOG_ERR("MQTT SUBACK error: %d", evt->result); + break; + } + + LOG_INF("SUBACK packet id: %u", evt->param.suback.message_id); + break; + + case MQTT_EVT_PINGRESP: + if (evt->result != 0) { + LOG_ERR("MQTT PINGRESP error: %d", evt->result); + } + break; + + default: + LOG_INF("Unhandled MQTT event type: %d", evt->type); + break; + } +} + +/**@brief Resolves the configured hostname and + * initializes the MQTT broker structure + */ +static int broker_init(void) +{ + int err; + struct addrinfo *result; + struct addrinfo *addr; + struct addrinfo hints = { + .ai_family = AF_INET, + .ai_socktype = SOCK_STREAM + }; + + err = getaddrinfo(CONFIG_MQTT_BROKER_HOSTNAME, NULL, &hints, &result); + if (err) { + LOG_ERR("getaddrinfo failed: %d", err); + return -ECHILD; + } + + addr = result; + + /* Look for address of the broker. */ + while (addr != NULL) { + /* IPv4 Address. */ + if (addr->ai_addrlen == sizeof(struct sockaddr_in)) { + struct sockaddr_in *broker4 = + ((struct sockaddr_in *)&broker); + char ipv4_addr[NET_IPV4_ADDR_LEN]; + + broker4->sin_addr.s_addr = + ((struct sockaddr_in *)addr->ai_addr) + ->sin_addr.s_addr; + broker4->sin_family = AF_INET; + broker4->sin_port = htons(CONFIG_MQTT_BROKER_PORT); + + inet_ntop(AF_INET, &broker4->sin_addr.s_addr, + ipv4_addr, sizeof(ipv4_addr)); + LOG_INF("IPv4 Address found %s", (char *)(ipv4_addr)); + + break; + } else { + LOG_ERR("ai_addrlen = %u should be %u or %u", + (unsigned int)addr->ai_addrlen, + (unsigned int)sizeof(struct sockaddr_in), + (unsigned int)sizeof(struct sockaddr_in6)); + } + + addr = addr->ai_next; + } + + /* Free the address. */ + freeaddrinfo(result); + + return err; +} + +/* Function to get the client id */ +static const uint8_t* client_id_get(void) +{ + static uint8_t client_id[MAX(sizeof(CONFIG_MQTT_CLIENT_ID), + CLIENT_ID_LEN)]; + + if (strlen(CONFIG_MQTT_CLIENT_ID) > 0) { + snprintf(client_id, sizeof(client_id), "%s", + CONFIG_MQTT_CLIENT_ID); + goto exit; + } + + char imei_buf[CGSN_RESPONSE_LENGTH + 1]; + int err; + + err = nrf_modem_at_cmd(imei_buf, sizeof(imei_buf), "AT+CGSN"); + if (err) { + LOG_ERR("Failed to obtain IMEI, error: %d", err); + goto exit; + } + + imei_buf[IMEI_LEN] = '\0'; + + snprintf(client_id, sizeof(client_id), "nrf-%.*s", IMEI_LEN, imei_buf); + +exit: + LOG_DBG("client_id = %s", (char *)(client_id)); + + return client_id; +} + + +/**@brief Initialize the MQTT client structure + */ +/* Define the function client_init() to initialize the MQTT client instance. */ +int client_init(struct mqtt_client *client) +{ + int err; + /* Initializes the client instance. */ + mqtt_client_init(client); + + /* Resolves the configured hostname and initializes the MQTT broker structure */ + err = broker_init(); + if (err) { + LOG_ERR("Failed to initialize broker connection"); + return err; + } + + /* MQTT client configuration */ + client->broker = &broker; + client->evt_cb = mqtt_evt_handler; + client->client_id.utf8 = client_id_get(); + client->client_id.size = strlen(client->client_id.utf8); + client->password = NULL; + client->user_name = NULL; + client->protocol_version = MQTT_VERSION_3_1_1; + + /* MQTT buffers configuration */ + client->rx_buf = rx_buffer; + client->rx_buf_size = sizeof(rx_buffer); + client->tx_buf = tx_buffer; + client->tx_buf_size = sizeof(tx_buffer); + + /* We are not using TLS */ + client->transport.type = MQTT_TRANSPORT_NON_SECURE; + + return err; +} + +/**@brief Initialize the file descriptor structure used by poll. + */ +int fds_init(struct mqtt_client *c, struct pollfd *fds) +{ + if (c->transport.type == MQTT_TRANSPORT_NON_SECURE) { + fds->fd = c->transport.tcp.sock; + } else { + return -ENOTSUP; + } + + fds->events = POLLIN; + + return 0; +}
\ No newline at end of file diff --git a/nrfdemo/src/mqtt_connection.h b/nrfdemo/src/mqtt_connection.h new file mode 100644 index 0000000..51765e8 --- /dev/null +++ b/nrfdemo/src/mqtt_connection.h @@ -0,0 +1,21 @@ +#ifndef _MQTTCONNECTION_H_ +#define _MQTTCONNECTION_H_ +#define LED_CONTROL_OVER_MQTT DK_LED1 /* Stratus LED to control over MQTT */ +#define IMEI_LEN 15 +#define CGSN_RESPONSE_LENGTH (IMEI_LEN + 6 + 1) /* Add 6 for \r\nOK\r\n and 1 for \0 */ +#define CLIENT_ID_LEN sizeof("nrf-") + IMEI_LEN + +/**@brief Initialize the MQTT client structure + */ +int client_init(struct mqtt_client *client); + +/**@brief Initialize the file descriptor structure used by poll. + */ +int fds_init(struct mqtt_client *c, struct pollfd *fds); + +/**@brief Function to publish data on the configured topic + */ +int data_publish(struct mqtt_client *c, enum mqtt_qos qos, + uint8_t *data, size_t len); + +#endif /* _CONNECTION_H_ */ |
