This article describes how to use the Paho Message Queuing Telemetry Transport (MQTT) library for Go to connect to IoT Platform and exchange messages with IoT Platform.

Prerequisites

A product and a device are created in the IoT Platform console.

For more information, see Create a product and Create a device.

Prepare the development environment

Install the Go language package.

  • On macOS, run the following command:
    brew install go
  • On Ubuntu, run the following command:
    sudo apt-get install golang-go
  • On Windows, download the installation package from the Golang official website and install the Go language package.
    Note If you are in mainland China, you need to use a virtual private network (VPN) to access the Golang official website.

Download the Paho MQTT library for Go

For more information about the Paho project and supported development languages, visit Eclipse Paho Downloads.

Run the following commands to download the Paho MQTT library for Go and the dependencies:

go get github.com/eclipse/paho.mqtt.golang
go get github.com/gorilla/websocket
go get golang.org/x/net/proxy

Connect to IoT Platform

  1. Click MqttSign.go to obtain the source code provided by Alibaba Cloud to calculate the MQTT connection parameters.

    The MqttSign.go file defines the function that calculates the MQTT connection parameters used by a device to connect to IoT Platform. Your device program for connecting to IoT Platform must call this function.

    • Prototype
      type AuthInfo struct {
          password, username, mqttClientId string;
      }
      
      func calculate_sign(clientId, productKey, deviceName, deviceSecret, timeStamp string) AuthInfo;
    • Description

      Calculates the MQTT connection parameters username, password, and mqttClientId.

    • Input parameters
      Parameter Type Description
      productKey String The ProductKey of the product to which the device belongs. It can be used to identify the device in IoT Platform.
      deviceName String The DeviceName of the device. It can be used to identify the device in IoT Platform.
      deviceSecret String The DeviceSecret of the device. It can be used to identify the device in IoT Platform.
      clientId String The ID of the device. It can be set to a string of no more than 64 characters. We recommend that you use the MAC address or serial number (SN) of the device as the ID.
      timeStamp String The timestamp of the current time in milliseconds.
    • Output parameters

      The return value of this function is an AuthInfo structure that contains the parameters described in the following table.

      Parameter Type Description
      username String The username that is used to establish the MQTT connection.
      password String The password that is used to establish the MQTT connection.
      mqttClientId String The ID of the MQTT client.
  2. Add a program file that can connect a device to IoT Platform.

    You must write a program to call the MqttSign.go file to calculate the parameters that are used to establish an MQTT connection to IoT Platform.

    This section provides the development instructions and sample code.

    • Set the device information.
      // set the device info, include product key, device name, and device secret
          var productKey string = "a1Zd7n5***"
          var deviceName string = "testdevice"
          var deviceSecret string = "UrwclDV33NaFSmk0JaBxNTqgSrJW****"
      
          // set timestamp, clientid, subscribe topic and publish topic
          var timeStamp string = "1528018257135"
          var clientId string = "192.168.****"
          var subTopic string = "/" + productKey + "/" + deviceName + "/user/get";
          var pubTopic string = "/" + productKey + "/" + deviceName + "/user/update";
    • Set the MQTT connection information.

      Call the calculate_sign() function defined in MqttSign.go file. This function calculates the username, password, and mqttClientId parameters based on the input parameters clientId, productKey, deviceName, deviceSecret, and timeStamp. Add the calculation result to the opts structure.

          // set the login broker url
          var raw_broker bytes.Buffer
          raw_broker.WriteString("tls://")
          raw_broker.WriteString(productKey)
          raw_broker.WriteString(".iot-as-mqtt.cn-shanghai.aliyuncs.com:1883")
          opts := MQTT.NewClientOptions().AddBroker(raw_broker.String());
      
          // calculate the login auth info, and set it into the connection options
          auth := calculate_sign(clientId, productKey, deviceName, deviceSecret, timeStamp)
          opts.SetClientID(auth.mqttClientId)
          opts.SetUsername(auth.username)
          opts.SetPassword(auth.password)
          opts.SetKeepAlive(60 * 2 * time.Second)
          opts.SetDefaultPublishHandler(f)
      Note Replace cn-shanghai in the code with the ID of the region where your device resides. For more information about region IDs, see Regions and zones.
    • Call the MQTT Connect() function to connect to IoT Platform.
          // create and start a client using the above ClientOptions
          c := MQTT.NewClient(opts)
          if token := c.Connect(); token.Wait() && token.Error() ! = nil {
              panic(token.Error())
          }
          fmt.Print("Connect aliyun IoT Cloud Sucess\n");
    • Call the Publish() function to publish messages. You must specify the topic to which messages are published and the payload of the published messages.
          // publish 5 messages to pubTopic("/a1Zd7n5****/deng/user/update")
          for i := 0; i < 5; i++ {
              fmt.Println("publish msg:", i)
              text := fmt.Sprintf("ABC #%d", i)
              token := c.Publish(pubTopic, 0, false, text)
              fmt.Println("publish msg: ", text)
              token.Wait()
              time.Sleep(2 * time.Second)
          }

      For more information about communication topics, see What is a topic?

    • Call the Subscribe() function to subscribe to the topic for receiving messages from IoT Platform.
          // subscribe to subTopic("/a1Zd7n5***/deng/user/get") and request messages to be delivered
          if token := c.Subscribe(subTopic, 0, nil); token.Wait() && token.Error() ! = nil {
              fmt.Println(token.Error())
              os.Exit(1)
          }
          fmt.Print("Subscribe topic " + subTopic + " success\n");
                                      

    For more information about the communication methods of devices, servers, and IoT Platform, see Overview.

  3. Compile the project.

