All Products
Search
Document Center

IoT Platform:Establish MQTT connections

最終更新日:Dec 12, 2023

This topic describes how to establish Message Queuing Telemetry Transport (MQTT) connections by using an MQTT client.

Background information

When you use an MQTT client to send an MQTT CONNECT message, take note of the following items:

  • If a device certificate (ProductKey, DeviceName, and DeviceSecret) or a combination of ProductKey, DeviceName, ClientID, and DeviceToken is used to connect multiple physical devices to IoT Platform, your MQTT client may repeatedly go online and offline. If a new device sends a verification request to IoT Platform, the original device is forced to go offline. After a device goes offline, the device automatically tries to re-establish the connection.
  • In MQTT connection mode, a Link SDK automatically tries to re-establish a connection after the device is disconnected. You can view the information about device behaviors by using Log Service.

Connect an MQTT client to IoT Platform

  1. To ensure communication security, you must use Transport Layer Security (TLS) to encrypt the data that is transmitted between IoT Platform and devices.
    Important Starting from August 2, 2022, new devices can no longer be connected to IoT Platform over unencrypted TCP channels. This limit ensures the security of IoT Platform and your business. The limit does not apply to the devices of the existing Alibaba Cloud accounts. We recommend that you enable TLS encryption for the devices that you want to connect to IoT Platform at the earliest opportunity.
    • A Link SDK integrates the TLS encryption feature. You do not need to configure this feature.
    • If you want to develop your own device-side SDK, download a root certificate. For information about how to use the root certificate, see CA Certificates.
      Important The root certificate is valid until 12:00:00 on January 28, 2028. After the root certificate expires, you cannot use the certificate to verify a certificate authority (CA) server. Make sure that all devices for which TLS encryption is enabled can update root certificates.
  2. Connect the MQTT client to the server. For more information about the connection method, visit GitHub.
    For more information about the MQTT protocol, see MQTT official documentation.
    Note Alibaba Cloud does not provide technical support for third-party code.
  3. Establish an MQTT connection.

    We recommend that you use device-side SDKs to connect devices to IoT Platform. If you use an SDK for C to connect a device to IoT Platform, see Connection over MQTT If you use your device SDK to connect the device, configure the parameters. The following table describes the parameters.

    ParameterDescription
    EndpointThe endpoint of the public instance or Enterprise Edition instance to which you want to connect the MQTT client. For more information about the supported endpoints, see Manage the endpoint of an instance.
    Variable header: Keep Alive The CONNECT message must include the Keep Alive parameter. The keep-alive period can be 30 to 1,200 seconds. We recommend that you set a keep-alive period that is longer than 300 seconds. If the network connection is unstable, we recommend that you set a longer keep-alive period. If the value of the Keep Alive parameter is not in this range, IoT Platform rejects the connection.

    For more information, see MQTT keep-alive mechanism.

    Parameters in an MQTT CONNECT messageUnique-certificate-per-device verification and pre-registration unique-certificate-per-product verification: Use the device certificate (ProductKey, DeviceName, and DeviceSecret) to connect the device to IoT Platform.
    mqttClientId: clientId+"|securemode=3,signmethod=hmacsha1,timestamp=132323232|"
    mqttUsername: deviceName+"&"+productKey
    mqttPassword: sign_hmac(deviceSecret,content)
    • mqttClientId: Extended parameters are placed between vertical bars (| |).
    • clientId: the ID of the client. You can specify a client ID based on your business requirements. The client ID cannot exceed 64 characters in length. We recommend that you use the MAC address or serial number (SN) of the device as the client ID.
    • securemode: the current security mode. Valid values: 2 (direct TLS connection) and 3 (direct TCP connection).
    • signmethod: the signature algorithm. Valid values: hmacmd5, hmacsha1, hmacsha256, and sha256. Default value: hmacmd5.
    • timestamp: the current time, in milliseconds. This parameter is optional.
    • mqttPassword: the password. Calculation method: Sort the parameters that are submitted to the server in alphabetical order and encrypt the parameters based on the specified signature algorithm. For more information about the signature calculation example, see Examples of creating signatures for MQTT connections.
    • content: a concatenated string consisting of the parameters that are submitted to the server. These parameters include productKey, deviceName, timestamp, and clientId. The parameters are sorted in alphabetical order and concatenated without delimiters.
      Important productKey and deviceName are required. timestamp and clientId are optional. If you configure the timestamp or clientId parameter, the parameter value must be the same as the value that is specified for the mqttClientId parameter.

    Example:

    The following values are specified: clientId=12345, deviceName=device, productKey=pk, timestamp=789, signmethod=hmacsha1, deviceSecret=secret. The following code shows the parameters in an MQTT CONNECT message that is sent over TCP:

    mqttclientId=12345|securemode=3,signmethod=hmacsha1,timestamp=789|
    mqttUsername=device&pk
    mqttPassword=hmacsha1("secret","clientId12345deviceNamedeviceproductKeypktimestamp789").toHexString(); 

    The encrypted password is a hexadecimal string that is converted from a binary string. The following code shows the result:

    FAFD82A3D602B37FB0FA8B7892F24A477F85****

    For more information about how to obtain the MQTT signature parameters, see How do I obtain MQTT parameters for authentication?.

    Preregistration-free unique-certificate-per-product verification: Use ProductKey, DeviceName, ClientID, and DeviceToken to connect the device to IoT Platform.
    mqttClientId: clientId+"|securemode=-2,authType=connwl|"
    mqttUsername: deviceName+"&"+productKey
    mqttPassword: deviceToken
    • mqttClientId: Extended parameters are placed between vertical bars (| |).
    • clientId, deviceToken: the ClientID and DeviceToken that are obtained when the device is dynamically registered. For more information, see MQTT-based dynamic registration.
    • securemode: the current security mode. If you use preregistration-free unique-certificate-per-product verification, set the value to -2.
    • authType: the verification method. If you use preregistration-free unique-certificate-per-product verification, set the value to connwl.

Examples

For more information about how to use open source MQTT clients to connect to IoT Platform, see the following topics:

MQTT keep-alive mechanism

During a keep-alive period, the device must send at least one message, including ping requests.

Valid values of the keep-alive period: 30 to 1,200 seconds. We recommend that you set the keep-alive period to a value that is more than 300 seconds.

A timer starts when IoT Platform sends a CONNACK message as a response to a CONNECT message. When IoT Platform receives a PUBLISH, SUBSCRIBE, PING, or PUBACK message, the timer is reset. IoT Platform checks the heartbeat of the MQTT connection every 30 seconds. The wait time for the heartbeat check is the period between the point in time at which a device connects to IoT Platform and the point in time at which the next heartbeat check is performed. The maximum timeout period is calculated by using the following formula: Heartbeat interval × 1.5 + Wait time for the heartbeat check. If the server receives no messages from the device within the maximum timeout period, the server ends the connection with the device.