This topic describes how to use the Golang library of Paho MQTT to access Alibaba Cloud IoT Platform for message exchanges.

Prerequisites

Products and devices are created in IoT Platform.

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

Prepare the development environment

Install the Go language package.

  • Run the following command for installation on macOS:
    brew install go
  • Run the following commands for installation in Ubuntu:
    sudo apt-get install golang-go
  • For Windows, download the installation package from the Golang official website.

Download the Go library for Paho MQTT

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

Use the following command to download the Go library for Paho MQTT 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 view and download the source code provided by Alibaba Cloud to calculate the MQTT connection parameters.

    The MqttSign.go file defines the function for calculating the MQTT connection parameters for devices to access IoT Platform. The following describes the parameters.

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

      Calculates the username, password, and mqttClientId parameters for MQTT connections to IoT Platform.

    • Input parameters
      Parameter Type Description
      ProductKey String The ProductKey of the product to which the device belongs.
      deviceName String The name of the device.
      deviceSecret String The device key.
      clientId String The device ID. It can be set to a string of no more than 64 characters. We recommend that you use the serial number or MAC address of the device ID.
      timeStamp String The timestamp of the current time in milliseconds.
    • Output parameters

      The return value of this function is an AuthInfo structure with the following parameters.

      Parameter Type Description
      username String The username required for the MQTT connection.
      password String The password required for the MQTT connection.
      mqttClientId String The ID of the MQTT client.
  2. Add the program file that enables the device to access IoT Platform.

    You must write a program which can call the MqttSign.go file to calculate the MQTT connection parameters and connect to IoT Platform.

    The development instructions and code examples are as follows.

    • 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 MQTT connection information.

      Call the calculate_sign function defined in MqttSign.go. Calculate the username, password, and mqttClientId based on the input parameters clientId, productKey, deviceName, deviceSecret, and timeStamp. Add the information 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 region ID of your IoT Platform device. For more information about region IDs, see Regions and zones.
    • Call the MQTT Connect() function to access 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 target topics and the payload of 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 topics and receive messages from the cloud.
          // 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 Communication methods.

  3. Compile the project.

Demo

Use the demo code to access IoT Platform.

  1. Download the demo package and extract the files.
    aiot-go-demo contains the following files.
    File Description
    MqttSign.go This file contains the code for generating the connection parameters that are used to access IoT Platform over MQTT. 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 code for connections and communications between the device and IoT Platform.
    x509 The root certificate of IoT Platform is required for devices to access IoT Platform.
  2. In the iot.go file, change the device information to your device information.

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

    • Replace the productKey, deviceName, and deviceSecret with your device certificate information.
    • (Optional) Replace the timeStamp and clientId parameter values. clientId can be replaced with the serial number and MAC address of your physical device.
    • Replace cn-shanghai in raw_broker.WriteString (".iot-as-mqtt.cn-shanghai.aliyuncs.com: 1883") with the region ID of your IoT Platform device. 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 running, you can view the local logs.
    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

    In the IoT Platform console, you can view the device status and logs.

    • Choose Devices > Devices. You can view that the status of the device is Online.
    • Choose Maintenance > Device Log. You can view the Device Activity Analysis and Upstream Analysis logs.