github.com/jingruilea/kubeedge@v1.2.0-beta.0.0.20200410162146-4bb8902b3879/cloud/pkg/devicecontroller/messagelayer/util.go (about)

     1  package messagelayer
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"strings"
     7  
     8  	deviceconstants "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/constants"
     9  	constants "github.com/kubeedge/kubeedge/common/constants"
    10  )
    11  
    12  // BuildResource return a string as "beehive/pkg/core/model".Message.Router.Resource
    13  func BuildResource(nodeID, resourceType, resourceID string) (resource string, err error) {
    14  	if nodeID == "" || resourceType == "" {
    15  		err = fmt.Errorf("required parameter are not set (node id, namespace or resource type)")
    16  		return
    17  	}
    18  	resource = fmt.Sprintf("%s%s%s%s%s", deviceconstants.ResourceNode, constants.ResourceSep, nodeID, constants.ResourceSep, resourceType)
    19  	if resourceID != "" {
    20  		resource += fmt.Sprintf("%s%s", constants.ResourceSep, resourceID)
    21  	}
    22  	return
    23  }
    24  
    25  // GetDeviceID returns the ID of the device
    26  func GetDeviceID(resource string) (string, error) {
    27  	res := strings.Split(resource, "/")
    28  	if len(res) >= deviceconstants.ResourceDeviceIDIndex+1 && res[deviceconstants.ResourceDeviceIndex] == deviceconstants.ResourceDevice {
    29  		return res[deviceconstants.ResourceDeviceIDIndex], nil
    30  	}
    31  	return "", errors.New("failed to get device id")
    32  }
    33  
    34  // GetResourceType returns the resourceType of message received from edge
    35  func GetResourceType(resource string) (string, error) {
    36  	if strings.Contains(resource, deviceconstants.ResourceTypeTwinEdgeUpdated) {
    37  		return deviceconstants.ResourceTypeTwinEdgeUpdated, nil
    38  	}
    39  	return "", errors.New("unknown resource")
    40  }