MQTT Connection Status -22

Hi. I am trying to develop a project that use mqtt connection using nrf9160. Currently using thingy:91 for evalutation board. I am using Mobily Network on NB IoT at Saudi Arabia. Now I manage to connect to NB-IoT Network but when it is trying to connect to mqtt connection, I got message that the connection status -22.

I am trying to find a solution that provide information about that error but I can't find anything about that. Please let me know if there is any information that I can check on the code or configuration. Thanks 

Parents Reply Children
  • Thanks for your fast response.

    The input is only a client object. 

    #include <zephyr.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <zephyr/kernel.h>
    #include <nrf_modem_at.h>
    #include <modem/lte_lc.h>
    #include <modem/location.h>
    #include <date_time.h>
    #include <zephyr/drivers/uart.h>
    #include <sys/printk.h>
    #include <usb/usb_device.h>
    #include <drivers/uart.h>
    #include <string.h>
    #include <zephyr/net/mqtt.h>
    #include <zephyr/net/socket.h>
    #include <zephyr/random/rand32.h>
    
    #if defined(CONFIG_NRF_MODEM_LIB)
    #include <nrf_modem_at.h>
    #endif
    
    #include <modem/lte_lc.h>
    #include <zephyr/logging/log.h>
    
    /* Check which one is the modem */
    #if defined(CONFIG_MODEM_KEY_MGMT)
    #include <modem/modem_key_mgmt.h>
    #endif
    
    #if defined(CONFIG_LWM2M_CARRIER)
    #include <lwm2m_carrier.h>
    #endif
    
    #include <dk_buttons_and_leds.h>
    
    #define CONFIG_LTE_CONNECT_RETRY_DELAY_S 3
    #define CONFIG_MQTT_RECONNECT_DELAY_S 5
    #define CONFIG_MQTT_MESSAGE_BUFFER_SIZE 128
    #define CONFIG_MQTT_PAYLOAD_BUFFER_SIZE 128
    #define CONFIG_MQTT_PUB_TOPIC "palmlab_gps_location"
    #define CONFIG_MQTT_SUB_TOPIC "palmlab_subs_location"
    #define CONFIG_MQTT_BROKER_HOSTNAME "broker.emqx.io"
    #define CONFIG_MQTT_CLIENT_ID "palmlab_thingy91"
    #define CONFIG_MQTT_BROKER_PORT 1883
    
    
    double latt, lon, acc, res;
    
    static K_SEM_DEFINE(location_event, 0, 1);
    static K_SEM_DEFINE(lte_connected, 0, 1);
    static K_SEM_DEFINE(time_update_finished, 0, 1);
    
    
    /* 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];
    
    static struct mqtt_client client;
    static struct sockaddr_storage broker;
    
    static struct pollfd fds;
    
    #if defined(CONFIG_MQTT_LIB_TLS)
    static int certificates_provision(void)
    {
        int err = 0;
        LOG_INF("Provisioning certificates");
    #if defined(CONFIG_NRF_MODEM_LIB) && defined(CONFIG_MODEM_KEY_MGMT)
    
        err = modem_key_mgmt_write(CONFIG_MQTT_TLS_SEC_TAG,
                       MODEM_KEY_MGMT_CRED_TYPE_CA_CHAIN,
                       CA_CERTIFICATE,
                       strlen(CA_CERTIFICATE));
        if (err) {
            LOG_ERR("Failed to provision CA certificate: %d", err);
            return err;
        }
    
    #elif defined(CONFIG_BOARD_QEMU_X86) && defined(CONFIG_NET_SOCKETS_SOCKOPT_TLS)
        err = tls_credential_add(CONFIG_MQTT_TLS_SEC_TAG,
                     TLS_CREDENTIAL_CA_CERTIFICATE,
                     CA_CERTIFICATE,
                     sizeof(CA_CERTIFICATE));
        if (err) {
            LOG_ERR("Failed to register CA certificate: %d", err);
            return err;
        }
    #endif
    
        return err;
    }
    #endif /* defined(CONFIG_MQTT_LIB_TLS) */
    
    
    #if defined(CONFIG_LWM2M_CARRIER)
    K_SEM_DEFINE(carrier_registered, 0, 1);
    int lwm2m_carrier_event_handler(const lwm2m_carrier_event_t *event)
    {
        switch (event->type) {
        case LWM2M_CARRIER_EVENT_BSDLIB_INIT:
            LOG_INF("LWM2M_CARRIER_EVENT_BSDLIB_INIT");
            break;
        case LWM2M_CARRIER_EVENT_CONNECTING:
            LOG_INF("LWM2M_CARRIER_EVENT_CONNECTING");
            break;
        case LWM2M_CARRIER_EVENT_CONNECTED:
            LOG_INF("LWM2M_CARRIER_EVENT_CONNECTED");
            break;
        case LWM2M_CARRIER_EVENT_DISCONNECTING:
            LOG_INF("LWM2M_CARRIER_EVENT_DISCONNECTING");
            break;
        case LWM2M_CARRIER_EVENT_DISCONNECTED:
            LOG_INF("LWM2M_CARRIER_EVENT_DISCONNECTED");
            break;
        case LWM2M_CARRIER_EVENT_BOOTSTRAPPED:
            LOG_INF("LWM2M_CARRIER_EVENT_BOOTSTRAPPED");
            break;
        case LWM2M_CARRIER_EVENT_REGISTERED:
            LOG_INF("LWM2M_CARRIER_EVENT_REGISTERED");
            k_sem_give(&carrier_registered);
            break;
        case LWM2M_CARRIER_EVENT_DEFERRED:
            LOG_INF("LWM2M_CARRIER_EVENT_DEFERRED");
            break;
        case LWM2M_CARRIER_EVENT_FOTA_START:
            LOG_INF("LWM2M_CARRIER_EVENT_FOTA_START");
            break;
        case LWM2M_CARRIER_EVENT_REBOOT:
            LOG_INF("LWM2M_CARRIER_EVENT_REBOOT");
            break;
        case LWM2M_CARRIER_EVENT_ERROR:
            LOG_ERR("LWM2M_CARRIER_EVENT_ERROR: code %d, value %d",
                ((lwm2m_carrier_event_error_t *)event->data)->code,
                ((lwm2m_carrier_event_error_t *)event->data)->value);
            break;
        default:
            LOG_WRN("Unhandled LWM2M_CARRIER_EVENT: %d", event->type);
            break;
        }
    
        return 0;
    }
    #endif /* defined(CONFIG_LWM2M_CARRIER) */
    
    // print a new strings without a 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;
        printk(buf);
    }
    
    // publish data to configured topic
    static 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);
        printk("to topic: %s len: %u",
            CONFIG_MQTT_PUB_TOPIC,
            (unsigned int)strlen(CONFIG_MQTT_PUB_TOPIC));
    
        return mqtt_publish(c, &param);
    }
    
    // subscribe to configured topic
    static int subscribe(void)
    {
        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
        };
    
        printk("Subscribing to: %s len %u", CONFIG_MQTT_SUB_TOPIC,
            (unsigned int)strlen(CONFIG_MQTT_SUB_TOPIC));
    
        return mqtt_subscribe(&client, &subscription_list);
    }
    
    // get the payload to the configured topic as a client
    static int publish_get_payload(struct mqtt_client *c, size_t length)
    {
        int ret;
        int err = 0;
    
        if (length > sizeof(payload_buf)) {
            err = -EMSGSIZE;
        }
    
        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;
    }
    
    // MQTT 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:
            if (evt->result != 0) {
                printk("MQTT connect failed: %d", evt->result);
                break;
            }
    
            printk("MQTT client connected");
            subscribe();
            break;
    
        case MQTT_EVT_DISCONNECT:
            printk("MQTT client disconnected: %d", evt->result);
            break;
    
        case MQTT_EVT_PUBLISH: {
            const struct mqtt_publish_param *p = &evt->param.publish;
    
            printk("MQTT PUBLISH result=%d len=%d",
                evt->result, p->message.payload.len);
            err = publish_get_payload(c, p->message.payload.len);
    
            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(&client, &ack);
            }
    
            if (err >= 0) {
                data_print("Received: ", payload_buf,
                    p->message.payload.len);
                /* Echo back received data */
                data_publish(&client, MQTT_QOS_1_AT_LEAST_ONCE,
                    payload_buf, p->message.payload.len);
            } else if (err == -EMSGSIZE) {
                printk("Received payload (%d bytes) is larger than the payload buffer "
                    "size (%d bytes).",
                    p->message.payload.len, sizeof(payload_buf));
            } else {
                printk("publish_get_payload failed: %d", err);
                printk("Disconnecting MQTT client...");
    
                err = mqtt_disconnect(c);
                if (err) {
                    printk("Could not disconnect: %d", err);
                }
            }
        } break;
    
        case MQTT_EVT_PUBACK:
            if (evt->result != 0) {
                printk("MQTT PUBACK error: %d", evt->result);
                break;
            }
    
            printk("PUBACK packet id: %u", evt->param.puback.message_id);
            break;
    
        case MQTT_EVT_SUBACK:
            if (evt->result != 0) {
                printk("MQTT SUBACK error: %d", evt->result);
                break;
            }
    
            printk("SUBACK packet id: %u", evt->param.suback.message_id);
            break;
    
        case MQTT_EVT_PINGRESP:
            if (evt->result != 0) {
                printk("MQTT PINGRESP error: %d", evt->result);
            }
            break;
    
        default:
            printk("Unhandled MQTT event type: %d", evt->type);
            break;
        }
    }
    
    // initialize the broker
    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) {
            printk("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));
                printk("IPv4 Address found %s", log_strdup(ipv4_addr));
    
                break;
            } else {
                printk("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;
        }
    
        freeaddrinfo(result);
        return err;
    }
    
    #if defined(CONFIG_NRF_MODEM_LIB)
    #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
    #else
    #define RANDOM_LEN 10
    #define CLIENT_ID_LEN sizeof(CONFIG_BOARD) + 1 + RANDOM_LEN
    #endif /* defined(CONFIG_NRF_MODEM_LIB) */
    
    // get the client id information
    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) {
            snprintk(client_id, sizeof(client_id), "%s",
                 CONFIG_MQTT_CLIENT_ID);
            goto exit;
        }
    
    #if defined(CONFIG_NRF_MODEM_LIB)
        char imei_buf[CGSN_RESPONSE_LENGTH + 1];
        int err;
    
        err = nrf_modem_at_cmd(imei_buf, sizeof(imei_buf), "AT+CGSN");
        if (err) {
            printk("Failed to obtain IMEI, error: %d", err);
            goto exit;
        }
    
        imei_buf[IMEI_LEN] = '\0';
    
        snprintk(client_id, sizeof(client_id), "nrf-%.*s", IMEI_LEN, imei_buf);
    #else
        uint32_t id = sys_rand32_get();
        snprintk(client_id, sizeof(client_id), "%s-%010u", CONFIG_BOARD, id);
    #endif /* !defined(NRF_CLOUD_CLIENT_ID) */
    
    exit:
        printk("client_id = %s", log_strdup(client_id));
    
        return client_id;
    }
    
    // initialize client for MQTT
    static int client_init(struct mqtt_client *client)
    {
        int err;
    
        mqtt_client_init(client);
    
        err = broker_init();
        if (err) {
            printk("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);
    
        /* MQTT transport configuration */
        #if defined(CONFIG_MQTT_LIB_TLS)
            struct mqtt_sec_config *tls_cfg = &(client->transport).tls.config;
            static sec_tag_t sec_tag_list[] = { CONFIG_MQTT_TLS_SEC_TAG };
    
            LOG_INF("TLS enabled");
            client->transport.type = MQTT_TRANSPORT_SECURE;
    
            tls_cfg->peer_verify = CONFIG_MQTT_TLS_PEER_VERIFY;
            tls_cfg->cipher_count = 0;
            tls_cfg->cipher_list = NULL;
            tls_cfg->sec_tag_count = ARRAY_SIZE(sec_tag_list);
            tls_cfg->sec_tag_list = sec_tag_list;
            tls_cfg->hostname = CONFIG_MQTT_BROKER_HOSTNAME;
    
            #if defined(CONFIG_NRF_MODEM_LIB)
                tls_cfg->session_cache = IS_ENABLED(CONFIG_MQTT_TLS_SESSION_CACHING) ?
                            TLS_SESSION_CACHE_ENABLED :
                            TLS_SESSION_CACHE_DISABLED;
            #else
                /* TLS session caching is not supported by the Zephyr network stack */
                tls_cfg->session_cache = TLS_SESSION_CACHE_DISABLED;
    
            #endif
        #else
            client->transport.type = MQTT_TRANSPORT_NON_SECURE;
        #endif
    
        return err;
    }
    
    // initialize file descriptor structure that will be used by poll
    static int fds_init(struct mqtt_client *c)
    {
        if (c->transport.type == MQTT_TRANSPORT_NON_SECURE) {
            fds.fd = c->transport.tcp.sock;
        } else {
    #if defined(CONFIG_MQTT_LIB_TLS)
            fds.fd = c->transport.tls.sock;
    #else
            return -ENOTSUP;
    #endif
        }
    
        fds.events = POLLIN;
    
        return 0;
    }
    
    // configure modem that provide LTE Link. It will block any information until the connection established successfully.
    static int modem_configure(void)
    {
        #if defined(CONFIG_LTE_LINK_CONTROL)
            /* Turn off LTE power saving features for a more responsive demo. Also,
            * request power saving features before network registration. Some
            * networks rejects timer updates after the device has registered to the
            * LTE network.
            */
            printk("Disabling PSM and eDRX");
            lte_lc_psm_req(false);
            lte_lc_edrx_req(false);
    
            if (IS_ENABLED(CONFIG_LTE_AUTO_INIT_AND_CONNECT)) {
                /* Do nothing, modem is already turned on
                * and connected.
                */
            } else {
                #if defined(CONFIG_LWM2M_CARRIER)
                /* Wait for the LWM2M_CARRIER to configure the modem and
                * start the connection.
                */
                    printk("Waitng for carrier registration...");
                    k_sem_take(&carrier_registered, K_FOREVER);
                    printk("Registered!");
                #else /* defined(CONFIG_LWM2M_CARRIER) */
                    int err;
    
                    printk("Connecting to NB-IOT Network.");
                    err = lte_lc_init_and_connect();
                    if (err) {
                        printk("Failed to establish NB-IOT connection: %d", err);
                  %C2%A0     return err;
                    }
                    printk("Connected to the network!");
                #endif /* defined(CONFIG_LWM2M_CARRIER) */
            }
        #endif /* defined(CONFIG_LTE_LINK_CONTROL) */
        return 0;
    }
    
    // set date time for event handling
    static void date_time_evt_handler(const struct date_time_evt *evt)
    {
        k_sem_give(&time_update_finished);
    }
    
    // event handling for LTE connection
    static void lte_event_handler(const struct lte_lc_evt *const evt)
    {
        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)) {
                printk("Connected to NB-IOT\n");
                k_sem_give(&lte_connected);
            }
            break;
        default:
            break;
        }
    }
    
    // get handling location event
    static void location_event_handler(const struct location_event_data *event_data)
    {
        switch (event_data->id) {
        case LOCATION_EVT_LOCATION:
            printk("Got location:\n");
            printk("  method: %s\n", location_method_str(event_data->location.method));
            printk("  latitude: %.06f\n", event_data->location.latitude);
            printk("  longitude: %.06f\n", event_data->location.longitude);
            printk("  accuracy: %.01f m\n", event_data->location.accuracy);
            printk("  Google maps URL: https://maps.google.com/?q=%.06f,%.06f\n\n",
                event_data->location.latitude, event_data->location.longitude);
            char temp_latt[12];
            char temp_long[12];
            char temp_acc[12];
            char result[50];
    
            gcvt(event_data->location.latitude, 12, temp_latt);
            latt = atof(temp_latt);
            gcvt(event_data->location.longitude, 12, temp_long);
            lon = atof(temp_long);
            gcvt(event_data->location.accuracy, 12, temp_acc);
            acc = atof(temp_acc);
            res = 200;
            sprintf(result, "%f %f %f", latt, lon, acc);
            int result_len = strlen(result);
            printk(result);
            printk("Publishing message to MQTT Broker.");
            data_publish(&client, MQTT_QOS_1_AT_LEAST_ONCE,
                    result, result_len);
            printk("Done publishing.");
            break;
    
        case LOCATION_EVT_TIMEOUT:
            printk("Retrieving location timed out\n\n");
            break;
    
        case LOCATION_EVT_ERROR:
            printk("Retrieving location failed\n\n");
            break;
    
        case LOCATION_EVT_GNSS_ASSISTANCE_REQUEST:
            printk("Retrieving location assistance requested (A-GPS). Not doing anything.\n\n");
            break;
    
        case LOCATION_EVT_GNSS_PREDICTION_REQUEST:
            printk("Retrieving location assistance requested (P-GPS). Not doing anything.\n\n");
            break;
    
        default:
            printk("Retrieving location: Unknown event\n\n");
            break;
        }
    
        k_sem_give(&location_event);
    }
    
    static void location_event_wait(void)
    {
        k_sem_take(&location_event, K_FOREVER);
    }
     
    static void location_with_fallback_get(void)
    {
        int err;
        struct location_config config;
        enum location_method methods[] = {LOCATION_METHOD_GNSS, LOCATION_METHOD_CELLULAR};
    
        location_config_defaults_set(&config, ARRAY_SIZE(methods), methods);
        config.methods[0].gnss.timeout = 1;
        config.methods[1].cellular.timeout = 30;
    
        printk("Requesting location with short GNSS timeout to trigger fallback to cellular...\n");
    
        err = location_request(&config);
        if (err) {
            printk("Requesting location failed, error: %d\n", err);
            return;
        }
    
        location_event_wait();
    }
    
    
    static void location_default_get(void)
    {
        int err;
    
        printk("Requesting location with the default configuration...\n");
    
        err = location_request(NULL);
        if (err) {
            printk("Requesting location failed, error: %d\n", err);
            return;
        }
    
        location_event_wait();
    }
    
    static void location_gnss_low_accuracy_get(void)
    {
        int err;
        struct location_config config;
        enum location_method methods[] = {LOCATION_METHOD_GNSS};
    
        location_config_defaults_set(&config, ARRAY_SIZE(methods), methods);
        config.methods[0].gnss.accuracy = LOCATION_ACCURACY_LOW;
    
        printk("Requesting low accuracy GNSS location...\n");
    
        err = location_request(&config);
        if (err) {
            printk("Requesting location failed, error: %d\n", err);
            return;
        }
    
        location_event_wait();
    }
    
    /**
     * @brief Retrieve location with GNSS high accuracy.
     */
    static void location_gnss_high_accuracy_get(void)
    {
        int err;
        struct location_config config;
        enum location_method methods[] = {LOCATION_METHOD_GNSS};
    
        location_config_defaults_set(&config, ARRAY_SIZE(methods), methods);
        config.methods[0].gnss.accuracy = LOCATION_ACCURACY_HIGH;
    
        printk("Requesting high accuracy GNSS location...\n");
    
        err = location_request(&config);
        if (err) {
            printk("Requesting location failed, error: %d\n", err);
            return;
        }
    
        location_event_wait();
    }
    
    /**
     * @brief Retrieve location periodically with GNSS as first priority and cellular as second.
     */
    static void location_gnss_periodic_get(void)
    {
        int err;
        printk("retrieving location.");
        struct location_config config;
        enum location_method methods[] = {LOCATION_METHOD_GNSS, LOCATION_METHOD_CELLULAR};
    
        location_config_defaults_set(&config, ARRAY_SIZE(methods), methods);
        config.interval = 30;
    
        printk("Requesting 30s periodic GNSS location with cellular fallback...\n");
    
        err = location_request(&config);
        if (err) {
            printk("Requesting location failed, error: %d\n", err);
            return;
        }
    }
    
    int main(void)
    {
        int err;
        printk("Starting firmwre.\n");
        uint32_t connect_attempt = 0;
        printk("checking time settings.\n");
        if (IS_ENABLED(CONFIG_DATE_TIME)) {
            date_time_register_handler(date_time_evt_handler);
        }
    
        do {
            printk("configuring modem.\n");
            err = modem_configure();
            if (err) {
                printk(".");
                k_sleep(K_SECONDS(CONFIG_LTE_CONNECT_RETRY_DELAY_S));
            }
        } while (err);
    
        printk("Modem Connected.\n");
        printk("Connecting to NB-IOT Signals.\n");
    
        lte_lc_init();
        lte_lc_register_handler(lte_event_handler);
        printk("Connected to NB-IOT Signals.");
    
        /* Enable PSM. */
        // lte_lc_psm_req(true);
        // lte_lc_connect();
        // k_sem_take(&lte_connected, K_FOREVER);
        // printk("Enabling PSM.");
    
    do_connect:
        if (connect_attempt++ > 0) {
            printk(".");
            k_sleep(K_SECONDS(1));
        }
        printk("\n");
        err = mqtt_connect(&client);
        if (err != 0) {
            printk("mqtt connection status : %d\n", err);
            goto do_connect;
        }
    
        printk("Connected to MQTT server.\n");
        printk("Starting program..\n");
        k_sleep(K_SECONDS(CONFIG_MQTT_RECONNECT_DELAY_S));
    
        while (1) {
            printk("re-doing program");
            err = location_init(location_event_handler);
            if (err) {
                printk("Initializing the Location library failed, error: %d\n", err);
                return -1;
            }
    
            err = mqtt_live(&client);
            if ((err != 0) && (err != -EAGAIN)) {
                printk("ERROR: mqtt_live: %d", err);
                break;
            }
    
            location_with_fallback_get();
            location_default_get();
            location_gnss_low_accuracy_get();
            location_gnss_high_accuracy_get();
            location_gnss_periodic_get();
        }
        err = mqtt_disconnect(&client);
        if (err) {
            printk("Could not disconnect MQTT.");
        }
        goto do_connect;
    }
    Thanks.
  • What specific function returns the error code?

  • It looks like you're doing something very similar to this sample setup, which should work:

    http://developer.nordicsemi.com/nRF_Connect_SDK/doc/latest/zephyr/connectivity/networking/api/mqtt.html

    The first thing I notice is that you're using the arrow operator where the sample uses the dot operator (client->broker vs client.broker).

    Any reason you've done this?

    Since you get an error related to the input, the first thing I would do is check that the client object looks like you expect before it's given to the mqtt_connect function.

    Try to print all the values in your client object and check that they are what you expect.

    -Einar

Related