How to create a Device in Azure IoT Hub with go sdk

64 Views Asked by At

Can you point me to an example on which module is providing CRUD operations on Devices for Azure Iot Hub GO SDK? I've checked https://github.com/Azure-Samples/azure-sdk-for-go-samples/tree/main but I've not found valid example. In the specific, I'm interested in which go module is providing such APIs: (https://learn.microsoft.com/en-us/rest/api/iothub/service/devices/create-or-update-identity?view=rest-iothub-service-2020-03-13)

Thanks!

1

There are 1 best solutions below

0
On

The code below demonstrates creating a device in Azure IoT Hub using Go and the REST API.

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

func main() {

    sasToken :="SharedAccessSignature sr=<your IoT Hub name>.azure-devices.net/devices/<your device ID>&sig=<your signature>&se=<expiry time>&skn=<policy name>"


    
    deviceID := "sampath671"
    iotHubName := "certificate122ravi"


    url := fmt.Sprintf("https://%s.azure-devices.net/devices/%s?api-version=2020-05-31-preview", iotHubName, deviceID)

    
    requestBody := map[string]interface{}{
        "deviceId": deviceID,
    }
    requestBodyBytes, err := json.Marshal(requestBody)
    if err != nil {
        log.Fatal(err)
    }

    
    req, err := http.NewRequest("PUT", url, bytes.NewBuffer(requestBodyBytes))
    if err != nil {
        log.Fatal(err)
    }

    
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", sasToken )

    // Send the HTTP request
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()


    responseBody, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }

    
    if resp.StatusCode != http.StatusOK {
        log.Fatalf("Failed to create device: %s", responseBody)
    }

    fmt.Println("Device created successfully!")


    fmt.Println("Response Body:", string(responseBody))
}

Output:

enter image description here

The code below updates the device status in Azure IoT Hub using the Azure IoT Hub REST API.

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    
    sasToken :="SharedAccessSignature sr=<your IoT Hub name>.azure-devices.net/devices/<your device ID>&sig=<your signature>&se=<expiry time>&skn=<policy name>"

    
    deviceID := "sampath671"
    iotHubName := "certificate122ravi"

    
    url := fmt.Sprintf("https://%s.azure-devices.net/devices/%s?api-version=2020-05-31-preview", iotHubName, deviceID)

    
    requestBody := map[string]interface{}{
        "deviceId":                  deviceID,
        "status":                    "disabled",                        
        "statusReason":              "Device disabled for maintenance",
        "connectionState":           "Disconnected",                    
        "lastActivityTime":          "2024-03-12T12:00:00Z",        
        "cloudToDeviceMessageCount": 10,                                
    }
    requestBodyBytes, err := json.Marshal(requestBody)
    if err != nil {
        log.Fatal(err)
    }

    
    req, err := http.NewRequest("PUT", url, bytes.NewBuffer(requestBodyBytes))
    if err != nil {
        log.Fatal(err)
    }

    
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", sasToken)


    currentETag, err := getCurrentETag(deviceID, sasToken, iotHubName)
    if err != nil {
        log.Fatal(err)
    }

    
    req.Header.Set("If-Match", currentETag)

    
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    
    responseBody, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }


    if resp.StatusCode != http.StatusOK {
        log.Fatalf("Failed to update device: %s", responseBody)
    }

    fmt.Println("Device updated successfully!")

    
    fmt.Println("Response Body:", string(responseBody))
}


func getCurrentETag(deviceID, sasToken, iotHubName string) (string, error) {
    url := fmt.Sprintf("https://%s.azure-devices.net/devices/%s?api-version=2020-05-31-preview", iotHubName, deviceID)

    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return "", err
    }

    req.Header.Set("Authorization", sasToken)

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()

    
    if resp.StatusCode != http.StatusOK {
        return "", fmt.Errorf("Failed to fetch device details: %s", resp.Status)
    }

    
    etag := resp.Header.Get("ETag")
    if etag == "" {
        return "", fmt.Errorf("ETag not found in response headers")
    }

    return etag, nil
}

Output: enter image description here

The code below generates a Shared Access Signature (SAS) token for Azure IoT Hub authentication. This token can be used by devices to authenticate with the Azure IoT Hub service from link.

const crypto = require('crypto');

function generateSasToken(hostName, sharedAccessKeyName, sharedAccessKey, expiresInMinutes) {

const resourceUri = `${hostName}/devices`;

const expiry = Math.round(new Date().getTime() / 1000) + expiresInMinutes * 60;

const toSign = encodeURIComponent(resourceUri) + '\n' + expiry;

  

const hmac = crypto.createHmac('sha256', Buffer.from(sharedAccessKey, 'base64'));

hmac.update(toSign);

const base64UriEncoded = encodeURIComponent(hmac.digest('base64'));

  

const token = `SharedAccessSignature sr=${encodeURIComponent(resourceUri)}&sig=${base64UriEncoded}&se=${expiry}&skn=${sharedAccessKeyName}`;

return token;

}

  

// Example usage

const hostName = "your-iot-hub-name>.azure-devices.net";

const sharedAccessKeyName = "your-shared-access-policy-name";

const sharedAccessKey = "your-shared-access-policy-key";

const expiresInMinutes = 60; // Token expiration time in minutes

  

const sasToken = generateSasToken(hostName, sharedAccessKeyName, sharedAccessKey, expiresInMinutes);

console.log("Generated SAS token:", sasToken);

Output: enter image description here