MQTT client library
Overview

MQTT client library provides easy-to-use APIs for Infineon devices to connect with cloud MQTT brokers and perform MQTT publish and subscribe operations.

Library components

This MQTT library consists of two components:
1) MQTT wrapper layer
2) AWS IoT device SDK C library

AWS-IoT Device SDK C Library is an open-source library, which uses the aws-iot-device-sdk-port library functions to perform MQTT network-related operations. Applications that uses this library should invoke the MQTT wrapper-layer API functions and those which internally calls AWS IoT device SDK library and aws-iot-device-sdk-port library API functions to perform MQTT publish/subscribe operations.

MQTT wrapper layer

This wrapper layer provides the APIs that are required to perform MQTT publish and subscribe operations on Infineon platforms. This layer contains APIs that are used for creating MQTT instances and establishing "secure" or non-secure MQTT client session with an MQTT broker to send and receive MQTT messages. This layer also handles the retry logic for failed publish messages.

AWS IoT Device SDK C - Tag: 202103.00

This is an open-source MQTT library developed and maintained by Amazon. This library implements the core MQTT protocol logic.

Multi-core architecture and virtual API support

The library supports multi-core architecture by making a subset of APIs available as virtual APIs. The virtualization of the MQTT library helps to access the MQTT APIs defined in one core from the other core using Inter Process Communication (IPC). MQTT can now be run on two cores simultaneously, with one core containing the full stack (primary core) and the other core containing the subset of virtual-only APIs (secondary core). The virtual APIs pipe the API requests over IPC to the primary core where the API is actually executed and the result is passed back to the secondary core. This virtualization abstracts out the implementation details and complexity of IPC, thus making multi-core connectivity application development simple.

  • The AWS IoT Device SDK C library provides the following features:
    • Supports Wi-Fi and Ethernet connections
    • MQTT 3.1.1 client
    • Synchronous API for MQTT operations
    • Multi-threaded API by default
    • Complete separation of MQTT and the network stack, allowing MQTT to run on top of any network stack
    • Supports MQTT persistent sessions
    • Supports quality-of-service (QoS) levels 0, 1, and 2
    • Supports MQTT connection over both secured and non-secured TCP connections
    • Supports multi-core architecture by providing the following APIs as virtual APIs which can be invoked from another core:
      • cy_mqtt_get_handle
      • cy_mqtt_register_event_callback
      • cy_mqtt_deregister_event_callback
      • cy_mqtt_publish
      • cy_mqtt_subscribe
      • cy_mqtt_unsubscribe

Supported platforms

This library and its features are supported on the following Infineon platforms:

Note
Virtual APIs are supported on all PSoC 62 devices, but they have only been tested on the CY8CEVAL-062S2-MUR-43439M2 kit.

Dependent libraries

This MQTT client library depends on the following library. This library is included by default.

If virtual APIs are to be used, it additionally depends on Virtual Connectivity Manager library.

