Quality RTOS & Embedded Software

  Real time embedded FreeRTOS RSS feed  
NOTE: The MQTT library and documentation are in the FreeRTOS Labs.  The libraries in the FreeRTOS Labs download directory are fully functional, but undergoing optimizations or refactoring to improve memory usage, modularity, documentation, demo usability, or test coverage.  They are available as part of the main download.

MQTT Demo (with basic TLS – only Server Authentication)

Notice: It is our recommendation to always use strong mutual authentication in any Internet of Things (IoT) application. The first project is only provided to validate that MQTT communication can be established prior to introducing encryption and authentication, and to allow the MQTT packets to be observed using a network packet sniffer such as Wireshark for those who wish to do so. The first two projects are not intended to be examples suitable for production use.  

 

Introduction

The MQTT demo project uses the FreeRTOS Windows port, enabling it to be built and evaluated with the free Community version of Visual Studio on Windows, so without the need for any particular MCU hardware.  This demo establishes a connection to a public internet MQTT broker using TLS.  Other than the addition of TLS, this demo has the same functionality as the basic MQTT demo.

The example projects documented on these pages introduce the concepts described in the “TLS Introduction” section one at a time. The first example demonstrates unencrypted MQTT communication, the second example (this page) builds on the first to introduce weak server authentication, and the third example builds on the second to introduce strong mutual authentication.

This demo is intended to be used as a learning exercise only.  The server authentication for the internet MQTT broker is based on 1024-bit RSA, a cipher that is not recommended for production purposes.  Do NOT send any confidential information from your device to the MQTT broker.  The MQTT broker is publicly accessible and does not have the same security standards as many industry provided MQTT brokers.  The MQTT broker is hosted by a 3rd party that is not affiliated with FreeRTOS.  It may be unavailable at any time and it is not maintained by FreeRTOS.  

Note: Mosquitto is an open source MQTT message broker that supports MQTT versions 5.0, 3.1.1, and 3.1.  It is part of the Eclipse foundation and is an project.

Source Code Organization

The source code is organized in the same manner as the basic MQTT demo (without TLS).  

Configuring the Demo Project

The demo project is configured in the same manner as the basic MQTT demo (without TLS).

Configuring the MQTT Broker Connection

Configure the Client ID

The Client ID is currently hard coded within the source file (FreeRTOS-Plus\Demo\FreeRTOS_IoT_Libraries\include\mqtt_demo_profile.h).  As it is hard coded, every user who downloads the demo will have the same Client ID.  Change it to something unique in the line below or else only one client will be able to connect to the broker at a time.  

#define mqttdemoprofileCLIENT_IDENTIFIER "mqttexampleclient"

Mosquitto Public Message Broker (Web Hosted)

The demo project is pre-configured to communicate with Mosquitto’s publicly hosted message broker at “test.mosqitto.org” – so the network to which the demo is connected must have a DHCP service and internet access.  Note public MQTT brokers can be slow.

If you would like to connect to a different public broker then:

  1. Open FreeRTOS-Plus\Demo\FreeRTOS_IoT_Libraries\include\mqtt_demo_profile.h.
  2. Edit the following lines to be correct for your chosen broker:

    #define mqttdemoprofileBROKER_ENDPOINT "test.mosquitto.org"
    #define mqttdemoprofileBROKER_PORT 8883

  3. Edit the following lines to be correct for your chosen broker:

    #define mqttdemoprofileBROKER_CERTIFICATE_PEM

Building the Demo Project

The demo project is built in the same way as the basic MQTT demo (without TLS).

  • Open the \FreeRTOS-Plus\Demo\FreeRTOS_IoT_Libraries\mqtt\mqtt_basic_tls_server_auth\mqtt_basic_tls_demo.sln Visual Studio solution file from within the Visual Studio IDE

Functionality

The demo provides the same functionality as the basic MQTT demo with the addition of connecting with TLS to a public MQTT broker.  For details on the additional functionality, please view the basic MQTT demo (without TLS).

Connecting to the MQTT Broker (with TLS)

The function prvMQTTConnect() demonstrates how to establish a TLS connection to a MQTT broker with clean session. It uses the FreeRTOS+TCP network interface which is implemented in the file FreeRTOS-Plus\Source\FreeRTOS-IoT-Libraries\abstractions\platform\freertos\iot_network_freertos.c.

Please note that while a secure connection is established, the demo utilizes RSA1024 for encryption which is not suitable for production environments.    