Demo

The demo code demonstrates how to connect a device to IoT Platform.

  1. Download the demo package and decompress it.
    The following table describes the files that are contained in the aiot-go-demo package.
    File Description
    MqttSign.go This file contains the code that is used to calculate the parameters for establishing an MQTT connection to IoT Platform. When you run the iot.go file, the calculate_sign() function is called to calculate the connection parameters username, password, and mqttClientId.
    iot.go This file contains the logic code that is used to establish a connection and exchange messages between the device and IoT Platform.
    x509 The root certificate of IoT Platform. This certificate is required by the device to connect to IoT Platform.
  2. In the iot.go file, replace the device information with your device information.

    You can use tools such as Linux vi to modify the iot.go file.

    • Replace the values of the productKey, deviceName, and deviceSecret parameters with your device certificate information.
    • Optional. Set the timeStamp and clientId parameters. You can replace the value of the clientId parameter with the MAC address or SN of your device.

      If you do not set the two parameters, you can still connect to IoT Platform. However, we recommend that you replace them with actual values.

    • Replace cn-shanghai in raw_broker.WriteString (".iot-as-mqtt.cn-shanghai.aliyuncs.com: 1883") with the ID of the region where your device resides. For more information about region IDs, see Regions and zones.
  3. Run the following command in the command line to run the iot.go file:
    go run iot.go MqttSign.go 
    After the file is run, you can view the local logs about the connection to IoT Platform.
    clientId192.168.****deviceNametestdeviceproductKeya1Zd7n5****timestamp1528018257135
    1b865320fc183cc747041c9faffc9055fc45****
    Connect aliyun IoT Cloud Sucess
    Subscribe topic /a1Zd7n5****/testdevice/user/get success
    publish msg: 0
    publish msg:  ABC #0
    publish msg: 1
    publish msg:  ABC #1
    publish msg: 2
    publish msg:  ABC #2
    publish msg: 3
    publish msg:  ABC #3
    publish msg: 4
    publish msg:  ABC #4
    publish msg: 5
    publish msg:  ABC #5

    Log on to the IoT Platform console.View device status and logs.

    • Choose Devices > Devices. You can find that the status of the device is Online.
    • Choose Maintenance > Device Log to view logs on the Cloud run log and Device local log tabs. For more information, see IoT Platform logs and Local device logs.

      If the Mqtt5App program is run, you can view the reported custom properties in the log details.

Error codes

If a device fails to establish an MQTT connection to IoT Platform, you can troubleshoot the issue based on the error code. For more information about the error codes that may be returned by IoT Platform, see Troubleshooting.