Quick start

  • To use mqtt library with Wi-Fi kits on FreeRTOS, lwIP, and Mbed TLS combination, the application should pull mqtt library and wifi-core-freertos-lwip-mbedtls library which will internally pull secure-sockets, wifi-connection-manager, FreeRTOS, lwIP, Mbed TLS and other dependent modules. To pull wifi-core-freertos-lwip-mbedtls and mqtt libraries create the following .mtb files in deps folder.
  • To use mqtt library with Ethernet kits on FreeRTOS, lwIP, and Mbed TLS combination, the application should pull mqtt library and ethernet-core-freertos-lwip-mbedtls library which will internally pull secure-sockets, ethernet-connection-manager, FreeRTOS, lwIP, Mbed TLS and other dependent modules. To pull ethernet-core-freertos-lwip-mbedtls and mqtt libraries create the following .mtb files in deps folder.
  • Ensure that the application includes ./include/cy_mqtt_api.h to use the library APIs and structure.
  • The reference ./include/core_mqtt_config.h file that is bundled with this library provides the default configurations required for the AWS IoT device SDK library.
  • By default, AWS IoT device SDK library logging is turned off. To enable log messages, map the logging-related macros LogError, LogWarn, LogInfo, and LogDebug in ./include/core_mqtt_config.h to the application-specific logging implementation.
  • A "reasonable amount of time" to wait for keepalive response from the MQTT broker. The timeout value can be configured using the MQTT_PINGRESP_TIMEOUT_MS macro in the application Makefile. This value may be adjusted to suit the use case and network conditions. The Makefile entry should look like the following:
    DEFINES += MQTT_PINGRESP_TIMEOUT_MS=5000
  • A "maximum polling duration" that is allowed without any data reception from the network for the incoming packet. The timeout value can be configured using the MQTT_RECV_POLLING_TIMEOUT_MS macro in the application Makefile. This value may be adjusted to suit the use case and network conditions. The Makefile entry should look like the following:
    DEFINES += MQTT_RECV_POLLING_TIMEOUT_MS=1000
    1. It is important to note that having this timeout too short will result in MQTT being disconnected due to the possibility of partial data being received. If you have small TCP buffers and a high-latency network, the optimum value for the timeout can be surprisingly long. In such cases, the optimum value for timeout can be better determined based on experimenting the MQTT applications with payloads bigger than the TCP buffer. See AWS coreMQTT documentation for more details.
  • A "maximum duration" that is allowed for no data transmission over the network through the transport send function. The timeout value can be configured using the MQTT_SEND_RETRY_TIMEOUT_MS macro in the application Makefile. This value may be adjusted to suit the use case and network conditions. The Makefile entry should look like the following:
    DEFINES += MQTT_SEND_RETRY_TIMEOUT_MS=500
    1. See AWS coreMQTT documentation for more details.
  • A "reasonable amount of time" to wait for receiving the acknowledgment packet from the MQTT broker for MQTT publish/Subscribe messages with QoS1/QoS2. The timeout value can be configured using the CY_MQTT_ACK_RECEIVE_TIMEOUT_MS macro in the application Makefile. This value may be adjusted to suit the use case and network conditions. The Makefile entry should look like the following:
    #define CY_MQTT_ACK_RECEIVE_TIMEOUT_MS
    Maximum wait time in milliseconds to receive acknowledgment packet from the MQTT broker for QoS1/QoS2...
    Definition: cy_mqtt_api.h:166
  • The MQTT message send timeout can be configured using the CY_MQTT_MESSAGE_SEND_TIMEOUT_MS macro in the application Makefile. This value can be adjusted to suit the use case and network conditions. The Makefile entry should look like the following:
    #define CY_MQTT_MESSAGE_SEND_TIMEOUT_MS
    MQTT message send timeout in milliseconds.
    Definition: cy_mqtt_api.h:177
  • The MQTT message receive timeout can be configured using the CY_MQTT_MESSAGE_RECEIVE_TIMEOUT_MS macro in the application Makefile. This value can be adjusted to suit the use case and network conditions. The Makefile entry should look like the following:
    #define CY_MQTT_MESSAGE_RECEIVE_TIMEOUT_MS
    MQTT message receive timeout for the subscribed topic, represented in milliseconds.
    Definition: cy_mqtt_api.h:188
  • The MQTT library provides a retry mechanism for MQTT publish/subscribe/unsubscribe messages when the acknowledgement is not received from the broker on time. You can configure the maximum number of retries by defining the CY_MQTT_MAX_RETRY_VALUE macro in the application Makefile. The Makefile entry should look like the following:
    #define CY_MQTT_MAX_RETRY_VALUE
    Maximum number of retry for MQTT publish/subscribe/unsubcribe message send.
    Definition: cy_mqtt_api.h:199
  • To perform multiple publish operations simultaneously on a single MQTT instance, configure theCY_MQTT_MAX_OUTGOING_PUBLISHES` macro with the number of simultaneous publish operations to be performed. For the default value of this macro, see the MQTT library API header file. This macro can be configured by adding a define in the application Makefile. The Makefile entry should look like the following:
    #define CY_MQTT_MAX_OUTGOING_PUBLISHES
    Configure value of maximum number of outgoing publishes maintained in MQTT library until an ack is re...
    Definition: cy_mqtt_api.h:212
  • To perform multiple subscribe operations simultaneously on a single MQTT instance, configure the CY_MQTT_MAX_OUTGOING_SUBSCRIBES macro with the number of simultaneous subscribe operations to be performed. For the default value of this macro, see the MQTT library API header file. This macro can be configured by adding a define in the application Makefile. The Makefile entry should look like the following:
    #define CY_MQTT_MAX_OUTGOING_SUBSCRIBES
    Configure value of maximum number of outgoing subscription topics maintained in MQTT library until an...
    Definition: cy_mqtt_api.h:219
  • This MQTT Client library does not support secure connections to the public test.mosquitto.org broker by default. This is because the server uses the SHA1 hashing algorithm. As cautioned by Mbed TLS, SHA-1 is considered a weak message digest and is therefore not enabled in Mbed TLS by default. The use of SHA-1 for certificate signing constitutes a security risk. It is recommended to avoid dependencies on it, and consider stronger message digests instead.
  • Review and make the required changes to the pre-defined configuration files.
    • The configuration files are bundled with the wifi-mw-core library for FreeRTOS, lwIP, and Mbed TLS. See README.md for more details.
    • If the application uses the bundle library, the configuration files are in the bundle library. For example, if the application uses the Wi-Fi core FreeRTOS lwIP Mbed TLS bundle library, the configuration files are in the wifi-core-freertos-lwip-mbedtls/configs folder. Similarly, if the application uses the Ethernet Core FreeRTOS lwIP Mbed TLS library, the configuration files are in the ethernet-core-freertos-lwip-mbedtls/configs folder.
  • Define the following COMPONENTS in the application's Makefile for the MQTT library.
    COMPONENTS=FREERTOS MBEDTLS LWIP SECURE_SOCKETS
  • The "aws-iot-device-sdk-port" layer includes the "coreHTTP" and "coreMQTT" modules of the "aws-iot-device-sdk-embedded-C" library by default. If the user application doesn't use HTTP client features, update the application Makefile to exclude the coreHTTP source files from the build. The Makefile entry should look like the following:
    CY_IGNORE+= $(SEARCH_aws-iot-device-sdk-embedded-C)/libraries/standard/coreHTTP
  • The MQTT library is supported on multiple platforms. When it is used on secured platforms such as CY8CKIT-064S0S2-4343W, the macros CY_TFM_PSA_SUPPORTED and TFM_MULTI_CORE_NS_OS need to be defined in the application Makefile. The Makefile entry should look like the following:
    DEFINES += CY_TFM_PSA_SUPPORTED TFM_MULTI_CORE_NS_OS
  • To enable PKCS-PSA support on secured platforms such as CY8CKIT-064S0S2-4343W, the CY_SECURE_SOCKETS_PKCS_SUPPORT macro needs to be defined in the application Makefile. The Makefile entry should look like the following:
    DEFINES += CY_SECURE_SOCKETS_PKCS_SUPPORT
  • Secured platforms like CY8CKIT-064S0S2-4343W use trusted-firmware-m library for crypto operations. Due to security vulnerability in HW acceleration, trusted-firmware-m version v1.3.3 uses software implementation for ECC crypto algorithm. Because the software implementation is slower, it is recommended to set configEXPECTED_IDLE_TIME_BEFORE_SLEEP to at least 100 in the application's FreeRTOSConfig.h file.
  • To compile the MQTT library successfully for secure platforms such as CY8CKIT-064S0S2-4343W, the trusted firmware library include path needs to be added before the Mbed TLS library include path in the application Makefile. The Makefile entry should look like the following:
    INCLUDES=$(SEARCH_trusted-firmware-m)/COMPONENT_TFM_NS_INTERFACE/include
    INCLUDES+=libs/trusted-firmware-m/COMPONENT_TFM_NS_INTERFACE/include
  • The MQTT Library disables all the debug log messages by default. To enable log messages, the application must perform the following:
    1. Add the ENABLE_MQTT_LOGS macro to the DEFINES in the code example's Makefile. The Makefile entry should look like as follows:
      DEFINES+=ENABLE_MQTT_LOGS
    2. Call the cy_log_init() function provided by the cy-log module. cy-log is part of the connectivity-utilities library. See connectivity-utilities library API documentation for cy-log details.

Virtual API usage

  • To use virtual MQTT APIs, pull Virtual Connectivity Manager library. Create the following .mtb file to pull the library
  • Define the following compile-time macro in the primary core application's Makefile:
    DEFINES+=ENABLE_MULTICORE_CONN_MW VCM_ENABLE_MQTT
  • Define the following compile-time macros in the secondary core application's Makefile:
    DEFINES+=ENABLE_MULTICORE_CONN_MW USE_VIRTUAL_API VCM_ENABLE_MQTT
  • Call the cy_vcm_init() function provided by the VCM library from the application on both cores, before invoking the virtual MQTT APIs. See Virtual Connectivity Manager API documentation.
    Note
    - To ensure that the VCM initialization is synchronized, the project which boots first(i.e CM0+ project in case of psoc62) must call cy_vcm_init before bringing up the second project(i.e CM4 project in case of psoc62).
    - The first project must initialize VCM, by passing config.hal_resource_opt as CY_VCM_CREATE_HAL_RESOURCE in cy_vcm_init. The second project must pass config.hal_resource_opt as CY_VCM_USE_HAL_RESOURCE.

Library usage notes

Additional information

API call sequence

This section provides the details of the API call sequence for performing various MQTT operations. This call sequence uses APIs defined by the MQTT library.

For init, create, connect, publish, and subscribe

Use the following API call sequence to connect to a MQTT broker and to perform MQTT subscribe and publish operations:

                    +-----------------------+
                    |     cy_mqtt_init()    |
                    +-----------------------+
                                |
                                v
                    +-----------------------+
                    |    cy_mqtt_create()   |
                    +-----------------------+
                                |
                                v
                    +-----------------------+
                    |   cy_mqtt_connect()   |
                    +-----------------------+
                                |
                                v
                    +-----------------------+
                    |  cy_mqtt_subscribe()  |
                    +-----------------------+
                                |
                                v
                    +-----------------------+
                    |   cy_mqtt_publish()   |
                    +-----------------------+

For unSubscribe, disconnect, delete, and deinit

Use the following API call sequence to perform MQTT unsubscribe and disconnect operations with the MQTT broker:

                   +-----------------------+
                   | cy_mqtt_unsubscribe() |
                   +-----------------------+
                               |
                               v
                   +-----------------------+
                   |  cy_mqtt_disconnect() |
                   +-----------------------+
                               |
                               v
                   +-----------------------+
                   |    cy_mqtt_delete()   |
                   +-----------------------+
                               |
                               v
                   +-----------------------+
                   |    cy_mqtt_deinit()   |
                   +-----------------------+

For virtual APIs

Perform the following API call sequence on the primary core first before the virtual MQTT APIs can be invoked from the secondary core:

On the primary core, create the MQTT handle and establish the required connections to the MQTT broker:

                   +----------------------+
                   |    cy_mqtt_init()    |
                   +----------------------+
                               |
                               v
                   +----------------------+
                   |   cy_mqtt_create()   |
                   +----------------------+
                               |
                               v
                   +-----------------------+
                   |   cy_mqtt_connect()   |
                   +-----------------------+

On the secondary core the following API sequence can be performed once the MQTT connection is established on the primary core:

                  +------------------------+
                  |  cy_mqtt_get_handle()  |
                  +------------------------+
                               |
                               v
             +-------------------------------------+
             |  cy_mqtt_register_event_callback()  |
             +-------------------------------------+
                               |
                               v
                  +-------------------------+
                  |   cy_mqtt_subscribe()   |
                  +-------------------------+
                               |
                               v
                   +-----------------------+
                   |  cy_mqtt_publish()    |
                   +-----------------------+
                               |
                               v
                              ....
                  +-------------------------+
                  |  cy_mqtt_unsubscribe()  |
                  +-------------------------+

Note:

  • Functions cy_mqtt_init and cy_mqtt_deinit are not thread-safe.
  • The application should allocate a network buffer and the same buffer must be passed while creating the MQTT object. The MQTT library uses this buffer for sending and receiving MQTT packets. CY_MQTT_MIN_NETWORK_BUFFER_SIZE is the minimum size of the network buffer required for the library to handle MQTT packets.
  • The application should call cy_mqtt_init before calling any other MQTT library function, and should not call other MQTT library functions after calling cy_mqtt_deinit.
  • The MQTT instance is created using the cy_mqtt_create function. The MQTT library allocates resources for each created instance; therefore, the application should delete the MQTT instance by calling cy_mqtt_delete after performing the desired MQTT operations.
  • After calling the cy_mqtt_delete API function, all resources associated with the MQTT handle are freed. Therefore, the application must not use the same MQTT handle after delete.
  • The MQTT disconnection event notification is not sent to the application when the disconnection is initiated from the application.
  • When the application receives the MQTT disconnection event notification due to the following reasons, the application must call the cy_mqtt_disconnect function to release the resources allocated during cy_mqtt_connect.
    1. Network is disconnected.
    2. Ping response is not received from broker for the ping request sent, possibly broker is down.
    3. A bad response received form the MQTT broker. Possibly received a MQTT packet with invalid packet type ID.
    4. MQTT packet send/receive failed due to high network latency and smaller values set for MQTT_RECV_POLLING_TIMEOUT_MS and/or MQTT_SEND_RETRY_TIMEOUT_MS macros.

For secured platform CY8CKIT-064S0S2-4343W:

Code snippets

Code Snippet 1: Initialize an MQTT network socket

This code snippet demonstrates the initialization of the network sockets required for the MQTT library.

void snippet_cy_mqtt_init( void )
{
/* Status variables for various operations. */
cy_rslt_t TestRes = CY_RSLT_SUCCESS;
(void)TestRes;
/* Initialize the MQTT network socket. */
TestRes = cy_mqtt_init();
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
}
}
cy_rslt_t cy_mqtt_init(void)
Performs network sockets initialization required for the MQTT library.

Code Snippet 2: Creating an MQTT instance for secured connection with the MQTT broker

This code snippet demonstrates the initialization of the configuration structures required for creating an MQTT client handle for establishing a secured connection with an MQTT broker, and the usage of the cy_mqtt_create() API function.

#define MQTT_BROKER " " /* Add the broker end point info here. */
#define MQTT_PORT_SECURED ( 8883 )
#define NETWORK_BUFFER_SIZE ( 1024U )
static const char client_cert[] = { "Paste client certificate here" };
static const char client_key[] = { "Paste client key here" };
static const char root_ca_cert[] = { "Paste RootCA certificate here" };
cy_mqtt_t secure_mqtthandle;
/* Callback function registered with MQTT library while creating handle for MQTT connection.
This callback function will be called by MQTT library upon receiving MQTT messages on subscribed topics or when
network disconnection happens. */
void mqtt_secure_event_cb( cy_mqtt_t mqtt_handle, cy_mqtt_event_t event, void *user_data )
{
printf( "\nMQTT App callback with handle : %p \n", mqtt_handle );
(void)user_data;
switch( event.type )
{
printf( "\nEvent : Received MQTT Disconnect event.\n" );
switch( event.data.reason )
{
/* Keep-alive response not received from broker, possibly broker is down. */
printf( "Reason : MQTT Ping response not received within keep-alive response timeout... \n\n" );
break;
/* Network is disconnected. */
printf( "Reason : Network is disconnected... \n\n" );
break;
/* MQTT packet send or receive operation failed due to network latency (or) send/receive related timeouts. */
printf( "Reason : MQTT packet send or receive operation failed... \n\n" );
break;
/* Bad response from MQTT broker. Possibly received MQTT packet with invalid packet type ID. */
printf( "Reason : Bad response from MQTT broker... \n\n" );
break;
default :
printf( "\n Unknown disconnect reason .....\n" );
break;
}
break;
/* Received MQTT messages on subscribed topic. */
printf( "\nEvent : Received MQTT subscribed message receive event.\n" );
received_msg = &(event.data.pub_msg.received_message);
printf( "Incoming Publish Topic Name: %.*s\n", received_msg->topic_len, received_msg->topic );
printf( "Incoming Publish message Packet Id is %u.\n", event.data.pub_msg.packet_id );
printf( "Incoming Publish Message : %.*s.\n\n", ( int )received_msg->payload_len, ( const char * )received_msg->payload );
break;
default :
printf( "\nUNKNOWN EVENT .....\n" );
break;
}
}
void snippet_cy_mqtt_create_secure( void )
{
/* Status variables for various operations. */
cy_rslt_t TestRes = CY_RSLT_SUCCESS;
cy_mqtt_broker_info_t broker_info;
cy_awsport_ssl_credentials_t credentials;
cy_awsport_ssl_credentials_t *security = NULL;
uint8_t *buffer = NULL;
(void)TestRes;
/* Initialize the MQTT network socket. */
TestRes = cy_mqtt_init();
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/*Allocate the network buffer. */
buffer = (uint8_t *) malloc( sizeof(uint8_t) * NETWORK_BUFFER_SIZE );
if( buffer == NULL )
{
/* Failure path. */
return;
}
memset( &broker_info, 0x00, sizeof( cy_mqtt_broker_info_t ) );
memset( &credentials, 0x00, sizeof( cy_awsport_ssl_credentials_t ) );
/* Set the credential information. */
credentials.client_cert = (const char *) &client_cert;
credentials.client_cert_size = sizeof( client_cert );
credentials.private_key = (const char *) &client_key;
credentials.private_key_size = sizeof( client_key );
credentials.root_ca = (const char *) &root_ca_cert;
credentials.root_ca_size = sizeof( root_ca_cert );
security = &credentials;
/* MQTT broker information. */
broker_info.hostname = MQTT_BROKER;
broker_info.hostname_len = strlen(MQTT_BROKER);
broker_info.port = MQTT_PORT_SECURED;
/* Create MQTT Handle. */
TestRes = cy_mqtt_create( buffer, NETWORK_BUFFER_SIZE,
security, &broker_info,
"broker1",
&secure_mqtthandle );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Register callback for MQTT events. */
TestRes = cy_mqtt_register_event_callback(secure_mqtthandle, (cy_mqtt_callback_t)mqtt_secure_event_cb, NULL);
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
}
void(* cy_mqtt_callback_t)(cy_mqtt_t mqtt_handle, cy_mqtt_event_t event, void *user_data)
MQTT event callback functions type used to process the disconnect event and incoming MQTT publish pac...
Definition: cy_mqtt_api.h:426
cy_rslt_t cy_mqtt_register_event_callback(cy_mqtt_t mqtt_handle, cy_mqtt_callback_t event_callback, void *user_data)
Registers an event callback for the given MQTT handle.
cy_rslt_t cy_mqtt_create(uint8_t *buffer, uint32_t buff_len, cy_awsport_ssl_credentials_t *security, cy_mqtt_broker_info_t *broker_info, char *descriptor, cy_mqtt_t *mqtt_handle)
Creates an MQTT instance and initializes its members based on the supplied arguments.
@ CY_MQTT_EVENT_TYPE_DISCONNECT
Disconnected from MQTT broker.
Definition: cy_mqtt_api.h:270
@ CY_MQTT_EVENT_TYPE_SUBSCRIPTION_MESSAGE_RECEIVE
Message from the subscribed topic.
Definition: cy_mqtt_api.h:269
@ CY_MQTT_DISCONN_TYPE_NETWORK_DOWN
Network is disconnected.
Definition: cy_mqtt_api.h:280
@ CY_MQTT_DISCONN_TYPE_SND_RCV_FAIL
MQTT packet send or receive operation failed due to network latency (or) send/receive related timeout...
Definition: cy_mqtt_api.h:282
@ CY_MQTT_DISCONN_TYPE_BAD_RESPONSE
Bad response from MQTT broker.
Definition: cy_mqtt_api.h:281
@ CY_MQTT_DISCONN_TYPE_BROKER_DOWN
Keep-alive not received from broker, possibly broker is down
Definition: cy_mqtt_api.h:279
MQTT broker information structure.
Definition: cy_mqtt_api.h:339
const char * hostname
Server host name.
Definition: cy_mqtt_api.h:340
uint16_t hostname_len
Length of the server host name.
Definition: cy_mqtt_api.h:341
uint16_t port
Server port in host-order.
Definition: cy_mqtt_api.h:342
MQTT event information structure.
Definition: cy_mqtt_api.h:380
union cy_mqtt_event_t::@0 data
Event data.
cy_mqtt_message_t pub_msg
Received MQTT message for event type CY_MQTT_EVENT_TYPE_SUBSCRIPTION_MESSAGE_RECEIVE.
Definition: cy_mqtt_api.h:385
cy_mqtt_event_type_t type
Event type.
Definition: cy_mqtt_api.h:381
cy_mqtt_disconn_type_t reason
Disconnection reason for event type CY_MQTT_EVENT_TYPE_DISCONNECT.
Definition: cy_mqtt_api.h:384
uint16_t packet_id
Packet ID of the MQTT message.
Definition: cy_mqtt_api.h:372
MQTT publish information structure.
Definition: cy_mqtt_api.h:325
size_t payload_len
Message payload length.
Definition: cy_mqtt_api.h:332
const char * payload
Message payload.
Definition: cy_mqtt_api.h:331
const char * topic
Topic name on which the message is published.
Definition: cy_mqtt_api.h:329
uint16_t topic_len
Length of topic name.
Definition: cy_mqtt_api.h:330

Code Snippet 3: Creating an MQTT instance for a non-secured connection with an MQTT broker

This code snippet demonstrates the initialization of the configuration structures required for creating an MQTT client handle for establishing a non-secured connection with an MQTT broker, and the usage of the cy_mqtt_create() API function.

#define MQTT_BROKER " " /* Add the broker end point info here. */
#define MQTT_PORT_NON_SECURED ( 1883 )
#define NETWORK_BUFFER_SIZE ( 1024U )
cy_mqtt_t nonsecure_mqtthandle;
/* Callback function registered with MQTT library while creating handle for MQTT connection.
This callback function will be called by MQTT library upon receiving MQTT messages on subscribed topics or when
network disconnection happens. */
void mqtt_non_secure_event_cb( cy_mqtt_t mqtt_handle, cy_mqtt_event_t event, void *user_data )
{
printf( "\nMQTT App callback with handle : %p \n", mqtt_handle );
(void)user_data;
switch( event.type )
{
printf( "\nEvent : Received MQTT Disconnect event.\n" );
switch( event.data.reason )
{
/* Keep-alive response not received from broker, possibly broker is down. */
printf( "Reason : MQTT Ping response not received within keep-alive response timeout... \n\n" );
break;
/* Network is disconnected. */
printf( "Reason : Network is disconnected... \n\n" );
break;
/* MQTT packet send or receive operation failed due to network latency (or) send/receive related timeouts. */
printf( "Reason : MQTT packet send or receive operation failed... \n\n" );
break;
/* Bad response from MQTT broker. Possibly received MQTT packet with invalid packet type ID. */
printf( "Reason : Bad response from MQTT broker... \n\n" );
break;
default :
printf( "\n Unknown disconnect reason .....\n" );
break;
}
break;
/* Received MQTT messages on subscribed topic. */
printf( "\nEvent : Received MQTT subscribed message receive event.\n" );
received_msg = &(event.data.pub_msg.received_message);
printf( "Incoming Publish Topic Name: %.*s\n", received_msg->topic_len, received_msg->topic );
printf( "Incoming Publish message Packet Id is %u.\n", event.data.pub_msg.packet_id );
printf( "Incoming Publish Message : %.*s.\n\n", ( int )received_msg->payload_len, ( const char * )received_msg->payload );
break;
default :
printf( "\nUNKNOWN EVENT .....\n" );
break;
}
}
void snippet_cy_mqtt_create_non_secure( void )
{
/* Status variables for various operations. */
cy_rslt_t TestRes = CY_RSLT_SUCCESS;
cy_mqtt_broker_info_t broker_info;
uint8_t *buffer = NULL;
(void)TestRes;
/* Initialize the MQTT network socket. */
TestRes = cy_mqtt_init();
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/*Allocate the network buffer. */
buffer = (uint8_t *) malloc( sizeof(uint8_t) * NETWORK_BUFFER_SIZE );
if( buffer == NULL )
{
/* Failure path. */
return;
}
memset( &broker_info, 0x00, sizeof( cy_mqtt_broker_info_t ) );
/* MQTT broker information. */
broker_info.hostname = MQTT_BROKER;
broker_info.hostname_len = strlen(MQTT_BROKER);
broker_info.port = MQTT_PORT_NON_SECURED;
/* Create MQTT Handle. */
TestRes = cy_mqtt_create( buffer, NETWORK_BUFFER_SIZE,
NULL, &broker_info,
"broker2",
&nonsecure_mqtthandle );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Register callback for MQTT events. */
TestRes = cy_mqtt_register_event_callback(nonsecure_mqtthandle, (cy_mqtt_callback_t)mqtt_non_secure_event_cb, NULL);
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
}

Code Snippet 4: Establishing an MQTT client session

This code snippet demonstrates the steps to establish an MQTT client session with an MQTT broker using the previously created MQTT handle, and the usage of the cy_mqtt_connect() API function.

#define MQTT_BROKER " " /* Add the broker end point info here. */
#define MQTT_PORT_SECURED ( 8883 )
#define MQTT_CLIENT_IDENTIFIER "CypressTest"
#define MQTT_CLIENT_IDENTIFIER_LENGTH ( ( uint16_t ) ( sizeof( MQTT_CLIENT_IDENTIFIER ) - 1 ) )
#define MQTT_KEEP_ALIVE_INTERVAL_SECONDS ( 60U )
#define MQTT_QOS2 ( 2U )
#define MQTT_TOPIC "Test_Topic"
#define MQTT_TOPIC_LENGTH ( ( uint16_t ) ( sizeof( MQTT_TOPIC ) - 1 ) )
#define MQTT_WILL_MESSAGE "Will message - World!"
#define MQTT_WILL_MESSAGE_LENGTH ( ( uint16_t ) ( sizeof( MQTT_WILL_MESSAGE ) - 1 ) )
#define NETWORK_BUFFER_SIZE ( 1024U )
static const char clientcert[] = { "Paste client certificate here" };
static const char clientkey[] = { "Paste client key here" };
static const char rootcacertificate[] = { "Paste RootCA certificate here" };
cy_mqtt_t mqtthandle;
/* Callback function registered with MQTT library while creating handle for MQTT connection.
This callback function will be called by MQTT library upon receiving MQTT messages on subscribed topics or when
network disconnection happens. */
static void mqtt_event_cb( cy_mqtt_t mqtt_handle, cy_mqtt_event_t event, void *user_data )
{
printf( "\nMQTT App callback with handle : %p \n", mqtt_handle );
(void)user_data;
switch( event.type )
{
printf( "\nEvent : Received MQTT Disconnect event.\n" );
switch( event.data.reason )
{
/* Keep-alive response not received from broker, possibly broker is down. */
printf( "Reason : MQTT Ping response not received within keep-alive response timeout... \n\n" );
break;
/* Network is disconnected. */
printf( "Reason : Network is disconnected... \n\n" );
break;
/* MQTT packet send or receive operation failed due to network latency (or) send/receive related timeouts. */
printf( "Reason : MQTT packet send or receive operation failed... \n\n" );
break;
/* Bad response from MQTT broker. Possibly received MQTT packet with invalid packet type ID. */
printf( "Reason : Bad response from MQTT broker... \n\n" );
break;
default :
printf( "\n Unknown disconnect reason .....\n" );
break;
}
break;
/* Received MQTT messages on subscribed topic. */
printf( "\nEvent : Received MQTT subscribed message receive event.\n" );
received_msg = &(event.data.pub_msg.received_message);
printf( "Incoming Publish Topic Name: %.*s\n", received_msg->topic_len, received_msg->topic );
printf( "Incoming Publish message Packet Id is %u.\n", event.data.pub_msg.packet_id );
printf( "Incoming Publish Message : %.*s.\n\n", ( int )received_msg->payload_len, ( const char * )received_msg->payload );
break;
default :
printf( "\nUNKNOWN EVENT .....\n" );
break;
}
}
void snippet_cy_mqtt_connect( void )
{
/* Status variables for various operations. */
cy_rslt_t TestRes = CY_RSLT_SUCCESS;
cy_mqtt_connect_info_t connect_info;
cy_mqtt_broker_info_t broker_info;
cy_awsport_ssl_credentials_t credentials;
cy_awsport_ssl_credentials_t *security = NULL;
uint8_t *buffer = NULL;
(void)TestRes;
/* Initialize the MQTT network socket. */
TestRes = cy_mqtt_init();
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/*Allocate the network buffer. */
buffer = (uint8_t *) malloc( sizeof(uint8_t) * NETWORK_BUFFER_SIZE );
if( buffer == NULL )
{
/* Failure path. */
return;
}
memset( &will_msg, 0x00, sizeof( cy_mqtt_publish_info_t ) );
memset( &broker_info, 0x00, sizeof( cy_mqtt_broker_info_t ) );
memset( &connect_info, 0x00, sizeof( cy_mqtt_connect_info_t ) );
memset( &credentials, 0x00, sizeof( cy_awsport_ssl_credentials_t ) );
/* Set the will information. */
will_msg.qos = (cy_mqtt_qos_t) MQTT_QOS2;
will_msg.topic = MQTT_TOPIC;
will_msg.topic_len = MQTT_TOPIC_LENGTH;
will_msg.payload = MQTT_WILL_MESSAGE;
will_msg.payload_len = MQTT_WILL_MESSAGE_LENGTH;
/* Set the credential information. */
credentials.client_cert = (const char *) &clientcert;
credentials.client_cert_size = sizeof( clientcert );
credentials.private_key = (const char *) &clientkey;
credentials.private_key_size = sizeof( clientkey );
credentials.root_ca = (const char *) &rootcacertificate;
credentials.root_ca_size = sizeof( rootcacertificate );
security = &credentials;
connect_info.client_id = MQTT_CLIENT_IDENTIFIER;
connect_info.client_id_len = MQTT_CLIENT_IDENTIFIER_LENGTH;
connect_info.keep_alive_sec = MQTT_KEEP_ALIVE_INTERVAL_SECONDS;
connect_info.will_info = &will_msg;
/* MQTT broker information. */
broker_info.hostname = MQTT_BROKER;
broker_info.hostname_len = strlen(MQTT_BROKER);
broker_info.port = MQTT_PORT_SECURED;
/* Create MQTT Handle. */
TestRes = cy_mqtt_create( buffer, NETWORK_BUFFER_SIZE,
security, &broker_info,
"broker3",
&mqtthandle );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Register callback for MQTT events. */
TestRes = cy_mqtt_register_event_callback(mqtthandle, (cy_mqtt_callback_t)mqtt_event_cb, NULL);
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
TestRes = cy_mqtt_connect( mqtthandle, &connect_info );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
}
cy_rslt_t cy_mqtt_connect(cy_mqtt_t mqtt_handle, cy_mqtt_connect_info_t *connect_info)
Connects to the given MQTT broker using a secured/non-secured TCP connection and establishes MQTT cli...
cy_mqtt_qos_t
MQTT QoS levels.
Definition: cy_mqtt_api.h:257
MQTT connect information structure.
Definition: cy_mqtt_api.h:349
cy_mqtt_publish_info_t * will_info
MQTT will message.
Definition: cy_mqtt_api.h:358
const char * client_id
MQTT client identifier.
Definition: cy_mqtt_api.h:350
uint16_t keep_alive_sec
MQTT keep alive period.
Definition: cy_mqtt_api.h:357
uint16_t client_id_len
Length of the client identifier.
Definition: cy_mqtt_api.h:351
cy_mqtt_qos_t qos
Quality of Service for message.
Definition: cy_mqtt_api.h:326

Code Snippet 5: MQTT subscribe and unsubscribe

This code snippet demonstrates the steps to subscribe for particular topic, unsubscribe from a previously subscribed MQTT topic, and the usage of the cy_mqtt_subscribe() and cy_mqtt_unsubscribe() API functions.

#define MQTT_BROKER " " /* Add the broker end point info here. */
#define MQTT_PORT_SECURED ( 8883 )
#define MQTT_CLIENT_IDENTIFIER "CypressTest"
#define MQTT_CLIENT_IDENTIFIER_LENGTH ( ( uint16_t ) ( sizeof( MQTT_CLIENT_IDENTIFIER ) - 1 ) )
#define MQTT_KEEP_ALIVE_INTERVAL_SECONDS ( 60U )
#define MQTT_QOS2 ( 2U )
#define MQTT_TOPIC "Test_Topic"
#define MQTT_TOPIC_LENGTH ( ( uint16_t ) ( sizeof( MQTT_TOPIC ) - 1 ) )
#define MQTT_WILL_MESSAGE "Will message - World!"
#define MQTT_WILL_MESSAGE_LENGTH ( ( uint16_t ) ( sizeof( MQTT_WILL_MESSAGE ) - 1 ) )
#define MQTT_NUM_OF_SUBS_IN_SINGLE_REQ ( 1U )
#define MQTT_NUM_OF_UNSUBS_IN_SINGLE_REQ MQTT_NUM_OF_SUBS_IN_SINGLE_REQ
#define NETWORK_BUFFER_SIZE ( 1024U )
static const char client_certificate[] = { "Paste client certificate here" };
static const char client_private_key[] = { "Paste client key here" };
static const char root_ca_certificate[] = { "Paste RootCA certificate here" };
cy_mqtt_t mqtt_handle;
/* Callback function registered with MQTT library while creating handle for MQTT connection.
This callback function will be called by MQTT library upon receiving MQTT messages on subscribed topics or when
network disconnection happens. */
void mqtt_eventcb( cy_mqtt_t mqtt_handle, cy_mqtt_event_t event, void *user_data )
{
printf( "\nMQTT App callback with handle : %p \n", mqtt_handle );
(void)user_data;
switch( event.type )
{
printf( "\nEvent : Received MQTT Disconnect event.\n" );
switch( event.data.reason )
{
/* Keep-alive response not received from broker, possibly broker is down. */
printf( "Reason : MQTT Ping response not received within keep-alive response timeout... \n\n" );
break;
/* Network is disconnected. */
printf( "Reason : Network is disconnected... \n\n" );
break;
/* MQTT packet send or receive operation failed due to network latency (or) send/receive related timeouts. */
printf( "Reason : MQTT packet send or receive operation failed... \n\n" );
break;
/* Bad response from MQTT broker. Possibly received MQTT packet with invalid packet type ID. */
printf( "Reason : Bad response from MQTT broker... \n\n" );
break;
default :
printf( "\n Unknown disconnect reason .....\n" );
break;
}
break;
/* Received MQTT messages on subscribed topic. */
printf( "\nEvent : Received MQTT subscribed message receive event.\n" );
received_msg = &(event.data.pub_msg.received_message);
printf( "Incoming Publish Topic Name: %.*s\n", received_msg->topic_len, received_msg->topic );
printf( "Incoming Publish message Packet Id is %u.\n", event.data.pub_msg.packet_id );
printf( "Incoming Publish Message : %.*s.\n\n", ( int )received_msg->payload_len, ( const char * )received_msg->payload );
break;
default :
printf( "\nUNKNOWN EVENT .....\n" );
break;
}
}
void snippet_cy_mqtt_subscribe_unsubscribe( void )
{
/* Status variables for various operations. */
cy_rslt_t TestRes = CY_RSLT_SUCCESS;
cy_mqtt_connect_info_t connect_info;
cy_mqtt_broker_info_t broker_info;
cy_awsport_ssl_credentials_t credentials;
cy_awsport_ssl_credentials_t *security = NULL;
uint8_t *buffer = NULL;
(void)TestRes;
/* Initialize the MQTT network socket. */
TestRes = cy_mqtt_init();
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/*Allocate the network buffer. */
buffer = (uint8_t *) malloc( sizeof(uint8_t) * NETWORK_BUFFER_SIZE );
if( buffer == NULL )
{
/* Failure path. */
return;
}
memset( &will_msg, 0x00, sizeof( cy_mqtt_publish_info_t ) );
memset( &broker_info, 0x00, sizeof( cy_mqtt_broker_info_t ) );
memset( &connect_info, 0x00, sizeof( cy_mqtt_connect_info_t ) );
memset( &credentials, 0x00, sizeof( cy_awsport_ssl_credentials_t ) );
memset( &sub_msg, 0x00, sizeof( cy_mqtt_subscribe_info_t ) );
memset( &unsub_msg, 0x00, sizeof( cy_mqtt_unsubscribe_info_t ) );
/* Set the will information. */
will_msg.qos = (cy_mqtt_qos_t)MQTT_QOS2;
will_msg.topic = MQTT_TOPIC;
will_msg.topic_len = MQTT_TOPIC_LENGTH;
will_msg.payload = MQTT_WILL_MESSAGE;
will_msg.payload_len = MQTT_WILL_MESSAGE_LENGTH;
/* Set the credential information. */
credentials.client_cert = (const char *) &client_certificate;
credentials.client_cert_size = sizeof( client_certificate );
credentials.private_key = (const char *) &client_private_key;
credentials.private_key_size = sizeof( client_private_key );
credentials.root_ca = (const char *) &root_ca_certificate;
credentials.root_ca_size = sizeof( root_ca_certificate );
security = &credentials;
connect_info.client_id = MQTT_CLIENT_IDENTIFIER;
connect_info.client_id_len = MQTT_CLIENT_IDENTIFIER_LENGTH;
connect_info.keep_alive_sec = MQTT_KEEP_ALIVE_INTERVAL_SECONDS;
connect_info.will_info = &will_msg;
/* MQTT broker information. */
broker_info.hostname = MQTT_BROKER;
broker_info.hostname_len = strlen(MQTT_BROKER);
broker_info.port = MQTT_PORT_SECURED;
/* Create MQTT Handle. */
TestRes = cy_mqtt_create( buffer, NETWORK_BUFFER_SIZE,
security, &broker_info,
"broker4",
&mqtt_handle );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Register callback for MQTT events. */
TestRes = cy_mqtt_register_event_callback(mqtt_handle, (cy_mqtt_callback_t)mqtt_eventcb, NULL);
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
TestRes = cy_mqtt_connect( mqtt_handle, &connect_info );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Subscribe request. */
sub_msg[0].qos = (cy_mqtt_qos_t)MQTT_QOS2;
sub_msg[0].topic = MQTT_TOPIC;
sub_msg[0].topic_len = MQTT_TOPIC_LENGTH;
TestRes = cy_mqtt_subscribe( mqtt_handle, &sub_msg[0], MQTT_NUM_OF_SUBS_IN_SINGLE_REQ );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Check status of MQTT broker allocated QoS level for subscribed topics in subscribe request. */
if( sub_msg[0].allocated_qos == CY_MQTT_QOS_INVALID )
{
/* MQTT broker rejected subscribe request for the given topic/QoS level. */
}
else
{
/* MQTT broker assigned the QoS level 'sub_msg[0].allocated_qos' for the subscribed topic. */
}
/*
* Wait for some time for subscribed topic messages.
* Once after receiving the message on the subscribed topic, callback function
* mqtt_eventcb() will be called from mqtt library context with
* receive event type 'CY_MQTT_EVENT_TYPE_SUBSCRIPTION_MESSAGE_RECEIVE' and payload.
*
* ----- Add the code logic here to wait for the subscribed messages. -----
*
*/
/* Unsubscribe request. */
unsub_msg[0].qos = (cy_mqtt_qos_t)MQTT_QOS2;
unsub_msg[0].topic = MQTT_TOPIC;
unsub_msg[0].topic_len = MQTT_TOPIC_LENGTH;
TestRes = cy_mqtt_unsubscribe( mqtt_handle, &unsub_msg[0], MQTT_NUM_OF_UNSUBS_IN_SINGLE_REQ );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
}
cy_rslt_t cy_mqtt_unsubscribe(cy_mqtt_t mqtt_handle, cy_mqtt_unsubscribe_info_t *unsub_info, uint8_t unsub_count)
Unsubscribes from a given MQTT topic.
cy_rslt_t cy_mqtt_subscribe(cy_mqtt_t mqtt_handle, cy_mqtt_subscribe_info_t *sub_info, uint8_t sub_count)
Subscribes for MQTT message on the given MQTT topic or list of topics.
@ CY_MQTT_QOS_INVALID
Invalid QoS.
Definition: cy_mqtt_api.h:261
MQTT subscribe information structure.
Definition: cy_mqtt_api.h:313
uint16_t topic_len
Length of subscription topic filter.
Definition: cy_mqtt_api.h:316
const char * topic
Topic filter to subscribe to.
Definition: cy_mqtt_api.h:315
cy_mqtt_qos_t qos
Requested quality of Service for the subscription.
Definition: cy_mqtt_api.h:314

Code Snippet 6: MQTT publish

This code snippet demonstrates the steps to publish messages on an MQTT topic, and the usage of the cy_mqtt_publish() API function. You can choose an appropriate QoS level for the application. In this snippet, the QoS level is set as 2.

#define MQTT_BROKER " " /* Add the broker end point info here. */
#define MQTT_PORT_SECURED ( 8883 )
#define MQTT_CLIENT_IDENTIFIER "CypressTest"
#define MQTT_CLIENT_IDENTIFIER_LENGTH ( ( uint16_t ) ( sizeof( MQTT_CLIENT_IDENTIFIER ) - 1 ) )
#define MQTT_KEEP_ALIVE_INTERVAL_SECONDS ( 60U )
#define MQTT_QOS2 ( 2U )
#define MQTT_TOPIC "Test_Topic"
#define MQTT_TOPIC_LENGTH ( ( uint16_t ) ( sizeof( MQTT_TOPIC ) - 1 ) )
#define MQTT_WILL_MESSAGE "Will message - World!"
#define MQTT_WILL_MESSAGE_LENGTH ( ( uint16_t ) ( sizeof( MQTT_WILL_MESSAGE ) - 1 ) )
#define MQTT_PUB_MESSAGE "Publish - Hello MQTT!"
#define MQTT_PUB_MESSAGE_LENGTH ( ( uint16_t ) ( sizeof( MQTT_PUB_MESSAGE ) - 1 ) )
#define NETWORK_BUFFER_SIZE ( 1024U )
static const char clientcertificate[] = { "Paste client certificate here" };
static const char clientprivate_key[] = { "Paste client key here" };
static const char rootca_certificate[] = { "Paste RootCA certificate here" };
cy_mqtt_t MQTThandle;
/* Callback function registered with MQTT library while creating handle for MQTT connection.
This callback function will be called by MQTT library upon receiving MQTT messages on subscribed topics or when
network disconnection happens. */
void mqtt_event_call_back( cy_mqtt_t mqtt_handle, cy_mqtt_event_t event, void *user_data )
{
printf( "\nMQTT App callback with handle : %p \n", mqtt_handle );
(void)user_data;
switch( event.type )
{
printf( "\nEvent : Received MQTT Disconnect event.\n" );
switch( event.data.reason )
{
/* Keep-alive response not received from broker, possibly broker is down. */
printf( "Reason : MQTT Ping response not received within keep-alive response timeout... \n\n" );
break;
/* Network is disconnected. */
printf( "Reason : Network is disconnected... \n\n" );
break;
/* MQTT packet send or receive operation failed due to network latency (or) send/receive related timeouts. */
printf( "Reason : MQTT packet send or receive operation failed... \n\n" );
break;
/* Bad response from MQTT broker. Possibly received MQTT packet with invalid packet type ID. */
printf( "Reason : Bad response from MQTT broker... \n\n" );
break;
default :
printf( "\n Unknown disconnect reason .....\n" );
break;
}
break;
/* Received MQTT messages on subscribed topic. */
printf( "\nEvent : Received MQTT subscribed message receive event.\n" );
received_msg = &(event.data.pub_msg.received_message);
printf( "Incoming Publish Topic Name: %.*s\n", received_msg->topic_len, received_msg->topic );
printf( "Incoming Publish message Packet Id is %u.\n", event.data.pub_msg.packet_id );
printf( "Incoming Publish Message : %.*s.\n\n", ( int )received_msg->payload_len, ( const char * )received_msg->payload );
break;
default :
printf( "\nUNKNOWN EVENT .....\n" );
break;
}
}
void snippet_cy_mqtt_publish( void )
{
/* Status variables for various operations. */
cy_rslt_t TestRes = CY_RSLT_SUCCESS;
cy_mqtt_connect_info_t connect_info;
cy_mqtt_broker_info_t broker_info;
cy_awsport_ssl_credentials_t credentials;
cy_awsport_ssl_credentials_t *security = NULL;
uint8_t *buffer = NULL;
(void)TestRes;
/* Initialize the MQTT network socket. */
TestRes = cy_mqtt_init();
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/*Allocate the network buffer. */
buffer = (uint8_t *) malloc( sizeof(uint8_t) * NETWORK_BUFFER_SIZE );
if( buffer == NULL )
{
/* Failure path. */
return;
}
memset( &will_msg, 0x00, sizeof( cy_mqtt_publish_info_t ) );
memset( &broker_info, 0x00, sizeof( cy_mqtt_broker_info_t ) );
memset( &connect_info, 0x00, sizeof( cy_mqtt_connect_info_t ) );
memset( &credentials, 0x00, sizeof( cy_awsport_ssl_credentials_t ) );
memset( &pub_msg, 0x00, sizeof( cy_mqtt_publish_info_t ) );
/* Set the will information. */
will_msg.qos = (cy_mqtt_qos_t)MQTT_QOS2;
will_msg.topic = MQTT_TOPIC;
will_msg.topic_len = MQTT_TOPIC_LENGTH;
will_msg.payload = MQTT_WILL_MESSAGE;
will_msg.payload_len = MQTT_WILL_MESSAGE_LENGTH;
/* Set the credential information. */
credentials.client_cert = (const char *) &clientcertificate;
credentials.client_cert_size = sizeof( clientcertificate );
credentials.private_key = (const char *) &clientprivate_key;
credentials.private_key_size = sizeof( clientprivate_key );
credentials.root_ca = (const char *) &rootca_certificate;
credentials.root_ca_size = sizeof( rootca_certificate );
security = &credentials;
connect_info.client_id = MQTT_CLIENT_IDENTIFIER;
connect_info.client_id_len = MQTT_CLIENT_IDENTIFIER_LENGTH;
connect_info.keep_alive_sec = MQTT_KEEP_ALIVE_INTERVAL_SECONDS;
connect_info.will_info = &will_msg;
/* MQTT broker information. */
broker_info.hostname = MQTT_BROKER;
broker_info.hostname_len = strlen(MQTT_BROKER);
broker_info.port = MQTT_PORT_SECURED;
/* Create MQTT Handle. */
TestRes = cy_mqtt_create( buffer, NETWORK_BUFFER_SIZE,
security, &broker_info,
"broker5",
&MQTThandle );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Register callback for MQTT events. */
TestRes = cy_mqtt_register_event_callback(MQTThandle, (cy_mqtt_callback_t)mqtt_event_call_back, NULL);
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
TestRes = cy_mqtt_connect( MQTThandle, &connect_info );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
pub_msg.qos = (cy_mqtt_qos_t)MQTT_QOS2;
pub_msg.topic = MQTT_TOPIC;
pub_msg.topic_len = MQTT_TOPIC_LENGTH;
pub_msg.payload = MQTT_PUB_MESSAGE;
pub_msg.payload_len = MQTT_PUB_MESSAGE_LENGTH;
TestRes = cy_mqtt_publish( MQTThandle, &pub_msg );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
}
cy_rslt_t cy_mqtt_publish(cy_mqtt_t mqtt_handle, cy_mqtt_publish_info_t *pub_msg)
Publishes the MQTT message on given MQTT topic.

Code Snippet 7: MQTT disconnect

This code snippet demonstrates the steps to end an already established MQTT client session with an MQTT broker, and the usage of the cy_mqtt_disconnect() API function.

#define MQTT_BROKER " " /* Add the broker end point info here. */
#define MQTT_PORT_SECURED ( 8883 )
#define MQTT_CLIENT_IDENTIFIER "CypressTest"
#define MQTT_CLIENT_IDENTIFIER_LENGTH ( ( uint16_t ) ( sizeof( MQTT_CLIENT_IDENTIFIER ) - 1 ) )
#define MQTT_KEEP_ALIVE_INTERVAL_SECONDS ( 60U )
#define MQTT_QOS2 ( 2U )
#define MQTT_TOPIC "Test_Topic"
#define MQTT_TOPIC_LENGTH ( ( uint16_t ) ( sizeof( MQTT_TOPIC ) - 1 ) )
#define MQTT_WILL_MESSAGE "Will message - World!"
#define MQTT_WILL_MESSAGE_LENGTH ( ( uint16_t ) ( sizeof( MQTT_WILL_MESSAGE ) - 1 ) )
#define NETWORK_BUFFER_SIZE ( 1024U )
static const char MQTT_clientcertificate[] = { "Paste client certificate here" };
static const char MQTT_clientprivate_key[] = { "Paste client key here" };
static const char MQTT_rootca_certificate[] = { "Paste RootCA certificate here" };
cy_mqtt_t MQTT_handle;
/* Callback function registered with MQTT library while creating handle for MQTT connection.
This callback function will be called by MQTT library upon receiving MQTT messages on subscribed topics or when
network disconnection happens. */
void mqtt_events_cb( cy_mqtt_t mqtt_handle, cy_mqtt_event_t event, void *user_data )
{
printf( "\nMQTT App callback with handle : %p \n", mqtt_handle );
(void)user_data;
switch( event.type )
{
printf( "\nEvent : Received MQTT Disconnect event.\n" );
switch( event.data.reason )
{
/* Keep-alive response not received from broker, possibly broker is down. */
printf( "Reason : MQTT Ping response not received within keep-alive response timeout... \n\n" );
break;
/* Network is disconnected. */
printf( "Reason : Network is disconnected... \n\n" );
break;
/* MQTT packet send or receive operation failed due to network latency (or) send/receive related timeouts. */
printf( "Reason : MQTT packet send or receive operation failed... \n\n" );
break;
/* Bad response from MQTT broker. Possibly received MQTT packet with invalid packet type ID. */
printf( "Reason : Bad response from MQTT broker... \n\n" );
break;
default :
printf( "\n Unknown disconnect reason .....\n" );
break;
}
break;
/* Received MQTT messages on subscribed topic. */
printf( "\nEvent : Received MQTT subscribed message receive event.\n" );
received_msg = &(event.data.pub_msg.received_message);
printf( "Incoming Publish Topic Name: %.*s\n", received_msg->topic_len, received_msg->topic );
printf( "Incoming Publish message Packet Id is %u.\n", event.data.pub_msg.packet_id );
printf( "Incoming Publish Message : %.*s.\n\n", ( int )received_msg->payload_len, ( const char * )received_msg->payload );
break;
default :
printf( "\nUNKNOWN EVENT .....\n" );
break;
}
}
void snippet_cy_mqtt_disconnect( void )
{
/* Status variables for various operations. */
/* Status variables for various operations. */
cy_rslt_t TestRes = CY_RSLT_SUCCESS;
cy_mqtt_connect_info_t connect_info;
cy_mqtt_broker_info_t broker_info;
cy_awsport_ssl_credentials_t credentials;
cy_awsport_ssl_credentials_t *security = NULL;
uint8_t *buffer = NULL;
(void)TestRes;
/* Initialize the MQTT network socket. */
TestRes = cy_mqtt_init();
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/*Allocate the network buffer. */
buffer = (uint8_t *) malloc( sizeof(uint8_t) * NETWORK_BUFFER_SIZE );
if( buffer == NULL )
{
/* Failure path. */
return;
}
memset( &will_msg, 0x00, sizeof( cy_mqtt_publish_info_t ) );
memset( &broker_info, 0x00, sizeof( cy_mqtt_broker_info_t ) );
memset( &connect_info, 0x00, sizeof( cy_mqtt_connect_info_t ) );
memset( &credentials, 0x00, sizeof( cy_awsport_ssl_credentials_t ) );
/* Set the will information. */
will_msg.qos = (cy_mqtt_qos_t)MQTT_QOS2;
will_msg.topic = MQTT_TOPIC;
will_msg.topic_len = MQTT_TOPIC_LENGTH;
will_msg.payload = MQTT_WILL_MESSAGE;
will_msg.payload_len = MQTT_WILL_MESSAGE_LENGTH;
/* Set the credential information. */
credentials.client_cert = (const char *) &MQTT_clientcertificate;
credentials.client_cert_size = sizeof( MQTT_clientcertificate );
credentials.private_key = (const char *) &MQTT_clientprivate_key;
credentials.private_key_size = sizeof( MQTT_clientprivate_key );
credentials.root_ca = (const char *) &MQTT_rootca_certificate;
credentials.root_ca_size = sizeof( MQTT_rootca_certificate );
security = &credentials;
connect_info.client_id = MQTT_CLIENT_IDENTIFIER;
connect_info.client_id_len = MQTT_CLIENT_IDENTIFIER_LENGTH;
connect_info.keep_alive_sec = MQTT_KEEP_ALIVE_INTERVAL_SECONDS;
connect_info.will_info = &will_msg;
/* MQTT broker information. */
broker_info.hostname = MQTT_BROKER;
broker_info.hostname_len = strlen(MQTT_BROKER);
broker_info.port = MQTT_PORT_SECURED;
/* Create MQTT Handle. */
TestRes = cy_mqtt_create( buffer, NETWORK_BUFFER_SIZE,
security, &broker_info,
"broker6",
&MQTT_handle );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Register callback for MQTT events. */
TestRes = cy_mqtt_register_event_callback(MQTT_handle, (cy_mqtt_callback_t)mqtt_events_cb, NULL);
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
TestRes = cy_mqtt_connect( MQTT_handle, &connect_info );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Do MQTT publish and subscribe here. */
/* Calling MQTT disconnect to end the MQTT client session with the broker. */
TestRes = cy_mqtt_disconnect( MQTT_handle );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
}
cy_rslt_t cy_mqtt_disconnect(cy_mqtt_t mqtt_handle)
Initiates MQTT client disconnection from connected MQTT broker.

Code Snippet 8: MQTT delete and deinit

This code snippet demonstrates the de-allocation of the configuration structures and resources which are allocated during an MQTT client handle creation, and the usage of the cy_mqtt_delete() and cy_mqtt_deinit() API functions.

#define MQTT_BROKER " " /* Add the broker end point info here. */
#define MQTT_PORT_SECURED ( 8883 )
#define MQTT_CLIENT_IDENTIFIER "CypressTest"
#define MQTT_CLIENT_IDENTIFIER_LENGTH ( ( uint16_t ) ( sizeof( MQTT_CLIENT_IDENTIFIER ) - 1 ) )
#define MQTT_KEEP_ALIVE_INTERVAL_SECONDS ( 60U )
#define MQTT_QOS2 ( 2U )
#define MQTT_TOPIC "Test_Topic"
#define MQTT_TOPIC_LENGTH ( ( uint16_t ) ( sizeof( MQTT_TOPIC ) - 1 ) )
#define MQTT_WILL_MESSAGE "Will message - World!"
#define MQTT_WILL_MESSAGE_LENGTH ( ( uint16_t ) ( sizeof( MQTT_WILL_MESSAGE ) - 1 ) )
#define NETWORK_BUFFER_SIZE ( 1024U )
static const char MQTT_client_certificate[] = { "Paste client certificate here" };
static const char MQTT_client_key[] = { "Paste client key here" };
static const char MQTT_root_ca_certificate[] = { "Paste RootCA certificate here" };
cy_mqtt_t MQTT_obj_handle;
/* Callback function registered with MQTT library while creating handle for MQTT connection.
This callback function will be called by MQTT library upon receiving MQTT messages on subscribed topics or when
network disconnection happens. */
void mqtt_callback( cy_mqtt_t mqtt_handle, cy_mqtt_event_t event, void *user_data )
{
printf( "\nMQTT App callback with handle : %p \n", mqtt_handle );
(void)user_data;
switch( event.type )
{
printf( "\nEvent : Received MQTT Disconnect event.\n" );
switch( event.data.reason )
{
/* Keep-alive response not received from broker, possibly broker is down. */
printf( "Reason : MQTT Ping response not received within keep-alive response timeout... \n\n" );
break;
/* Network is disconnected. */
printf( "Reason : Network is disconnected... \n\n" );
break;
/* MQTT packet send or receive operation failed due to network latency (or) send/receive related timeouts. */
printf( "Reason : MQTT packet send or receive operation failed... \n\n" );
break;
/* Bad response from MQTT broker. Possibly received MQTT packet with invalid packet type ID. */
printf( "Reason : Bad response from MQTT broker... \n\n" );
break;
default :
printf( "\n Unknown disconnect reason .....\n" );
break;
}
break;
/* Received MQTT messages on subscribed topic. */
printf( "\nEvent : Received MQTT subscribed message receive event.\n" );
received_msg = &(event.data.pub_msg.received_message);
printf( "Incoming Publish Topic Name: %.*s\n", received_msg->topic_len, received_msg->topic );
printf( "Incoming Publish message Packet Id is %u.\n", event.data.pub_msg.packet_id );
printf( "Incoming Publish Message : %.*s.\n\n", ( int )received_msg->payload_len, ( const char * )received_msg->payload );
break;
default :
printf( "\nUNKNOWN EVENT .....\n" );
break;
}
}
void snippet_cy_mqtt_delete( void )
{
/* Status variables for various operations. */
/* Status variables for various operations */
cy_rslt_t TestRes = CY_RSLT_SUCCESS;
cy_mqtt_broker_info_t broker_info;
cy_awsport_ssl_credentials_t credentials;
cy_awsport_ssl_credentials_t *security = NULL;
uint8_t *buffer = NULL;
(void)TestRes;
/* Initialize the MQTT network socket. */
TestRes = cy_mqtt_init();
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/*Allocate the network buffer. */
buffer = (uint8_t *) malloc( sizeof(uint8_t) * NETWORK_BUFFER_SIZE );
if( buffer == NULL )
{
/* Failure path. */
return;
}
memset( &broker_info, 0x00, sizeof( cy_mqtt_broker_info_t ) );
memset( &credentials, 0x00, sizeof( cy_awsport_ssl_credentials_t ) );
/* Set the credential information. */
credentials.client_cert = (const char *) &MQTT_client_certificate;
credentials.client_cert_size = sizeof( MQTT_client_certificate );
credentials.private_key = (const char *) &MQTT_client_key;
credentials.private_key_size = sizeof( MQTT_client_key );
credentials.root_ca = (const char *) &MQTT_root_ca_certificate;
credentials.root_ca_size = sizeof( MQTT_root_ca_certificate );
security = &credentials;
/* MQTT broker information. */
broker_info.hostname = MQTT_BROKER;
broker_info.hostname_len = strlen(MQTT_BROKER);
broker_info.port = MQTT_PORT_SECURED;
/* Create MQTT Handle. */
TestRes = cy_mqtt_create( buffer, NETWORK_BUFFER_SIZE,
security, &broker_info,
"broker7",
&MQTT_obj_handle );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Register callback for MQTT events. */
TestRes = cy_mqtt_register_event_callback(MQTT_obj_handle, (cy_mqtt_callback_t)mqtt_callback, NULL);
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Calling MQTT Delete to clean up the resources allocated during create. */
TestRes = cy_mqtt_delete( MQTT_obj_handle );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
MQTT_obj_handle = NULL;
/* De-initialize the MQTT network socket. */
TestRes = cy_mqtt_deinit();
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
}
cy_rslt_t cy_mqtt_deinit(void)
One-time deinitialization function for network sockets implementation.
cy_rslt_t cy_mqtt_delete(cy_mqtt_t mqtt_handle)
Deletes the given MQTT instance and frees the resources allocated for the instance by the cy_mqtt_cre...

Code Snippet 9: MQTT client on the secured platform CY8CKIT-064S0S2-4343W

This code snippet demonstrates the steps to establish an MQTT client session using the certificates and keys stored in the secured memory.

#define MQTT_BROKER " " /* Add the broker end point info here. */
#define MQTT_PORT_SECURED ( 8883 )
#define MQTT_CLIENT_IDENTIFIER "CypressTest"
#define MQTT_CLIENT_IDENTIFIER_LENGTH ( ( uint16_t ) ( sizeof( MQTT_CLIENT_IDENTIFIER ) - 1 ) )
#define MQTT_KEEP_ALIVE_INTERVAL_SECONDS ( 60U )
#define NETWORK_BUFFER_SIZE ( 1024U )
cy_mqtt_t mqtthandle_pkcs;
/* Callback function registered with MQTT library while creating handle for MQTT connection.
This callback function will be called by MQTT library upon receiving MQTT messages on subscribed topics or when
network disconnection happens. */
static void mqtt_event_cb_pkcs( cy_mqtt_t mqtt_handle, cy_mqtt_event_t event, void *user_data )
{
printf( "\nMQTT App callback with handle : %p \n", mqtt_handle );
(void)user_data;
switch( event.type )
{
printf( "\nEvent : Received MQTT Disconnect event.\n" );
switch( event.data.reason )
{
/* Keep-alive response not received from broker, possibly broker is down. */
printf( "Reason : MQTT Ping response not received within keep-alive response timeout... \n\n" );
break;
/* Network is disconnected. */
printf( "Reason : Network is disconnected... \n\n" );
break;
/* MQTT packet send or receive operation failed due to network latency (or) send/receive related timeouts. */
printf( "Reason : MQTT packet send or receive operation failed... \n\n" );
break;
/* Bad response from MQTT broker. Possibly received MQTT packet with invalid packet type ID. */
printf( "Reason : Bad response from MQTT broker... \n\n" );
break;
default :
printf( "\n Unknown disconnect reason .....\n" );
break;
}
break;
/* Received MQTT messages on subscribed topic. */
printf( "\nEvent : Received MQTT subscribed message receive event.\n" );
received_msg = &(event.data.pub_msg.received_message);
printf( "Incoming Publish Topic Name: %.*s\n", received_msg->topic_len, received_msg->topic );
printf( "Incoming Publish message Packet Id is %u.\n", event.data.pub_msg.packet_id );
printf( "Incoming Publish Message : %.*s.\n\n", ( int )received_msg->payload_len, ( const char * )received_msg->payload );
break;
default :
printf( "\nUNKNOWN EVENT .....\n" );
break;
}
}
#ifdef CY_TFM_PSA_SUPPORTED
static struct ns_mailbox_queue_t ns_mailbox_queue;
static void tfm_ns_multi_core_boot(void)
{
int32_t ret;
if (tfm_ns_wait_for_s_cpu_ready())
{
/* Error sync'ing with secure core */
/* Avoid undefined behavior after multi-core sync-up failed */
for (;;)
{
}
}
ret = tfm_ns_mailbox_init(&ns_mailbox_queue);
if (ret != MAILBOX_SUCCESS)
{
/* Non-secure mailbox initialization failed. */
/* Avoid undefined behavior after NS mailbox initialization failed */
for (;;)
{
}
}
}
#endif
void snippet_cy_mqtt_connect_pkcs( void )
{
/* Status variables for various operations. */
cy_rslt_t TestRes = CY_RSLT_SUCCESS;
cy_mqtt_connect_info_t connect_info;
cy_mqtt_broker_info_t broker_info;
cy_awsport_ssl_credentials_t credentials;
cy_awsport_ssl_credentials_t *security = NULL;
uint8_t *buffer = NULL;
(void)TestRes;
#ifdef CY_TFM_PSA_SUPPORTED
tfm_ns_multi_core_boot();
/* Initialize TFM interface */
tfm_ns_interface_init();
#endif
/* Initialize the MQTT network socket. */
TestRes = cy_mqtt_init();
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/*Allocate the network buffer. */
buffer = (uint8_t *) malloc( sizeof(uint8_t) * NETWORK_BUFFER_SIZE );
if( buffer == NULL )
{
/* Failure path. */
return;
}
memset( &broker_info, 0x00, sizeof( cy_mqtt_broker_info_t ) );
memset( &connect_info, 0x00, sizeof( cy_mqtt_connect_info_t ) );
memset( &credentials, 0x00, sizeof( cy_awsport_ssl_credentials_t ) );
/* Do not pass any certificate and key from application. */
credentials.client_cert = NULL;
credentials.client_cert_size = 0;
credentials.private_key = NULL;
credentials.private_key_size = 0;
credentials.root_ca = NULL;
credentials.root_ca_size = 0;
security = &credentials;
connect_info.client_id = MQTT_CLIENT_IDENTIFIER;
connect_info.client_id_len = MQTT_CLIENT_IDENTIFIER_LENGTH;
connect_info.keep_alive_sec = MQTT_KEEP_ALIVE_INTERVAL_SECONDS;
connect_info.will_info = NULL;
/* MQTT broker information. */
broker_info.hostname = MQTT_BROKER;
broker_info.hostname_len = strlen(MQTT_BROKER);
broker_info.port = MQTT_PORT_SECURED;
/* Create MQTT Handle. */
TestRes = cy_mqtt_create( buffer, NETWORK_BUFFER_SIZE,
security, &broker_info,
"broker8",
&mqtthandle_pkcs );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Register callback for MQTT events. */
TestRes = cy_mqtt_register_event_callback(mqtthandle_pkcs, (cy_mqtt_callback_t)mqtt_event_cb_pkcs, NULL);
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* During connect, certificates and keys stored in secured memory of 'CY8CKIT-064S0S2-4343W' will be used. */
TestRes = cy_mqtt_connect( mqtthandle_pkcs, &connect_info );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
}

Code Snippet 10: MQTT get handle

This code snippet demonstrates the usage of cy_mqtt_get_handle API

#define MQTT_BROKER " " /* Add the broker end point info here. */
#define MQTT_PORT_SECURED ( 8883 )
#define MQTT_CLIENT_IDENTIFIER "CypressTest"
#define MQTT_CLIENT_IDENTIFIER_LENGTH ( ( uint16_t ) ( sizeof( MQTT_CLIENT_IDENTIFIER ) - 1 ) )
#define MQTT_KEEP_ALIVE_INTERVAL_SECONDS ( 60U )
#define MQTT_QOS2 ( 2U )
#define MQTT_TOPIC "Test_Topic"
#define MQTT_TOPIC_LENGTH ( ( uint16_t ) ( sizeof( MQTT_TOPIC ) - 1 ) )
#define MQTT_WILL_MESSAGE "Will message - World!"
#define MQTT_WILL_MESSAGE_LENGTH ( ( uint16_t ) ( sizeof( MQTT_WILL_MESSAGE ) - 1 ) )
#define NETWORK_BUFFER_SIZE ( 1024U )
static const char MQTTClientCertificate[] = { "Paste client certificate here" };
static const char MQTTClientKey[] = { "Paste client key here" };
static const char MQTTRootCACertificate[] = { "Paste RootCA certificate here" };
cy_mqtt_t MQTT_obj_handle;
/* Callback function registered with MQTT library while creating handle for MQTT connection.
This callback function will be called by MQTT library upon receiving MQTT messages on subscribed topics or when
network disconnection happens. */
void mqtt_call_back( cy_mqtt_t mqtt_handle, cy_mqtt_event_t event, void *user_data )
{
printf( "\nMQTT App callback with handle : %p \n", mqtt_handle );
(void)user_data;
switch( event.type )
{
printf( "\nEvent : Received MQTT Disconnect event.\n" );
switch( event.data.reason )
{
/* Keep-alive response not received from broker, possibly broker is down. */
printf( "Reason : MQTT Ping response not received within keep-alive response timeout... \n\n" );
break;
/* Network is disconnected. */
printf( "Reason : Network is disconnected... \n\n" );
break;
/* MQTT packet send or receive operation failed due to network latency (or) send/receive related timeouts. */
printf( "Reason : MQTT packet send or receive operation failed... \n\n" );
break;
/* Bad response from MQTT broker. Possibly received MQTT packet with invalid packet type ID. */
printf( "Reason : Bad response from MQTT broker... \n\n" );
break;
default :
printf( "\n Unknown disconnect reason .....\n" );
break;
}
break;
/* Received MQTT messages on subscribed topic. */
printf( "\nEvent : Received MQTT subscribed message receive event.\n" );
received_msg = &(event.data.pub_msg.received_message);
printf( "Incoming Publish Topic Name: %.*s\n", received_msg->topic_len, received_msg->topic );
printf( "Incoming Publish message Packet Id is %u.\n", event.data.pub_msg.packet_id );
printf( "Incoming Publish Message : %.*s.\n\n", ( int )received_msg->payload_len, ( const char * )received_msg->payload );
break;
default :
printf( "\nUNKNOWN EVENT .....\n" );
break;
}
}
void snippet_cy_mqtt_get_handle( void )
{
/* Status variables for various operations. */
/* Status variables for various operations */
cy_rslt_t TestRes = CY_RSLT_SUCCESS;
cy_mqtt_broker_info_t broker_info;
cy_awsport_ssl_credentials_t credentials;
cy_awsport_ssl_credentials_t *security = NULL;
uint8_t *buffer = NULL;
(void)TestRes;
cy_mqtt_t handle;
/* Initialize the MQTT network socket. */
TestRes = cy_mqtt_init();
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/*Allocate the network buffer. */
buffer = (uint8_t *) malloc( sizeof(uint8_t) * NETWORK_BUFFER_SIZE );
if( buffer == NULL )
{
/* Failure path. */
return;
}
memset( &broker_info, 0x00, sizeof( cy_mqtt_broker_info_t ) );
memset( &credentials, 0x00, sizeof( cy_awsport_ssl_credentials_t ) );
/* Set the credential information. */
credentials.client_cert = (const char *) &MQTTClientCertificate;
credentials.client_cert_size = sizeof( MQTTClientCertificate );
credentials.private_key = (const char *) &MQTTClientKey;
credentials.private_key_size = sizeof( MQTTClientKey );
credentials.root_ca = (const char *) &MQTTRootCACertificate;
credentials.root_ca_size = sizeof( MQTTRootCACertificate );
security = &credentials;
/* MQTT broker information. */
broker_info.hostname = MQTT_BROKER;
broker_info.hostname_len = strlen(MQTT_BROKER);
broker_info.port = MQTT_PORT_SECURED;
/* Create MQTT Handle. */
TestRes = cy_mqtt_create( buffer, NETWORK_BUFFER_SIZE,
security, &broker_info,
"broker7",
&MQTT_obj_handle );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Get MQTT handle using descriptor. */
TestRes = cy_mqtt_get_handle( &handle, "broker7");
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Register callback for MQTT events using the handle obtained above. */
TestRes = cy_mqtt_register_event_callback(handle, (cy_mqtt_callback_t)mqtt_call_back, NULL);
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
}
cy_rslt_t cy_mqtt_get_handle(cy_mqtt_t *mqtt_handle, char *descriptor)
Gets the MQTT handle associated with a user defined descriptor passed in cy_mqtt_create.

Code Snippet 11: MQTT virtual API usage to publish message

This code snippet demonstrates the steps to use the virtual APIs of MQTT in a multi-core environment to publish a message to an MQTT broker from the secondary core.

/***************************** Secondary core ***************************/
#define MQTT_QOS2 ( 2U )
#define MQTT_TOPIC "Test_Topic"
#define MQTT_TOPIC_LENGTH ( ( uint16_t ) ( sizeof( MQTT_TOPIC ) - 1 ) )
#define MQTT_PUB_MESSAGE "Publish - Hello MQTT!"
#define MQTT_PUB_MESSAGE_LENGTH ( ( uint16_t ) ( sizeof( MQTT_PUB_MESSAGE ) - 1 ) )
/* Flag to be set when VCM initialization is completed on the other core */
static bool is_vcm_init_complete = false;
/* Callback registered on the secondary core to handle events from VCM. */
void vcm_callback_sec_core(cy_vcm_event_t event)
{
switch(event)
{
case CY_VCM_EVENT_INIT_COMPLETE:
{
/* VCM init complete */
is_vcm_init_complete = true;
break;
}
default:
break;
}
}
/* The following snippet demostrates usage of VCM and virtual MQTT APIs from the secondary core.
* The primary core is where the full MQTT implementation is present. The secondary core only
* has the virtual implementation.
* In this example, the secondary core application runs first and it enables the primary core.
* Before enabling the primary core, the secondary core initializes VCM library.
*/
void snippet_mqtt_virtual_api_usage_sec_core( void )
{
cy_rslt_t TestRes = CY_RSLT_SUCCESS;
cy_vcm_config_t vcm_config;
(void)TestRes;
cy_mqtt_t handle;
/* Initialize the VCM library */
vcm_config.hal_resource_opt = CY_VCM_CREATE_HAL_RESOURCE; /* set to CY_VCM_CREATE_HAL_RESOURCE as the secondary core is the first one to initialize VCM. */
vcm_config.channel_num = CYHAL_IPC_CHAN_0;
vcm_config.event_cb = vcm_callback_sec_core;
TestRes = cy_vcm_init(&vcm_config);
if( TestRes != CY_RSLT_SUCCESS )
{
printf("\n cy_vcm_init failed on the secondary core! \n");
return;
}
/* Enable the other core.
* For example, for enabling CM4, the following code is applicable.
* When this is called, the application on core 2 will begin executing. Ensure cy_vcm_init()
* is called on the second core when the execution begins.
*/
Cy_SysEnableCM4(CY_CORTEX_M4_APPL_ADDR);
/* Wait for VCM initialization to complete */
while ( !is_vcm_init_complete )
{
cy_rtos_delay_milliseconds(1000);
}
/* Initialize the MQTT library */
TestRes = cy_mqtt_init();
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Ensure MQTT connection is established to "test-broker" in primary core. */
/* Get the MQTT handle using descriptor. */
TestRes = cy_mqtt_get_handle( &handle, "test-broker");
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Publish a message to the broker whose handle is obtained above. */
memset( &pub_msg, 0, sizeof(cy_mqtt_publish_info_t) );
pub_msg.qos = (cy_mqtt_qos_t)MQTT_QOS2;
pub_msg.topic = MQTT_TOPIC;
pub_msg.topic_len = MQTT_TOPIC_LENGTH;
pub_msg.payload = MQTT_PUB_MESSAGE;
pub_msg.payload_len = MQTT_PUB_MESSAGE_LENGTH;
TestRes = cy_mqtt_publish( handle, &pub_msg );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
while(1)
{
cy_rtos_delay_milliseconds(1000);
}
}
/***************************** Primary core ***************************/
#define MQTT_BROKER " " /* Add the broker end point info here. */
#define MQTT_PORT_SECURED ( 8883 )
#define MQTT_CLIENT_IDENTIFIER "CypressTest"
#define MQTT_CLIENT_IDENTIFIER_LENGTH ( ( uint16_t ) ( sizeof( MQTT_CLIENT_IDENTIFIER ) - 1 ) )
#define MQTT_KEEP_ALIVE_INTERVAL_SECONDS ( 60U )
#define NETWORK_BUFFER_SIZE ( 1024U )
static const char MQTTClientCertificate11[] = { "Paste client certificate here" };
static const char MQTTClientKey11[] = { "Paste client key here" };
static const char MQTTRootCACertificate11[] = { "Paste RootCA certificate here" };
cy_mqtt_t MQTT_obj_handle11;
/* Flag that is set when VCM deinit is started by the other core.
* When this event is received, call cy_vcm_deinit() to deinitialize VCM
* on the current core.
*/
static bool is_vcm_deinit_requested = false;
/* Callback registered on the primary core to handle events from VCM. */
void vcm_callback_prim_core(cy_vcm_event_t event)
{
switch(event)
{
case CY_VCM_EVENT_DEINIT:
{
/* The other core has initiated VCM deinit. Deinitialize VCM locally. */
is_vcm_deinit_requested = true;
break;
}
default:
break;
}
}
/* The following snippet demostrates usage of VCM on the primary core.
* The primary core is where the full MQTT implementation is present. The secondary core only
* has the virtual implementation. The primary core initializes creates an MQTT handle and
* establishes connection with a broker.
* Ensure that this snippet is executed when the primary core is enabled.
*/
void snippet_mqtt_virtual_api_usage_prim_core( void )
{
/* Status variables for various operations. */
cy_rslt_t TestRes = CY_RSLT_SUCCESS;
cy_vcm_config_t vcm_config;
cy_mqtt_broker_info_t broker_info;
cy_mqtt_connect_info_t connect_info;
cy_awsport_ssl_credentials_t credentials;
cy_awsport_ssl_credentials_t *security = NULL;
uint8_t *buffer = NULL;
(void)TestRes;
cy_mqtt_t MQTT_obj_handle;
/* Initialize the VCM library */
vcm_config.hal_resource_opt = CY_VCM_USE_HAL_RESOURCE; /* set to CY_VCM_USE_HAL_RESOURCE as primary core initializes VCM after the secondary core. */
vcm_config.channel_num = CYHAL_IPC_CHAN_0;
vcm_config.event_cb = vcm_callback_prim_core;
TestRes = cy_vcm_init(&vcm_config);
if( TestRes != CY_RSLT_SUCCESS )
{
printf("\n cy_vcm_init failed on primary core! \n");
return;
}
/* Initialize the MQTT library */
TestRes = cy_mqtt_init();
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/*Allocate the network buffer. */
buffer = (uint8_t *) malloc( sizeof(uint8_t) * NETWORK_BUFFER_SIZE );
if( buffer == NULL )
{
/* Failure path. */
return;
}
memset( &broker_info, 0x00, sizeof( cy_mqtt_broker_info_t ) );
memset( &credentials, 0x00, sizeof( cy_awsport_ssl_credentials_t ) );
memset( &connect_info, 0x00, sizeof( cy_mqtt_connect_info_t ) );
/* Set the credential information. */
credentials.client_cert = (const char *) &MQTTClientCertificate11;
credentials.client_cert_size = sizeof( MQTTClientCertificate11 );
credentials.private_key = (const char *) &MQTTClientKey11;
credentials.private_key_size = sizeof( MQTTClientKey11 );
credentials.root_ca = (const char *) &MQTTRootCACertificate11;
credentials.root_ca_size = sizeof( MQTTRootCACertificate11 );
security = &credentials;
connect_info.client_id = MQTT_CLIENT_IDENTIFIER;
connect_info.client_id_len = MQTT_CLIENT_IDENTIFIER_LENGTH;
connect_info.keep_alive_sec = MQTT_KEEP_ALIVE_INTERVAL_SECONDS;
connect_info.will_info = NULL;
/* MQTT broker information. */
broker_info.hostname = MQTT_BROKER;
broker_info.hostname_len = strlen(MQTT_BROKER);
broker_info.port = MQTT_PORT_SECURED;
/* Create MQTT Handle. */
TestRes = cy_mqtt_create( buffer, NETWORK_BUFFER_SIZE,
security, &broker_info,
"test-broker",
&MQTT_obj_handle11 );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Connect to the MQTT broker */
TestRes = cy_mqtt_connect( MQTT_obj_handle11, &connect_info );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
while(1)
{
cy_rtos_delay_milliseconds(1000);
}
}

Code Snippet 12: MQTT virtual API usage to subscribe to a topic

This code snippet demonstrates the steps to use the virtual APIs of MQTT in a multi-core environment to subscribe to a message topic with an MQTT broker from the secondary core.

/***************************** Secondary core ***************************/
#define MQTT_QOS2 ( 2U )
#define MQTT_TOPIC "Test_Topic"
#define MQTT_TOPIC_LENGTH ( ( uint16_t ) ( sizeof( MQTT_TOPIC ) - 1 ) )
#define MQTT_NUM_OF_SUBS_IN_SINGLE_REQ ( 1U )
#define MQTT_NUM_OF_UNSUBS_IN_SINGLE_REQ MQTT_NUM_OF_SUBS_IN_SINGLE_REQ
/* Flag to be set when VCM initialization is completed on the other core */
static bool is_vcm_init_complete = false;
/* Callback registered on the secondary core to handle events from VCM. */
void vcm_callback_sec_core(cy_vcm_event_t event)
{
switch(event)
{
case CY_VCM_EVENT_INIT_COMPLETE:
{
/* VCM init complete */
is_vcm_init_complete = true;
break;
}
default:
break;
}
}
/* Callback function registered with MQTT library.
* This callback function will be called by the MQTT library upon receiving MQTT messages on subscribed topics or when
* network disconnection happens. */
void mqtt_callback_sec_core( cy_mqtt_t mqtt_handle, cy_mqtt_event_t event, void *user_data )
{
printf( "\nMQTT App callback with handle : %p \n", mqtt_handle );
(void)user_data;
switch( event.type )
{
printf( "\nEvent : Received MQTT Disconnect event.\n" );
switch( event.data.reason )
{
/* Keep-alive response not received from broker, possibly broker is down. */
printf( "Reason : MQTT Ping response not received within keep-alive response timeout... \n\n" );
break;
/* Network is disconnected. */
printf( "Reason : Network is disconnected... \n\n" );
break;
/* MQTT packet send or receive operation failed due to network latency (or) send/receive related timeouts. */
printf( "Reason : MQTT packet send or receive operation failed... \n\n" );
break;
/* Bad response from MQTT broker. Possibly received MQTT packet with invalid packet type ID. */
printf( "Reason : Bad response from MQTT broker... \n\n" );
break;
default :
printf( "\n Unknown disconnect reason .....\n" );
break;
}
break;
/* Received MQTT messages on subscribed topic. */
printf( "\nEvent : Received MQTT subscribed message receive event.\n" );
received_msg = &(event.data.pub_msg.received_message);
printf( "Incoming Publish Topic Name: %.*s\n", received_msg->topic_len, received_msg->topic );
printf( "Incoming Publish message Packet Id is %u.\n", event.data.pub_msg.packet_id );
printf( "Incoming Publish Message : %.*s.\n\n", ( int )received_msg->payload_len, ( const char * )received_msg->payload );
break;
default :
printf( "\nUNKNOWN EVENT .....\n" );
break;
}
}
/* The following snippet demostrates usage of VCM and virtual MQTT APIs from the secondary core.
* The primary core is where the full MQTT implementation is present. The secondary core only
* has the virtual implementation.
* In this example, the secondary core application runs first and it enables the primary core.
* Before enabling the primary core, the secondary core initializes VCM library.
*/
void snippet_mqtt_virtual_api_usage_sec_core( void )
{
cy_rslt_t TestRes = CY_RSLT_SUCCESS;
cy_vcm_config_t vcm_config;
(void)TestRes;
cy_mqtt_t handle;
cy_mqtt_subscribe_info_t_info_t sub_msg[1];
/* Initialize the VCM library */
vcm_config.hal_resource_opt = CY_VCM_CREATE_HAL_RESOURCE; /* set to CY_VCM_CREATE_HAL_RESOURCE as the secondary core is the first one to initialize VCM. */
vcm_config.channel_num = CYHAL_IPC_CHAN_0;
vcm_config.event_cb = vcm_callback_sec_core;
TestRes = cy_vcm_init(&vcm_config);
if( TestRes != CY_RSLT_SUCCESS )
{
printf("\n cy_vcm_init failed on the secondary core! \n");
return;
}
/* Enable the other core.
* For example, for enabling CM4, the following code is applicable.
* When this is called, the application on core 2 will begin executing. Ensure cy_vcm_init()
* is called on the second core when the execution begins.
*/
Cy_SysEnableCM4(CY_CORTEX_M4_APPL_ADDR);
/* Wait for VCM initialization to complete */
while ( !is_vcm_init_complete )
{
cy_rtos_delay_milliseconds(1000);
}
/* Initialize the MQTT library */
TestRes = cy_mqtt_init();
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Ensure MQTT connection is established to "test-broker" in primary core. */
/* Get the MQTT handle using descriptor. */
TestRes = cy_mqtt_get_handle( &handle, "test-broker");
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Register MQTT event callback to receive data */
TestRes = cy_mqtt_register_event_callback( handle, mqtt_callback_sec_core );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Subscribe to message topic with the broker whose handle is obtained above. */
memset( &sub_msg[0], 0, sizeof(cy_mqtt_subscribe_info_t) );
sub_msg[0].qos = (cy_mqtt_qos_t)MQTT_QOS2;
sub_msg[0].topic = MQTT_TOPIC;
sub_msg[0].topic_len = MQTT_TOPIC_LENGTH;
TestRes = cy_mqtt_subscribe( handle, &sub_msg[0], MQTT_NUM_OF_SUBS_IN_SINGLE_REQ );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
while(1)
{
cy_rtos_delay_milliseconds(1000);
}
}
/***************************** Primary core ***************************/
#define MQTT_BROKER " " /* Add the broker end point info here. */
#define MQTT_PORT_SECURED ( 8883 )
#define MQTT_CLIENT_IDENTIFIER "CypressTest"
#define MQTT_CLIENT_IDENTIFIER_LENGTH ( ( uint16_t ) ( sizeof( MQTT_CLIENT_IDENTIFIER ) - 1 ) )
#define MQTT_KEEP_ALIVE_INTERVAL_SECONDS ( 60U )
#define NETWORK_BUFFER_SIZE ( 1024U )
static const char MQTTClientCertificate12[] = { "Paste client certificate here" };
static const char MQTTClientKey12[] = { "Paste client key here" };
static const char MQTTRootCACertificate12[] = { "Paste RootCA certificate here" };
cy_mqtt_t MQTT_obj_handle12;
/* Flag that is set when VCM deinit is started by the other core.
* When this event is received, call cy_vcm_deinit() to deinitialize VCM
* on the current core.
*/
static bool is_vcm_deinit_requested = false;
/* Callback registered on the primary core to handle events from VCM. */
void vcm_callback_prim_core(cy_vcm_event_t event)
{
switch(event)
{
case CY_VCM_EVENT_DEINIT:
{
/* The other core has initiated VCM deinit. Deinitialize VCM locally. */
is_vcm_deinit_requested = true;
break;
}
default:
break;
}
}
/* The following snippet demostrates usage of VCM on the primary core.
* The primary core is where the full MQTT implementation is present. The secondary core only
* has the virtual implementation. The primary core initializes creates an MQTT handle and
* establishes connection with a broker.
* Ensure that this snippet is executed when the primary core is enabled.
*/
void snippet_mqtt_virtual_api_usage_prim_core( void )
{
/* Status variables for various operations. */
cy_rslt_t TestRes = CY_RSLT_SUCCESS;
cy_vcm_config_t vcm_config;
cy_mqtt_broker_info_t broker_info;
cy_mqtt_connect_info_t connect_info;
cy_awsport_ssl_credentials_t credentials;
cy_awsport_ssl_credentials_t *security = NULL;
uint8_t *buffer = NULL;
(void)TestRes;
cy_mqtt_t MQTT_obj_handle;
/* Initialize the VCM library */
vcm_config.hal_resource_opt = CY_VCM_USE_HAL_RESOURCE; /* set to CY_VCM_USE_HAL_RESOURCE as primary core initializes VCM after the secondary core. */
vcm_config.channel_num = CYHAL_IPC_CHAN_0;
vcm_config.event_cb = vcm_callback_prim_core;
TestRes = cy_vcm_init(&vcm_config);
if( TestRes != CY_RSLT_SUCCESS )
{
printf("\n cy_vcm_init failed on primary core! \n");
return;
}
/* Initialize the MQTT library */
TestRes = cy_mqtt_init();
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/*Allocate the network buffer. */
buffer = (uint8_t *) malloc( sizeof(uint8_t) * NETWORK_BUFFER_SIZE );
if( buffer == NULL )
{
/* Failure path. */
return;
}
memset( &broker_info, 0x00, sizeof( cy_mqtt_broker_info_t ) );
memset( &credentials, 0x00, sizeof( cy_awsport_ssl_credentials_t ) );
memset( &connect_info, 0x00, sizeof( cy_mqtt_connect_info_t ) );
/* Set the credential information. */
credentials.client_cert = (const char *) &MQTTClientCertificate12;
credentials.client_cert_size = sizeof( MQTTClientCertificate12 );
credentials.private_key = (const char *) &MQTTClientKey12;
credentials.private_key_size = sizeof( MQTTClientKey12 );
credentials.root_ca = (const char *) &MQTTRootCACertificate12;
credentials.root_ca_size = sizeof( MQTTRootCACertificate12 );
security = &credentials;
connect_info.client_id = MQTT_CLIENT_IDENTIFIER;
connect_info.client_id_len = MQTT_CLIENT_IDENTIFIER_LENGTH;
connect_info.keep_alive_sec = MQTT_KEEP_ALIVE_INTERVAL_SECONDS;
connect_info.will_info = NULL;
/* MQTT broker information. */
broker_info.hostname = MQTT_BROKER;
broker_info.hostname_len = strlen(MQTT_BROKER);
broker_info.port = MQTT_PORT_SECURED;
/* Create MQTT Handle. */
TestRes = cy_mqtt_create( buffer, NETWORK_BUFFER_SIZE,
security, &broker_info,
"test-broker",
&MQTT_obj_handle12 );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
/* Connect to the MQTT broker */
TestRes = cy_mqtt_connect( MQTT_obj_handle12, &connect_info );
if( TestRes != CY_RSLT_SUCCESS )
{
/* Failure path. */
return;
}
while(1)
{
cy_rtos_delay_milliseconds(1000);
}
}