代理代码

This commit is contained in:
winc-link 2024-07-10 16:16:35 +08:00
parent 329c98ebc5
commit 4dd48bcc65
34 changed files with 86 additions and 1529 deletions

1
.gitignore vendored
View File

@ -17,3 +17,4 @@ cmd/mqtt-broker/mqtt-broker
kuiper kuiper
db-data/leveldb-core-data db-data/leveldb-core-data
manifest/docker/db-data/leveldb-core-data/

View File

@ -7,7 +7,6 @@ package dtos
import ( import (
"encoding/json" "encoding/json"
"github.com/winc-link/hummingbird/internal/models"
//"gitlab.com/tedge/edgex/internal/models" //"gitlab.com/tedge/edgex/internal/models"
) )
@ -36,30 +35,6 @@ type ServiceStats struct {
ServiceType string `json:"service_type" binding:"required"` ServiceType string `json:"service_type" binding:"required"`
} }
func FromModelsServiceStatsToDTO(s models.ServiceStats) ServiceStats {
return ServiceStats{
Id: s.Id,
Name: s.Name,
Healthy: s.Healthy,
Created: s.Created,
Started: s.Started,
LogPath: s.LogPath,
ServiceType: s.ServiceType,
}
}
func FromDTOServiceStatsToModel(s ServiceStats) models.ServiceStats {
return models.ServiceStats{
Id: s.Id,
Name: s.Name,
Healthy: s.Healthy,
Created: s.Created,
Started: s.Started,
LogPath: s.LogPath,
ServiceType: s.ServiceType,
}
}
type Logging struct { type Logging struct {
Log string `json:"log"` Log string `json:"log"`
} }
@ -92,14 +67,6 @@ type Metrics struct {
MemoryUsed int64 `json:"memoryUsed"` // 内存使用大小,单位:字节 MemoryUsed int64 `json:"memoryUsed"` // 内存使用大小,单位:字节
} }
func FromModelsMetricsToDTO(m models.Metrics) Metrics {
return Metrics{
Timestamp: m.Timestamp,
CpuUsedPercent: m.CpuUsedPercent,
MemoryUsed: m.MemoryUsed,
}
}
func (m Metrics) ToJSON() string { func (m Metrics) ToJSON() string {
marshal, _ := json.Marshal(m) marshal, _ := json.Marshal(m)
return string(marshal) return string(marshal)

View File

@ -1,106 +0,0 @@
package dtos
import (
"github.com/winc-link/hummingbird/internal/models"
"github.com/winc-link/hummingbird/internal/pkg/constants"
"github.com/winc-link/hummingbird/internal/pkg/errort"
"github.com/winc-link/hummingbird/internal/pkg/i18n"
"time"
)
const (
SYSTEM_ALERT models.AlertType = iota + 1 // 系统告警
DRIVER_ALERT // 驱动告警
LICENSE_ALERT //证书过期
)
const (
ERROR models.AlertLevel = iota + 1 // 告警级别:错误
WARN // 告警级别:警告
NOTIFY // 告警级别: 通知
)
var (
AlertTypeTrans = map[models.AlertType]string{
SYSTEM_ALERT: i18n.AgentAlertSystem,
DRIVER_ALERT: i18n.AgentAlertDriver,
LICENSE_ALERT: i18n.LicenseAlertExpire,
}
AlertLevelTrans = map[models.AlertLevel]string{
NOTIFY: i18n.AgentAlertNotify,
WARN: i18n.AgentAlertWarn,
ERROR: i18n.AgentAlertError,
}
)
// AlertContent 服务和驱动上报告警消息
type (
ReportAlertsReq struct {
BaseRequest `json:",inline"`
ServiceName string `json:"name"` // 服务名
Type models.AlertType `json:"type" binding:"oneof=1 2"` // 告警类型
Level models.AlertLevel `json:"level" binding:"oneof=1 2 3"` // 告警级别
T int64 `json:"time"` // 告警时间
Content string `json:"content"`
}
AlertContentDTO struct {
ServiceName string `json:"name"` // 服务名
Type models.AlertType `json:"type" binding:"oneof=1 2" swaggertype:"integer"` // 告警类型
TypeValue string `json:"typeValue"`
Level models.AlertLevel `json:"level" binding:"oneof=1 2 3" swaggertype:"integer"` // 告警级别
LevelValue string `json:"levelValue"`
T int64 `json:"time"` // 告警时间
Content string `json:"content"` // 告警内容
}
)
func NewReportAlertsReq(serviceName string, tp models.AlertType, l models.AlertLevel, t int64, content string) ReportAlertsReq {
return ReportAlertsReq{
BaseRequest: NewBaseRequest(),
ServiceName: serviceName,
Type: tp,
Level: l,
T: t,
Content: content,
}
}
func ToAlertContent(req ReportAlertsReq) models.AlertContent {
return models.AlertContent{
ServiceName: req.ServiceName,
Type: req.Type,
Level: req.Level,
T: req.T,
Content: req.Content,
}
}
func AlertContentToDTO(ac models.AlertContent) AlertContentDTO {
return AlertContentDTO{
ServiceName: ac.ServiceName,
Type: ac.Type,
Level: ac.Level,
T: ac.T,
Content: ac.Content,
}
}
type ReportAlertRequest struct {
ServiceName string `json:"serviceName"`
AlertType int `json:"alertType"` // constants.AlertType_SERVICE
AlertLevel int `json:"alertLevel"` // constants.AlertLevel_ERROR
AlertTime int64 `json:"alertTime"`
Content string `json:"content"`
}
// GenServerAlert 生成服务警告内容
func GenServerAlert(lvl models.AlertLevel, err error) ReportAlertsReq {
errw := errort.NewCommonEdgeXWrapper(err)
return NewReportAlertsReq(
constants.CoreServiceKey,
SYSTEM_ALERT,
lvl,
time.Now().Unix(),
i18n.TransCodeDefault(errw.Code(), nil))
}

View File

@ -1,33 +0,0 @@
/*******************************************************************************
* Copyright 2017.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package dtos
const (
BackupFileTypeDbResource = "db_resource"
BackupFileTypeDbExpert = "db_expert"
BackupFileTypeDbGateway = "db_gateway"
BackupFileTypeCheck = "check.json"
BackupUnZipDir = "/tmp/edge-recover"
)
// 备份/恢复时的校验文件
type BackupFileCheck struct {
GatewayId string `json:"gateway_id"`
Version string `json:"version"`
}
type BackupCommand struct {
BackupType int
}

View File

@ -1,70 +0,0 @@
//
// Copyright (C) 2020 IOTech Ltd
//
// SPDX-License-Identifier: Apache-2.0
package dtos
import (
"github.com/google/uuid"
"github.com/winc-link/hummingbird/internal/pkg/constants"
//"gitlab.com/tedge/edgex/internal/pkg/constants"
)
// Request defines the base content for request DTOs (data transfer objects).
// This object and its properties correspond to the BaseRequest object in the APIv2 specification:
// https://app.swaggerhub.com/apis-docs/EdgeXFoundry1/core-data/2.x#/BaseRequest
type BaseRequest struct {
Versionable `json:",inline"`
RequestId string `json:"requestId" validate:"len=0|uuid"`
}
func NewBaseRequest() BaseRequest {
return BaseRequest{
Versionable: NewVersionable(),
RequestId: uuid.NewString(),
}
}
// BaseResponse defines the base content for response DTOs (data transfer objects).
// This object and its properties correspond to the BaseResponse object in the APIv2 specification:
// https://app.swaggerhub.com/apis-docs/EdgeXFoundry1/core-data/2.x#/BaseResponse
type BaseResponse struct {
Versionable `json:",inline"`
RequestId string `json:"requestId"`
Message interface{} `json:"message,omitempty"`
StatusCode int `json:"statusCode"`
}
// Versionable shows the API version in DTOs
type Versionable struct {
ApiVersion string `json:"apiVersion"`
}
// BaseWithIdResponse defines the base content for response DTOs (data transfer objects).
// This object and its properties correspond to the BaseWithIdResponse object in the APIv2 specification:
// https://app.swaggerhub.com/apis-docs/EdgeXFoundry1/core-data/2.x#/BaseWithIdResponse
type BaseWithIdResponse struct {
BaseResponse `json:",inline"`
Id string `json:"id"`
}
func NewBaseResponse(requestId string, message string, statusCode int) BaseResponse {
return BaseResponse{
Versionable: NewVersionable(),
RequestId: requestId,
Message: message,
StatusCode: statusCode,
}
}
func NewVersionable() Versionable {
return Versionable{ApiVersion: constants.ApiVersion}
}
func NewBaseWithIdResponse(requestId string, message string, statusCode int, id string) BaseWithIdResponse {
return BaseWithIdResponse{
BaseResponse: NewBaseResponse(requestId, message, statusCode),
Id: id,
}
}

View File

@ -1,61 +0,0 @@
package dtos
import (
"encoding/json"
"fmt"
)
// DebugAssistantReq 调试助手请求参数 TODO 可以直接使用 DpMessage
type DebugAssistantReq struct {
DeviceId string `json:"deviceId,omitempty"`
OpType int32 `json:"opType,omitempty"`
Data map[string]interface{} `json:"data" binding:"required"`
Protocol int32 `json:"protocol" binding:"required"`
S int64 `json:"s"`
T int64 `json:"t" binding:"required"`
}
func (r DebugAssistantReq) DataString() string {
body, _ := json.Marshal(r)
return string(body)
}
// 北向指令
type CmdRequest struct {
Cid string
Protocol int32
S int64
T int64
Data []byte // json encode
}
func (cr CmdRequest) String() string {
return fmt.Sprintf("cid: %s, protocol: %d, s: %d, t: %d, data: %s", cr.Cid, cr.Protocol, cr.S, cr.T, string(cr.Data))
}
type CommandResponse struct {
Id string `json:"id"` // uuid
Cid string `json:"cid"` // 设备ID
Protocol int32 `json:"protocol"` // 协议号
Timestamp int64 `json:"timestamp"`
Data map[string]interface{} `json:"data"` // 序列化后的数据
}
func (cmd CommandResponse) DataJSON() string {
b, _ := json.Marshal(cmd.Data)
return string(b)
}
type CommandQueryRequest struct {
DeviceId string `form:"device_id" binding:"required"`
}
type ListCommandResponse struct {
List []CommandResponse `json:"list"`
}
func NewListCommandResponse() ListCommandResponse {
return ListCommandResponse{
List: []CommandResponse{},
}
}

View File

@ -22,15 +22,6 @@ type PageRequest struct {
PageSize int `json:"pageSize" form:"pageSize"` PageSize int `json:"pageSize" form:"pageSize"`
} }
//func (p *PageRequest) ToRpc() *common.PageRequest {
// return &common.PageRequest{
// NameLike: p.NameLike,
// Page: int64(p.Page),
// PageSize: int64(p.PageSize),
// }
//}
type BaseSearchConditionQuery struct { type BaseSearchConditionQuery struct {
Page int `schema:"page,omitempty" form:"page"` Page int `schema:"page,omitempty" form:"page"`
PageSize int `schema:"pageSize,omitempty" form:"pageSize" json:"pageSize"` PageSize int `schema:"pageSize,omitempty" form:"pageSize" json:"pageSize"`
@ -59,15 +50,10 @@ func (req BaseSearchConditionQuery) GetPage() (int, int) {
return offset, limit return offset, limit
} }
func ApiParamsStringToArray(str string) []string { func ApiParamsStringToArray(str string) []string {
return strings.Split(str, ",") return strings.Split(str, ",")
} }
/**
前端/后端请求查询的通用order by查询key必须是models里存在的值
比如 通过models.Device.ProductName 排序 那么key的值为 ProductName或则对应的数据库字段 product_name 不能是 pn
*/
type ApiOrderBy struct { type ApiOrderBy struct {
Key string Key string
IsDesc bool IsDesc bool
@ -102,8 +88,6 @@ func ApiParamsStringToOrderBy(str string) []ApiOrderBy {
return orderBys return orderBys
} }
func ApiParamsArrayToString(arr []string) string { func ApiParamsArrayToString(arr []string) string {
return strings.Join(arr, ",") return strings.Join(arr, ",")
} }

View File

@ -1,34 +0,0 @@
package dtos
import (
"github.com/winc-link/hummingbird/internal/models"
"github.com/winc-link/hummingbird/internal/pkg/constants"
//"github.com/winc-link/hummingbird/proto/resource"
//"github.com/winc-link/hummingbird/proto/strategy"
)
type AdvanceConfig struct {
// 日志级别 默认为DEBUG
LogLevel constants.LogLevel
// 持久化存储开关 默认关闭
PersistStorage bool
// 存储时长 默认为0
StorageHour int32
}
func AdvanceConfigFromModelToDTO(config models.AdvanceConfig) AdvanceConfig {
return AdvanceConfig{
LogLevel: config.LogLevel,
PersistStorage: config.PersistStorage,
StorageHour: config.StorageHour,
}
}
func AdvanceConfigFromDTOToModel(config AdvanceConfig) models.AdvanceConfig {
return models.AdvanceConfig{
ID: constants.DefaultAdvanceConfigID,
LogLevel: config.LogLevel,
PersistStorage: config.PersistStorage,
StorageHour: config.StorageHour,
}
}

View File

@ -1,48 +0,0 @@
package dtos
import "encoding/json"
type ConfigNetWork struct {
NcId string `json:"ncId"`
LocalIp string `json:"localIp,omitempty"`
GwIp string `json:"gwIp,omitempty"`
SmIp string `json:"smIp,omitempty"`
Netlink bool `json:"netlink,omitempty"`
}
type ConfigNetworkUpdateRequest struct {
NcId string `json:"ncId" binding:"required"`
LocalIp string `json:"localIp" binding:"required,ipv4"`
GwIp string `json:"gwIp" binding:"required,ipv4"`
SmIp string `json:"smIp" binding:"required,ipv4"`
}
type ConfigDnsUpdateRequest struct {
Dns []string `json:"dns,omitempty" binding:"required"`
OpenSwitch bool `json:"openSwitch,omitempty"`
}
type ConfigNetWorkResponse struct {
List []ConfigNetWork `json:"list"`
}
func NewConfigNetWorkResponse() ConfigNetWorkResponse {
return ConfigNetWorkResponse{List: make([]ConfigNetWork, 0)}
}
func (d ConfigNetWorkResponse) MarshalBinary() ([]byte, error) {
return json.Marshal(d)
}
func (d *ConfigNetWorkResponse) UnmarshalBinary(data []byte) error {
return json.Unmarshal(data, &d)
}
type ConfigDnsResponse struct {
Dns []string `json:"dns"`
OpenSwitch bool `json:"openSwitch"`
}
func (d ConfigDnsResponse) MarshalBinary() ([]byte, error) {
return json.Marshal(d)
}

View File

@ -24,16 +24,6 @@ import (
type DeviceSyncRequest struct { type DeviceSyncRequest struct {
CloudInstanceId string `json:"cloud_instance_id"` CloudInstanceId string `json:"cloud_instance_id"`
DriveInstanceId string `json:"driver_instance_id"` DriveInstanceId string `json:"driver_instance_id"`
//Extra struct{
//
//} `json:"extra"`
//Aliyun *struct {
// ResourceGroupId string `json:"resource_group_id"`
//} `json:"ali_yun"`
//HuaweiYun *struct {
// ProjectId string `json:"project_id"`
// AppId string `json:"app_id"`
//} `json:"huawei_yun"`
} }
type DeviceSyncByIdRequest struct { type DeviceSyncByIdRequest struct {
@ -214,9 +204,6 @@ func DeviceAuthInfoResponseFromModel(p models.MqttAuth) DeviceAuthInfoResponse {
type DeviceUpdateRequest struct { type DeviceUpdateRequest struct {
Id string `json:"id"` Id string `json:"id"`
Description *string `json:"description"` Description *string `json:"description"`
//Ip *string `json:"ip"`
//Lat *string `json:"lat"`
//Lon *string `json:"lon"`
Name *string `json:"name"` Name *string `json:"name"`
InstallLocation *string `json:"install_location"` InstallLocation *string `json:"install_location"`
DriveInstanceId *string `json:"drive_instance_id"` DriveInstanceId *string `json:"drive_instance_id"`
@ -229,14 +216,6 @@ func ReplaceDeviceModelFields(ds *models.Device, patch DeviceUpdateRequest) {
if patch.Name != nil { if patch.Name != nil {
ds.Name = *patch.Name ds.Name = *patch.Name
} }
//
//if patch.Lat != nil {
// ds.Lat = *patch.Lat
//}
//
//if patch.Lon != nil {
// ds.Lon = *patch.Lon
//}
if patch.DriveInstanceId != nil { if patch.DriveInstanceId != nil {
ds.DriveInstanceId = *patch.DriveInstanceId ds.DriveInstanceId = *patch.DriveInstanceId
} }

View File

@ -29,12 +29,9 @@ func DeviceLibraryFromModel(d models.DeviceLibrary) DeviceLibrary {
Description: d.Description, Description: d.Description,
Protocol: d.Protocol, Protocol: d.Protocol,
Version: d.Version, Version: d.Version,
//LibFile: d.LibFile,
//ConfigFile: d.ConfigFile,
DockerConfigId: d.DockerConfigId, DockerConfigId: d.DockerConfigId,
DockerRepoName: d.DockerRepoName, DockerRepoName: d.DockerRepoName,
DockerImageId: d.DockerImageId, DockerImageId: d.DockerImageId,
//SupportVersions: SupperVersionsFromModel(d.SupportVersions),
} }
} }
@ -70,16 +67,6 @@ func FromDeviceLibraryRpcToModel(p *DeviceLibraryAddRequest) models.DeviceLibrar
DockerConfigId: p.DockerConfigId, DockerConfigId: p.DockerConfigId,
Language: p.Language, Language: p.Language,
} }
//dl.SupportVersions = append(dl.SupportVersions, models.SupportVersion{
// Version: p.Version,
// IsDefault: p.IsDefault,
// ConfigJson: p.ConfigJson,
// ConfigFile: p.ConfigFile,
// DockerParamsSwitch: p.DockerParamsSwitch,
// DockerParams: s.DockerParams,
// ExpertMode: s.ExpertMode,
// ExpertModeContent: s.ExpertModeContent,
//})
return dl return dl
} }

View File

@ -51,48 +51,6 @@ func DeviceServiceFromModel(ds models.DeviceService) DeviceService {
return dto return dto
} }
//func FromDeviceServiceModelToRPC(mds models.DeviceService) *deviceserviceProto.DeviceService {
// byteConfig, _ := json.Marshal(mds.Config)
// var ds deviceserviceProto.DeviceService
// ds.Id = mds.Id
// ds.Name = mds.Name
// ds.BaseAddress = mds.BaseAddress
// ds.DeviceLibraryId = mds.DeviceLibraryId
// ds.DockerContainerId = mds.DockerContainerId
// ds.Config = byteConfig
// ds.ExpertMode = mds.ExpertMode
// ds.ExpertModeContent = mds.ExpertModeContent
// ds.DockerParamsSwitch = mds.DockerParamsSwitch
// ds.DockerParams = mds.DockerParams
// ds.LogLevel = int64(mds.LogLevel)
// ds.RunStatus = int32(mds.RunStatus)
// ds.ImageExist = mds.ImageExist
// return &ds
//}
//func FromDeviceServiceRpcToModel(ds *deviceserviceProto.DeviceService) models.DeviceService {
// var config map[string]interface{}
// if ds.Config != nil {
// _ = json.Unmarshal(ds.Config, &config)
// }
//
// var mds models.DeviceService
// mds.Id = ds.Id
// mds.Name = ds.Name
// mds.BaseAddress = ds.BaseAddress
// mds.DeviceLibraryId = ds.DeviceLibraryId
// mds.DockerContainerId = ds.DockerContainerId
// mds.RunStatus = int(ds.RunStatus)
// mds.Config = config
// mds.ExpertMode = ds.ExpertMode
// mds.ExpertModeContent = ds.ExpertModeContent
// mds.DockerParamsSwitch = ds.DockerParamsSwitch
// mds.DockerParams = ds.DockerParams
// mds.ImageExist = ds.ImageExist
// mds.DriverType = int(ds.DriverType)
// return mds
//}
type DeviceServiceAddRequest struct { type DeviceServiceAddRequest struct {
Id string `json:"id,omitempty" binding:"omitempty,t-special-char"` Id string `json:"id,omitempty" binding:"omitempty,t-special-char"`
Name string `json:"name"` Name string `json:"name"`
@ -105,35 +63,6 @@ type DeviceServiceAddRequest struct {
DriverType int `json:"driverType" binding:"omitempty,oneof=1 2"` //驱动库类型1驱动2三方应用 DriverType int `json:"driverType" binding:"omitempty,oneof=1 2"` //驱动库类型1驱动2三方应用
} }
//func FromDeviceServiceAddToRpc(req DeviceServiceAddRequest) *deviceserviceProto.DeviceService {
// byteConfig, _ := json.Marshal(req.Config)
// return &deviceserviceProto.DeviceService{
// Id: req.Id,
// Name: req.Name,
// DeviceLibraryId: req.DeviceLibraryId,
// Config: byteConfig,
// ExpertMode: req.ExpertMode,
// ExpertModeContent: req.ExpertModeContent,
// DockerParamsSwitch: req.DockerParamsSwitch,
// DockerParams: req.DockerParams,
// DriverType: int32(req.DriverType),
// }
//}
func DeviceServiceFromDeviceServiceAddRequest(ds DeviceServiceAddRequest) models.DeviceService {
var mds models.DeviceService
mds.Id = ds.Id
mds.Name = ds.Name
mds.Config = ds.Config
mds.DeviceLibraryId = ds.DeviceLibraryId
mds.ExpertMode = ds.ExpertMode
mds.ExpertModeContent = ds.ExpertModeContent
mds.DockerParamsSwitch = ds.DockerParamsSwitch
mds.DockerParams = ds.DockerParams
mds.DriverType = ds.DriverType
return mds
}
type DeviceServiceUpdateRequest struct { type DeviceServiceUpdateRequest struct {
Id string `json:"id" binding:"required"` Id string `json:"id" binding:"required"`
DeviceLibraryId *string `json:"deviceLibraryId"` DeviceLibraryId *string `json:"deviceLibraryId"`
@ -147,23 +76,6 @@ type DeviceServiceUpdateRequest struct {
//IsIgnoreRunStatus bool //IsIgnoreRunStatus bool
} }
//func FromRpcToUpdateDeviceService(rpc *deviceserviceProto.UpdateDeviceService) DeviceServiceUpdateRequest {
// var config map[string]interface{}
// if rpc.Config != nil {
// _ = json.Unmarshal(rpc.Config, &config)
// }
// return DeviceServiceUpdateRequest{
// Id: rpc.Id,
// Name: rpc.Name,
// DeviceLibraryId: rpc.DeviceLibraryId,
// Config: &config,
// ExpertMode: rpc.ExpertMode,
// ExpertModeContent: rpc.ExpertModeContent,
// DockerParamsSwitch: rpc.DockerParamsSwitch,
// DockerParams: rpc.DockerParams,
// }
//}
type UpdateDeviceServiceRunStatusRequest struct { type UpdateDeviceServiceRunStatusRequest struct {
Id string `json:"id"` Id string `json:"id"`
RunStatus int `json:"run_status" binding:"required,oneof=1 2"` RunStatus int `json:"run_status" binding:"required,oneof=1 2"`
@ -178,28 +90,6 @@ type DeviceServiceDeleteRequest struct {
Id string `json:"id" binding:"required"` Id string `json:"id" binding:"required"`
} }
//func FromUpdateDeviceServiceRunStatusToRpc(req UpdateDeviceServiceRunStatusRequest) *deviceserviceProto.UpdateDeviceServiceRunStatusRequest {
// return &deviceserviceProto.UpdateDeviceServiceRunStatusRequest{
// Id: req.Id,
// RunStatus: int32(req.RunStatus),
// }
//}
//
//func FromDeviceServiceSearchQueryRequestToRpc(req DeviceServiceSearchQueryRequest) *deviceserviceProto.DeviceServiceSearchRequest {
// return &deviceserviceProto.DeviceServiceSearchRequest{
// BaseSearchConditionQuery: FromBaseSearchConditionQueryToRpc(req.BaseSearchConditionQuery),
// DeviceLibraryId: req.DeviceLibraryId,
// DriverType: int32(req.DriverType),
// }
//}
//func FromRpcToUpdateDeviceServiceRunStatus(rpc *deviceserviceProto.UpdateDeviceServiceRunStatusRequest) UpdateDeviceServiceRunStatusRequest {
// return UpdateDeviceServiceRunStatusRequest{
// Id: rpc.Id,
// RunStatus: int(rpc.RunStatus),
// }
//}
func ReplaceDeviceServiceModelFieldsWithDTO(ds *models.DeviceService, patch DeviceServiceUpdateRequest) { func ReplaceDeviceServiceModelFieldsWithDTO(ds *models.DeviceService, patch DeviceServiceUpdateRequest) {
if patch.Config != nil { if patch.Config != nil {
ds.Config = *patch.Config ds.Config = *patch.Config
@ -234,42 +124,6 @@ type DeviceServiceSearchQueryRequest struct {
DriverType int `form:"driver_type" binding:"omitempty,oneof=1 2"` //驱动库类型1驱动2三方应用 DriverType int `form:"driver_type" binding:"omitempty,oneof=1 2"` //驱动库类型1驱动2三方应用
} }
//func ToDeviceServiceSearchQueryRequestDTO(req *deviceserviceProto.DeviceServiceSearchRequest) DeviceServiceSearchQueryRequest {
//
// if req.BaseSearchConditionQuery == nil {
// return DeviceServiceSearchQueryRequest{
// DeviceLibraryId: req.DeviceLibraryId,
// DriverType: int(req.DriverType),
// }
// } else {
// return DeviceServiceSearchQueryRequest{
// BaseSearchConditionQuery: ToBaseSearchConditionQueryDTO(req.BaseSearchConditionQuery),
// DeviceLibraryId: req.DeviceLibraryId,
// DriverType: int(req.DriverType),
// }
// }
//}
//func FromDeviceServiceUpdateToRpc(req DeviceServiceUpdateRequest) *deviceserviceProto.UpdateDeviceService {
// var byteConfig []byte
// if req.Config != nil {
// byteConfig, _ = json.Marshal(&req.Config)
// } else {
// byteConfig = nil
// }
//
// return &deviceserviceProto.UpdateDeviceService{
// Id: req.Id,
// Name: req.Name,
// DeviceLibraryId: req.DeviceLibraryId,
// Config: byteConfig,
// ExpertMode: req.ExpertMode,
// ExpertModeContent: req.ExpertModeContent,
// DockerParamsSwitch: req.DockerParamsSwitch,
// DockerParams: req.DockerParams,
// }
//}
/************** Response **************/ /************** Response **************/
type DeviceServiceResponse struct { type DeviceServiceResponse struct {
@ -306,23 +160,6 @@ func DeviceServiceResponseFromModel(ds models.DeviceService, dl models.DeviceLib
} }
} }
//func FromDeviceServiceRpcToResponse(ds *deviceserviceProto.DeviceService, dl *devicelibraryProto.DeviceLibrary) DeviceServiceResponse {
// var cfg map[string]interface{}
// _ = json.Unmarshal(ds.Config, &cfg)
// return DeviceServiceResponse{
// Id: ds.Id,
// Name: ds.Name,
// RunStatus: int(ds.RunStatus),
// DeviceLibrary: FromDeviceLibraryRpcToResponse(dl),
// Config: cfg,
// ExpertMode: ds.ExpertMode,
// ExpertModeContent: ds.ExpertModeContent,
// DockerParamsSwitch: ds.DockerParamsSwitch,
// DockerParams: ds.DockerParams,
// ImageExist: ds.ImageExist,
// }
//}
func FromYamlStrToMap(yamlStr string) (m map[string]interface{}, err error) { func FromYamlStrToMap(yamlStr string) (m map[string]interface{}, err error) {
err = yaml.Unmarshal([]byte(yamlStr), &m) err = yaml.Unmarshal([]byte(yamlStr), &m)
if err != nil { if err != nil {

View File

@ -48,46 +48,34 @@ func (m *DriverConfigManage) SetNetworkName(networkName string) {
m.NetWorkName = networkName m.NetWorkName = networkName
} }
// 存储驱动上传配置定义文件目录 /var/tedge/edgex-driver-data/driver-library/
func (m *DriverConfigManage) GetLibraryDir() string { func (m *DriverConfigManage) GetLibraryDir() string {
return utils.GetPwdDir() + "/" + constants.DriverLibraryDir + "/" return utils.GetPwdDir() + "/" + constants.DriverLibraryDir + "/"
} }
// 驱动二进制文件路径 /var/tedge/edgex-driver-data/bin/modbus-1234
func (m *DriverConfigManage) GetBinPath(serverName string) string { func (m *DriverConfigManage) GetBinPath(serverName string) string {
return utils.GetPwdDir() + "/" + constants.DriverBinDir + "/" + serverName return utils.GetPwdDir() + "/" + constants.DriverBinDir + "/" + serverName
} }
// 驱动启动的配置文件路径 /var/edge/run-config/modbus-1234.toml
func (m *DriverConfigManage) GetRunConfigPath(serviceName string) string { func (m *DriverConfigManage) GetRunConfigPath(serviceName string) string {
return constants.DockerHummingbirdRootDir + "/" + constants.DriverRunConfigDir + "/" + serviceName + constants.ConfigSuffix return constants.DockerHummingbirdRootDir + "/" + constants.DriverRunConfigDir + "/" + serviceName + constants.ConfigSuffix
} }
// docker挂载
func (m *DriverConfigManage) GetHostRunConfigPath(serviceName string) string { func (m *DriverConfigManage) GetHostRunConfigPath(serviceName string) string {
return m.HostRootDir + "/" + constants.DriverRunConfigDir + "/" + serviceName + constants.ConfigSuffix return m.HostRootDir + "/" + constants.DriverRunConfigDir + "/" + serviceName + constants.ConfigSuffix
} }
// 二进制版本路径
// 驱动启动的配置文件路径 /var/edge/mnt/modbus-1234.toml
func (m *DriverConfigManage) GetMntDir(serviceName string) string { func (m *DriverConfigManage) GetMntDir(serviceName string) string {
return constants.DockerHummingbirdRootDir + "/" + constants.DriverMntDir + "/" + serviceName return constants.DockerHummingbirdRootDir + "/" + constants.DriverMntDir + "/" + serviceName
} }
// docker挂载 的日志只针对docker版本二进制版本需要改动日志存储地址 /var/edge/mnt/modbus-1234.toml
func (m *DriverConfigManage) GetHostMntDir(serviceName string) string { func (m *DriverConfigManage) GetHostMntDir(serviceName string) string {
return m.HostRootDir + "/" + constants.DriverMntDir + "/" + serviceName return m.HostRootDir + "/" + constants.DriverMntDir + "/" + serviceName
} }
// 二进制版本 驱动运行日志文件 /var/tedge/mnt/modbus-1234/logs/driver.log
func (m *DriverConfigManage) GetLogFilePath(serviceName string) string { func (m *DriverConfigManage) GetLogFilePath(serviceName string) string {
return utils.GetPwdDir() + "/" + constants.DriverMntDir + "/" + serviceName + "/" + constants.DriverDefaultLogPath return utils.GetPwdDir() + "/" + constants.DriverMntDir + "/" + serviceName + "/" + constants.DriverDefaultLogPath
} }
// docker挂载
//logfilePath = "/var/edge/edge-driver-data/mnt/aliyun-iot/edgex-aliyun-cloud.log"
///var/edge/edge-driver-data/mnt/aliyun-iot
func (m *DriverConfigManage) GetHostLogFilePath(serviceName string) string { func (m *DriverConfigManage) GetHostLogFilePath(serviceName string) string {
return constants.DockerHummingbirdRootDir + "/" + constants.DriverMntDir + "/" + serviceName + "/" + constants.DriverDefaultLogPath return constants.DockerHummingbirdRootDir + "/" + constants.DriverMntDir + "/" + serviceName + "/" + constants.DriverDefaultLogPath
} }

View File

@ -12,11 +12,6 @@ const (
DevicesFilename = "Devices" DevicesFilename = "Devices"
) )
var (
FuncPointImmutableHeader = []string{"DP ID", "Name", "DataType", "TransferType"}
FuncPointIntegerHeader = []string{"Scale", "ValueType"}
)
type ExportFile struct { type ExportFile struct {
Excel *excelize.File Excel *excelize.File
FileName string FileName string

View File

@ -1,53 +0,0 @@
package dtos
type NetIface struct {
Ifaces []string `json:"ifaces"`
}
type EdgeBaseConfig struct {
}
type EdgeGwConfig struct {
GwId string `json:"gwId"`
SecKey string `json:"secKey"`
LocalKey string `json:"localKey"`
Status bool `json:"status"`
}
type EdgeConfig struct {
//BaseConfig EdgeBaseConfig `yaml:"baseconfig"`
//GwConfig EdgeGwConfig `yaml:"gwconfig"`
//SubDeviceLimit int64 `yaml:"subdevicelimit"`
//ExpiryTime int64 `yaml:"expiry"`
//ActiveTime int64 `yaml:"activeTime"`
//LastExitTime int64 `yaml:"lastExitTime"`
//IsExpired bool `yaml:"isExpired"`
GwId string `yaml:"gwid"`
SecKey string `yaml:"seckey"`
Status bool `yaml:"status"`
ActiveTime string `yaml:"activetime"`
VersionNumber string `yaml:"versionnumber"`
SubDeviceLimit int64 `yaml:"subdevicelimit"`
}
func (c EdgeConfig) GetGatewayNumber() string {
switch c.VersionNumber {
case "ireland":
return "Ireland爱尔兰"
case "seattle":
return "Seattle西雅图"
case "kamakura镰仓":
return "Kamakura"
default:
return c.VersionNumber
}
}
func (c EdgeConfig) IsActivated() bool {
return c.Status
}
func (c EdgeConfig) CheckThingModelActiveGw() bool {
return c.GwId != "" && c.SecKey != ""
}

View File

@ -1,12 +0,0 @@
package dtos
import "fmt"
type Gps struct {
Longitude float64 `json:"longitude"`
Latitude float64 `json:"latitude"`
}
func (gps Gps) ToLocation() string {
return fmt.Sprintf("%f,%f", gps.Latitude, gps.Longitude)
}

View File

@ -19,17 +19,3 @@ func NewImportFile(f io.Reader) (*ImportFile, error) {
Excel: file, Excel: file,
}, nil }, nil
} }
type DeviceAddResponse struct {
List []DeviceAddResult `json:"list"`
ProcessNum int `json:"processNum"`
SuccessNum int `json:"successNum"`
FailNum int `json:"failNum"`
}
type DeviceAddResult struct {
Id string `json:"id"`
Name string `json:"name"`
Status bool `json:"status"`
Message string `json:"message"`
}

View File

@ -1,28 +0,0 @@
//
// Copyright (C) 2021 IOTech Ltd
//
// SPDX-License-Identifier: Apache-2.0
package dtos
import "encoding/json"
/*
* An Operation for SMA processing.
*
*
* Operation struct
*/
type Operation struct {
Action string `json:"action,omitempty" binding:"oneof=start stop restart"` // 动作,重启 restart
Service string `json:"service,omitempty" binding:"required"` // 服务名称
}
// String returns a JSON encoded string representation of the model
func (o Operation) String() string {
out, err := json.Marshal(o)
if err != nil {
return err.Error()
}
return string(out)
}

View File

@ -1,56 +1,11 @@
package dtos package dtos
type ReqPageInfo struct {
Page int `json:"page" form:"page"`
PageSize int `json:"page_size" form:"page_size"`
}
type ResPageResult struct {
List interface{} `json:"list"`
Total uint32 `json:"total"`
Page int `json:"page"`
PageSize int `json:"pageSize"`
}
func NewPageResult(responses interface{}, total uint32, page int, pageSize int) ResPageResult {
if responses == nil {
responses = make([]interface{}, 0)
}
return ResPageResult{
List: responses,
Total: total,
Page: page,
PageSize: pageSize,
}
}
type CommonResponse struct {
Success bool `json:"success"`
ErrorMsg string `json:"errorMsg"`
ErrorCode int `json:"errorCode"`
Result interface{} `json:"result"`
}
const ( const (
PageDefault = 1 PageDefault = 1
PageSizeDefault = 10 PageSizeDefault = 10
PageSizeMaxDefault = 1000 PageSizeMaxDefault = 1000
) )
// 校验并设置PageRequest参数
func CorrectionPageRequest(query *PageRequest) {
if query.Page <= 0 {
query.Page = PageDefault
}
if query.PageSize >= PageSizeMaxDefault {
query.PageSize = PageSizeMaxDefault
} else if query.PageSize <= 0 {
query.PageSize = PageSizeDefault
}
}
// 校验并设置page参数
func CorrectionPageParam(query *BaseSearchConditionQuery) { func CorrectionPageParam(query *BaseSearchConditionQuery) {
if query.Page <= 0 { if query.Page <= 0 {
query.Page = PageDefault query.Page = PageDefault

View File

@ -139,18 +139,6 @@ type OpenApiEvents struct {
CreatedAt int64 `json:"created_at"` CreatedAt int64 `json:"created_at"`
} }
//
//func (t *OpenApiEvents) TransformModelInPutParams() (inPutParams models.InPutParams) {
// for _, datum := range t.OutputParams {
// var inputOutput models.InputOutput
// inputOutput.Code = datum.Code
// inputOutput.Name = datum.Name
// inputOutput.TypeSpec = getThingModelTemplateTypeSpec(string(datum.TypeSpec.Type), datum.TypeSpec.Specs, nil)
// inPutParams = append(inPutParams, inputOutput)
// }
// return
//}
type OpenApiOutPutParams struct { type OpenApiOutPutParams struct {
Code string `json:"code"` Code string `json:"code"`
Name string `json:"name"` Name string `json:"name"`
@ -232,16 +220,6 @@ func ProductSearchOpenApiFromModel(p models.Product) ProductSearchOpenApiRespons
type ProductSyncRequest struct { type ProductSyncRequest struct {
CloudInstanceId string `json:"cloud_instance_id"` CloudInstanceId string `json:"cloud_instance_id"`
//Extra struct{
//
//} `json:"extra"`
//Aliyun *struct {
// ResourceGroupId string `json:"resource_group_id"`
//} `json:"ali_yun"`
//HuaweiYun *struct {
// ProjectId string `json:"project_id"`
// AppId string `json:"app_id"`
//} `json:"huawei_yun"`
} }
type ProductSyncByIdRequest struct { type ProductSyncByIdRequest struct {
@ -269,9 +247,6 @@ type OpenApiAddProductRequest struct {
DataFormat string `json:"data_format"` //数据类型 DataFormat string `json:"data_format"` //数据类型
Factory string `json:"factory"` //厂家 Factory string `json:"factory"` //厂家
Description string `json:"description"` //描述 Description string `json:"description"` //描述
//Properties []OpenApiProperties `json:"properties"`
//Events []OpenApiEvents `json:"events"`
//Actions []OpenApiActions `json:"services"`
} }
type OpenApiUpdateProductRequest struct { type OpenApiUpdateProductRequest struct {
@ -283,7 +258,4 @@ type OpenApiUpdateProductRequest struct {
DataFormat *string `json:"data_format"` //数据类型 DataFormat *string `json:"data_format"` //数据类型
Factory *string `json:"factory"` //厂家 Factory *string `json:"factory"` //厂家
Description *string `json:"description"` //描述 Description *string `json:"description"` //描述
//Properties []OpenApiProperties `json:"properties"`
//Events []OpenApiEvents `json:"events"`
//Actions []OpenApiActions `json:"services"`
} }

View File

@ -25,7 +25,6 @@ type SceneAddRequest struct {
type SceneUpdateRequest struct { type SceneUpdateRequest struct {
Id string `json:"id"` Id string `json:"id"`
//Condition constants.WorkerCondition `json:"condition"` //执行条件
Conditions []Condition `json:"conditions"` Conditions []Condition `json:"conditions"`
Actions []Action `json:"actions"` Actions []Action `json:"actions"`
} }
@ -60,7 +59,6 @@ func ReplaceSceneModelFields(scene *models.Scene, req SceneUpdateRequest) {
type Condition struct { type Condition struct {
ConditionType string `json:"condition_type"` ConditionType string `json:"condition_type"`
Option map[string]string `json:"option"` Option map[string]string `json:"option"`
//CronExpression string `json:"cron_expression"`
} }
type Action struct { type Action struct {
@ -81,7 +79,6 @@ type SceneSearchQueryRequest struct {
type SceneLogSearchQueryRequest struct { type SceneLogSearchQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"` BaseSearchConditionQuery `schema:",inline"`
//Name string `schema:"name,omitempty"`
StartAt int64 `schema:"start_time"` StartAt int64 `schema:"start_time"`
EndAt int64 `schema:"end_time"` EndAt int64 `schema:"end_time"`
SceneId string `json:"scene_id"` SceneId string `json:"scene_id"`

View File

@ -6,51 +6,6 @@ import (
"github.com/winc-link/hummingbird/internal/models" "github.com/winc-link/hummingbird/internal/models"
) )
type DeviceLibrarySupportVersion struct {
Version string `json:"version"`
IsDefault bool `json:"is_default"`
DockerParamsSwitch bool `json:"docker_params_switch"`
DockerParams string `json:"docker_params"`
ExpertMode bool `json:"expert_mode"`
ExpertModeContent string `json:"expert_mode_content"`
ConfigFile string `json:"config_file"`
ConfigJson string `json:"config_json"`
}
func SupperVersionsFromModel(versions []models.SupportVersion) []DeviceLibrarySupportVersion {
ret := make([]DeviceLibrarySupportVersion, 0)
for _, v := range versions {
ret = append(ret, DeviceLibrarySupportVersion{
Version: v.Version,
IsDefault: v.IsDefault,
DockerParamsSwitch: v.DockerParamsSwitch,
DockerParams: v.DockerParams,
ExpertMode: v.ExpertMode,
ExpertModeContent: v.ExpertModeContent,
ConfigJson: v.ConfigJson,
ConfigFile: v.ConfigFile,
})
}
return ret
}
//func FromDeviceLibrarySupperVersionsToRpc(versions []models.SupportVersion) []*devicelibrary.SupportVersion {
// ret := make([]*devicelibrary.SupportVersion, 0)
// for _, v := range versions {
// ret = append(ret, &devicelibrary.SupportVersion{
// Version: v.Version,
// IsDefault: v.IsDefault,
// DockerParamsSwitch: v.DockerParamsSwitch,
// DockerParams: v.DockerParams,
// ExpertMode: v.ExpertMode,
// ExpertModeContent: v.ExpertModeContent,
// ConfigJson: v.ConfigJson,
// ConfigFile: v.ConfigFile,
// })
// }
// return ret
//}
type DeviceLibrarySupportVersionSimple struct { type DeviceLibrarySupportVersionSimple struct {
Version string `json:"version"` Version string `json:"version"`
IsDefault bool `json:"is_default"` IsDefault bool `json:"is_default"`
@ -68,28 +23,3 @@ func DeviceLibrarySupportVersionSimpleFromModel(versions models.SupportVersions)
} }
return ret return ret
} }
//func FromSupportVersionSimpleRpcToDto(resp *devicelibrary.DeviceLibrary) []DeviceLibrarySupportVersionSimple {
// ret := make([]DeviceLibrarySupportVersionSimple, 0)
// for _, v := range resp.SupportVersions {
// ret = append(ret, DeviceLibrarySupportVersionSimple{
// Version: v.Version,
// IsDefault: v.IsDefault,
// ConfigFile: v.ConfigFile,
// })
// }
// return ret
//}
//
//func ModelSupportVersionFromRPC(s *devicelibrary.SupportVersion) models.SupportVersion {
// return models.SupportVersion{
// Version: s.Version,
// IsDefault: s.IsDefault,
// ConfigJson: s.ConfigJson,
// ConfigFile: s.ConfigFile,
// DockerParamsSwitch: s.DockerParamsSwitch,
// DockerParams: s.DockerParams,
// ExpertMode: s.ExpertMode,
// ExpertModeContent: s.ExpertModeContent,
// }
//}

View File

@ -70,7 +70,6 @@ type SystemThingModelSearchReq struct {
type OpenApiThingModelProperties struct { type OpenApiThingModelProperties struct {
Id string `json:"id"` Id string `json:"id"`
//ProductId string `json:"product_id"` // 产品ID
Name string `json:"name"` // 属性名称 Name string `json:"name"` // 属性名称
Code string `json:"code"` // 标识符 Code string `json:"code"` // 标识符
AccessMode string `json:"access_mode"` // 数据传输类型 AccessMode string `json:"access_mode"` // 数据传输类型
@ -81,7 +80,6 @@ type OpenApiThingModelProperties struct {
type OpenApiThingModelEvents struct { type OpenApiThingModelEvents struct {
Id string `json:"id"` Id string `json:"id"`
//ProductId string `json:"product_id"`
EventType string `json:"event_type"` EventType string `json:"event_type"`
Name string `json:"name"` // 功能名称 Name string `json:"name"` // 功能名称
Code string `json:"code"` // 标识符 Code string `json:"code"` // 标识符
@ -92,7 +90,6 @@ type OpenApiThingModelEvents struct {
type OpenApiThingModelServices struct { type OpenApiThingModelServices struct {
Id string `json:"id"` Id string `json:"id"`
//ProductId string `json:"product_id"`
Name string `json:"name"` // 功能名称 Name string `json:"name"` // 功能名称
Code string `json:"code"` // 标识符 Code string `json:"code"` // 标识符
Description string `json:"description"` Description string `json:"description"`

View File

@ -17,8 +17,6 @@ package dtos
type ThingModelDataBaseRequest struct { type ThingModelDataBaseRequest struct {
First bool `json:"first"` First bool `json:"first"`
Last bool `json:"last"` Last bool `json:"last"`
//Page int `json:"page"`
//PageSize int `json:"pageSize"`
Range []int64 `json:"range"` Range []int64 `json:"range"`
} }

View File

@ -30,29 +30,11 @@ type ThingModelTemplate struct {
Services []ThingModelTemplateServices `json:"services"` Services []ThingModelTemplateServices `json:"services"`
} }
//------------------------------------------------------------
//array
//{
//"childDataType":"TEXT",
//"customFlag":true,
//"dataType":"ARRAY",
//"size":128
//}
type ThingModelTemplateArray struct { type ThingModelTemplateArray struct {
ChildDataType string `json:"childDataType"` ChildDataType string `json:"childDataType"`
Size int `json:"size"` Size int `json:"size"`
} }
//------------------------------------------------------------
//{
// "dataType":"DOUBLE",
// "max":"23",
// "min":"16",
// "precise":7,
// "step":"0.01",
// "unit":"°C",
// "unitName":"摄氏度"
//}
type ThingModelTemplateIntOrFloat struct { type ThingModelTemplateIntOrFloat struct {
Max string `json:"max"` Max string `json:"max"`
Min string `json:"min"` Min string `json:"min"`
@ -61,55 +43,19 @@ type ThingModelTemplateIntOrFloat struct {
UnitName string `json:"unitName"` UnitName string `json:"unitName"`
} }
//------------------------------------------------------------
//[
//{
//"dataType":"BOOL",
//"name":"未查询",
//"value":0
//},
//{
//"dataType":"BOOL",
//"name":"查询",
//"value":1
//}
//]
type ThingModelTemplateBool struct { type ThingModelTemplateBool struct {
Name string `json:"name"` Name string `json:"name"`
Value int `json:"value"` Value int `json:"value"`
} }
//------------------------------------------------------------
//{
//"dataType":"TEXT",
//"length":255
//}
type ThingModelTemplateText struct { type ThingModelTemplateText struct {
Length int `json:"length"` Length int `json:"length"`
} }
//------------------------------------------------------------
//{
//"dataType":"Date",
//"length":255
//}
type ThingModelTemplateDate struct { type ThingModelTemplateDate struct {
Length string `json:"length"` Length string `json:"length"`
} }
//------------------------------------------------------------
//[
//{
//"dataType":"ENUM",
//"name":"电源",
//"value":0
//},
//{
//"dataType":"ENUM",
//"name":"电池",
//"value":1
//}
//]
type ThingModelTemplateEnum struct { type ThingModelTemplateEnum struct {
Name string `json:"name"` Name string `json:"name"`
Value int `json:"value"` Value int `json:"value"`
@ -489,88 +435,3 @@ func GetModelPropertyEventActionByThingModelTemplate(thingModelJSON string) (pro
} }
return return
} }
//func OpenApiGetModelPropertyEventActionByThingModelTemplate(req OpenApiAddRequest) (properties []models.Properties, events []models.Events, actions []models.Actions) {
// for _, property := range req.Properties {
// properties = append(properties, models.Properties{
// Id: utils.RandomNum(),
// Name: property.Name,
// Code: property.Code,
// AccessMode: property.AccessMode,
// Require: property.Required,
// Description: property.Description,
// TypeSpec: models.TypeSpec(property.TypeSpec),
// Tag: string(constants.TagNameCustom),
// Timestamps: models.Timestamps{
// Created: time.Now().UnixMilli(),
// },
// })
// }
//
// for _, event := range req.Events {
// var outPutParams models.OutPutParams
// for _, param := range event.OutputParams {
// outPutParams = append(outPutParams, models.InputOutput{
// Code: param.Code,
// Name: param.Name,
// TypeSpec: models.TypeSpec{
// Type: param.TypeSpec.Type,
// Specs: param.TypeSpec.Specs,
// },
// })
// }
// events = append(events, models.Events{
// Id: utils.RandomNum(),
// Name: event.Name,
// EventType: event.EventType,
// Code: event.Code,
// Require: event.Required,
// Description: event.Description,
// OutputParams: outPutParams,
// Tag: string(constants.TagNameCustom),
// Timestamps: models.Timestamps{
// Created: time.Now().UnixMilli(),
// },
// })
// }
//
// for _, action := range req.Actions {
// var inPutParams models.InPutParams
// var outPutParams models.OutPutParams
// for _, param := range action.InputParams {
// inPutParams = append(inPutParams, models.InputOutput{
// Code: param.Code,
// Name: param.Name,
// TypeSpec: models.TypeSpec{
// Type: param.TypeSpec.Type,
// Specs: param.TypeSpec.Specs,
// },
// })
// }
// for _, param := range action.OutputParams {
// outPutParams = append(outPutParams, models.InputOutput{
// Code: param.Code,
// Name: param.Name,
// TypeSpec: models.TypeSpec{
// Type: param.TypeSpec.Type,
// Specs: param.TypeSpec.Specs,
// },
// })
// }
// actions = append(actions, models.Actions{
// Id: utils.RandomNum(),
// Name: action.Name,
// Code: action.Code,
// CallType: action.CallType,
// Require: action.Required,
// Description: action.Description,
// InputParams: inPutParams,
// OutputParams: outPutParams,
// Tag: string(constants.TagNameCustom),
// Timestamps: models.Timestamps{
// Created: time.Now().UnixMilli(),
// },
// })
// }
// return
//}

View File

@ -22,18 +22,6 @@ const (
WsCodeDeviceLibraryDelete WsCode = 10003 // 驱动删除 WsCodeDeviceLibraryDelete WsCode = 10003 // 驱动删除
WsCodeDeviceServiceLog WsCode = 10004 // 驱动日志 WsCodeDeviceServiceLog WsCode = 10004 // 驱动日志
WsCodeCloudServiceDownload WsCode = 20001 // 云服务下载
WsCodeCloudServiceRunStatus WsCode = 20002 // 云服务重启/停止
WsCodeCloudServiceRunDelete WsCode = 20003 // 云服务删除
WsCodeCloudServiceRunLog WsCode = 20004 // 云服务日志
WsCodeCheckLang WsCode = 30001 // 切换语言 WsCodeCheckLang WsCode = 30001 // 切换语言
// 云端网络情况
WsCodeCloudState WsCode = 10007 // 云端网络情况
//OTA
WsCodeOTAUpgradeProgress WsCode = 10100 // OTA升级进度
WsCodeOTAFirmwareUpgrade WsCode = 10101 // OTA升级
// 严重警告
WsCodeSeriousAlert WsCode = 10200
) )

View File

@ -1,12 +1 @@
package container package container
import (
"github.com/winc-link/hummingbird/internal/pkg/di"
"github.com/winc-link/hummingbird/internal/tools/agentclient"
)
var AgentClientName = di.TypeInstanceToName((*agentclient.AgentClient)(nil))
func AgentClientNameFrom(get di.Get) agentclient.AgentClient {
return get(AgentClientName).(agentclient.AgentClient)
}

View File

@ -1,98 +0,0 @@
/*******************************************************************************
* Copyright 2017.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package gateway
import (
"github.com/gin-gonic/gin"
"github.com/winc-link/hummingbird/internal/dtos"
"github.com/winc-link/hummingbird/internal/pkg/errort"
"github.com/winc-link/hummingbird/internal/pkg/httphelper"
)
// @Tags 配网助手
// @Summary 获取网卡列表
// @Produce json
// @Success 200 {object} dtos.ConfigNetWorkResponse
// @Router /api/v1/local/config/network [get]
func (ctl *controller) ConfigNetWorkGet(c *gin.Context) {
lc := ctl.lc
res, edgeXErr := ctl.getSystemApp().ConfigNetWork(c, false)
if edgeXErr != nil {
httphelper.RenderFail(c, errort.NewCommonErr(errort.DefaultReqParamsError, edgeXErr), c.Writer, lc)
return
}
httphelper.ResultSuccess(res, c.Writer, lc)
}
// @Tags 配网助手
// @Summary 修改网卡
// @Produce json
// @Param req body dtos.ConfigNetworkUpdateRequest true "参数"
// @Success 200 {object} dtos.ConfigNetWorkResponse
// @Router /api/v1/local/config/network [put]
func (ctl *controller) ConfigNetWorkUpdate(c *gin.Context) {
lc := ctl.lc
var req dtos.ConfigNetworkUpdateRequest
if err := c.ShouldBind(&req); err != nil {
httphelper.RenderFail(c, errort.NewCommonErr(errort.DefaultReqParamsError, err), c.Writer, lc)
return
}
edgeXErr := ctl.getSystemApp().ConfigNetWorkUpdate(c, req)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}
// @Tags 配网助手
// @Summary 获取dns
// @Produce json
// @Success 200 {object} dtos.ConfigDnsResponse
// @Router /api/v1/local/config/dns [get]
func (ctl *controller) ConfigDnsGet(c *gin.Context) {
lc := ctl.lc
resp, edgeXErr := ctl.getSystemApp().ConfigDns(c)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(resp, c.Writer, lc)
}
// @Tags 配网助手
// @Summary 修改dns
// @Produce json
// @Param req body dtos.ConfigDnsUpdateRequest true "参数"
// @Success 200 {object} dtos.ConfigDnsResponse
// @Router /api/v1/local/config/dns [put]
func (ctl *controller) ConfigDnsUpdate(c *gin.Context) {
lc := ctl.lc
var req dtos.ConfigDnsUpdateRequest
if err := c.ShouldBind(&req); err != nil {
httphelper.RenderFail(c, errort.NewCommonErr(errort.DefaultReqParamsError, err), c.Writer, lc)
return
}
edgeXErr := ctl.getSystemApp().ConfigDnsUpdate(c, req)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}

View File

@ -1,67 +0,0 @@
/*******************************************************************************
* Copyright 2017.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package gateway
import (
"github.com/gin-gonic/gin"
"github.com/winc-link/hummingbird/internal/pkg/errort"
"github.com/winc-link/hummingbird/internal/pkg/httphelper"
"github.com/winc-link/hummingbird/internal/pkg/utils"
"path"
)
// @Tags 网关管理
// @Summary 网关备份下载
// @Produce json
// @Success 200 {object} httphelper.CommonResponse
// @Router /api/v1/system/backup [get]
func (ctl *controller) SystemBackupHandle(c *gin.Context) {
lc := ctl.lc
filePath, edgeXErr := ctl.getSystemApp().SystemBackupFileDownload(c)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
fileName := path.Base(filePath)
c.Header("Content-Type", "application/octet-stream")
c.Header("Content-Disposition", "attachment; filename="+fileName)
c.File(filePath)
// 删除zip文件
utils.RemoveFileOrDir(filePath)
}
func (ctl *controller) SystemRecoverHandle(c *gin.Context) {
lc := ctl.lc
file, err := c.FormFile("fileName")
if err != nil {
httphelper.RenderFail(c, errort.NewCommonErr(errort.DefaultReqParamsError, err), c.Writer, lc)
return
}
dist := "/tmp/tedge-recover.zip"
err = c.SaveUploadedFile(file, dist)
if err != nil {
httphelper.RenderFail(c, errort.NewCommonErr(errort.SystemErrorCode, err), c.Writer, lc)
return
}
edgeXErr := ctl.getSystemApp().SystemRecover(c, dist)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}

View File

@ -1,41 +1,11 @@
package interfaces package interfaces
import (
"context"
"github.com/winc-link/hummingbird/internal/dtos"
)
//先把这些临时放在这里
type SystemItf interface { type SystemItf interface {
GwConfigItf //GwConfigItf
AdvConfigItf //NetworkItf
NetworkItf //GatewayItf
GatewayItf
} }
type GwConfigItf interface { //type GatewayItf interface {
LoadGatewayConfig() error //
GetGatewayConfig() dtos.EdgeConfig //}
}
type AdvConfigItf interface {
GetAdvanceConfig(ctx context.Context) (dtos.AdvanceConfig, error)
UpdateAdvanceConfig(ctx context.Context, cfg dtos.AdvanceConfig) error
}
type NetworkItf interface {
GetNetworks(ctx context.Context) (dtos.ConfigNetWorkResponse, dtos.ConfigDnsResponse)
ConfigNetWork(ctx context.Context, isFlush bool) (resp dtos.ConfigNetWorkResponse, err error)
ConfigNetWorkUpdate(ctx context.Context, req dtos.ConfigNetworkUpdateRequest) error
ConfigDns(ctx context.Context) (dtos.ConfigDnsResponse, error)
ConfigDnsUpdate(ctx context.Context, req dtos.ConfigDnsUpdateRequest) error
}
type GatewayItf interface {
SystemBackupFileDownload(ctx context.Context) (string, error)
SystemRecover(ctx context.Context, filepath string) error
}
type Starter interface {
Conn() error
}

View File

@ -45,13 +45,6 @@ func RegisterGateway(engine *gin.Engine, dic *di.Container) {
{ {
v1Auth.GET("home-page", ctl.HomePage) v1Auth.GET("home-page", ctl.HomePage)
} }
{
v1Auth.GET("local/config/network", ctl.ConfigNetWorkGet)
v1Auth.PUT("local/config/network", ctl.ConfigNetWorkUpdate)
v1Auth.GET("local/config/dns", ctl.ConfigDnsGet)
v1Auth.PUT("local/config/dns", ctl.ConfigDnsUpdate)
}
{ {
/******* 运维管理-agentclient *******/ /******* 运维管理-agentclient *******/
v1Auth.GET("/metrics/system", ctl.SystemMetricsHandler) v1Auth.GET("/metrics/system", ctl.SystemMetricsHandler)

View File

@ -1,33 +0,0 @@
/*******************************************************************************
* Copyright 2017.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package agentclient
import (
"context"
"github.com/winc-link/hummingbird/internal/dtos"
)
type AgentClient interface {
GetGps(ctx context.Context) (dtos.Gps, error)
AddServiceMonitor(ctx context.Context, stats dtos.ServiceStats) error
DeleteServiceMonitor(ctx context.Context, serviceName string) error
GetAllDriverMonitor(ctx context.Context) ([]dtos.ServiceStats, error)
RestartGateway(ctx context.Context) error
OperationService(ctx context.Context, op dtos.Operation) error
GetAllAppServiceMonitor(ctx context.Context) ([]dtos.ServiceStats, error)
GetAllServices(ctx context.Context) (res dtos.ServicesStats, err error)
Exec(ctx context.Context, req dtos.AgentRequest) (res dtos.AgentResponse, err error)
ResetGateway(ctx context.Context) error
}

View File

@ -1,174 +0,0 @@
/*******************************************************************************
* Copyright 2017.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package agentclient
import (
"context"
"encoding/json"
"github.com/winc-link/hummingbird/internal/dtos"
"github.com/winc-link/hummingbird/internal/pkg/constants"
"github.com/winc-link/hummingbird/internal/pkg/errort"
"github.com/winc-link/hummingbird/internal/pkg/httphelper"
"net/url"
)
const (
ApiTerminalRoute = "/api/v1/terminal"
ApiServicesRoute = "/api/v1/services"
)
type agentClient struct {
baseUrl string
}
func New(baseUrl string) AgentClient {
return &agentClient{
baseUrl: baseUrl,
}
}
func (c agentClient) GetGps(ctx context.Context) (dtos.Gps, error) {
res := dtos.Gps{}
commonRes := httphelper.CommonResponse{}
err := httphelper.GetRequest(ctx, &commonRes, c.baseUrl, "/api/v1/gps", nil)
if err != nil {
return res, err
}
e := httphelper.CommResToSpecial(commonRes.Result, &res)
if e != nil {
return res, errort.NewCommonEdgeX(errort.DefaultSystemError, "res type is not gps", nil)
}
return res, nil
}
func (c agentClient) AddServiceMonitor(ctx context.Context, stats dtos.ServiceStats) error {
commonRes := httphelper.CommonResponse{}
return httphelper.PostRequest(ctx, &commonRes, c.baseUrl+"/api/v1/service/monitor", stats)
}
func (c *agentClient) DeleteServiceMonitor(ctx context.Context, serviceName string) error {
commonRes := httphelper.CommonResponse{}
var params = url.Values{}
params.Set("service_name", serviceName)
return httphelper.DeleteRequest(ctx, &commonRes, c.baseUrl, "/api/v1/service/monitor", params)
}
func (c *agentClient) GetAllDriverMonitor(ctx context.Context) ([]dtos.ServiceStats, error) {
var list []dtos.ServiceStats
commonRes := httphelper.CommonResponse{}
err := httphelper.GetRequest(ctx, &commonRes, c.baseUrl, "/api/v1/driver/monitor", nil)
if err != nil {
return list, err
}
e := httphelper.CommResToSpecial(commonRes.Result, &list)
if e != nil {
return list, errort.NewCommonEdgeX(errort.DefaultSystemError, "res type is not gps", nil)
}
return list, nil
}
func (c *agentClient) RestartGateway(ctx context.Context) error {
commonRes := httphelper.CommonResponse{}
err := httphelper.PostRequest(ctx, &commonRes, c.baseUrl+"/api/v1/restart", nil)
if err != nil {
return err
}
return nil
}
func (c *agentClient) OperationService(ctx context.Context, op dtos.Operation) error {
commonRes := httphelper.CommonResponse{}
err := httphelper.PostRequest(ctx, &commonRes, c.baseUrl+"/api/v1/operation", op)
if err != nil {
return err
}
return nil
}
func (c *agentClient) GetAllAppServiceMonitor(ctx context.Context) ([]dtos.ServiceStats, error) {
var list []dtos.ServiceStats
commonRes := httphelper.CommonResponse{}
err := httphelper.GetRequest(ctx, &commonRes, c.baseUrl, "/api/v1/app_service/monitor", nil)
if err != nil {
return list, err
}
e := httphelper.CommResToSpecial(commonRes.Result, &list)
if e != nil {
return list, errort.NewCommonEdgeX(errort.DefaultSystemError, "res type is not gps", nil)
}
return list, nil
}
func (c agentClient) GetAllServices(ctx context.Context) (res dtos.ServicesStats, err error) {
response := httphelper.CommonResponse{}
err = httphelper.GetRequest(ctx, &response, c.baseUrl, ApiServicesRoute, nil)
if err != nil {
return res, err
}
resultByte, _ := json.Marshal(response.Result)
errJson := json.Unmarshal(resultByte, &res)
if errJson != nil {
return res, errJson
}
return res, nil
}
func (c agentClient) Exec(ctx context.Context, req dtos.AgentRequest) (res dtos.AgentResponse, err error) {
if req.TimeoutSeconds == 0 {
req.TimeoutSeconds = constants.DefaultAgentReqTimeout
}
commonRes := httphelper.CommonResponse{}
err = httphelper.PostRequest(ctx, &commonRes, c.baseUrl+ApiTerminalRoute, req)
if err != nil {
return res, err
}
resultByte, _ := json.Marshal(commonRes.Result)
errJson := json.Unmarshal(resultByte, &res)
if errJson != nil {
return res, errJson
}
return res, nil
}
// 重置网关-并重启
func (c agentClient) ResetGateway(ctx context.Context) error {
commonRes := httphelper.CommonResponse{}
err := httphelper.PostRequest(ctx, &commonRes, c.baseUrl+"/api/v1/reset-gateway", nil)
if err != nil {
return err
}
return nil
}
//TODO: 重新构造一下Response返回agent的报错信息
//func (c *agentClient) ExecuteOTAUpgrade(ctx context.Context, pid, version string) (httphelper.CommonResponse, error) {
// upgradeReq := dtos.AgentOTAUpgradeReq{
// Pid: pid,
// Version: version,
// TimeoutSeconds: constants.AgentDownloadOTAFirmTimeout,
// }
//
// commonRes := httphelper.CommonResponse{}
// err := httphelper.PostRequest(ctx, &commonRes, c.baseUrl+"/api/v1/ota/upgrade", upgradeReq)
// if err != nil {
// return commonRes, err
// }
//
// return commonRes, nil
//}