Skip to content

Commit

Permalink
refactor: register-box by sdk
Browse files Browse the repository at this point in the history
Signed-off-by: yang <[email protected]>
  • Loading branch information
big-dust committed Sep 27, 2023
1 parent 387aa2d commit 7f2e38a
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 137 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ build
debug
#/*.sh
res/loadbin.go
.idea
167 changes: 47 additions & 120 deletions biz/service/pair/register_box.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,65 +27,36 @@ import (
"agent/biz/model/device_ability"
"agent/biz/service/encwrapper"
"agent/config"
"agent/utils"
"fmt"
"net/http"
"time"

"agent/utils/logger"

utilshttp "agent/utils/network/http"

"fmt"
"github.com/big-dust/platform-sdk-go/v2"
"github.com/dungeonsnd/gocom/encrypt/encoding"
"github.com/dungeonsnd/gocom/encrypt/random"
"time"
)

// 向平台注册盒子
func ServiceRegisterBox() error {
logger.AppLogger().Debugf("ServiceRegisterBox")

//先获取 box-reg-key
if boxRegKeyInfo, err := GetDeviceRegKey(""); err != nil {
var client *platform.Client
var err error
if client, err = GetSdkClientWithDeviceRegKey(""); err != nil {
logger.AppLogger().Warnf("ServiceRegisterBox, failed GetBoxRegKey, err:%+v", err)
return err
} else {
logger.AppLogger().Debugf("ServiceRegisterBox, succ GetBoxRegKey, boxRegKeyInfo:%+v", boxRegKeyInfo)
device.SetDeviceRegKey(boxRegKeyInfo.BoxRegKey, boxRegKeyInfo.ExpiresAt)
}

// 平台请求结构
type registryStruct struct {
BoxUUID string `json:"boxUUID"`
logger.AppLogger().Debugf("ServiceRegisterBox, succ GetSdkClientWithBoxRegKey, boxRegKeyInfo:%+v", client.TokenResults)
device.SetDeviceRegKey(client.TokenResults.BoxRegKey, client.TokenResults.ExpiresAt.String())
}
// 平台响应结构
type registryRspStruct struct {
BoxUUID string `json:"boxUUID"`
NetworkClient struct {
ClientID string `json:"clientId"`
SecretKey string `json:"secretKey"`
} `json:"networkClient"`
}

// 请求平台
parms := &registryStruct{BoxUUID: device.GetDeviceInfo().BoxUuid}
// url := config.Config.Platform.APIBase.Url + config.Config.Platform.RegistryBox.Path
url := device.GetApiBaseUrl() + config.Config.Platform.RegistryBox.Path
logger.AppLogger().Debugf("ServiceRegisterBox, v2, url:%+v, parms:%+v", url, parms)

var headers = map[string]string{"Request-Id": random.GenUUID(), "Box-Reg-Key": device.GetDeviceInfo().BoxRegKey}
var rsp registryRspStruct

tryTotal := 3
var httpReq *http.Request
var httpRsp *http.Response
var body []byte
var err1 error
var resp *platform.RegisterDeviceResponse
for i := 0; i < tryTotal; i++ {
httpReq, httpRsp, body, err1 = utilshttp.PostJsonWithHeaders(url, parms, headers, &rsp)
if err1 != nil {
logger.AppLogger().Warnf("Failed PostJson, err:%v, @@httpReq:%+v, @@httpRsp:%+v, @@body:%v", err1, httpReq, httpRsp, string(body))
resp, err = client.RegisterDevice()
if err != nil {
logger.AppLogger().Warnf("Failed PostJson, err:%v, @@resp:%+v", err, resp)
if i == tryTotal-1 {
return err1
return err
}
time.Sleep(time.Second * 2)
continue
Expand All @@ -94,60 +65,31 @@ func ServiceRegisterBox() error {
}
}

logger.AppLogger().Infof("ServiceRegisterBox, parms:%+v", parms)
logger.AppLogger().Infof("ServiceRegisterBox, rsp:%+v", rsp)
logger.AppLogger().Infof("ServiceRegisterBox, httpReq:%+v", httpReq)
logger.AppLogger().Infof("ServiceRegisterBox, httpRsp:%+v", httpRsp)
logger.AppLogger().Infof("ServiceRegisterBox, body:%v", string(body))

if httpRsp.StatusCode == http.StatusOK {
// 保存盒子信息
device.SetNetworkClient(&device.NetworkClientInfo{ClientID: rsp.NetworkClient.ClientID,
SecretKey: rsp.NetworkClient.SecretKey})
} else if httpRsp.StatusCode == http.StatusNotAcceptable {
boxInfo := device.GetDeviceInfo()
if len(boxInfo.BoxRegKey) < 1 {
logger.AppLogger().Warnf("ServiceRegisterBox, boxInfo.BoxRegKey: %+v", boxInfo.BoxRegKey)
logger.AppLogger().Warnf("ServiceRegisterBox, boxInfo.NetworkClient: %+v", boxInfo.NetworkClient)
return fmt.Errorf("box uuid had already registered in platform. Plz reset first!")
} else {
logger.AppLogger().Infof("ServiceRegisterBox, using exist BoxInfo: %+v", boxInfo)
}
} else {
return fmt.Errorf("httpRsp.StatusCode=%v, @@body:%v", httpRsp.StatusCode, string(body))
}
return nil
}
logger.AppLogger().Infof("ServiceRegisterBox, rsp:%+v", resp)

type BoxRegKeyInfo struct {
ServiceID string `json:"serviceId"`
BoxRegKey string `json:"boxRegKey"`
ExpiresAt string `json:"expiresAt"`
return nil
}

func GetDeviceRegKey(apiBaseUrl string) (*BoxRegKeyInfo, error) {
func GetSdkClientWithDeviceRegKey(apiBaseUrl string) (*platform.Client, error) {

logger.AppLogger().Debugf("getBoxRegKey")

// 平台请求结构
type authStruct struct {
BoxUUID string `json:"boxUUID"`
ServiceIds []string `json:"serviceIds"`
Sign string `json:"sign,omitempty"`
}

// 平台响应结构
type authRspStruct struct {
BoxUUID string `json:"boxUUID"`
TokenResults []BoxRegKeyInfo `json:"tokenResults"`
}

logger.AppLogger().Debugf("getBoxRegKey, apiBaseUrl:%+v, boxInfo.ApiBaseUrl:%+v, config.Config.Platform.APIBase.Url:%+v",
apiBaseUrl, device.GetDeviceInfo().ApiBaseUrl, config.Config.Platform.APIBase.Url)
if len(apiBaseUrl) == 0 {
apiBaseUrl = device.GetApiBaseUrl()
}

client, err := platform.NewClientWithHost(apiBaseUrl, nil)
if err != nil {
logger.AppLogger().Errorf("%+v", err)
}

type authStruct struct {
BoxUUID string `json:"boxUUID"`
ServiceIds []string `json:"serviceIds"`
Sign string `json:"sign,omitempty"`
}
sign := ""
// 生成签名
signObj := &authStruct{BoxUUID: device.GetDeviceInfo().BoxUuid,
Expand Down Expand Up @@ -188,24 +130,17 @@ func GetDeviceRegKey(apiBaseUrl string) (*BoxRegKeyInfo, error) {
logger.AppLogger().Debugf("GetBoxRegKey, SecurityChipSupport==false, sign:%v", sign)
}

// 请求平台
parms := &authStruct{BoxUUID: device.GetDeviceInfo().BoxUuid,
ServiceIds: []string{"10001"},
Sign: sign}
url, _ := utils.JoinUrl(apiBaseUrl, config.Config.Platform.AuthBox.Path)

logger.AppLogger().Debugf("getBoxRegKey, url:%+v, parms:%+v", url, parms)
var headers = map[string]string{"Request-Id": random.GenUUID()}
var rsp authRspStruct
tryTotal := 3
var httpReq *http.Request
var httpRsp *http.Response
var body []byte
var resp *platform.ObtainBoxRegKeyResponse
var err1 error
for i := 0; i < tryTotal; i++ {
httpReq, httpRsp, body, err1 = utilshttp.PostJsonWithHeaders(url, parms, headers, &rsp)
resp, err1 = client.ObtainBoxRegKey(&platform.ObtainBoxRegKeyRequest{
BoxUUID: device.GetDeviceInfo().BoxUuid,
ServiceIds: []string{"10001"},
Sign: sign,
})
if err1 != nil {
logger.AppLogger().Warnf("Failed PostJson, err:%v, @@httpReq:%+v, @@httpRsp:%+v, @@body:%v", err1, httpReq, httpRsp, string(body))
logger.AppLogger().Warnf("Failed PostJson, err:%v, @@resp:%+v", err1, resp)
if i == tryTotal-1 {
return nil, err1
}
Expand All @@ -215,29 +150,21 @@ func GetDeviceRegKey(apiBaseUrl string) (*BoxRegKeyInfo, error) {
break
}
}
logger.AppLogger().Infof("getBoxRegKey, httpReq:%+v", httpReq)
logger.AppLogger().Infof("getBoxRegKey, parms:%+v", parms)
logger.AppLogger().Infof("getBoxRegKey, httpRsp:%+v", httpRsp)
logger.AppLogger().Infof("getBoxRegKey, rsp:%+v", rsp)
logger.AppLogger().Infof("getBoxRegKey, body:%v", string(body))

if httpRsp.StatusCode == http.StatusOK {
if len(rsp.TokenResults) == 0 || len(rsp.TokenResults) > 2 {
return nil, fmt.Errorf("len(rsp.TokenResults)=%v", len(rsp.TokenResults))
}
// 保存盒子信息
for _, token := range rsp.TokenResults {
switch token.ServiceID {
case "10001":
return &token, nil
case "10002":

default:
return nil, fmt.Errorf("invalid serviceId(%v)", token.ServiceID)
}
logger.AppLogger().Infof("getBoxRegKey, httpReq:%+v", resp)

if len(resp.TokenResults) == 0 || len(resp.TokenResults) > 2 {
return nil, fmt.Errorf("len(rsp.TokenResults)=%v", len(resp.TokenResults))
}
// 保存盒子信息
for _, token := range resp.TokenResults {
switch token.ServiceId {
case "10001":
return client, nil
case "10002":

default:
return nil, fmt.Errorf("invalid serviceId(%v)", token.ServiceId)
}
} else {
return nil, fmt.Errorf("httpRsp.StatusCode=%v, @@body:%v", httpRsp.StatusCode, string(body))
}

return nil, fmt.Errorf("failed to get box-reg-key")
Expand Down
17 changes: 10 additions & 7 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ go 1.20

require (
github.com/asaskevich/EventBus v0.0.0-20200907212545-49d423059eef
github.com/big-dust/platform-sdk-go v0.0.6
github.com/docker/docker v20.10.8+incompatible
github.com/docker/go-connections v0.4.0
github.com/dungeonsnd/gocom v1.0.45
github.com/gibson042/canonicaljson-go v1.0.3
github.com/gin-gonic/gin v1.7.2
github.com/go-redis/redis/v8 v8.11.5
github.com/golang-jwt/jwt/v5 v5.0.0
github.com/google/uuid v1.2.0
github.com/google/uuid v1.3.0
github.com/imdario/mergo v0.3.12
github.com/jinzhu/configor v1.2.1
github.com/mr-tron/base58 v1.2.0
Expand Down Expand Up @@ -50,18 +51,20 @@ require (
github.com/go-openapi/jsonreference v0.20.0 // indirect
github.com/go-openapi/spec v0.20.6 // indirect
github.com/go-openapi/swag v0.21.1 // indirect
github.com/go-playground/locales v0.13.0 // indirect
github.com/go-playground/universal-translator v0.17.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator v9.31.0+incompatible // indirect
github.com/go-playground/validator/v10 v10.4.1 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.0 // indirect
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/jcelliott/lumber v0.0.0-20160324203708-dd349441af25 // indirect
github.com/jinzhu/copier v0.4.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.10 // indirect
github.com/leodido/go-urn v1.2.0 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible // indirect
github.com/lestrrat-go/strftime v1.0.5 // indirect
github.com/magiconair/properties v1.8.0 // indirect
Expand All @@ -77,7 +80,7 @@ require (
github.com/pelletier/go-toml v1.8.1 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pquerna/cachecontrol v0.0.0-20180517163645-1555304b9b35 // indirect
github.com/sirupsen/logrus v1.8.1 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/spf13/afero v1.2.2 // indirect
github.com/spf13/cast v1.3.0 // indirect
github.com/spf13/jwalterweatherman v1.0.0 // indirect
Expand All @@ -86,8 +89,8 @@ require (
go.uber.org/atomic v1.4.0 // indirect
go.uber.org/multierr v1.1.0 // indirect
golang.org/x/net v0.0.0-20220722155237-a158d28d115b // indirect
golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10 // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/sys v0.10.0 // indirect
golang.org/x/text v0.3.8 // indirect
golang.org/x/tools v0.1.12 // indirect
google.golang.org/genproto v0.0.0-20201110150050-8816d57aaa9a // indirect
google.golang.org/grpc v1.39.1 // indirect
Expand Down
Loading

0 comments on commit 7f2e38a

Please sign in to comment.