Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[iot] add iot client for iot core service #59

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@
# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736
.glide/

.idea
.idea

/**/config.json
64 changes: 64 additions & 0 deletions services/iot/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package iot

import (
"fmt"
"os"

"github.com/baidubce/bce-sdk-go/bce"
"github.com/baidubce/bce-sdk-go/http"
)

const (
defaultServiceDomain = "iot." + bce.DEFAULT_DOMAIN
)

type Client struct {
*bce.BceClient
}

func NewClient(ak, sk string) (*Client, error) {
client, err := bce.NewBceClientWithAkSk(ak, sk, defaultServiceDomain)
if err != nil {
return nil, err
}
return &Client{client}, nil
}

func (c *Client) CreateDevice(coreID, templateId, deviceName, authType, desc string) (*Device, error) {
if coreID == "" || templateId == "" || deviceName == "" || authType == "" {
return nil, os.ErrInvalid
}
result := &Device{
CoreId: coreID,
TemplateId: templateId,
Name: deviceName,
AuthType: authType,
Description: desc,
}
err := bce.NewRequestBuilder(c).
WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE).
WithURL(getDeviceURL(coreID) + "new").
WithMethod(http.POST).
WithBody(result).
WithResult(result).
Do()
if err != nil {
return nil, err
}
return result, nil
}

func (c *Client) DeleteDevice(coreID, deviceName string) error {
if coreID == "" || deviceName == "" {
return os.ErrInvalid
}
return bce.NewRequestBuilder(c).
WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE).
WithURL(getDeviceURL(coreID) + deviceName).
WithMethod(http.DELETE).
Do()
}

func getDeviceURL(id string) string {
return fmt.Sprintf("/v1/iotcore/%s/device/", id)
}
131 changes: 131 additions & 0 deletions services/iot/client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
package iot

import (
"encoding/json"
"os"
"reflect"
"runtime"
"strings"
"testing"

"github.com/baidubce/bce-sdk-go/util/log"
)

var (
client *Client
config *Conf
)

// For security reason, ak/sk should not hard write here.
type Conf struct {
AK string `json:"ak"`
SK string `json:"sk"`
CoreId string `json:"iotCoreId"`
TemplateId string `json:"templateId"`
}

func init() {
log.SetLogHandler(log.STDERR)
log.SetLogLevel(log.DEBUG)

configJson := "config.json"
fp, err := os.Open(configJson)
if err != nil {
log.Fatal("config json file of ak/sk not given:", configJson)
os.Exit(1)
}

config = &Conf{}
decoder := json.NewDecoder(fp)
decoder.Decode(config)

log.Debugln(config)
client, _ = NewClient(config.AK, config.SK)
}

// ExpectEqual is the helper function for test each case
func ExpectEqual(alert func(format string, args ...interface{}),
expected interface{}, actual interface{}) bool {
expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual)
equal := false
switch {
case expected == nil && actual == nil:
return true
case expected != nil && actual == nil:
equal = expectedValue.IsNil()
case expected == nil && actual != nil:
equal = actualValue.IsNil()
default:
if actualType := reflect.TypeOf(actual); actualType != nil {
if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
}
}
}
if !equal {
_, file, line, _ := runtime.Caller(1)
alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual)
return false
}
return true
}

func TestClientDevice(t *testing.T) {
err := client.DeleteDevice(config.CoreId, t.Name())
ExpectEqual(t.Errorf, nil, err)

result, err := client.CreateDevice(config.CoreId, config.TemplateId, t.Name(), SIGNATURE, "iot core test")
ExpectEqual(t.Errorf, nil, err)
ExpectEqual(t.Errorf, t.Name(), result.Name)

result, err = client.CreateDevice(config.CoreId, config.TemplateId, t.Name(), SIGNATURE, "iot core test")
ExpectEqual(t.Errorf, true, strings.Contains(err.Error(), "Device name has been occupied"))
ExpectEqual(t.Errorf, nil, result)

err = client.DeleteDevice(config.CoreId, t.Name())
ExpectEqual(t.Errorf, nil, err)
}

func TestClientDeviceException(t *testing.T) {
result, err := client.CreateDevice("", "", "", "", "")
ExpectEqual(t.Errorf, os.ErrInvalid, err)
ExpectEqual(t.Errorf, nil, result)

result, err = client.CreateDevice("1", "", "", "", "")
ExpectEqual(t.Errorf, os.ErrInvalid, err)
ExpectEqual(t.Errorf, nil, result)

result, err = client.CreateDevice("1", "2", "", "", "")
ExpectEqual(t.Errorf, os.ErrInvalid, err)
ExpectEqual(t.Errorf, nil, result)

result, err = client.CreateDevice("1", "", "", "", "")
ExpectEqual(t.Errorf, os.ErrInvalid, err)
ExpectEqual(t.Errorf, nil, result)

result, err = client.CreateDevice("1", "2", "", "", "")
ExpectEqual(t.Errorf, os.ErrInvalid, err)
ExpectEqual(t.Errorf, nil, result)

result, err = client.CreateDevice("1", "2", "3", "", "")
ExpectEqual(t.Errorf, os.ErrInvalid, err)
ExpectEqual(t.Errorf, nil, result)

result, err = client.CreateDevice("1", "2", "3", "4", "")
ExpectEqual(t.Errorf, true, strings.Contains(err.Error(), "Bad IotCoreId"))
ExpectEqual(t.Errorf, nil, result)

result, err = client.CreateDevice("1", "2", "3", "4", "5")
ExpectEqual(t.Errorf, true, strings.Contains(err.Error(), "Bad IotCoreId"))
ExpectEqual(t.Errorf, nil, result)


err = client.DeleteDevice("", "")
ExpectEqual(t.Errorf, os.ErrInvalid, err)

err = client.DeleteDevice("1", "")
ExpectEqual(t.Errorf, os.ErrInvalid, err)

err = client.DeleteDevice("1", "2")
ExpectEqual(t.Errorf, true, strings.Contains(err.Error(), "Bad IotCoreId"))
}
18 changes: 18 additions & 0 deletions services/iot/model.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package iot

const (
SIGNATURE = "SIGNATURE"
CERTIFICATE = "CERT"
)

type Device struct {
Name string `json:"name"`
Description string `json:"desc"`
CoreId string `json:"iotCoreId"`
TemplateId string `json:"templateId"`
AuthType string `json:"authType"`
SecretKey string `json:"secretKey,omitempty"`
PrivateKey string `json:"privateKey,omitempty"`
ClientCert string `json:"clientCert,omitempty"`
CreateTimestamp int64 `json:"createTs,omitempty"`
}