The definition of prvMQTTConnect() is shown below:

static void prvMQTTConnect( void )
{
IotMqttError_t xResult;

  /* Set the context to pass into the disconnect callback function. */
  xNetworkInfo.disconnectCallback.pCallbackContext = ( void * ) xTaskGetCurrentTaskHandle();

  /* Establish the connection to the MQTT broker - It is a blocking call and
   * will return only when connection is complete or a timeout occurs.  The
   * network and connection structures are declared and initialised at the top
   * of this file. */
  xResult = IotMqtt_Connect( &( xNetworkInfo ),
                             &( xConnectInfo ),
                             mqttexampleMQTT_TIMEOUT_MS,
                             &( xMQTTConnection ) );
  configASSERT( xResult == IOT_MQTT_SUCCESS );
}

Where xMQTTBrokerInfo, xNetworkInfo , and xConnectInfo is defined as: 

static const struct IotNetworkServerInfo xMQTTBrokerInfo =
{
  .pHostName = mqttexampleBROKER_ENDPOINT,
  .port = mqttexampleBROKER_PORT
};

static IotMqttNetworkInfo_t xNetworkInfo =
{
  /* No connection to the MQTT broker has been established yet and we want to
   * establish a new connection. */
  .createNetworkConnection = true,
  .u.setup.pNetworkServerInfo = &( xMQTTBrokerInfo ),

  /* Set the TLS credentials for the new MQTT connection. This member is NULL
   * for the plain text MQTT demo. */
  .u.setup.pNetworkCredentialInfo = &xNetworkSecurityCredentials,

  /* Use FreeRTOS+TCP network interface. */
  .pNetworkInterface = IOT_NETWORK_INTERFACE_FREERTOS,

  /* Setup the callback which is called when the MQTT connection is
   * disconnected. The task handle is passed as the callback context which
   * is used by the callback to send a task notification to this task.*/
  .disconnectCallback.function = prvExample_OnDisconnect
};

static const IotMqttConnectInfo_t xConnectInfo =
{
  /* Set this flag to true if connecting to the AWS IoT MQTT broker. */
  .awsIotMqttMode = false,

  /* Start with a clean session i.e. direct the MQTT broker to discard any
   * previous session data. Also, establishing a connection with clean session
   * will ensure that the broker does not store any data when this client
   * gets disconnected. */
  .cleanSession = true,

  /* Since we are starting with a clean session, there are no previous
   * subscriptions to be restored. */
  .pPreviousSubscriptions = NULL,
  .previousSubscriptionCount = 0,

  /* We do not want to publish Last Will and Testament (LWT) message if the
   * client gets disconnected. */
  .pWillInfo = NULL,

  /* Send an MQTT PING request every minute to keep the connection open if
  there is no other MQTT traffic. */
  .keepAliveSeconds = mqttexampleKEEP_ALIVE_SECONDS,

  /* The client identifier is used to uniquely identify this MQTT client to
   * the MQTT broker.  In a production device the identifier can be something
   * unique, such as a device serial number. */
  .pClientIdentifier = mqttexampleCLIENT_IDENTIFIER,
  .clientIdentifierLength = ( uint16_t ) sizeof( mqttexampleCLIENT_IDENTIFIER ) - 1,

  /* This example does not authenticate the client and therefore username and
   * password fields are not used. */
  .pUserName = NULL,
  .userNameLength = 0,
  .pPassword = NULL,
  .passwordLength = 0
};

The xNetworkSecurityCredentials for adding broker credential is defined as:

static struct IotNetworkCredentials xNetworkSecurityCredentials =
{
  /* Optional TLS extensions. For this demo, they are disabled. */
  .pAlpnProtos = NULL,
  .maxFragmentLength = 0,

  /* SNI is enabled by default. */
  .disableSni = false,

  /* Provide the certificate for validating the server. Only required for
   * demos using TLS. */
  .pRootCa = mqttexampleBROKER_CERTIFICATE_PEM,
  .rootCaSize = sizeof( mqttexampleBROKER_CERTIFICATE_PEM ),

  /* Strong mutual authentication to authenticate both the broker and
   * the client. */
  .pClientCert = NULL,
  .clientCertSize = 0,
  .pPrivateKey = NULL,
  .privateKeySize = 0
};
Copyright (C) Amazon Web Services, Inc. or its affiliates. All rights reserved.