This commit is contained in:
zhuhoujiu 2025-04-01 11:08:25 +08:00
parent 6787292051
commit 6f66f3b87b
46 changed files with 23 additions and 3958 deletions

View File

@ -29,19 +29,19 @@ Timeout = 120
[Databases]
[Databases.Metadata]
[Databases.Metadata.Primary]
#Type = 'sqlite'
#DataSource = 'manifest/docker/db-data/core-data/core.db?_timeout=5000'
Type = 'mysql'
Dsn = 'root:123456@tcp(127.0.0.1:3306)/open-hummingbird?charset=utf8mb4&parseTime=True&loc=Local'
Type = 'sqlite'
DataSource = 'manifest/docker/db-data/core-data/core.db?_timeout=5000'
#Type = 'mysql'
#Dsn = 'root:123456@tcp(127.0.0.1:3306)/open-hummingbird?charset=utf8mb4&parseTime=True&loc=Local'
[Databases.Data]
[Databases.Data.Primary]
Type = 'tstorage'
DataSource = 'manifest/docker/db-data/tstorage-data/'
#Type = 'tstorage'
#DataSource = 'manifest/docker/db-data/tstorage-data/'
#Type = 'tdengine'
#Dsn = 'root:taosdata@ws(127.0.0.1:6041)/hummingbird'
#Type = 'leveldb'
#DataSource = 'manifest/docker/db-data/leveldb-core-data/'
Type = 'leveldb'
DataSource = 'manifest/docker/db-data/leveldb-core-data/'
[MessageQueue]
Protocol = 'tcp'

View File

@ -1,7 +1,7 @@
{
"files": {
"main.css": "/static/css/main.822cee67.css",
"main.js": "/static/js/main.9a4b5878.js",
"main.js": "/static/js/main.37008bc2.js",
"static/js/342.e07172ae.chunk.js": "/static/js/342.e07172ae.chunk.js",
"static/js/558.d067177e.chunk.js": "/static/js/558.d067177e.chunk.js",
"static/js/324.bf4cc54f.chunk.js": "/static/js/324.bf4cc54f.chunk.js",
@ -19,7 +19,7 @@
"static/media/background.png": "/static/media/background.8ed5e5404edf817e15f5.png",
"index.html": "/index.html",
"main.822cee67.css.map": "/static/css/main.822cee67.css.map",
"main.9a4b5878.js.map": "/static/js/main.9a4b5878.js.map",
"main.37008bc2.js.map": "/static/js/main.37008bc2.js.map",
"342.e07172ae.chunk.js.map": "/static/js/342.e07172ae.chunk.js.map",
"558.d067177e.chunk.js.map": "/static/js/558.d067177e.chunk.js.map",
"324.bf4cc54f.chunk.js.map": "/static/js/324.bf4cc54f.chunk.js.map",
@ -28,6 +28,6 @@
},
"entrypoints": [
"static/css/main.822cee67.css",
"static/js/main.9a4b5878.js"
"static/js/main.37008bc2.js"
]
}

View File

@ -1 +1 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><link rel="apple-touch-icon" href="/favicon.ico"/><link rel="manifest" href="/manifest.json"/><title>登录</title><script defer="defer" src="/static/js/main.9a4b5878.js"></script><link href="/static/css/main.822cee67.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>
<!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><link rel="apple-touch-icon" href="/favicon.ico"/><link rel="manifest" href="/manifest.json"/><title>登录</title><script defer="defer" src="/static/js/main.37008bc2.js"></script><link href="/static/css/main.822cee67.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>

View File

@ -1,60 +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
import (
"github.com/winc-link/hummingbird/internal/models"
"github.com/winc-link/hummingbird/internal/pkg/constants"
)
type DataResourceSearchQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"`
Type string `schema:"type,omitempty"`
Health string `schema:"health,omitempty"`
}
type DataResourceInfo struct {
Name string `json:"name"`
Type string `json:"type"`
Option map[string]interface{} `json:"option"`
}
type AddDataResourceReq struct {
Name string `json:"name"`
Type string `json:"type"`
Option map[string]interface{} `json:"option"`
}
type UpdateDataResource struct {
Id string `json:"id"`
Name *string `json:"name"`
Type *string `json:"type"`
Option *map[string]interface{} `json:"option"`
}
func ReplaceDataResourceModelFields(ds *models.DataResource, patch UpdateDataResource) {
if patch.Name != nil {
ds.Name = *patch.Name
}
if patch.Type != nil {
ds.Type = constants.DataResourceType(*patch.Type)
}
if patch.Option != nil {
ds.Option = *patch.Option
ds.Option["sendSingle"] = true
}
ds.Health = false
}

View File

@ -1,114 +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
import (
"github.com/winc-link/hummingbird/internal/models"
)
type RuleEngineRequest struct {
Name string `json:"name"` //名字
Description string `json:"description"` //描述
Filter Filter `json:"filter"`
DataResourceId string `json:"data_resource_id"`
}
func (r RuleEngineRequest) BuildEkuiperSql() string {
return r.Filter.Sql
}
type Filter struct {
MessageSource string `json:"message_source"`
SelectName string `json:"select_name"`
Condition string `json:"condition"`
Sql string `json:"sql"`
}
type RuleEngineUpdateRequest struct {
Id string `json:"id"`
Name *string `json:"name"` //名字
Description *string `json:"description"` //描述
Filter *Filter `json:"filter"`
DataResourceId *string `json:"data_resource_id"`
}
func ReplaceRuleEngineModelFields(ds *models.RuleEngine, patch RuleEngineUpdateRequest) {
if patch.Name != nil {
ds.Name = *patch.Name
}
if patch.Description != nil {
ds.Description = *patch.Description
}
if patch.Filter != nil {
ds.Filter = models.Filter(*patch.Filter)
}
if patch.DataResourceId != nil {
ds.DataResourceId = *patch.DataResourceId
}
}
func (r RuleEngineUpdateRequest) BuildEkuiperSql() string {
return r.Filter.Sql
}
type RuleEngineFieldUpdateRequest struct {
Id string `json:"id"`
Name string `json:"name"`
//AlertLevel constants.AlertLevel `json:"alert_level"`
Description string `json:"description"`
}
type RuleEngineResponse struct {
Id string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Filter Filter `json:"filter"`
Created int64 `json:"created"`
DataResourceId string `json:"data_resource_id"`
DataResource DataResourceInfo `json:"dataResource"`
Modified int64 `json:"modified"`
}
type RuleEngineSearchQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"`
Name string `schema:"name,omitempty"`
Status string `schema:"status,omitempty"`
}
type RuleEngineSearchQueryResponse struct {
Id string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Created int64 `json:"created"`
Status string `json:"status"`
ResourceType string `json:"resource_type"`
DataResource DataResourceInfo `json:"dataResource"`
}
func RuleEngineSearchQueryResponseFromModel(p models.RuleEngine) RuleEngineSearchQueryResponse {
var dataResource DataResourceInfo
dataResource.Name = p.DataResource.Name
dataResource.Type = string(p.DataResource.Type)
dataResource.Option = p.DataResource.Option
return RuleEngineSearchQueryResponse{
Id: p.Id,
Name: p.Name,
Description: p.Description,
Created: p.Created,
Status: string(p.Status),
DataResource: dataResource,
}
}

View File

@ -1,85 +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
import (
"github.com/winc-link/hummingbird/internal/models"
)
type SceneAddRequest struct {
Name string `json:"name"` //名字
Description string `json:"description"` //描述
}
type SceneUpdateRequest struct {
Id string `json:"id"`
Conditions []Condition `json:"conditions"`
Actions []Action `json:"actions"`
}
func ReplaceSceneModelFields(scene *models.Scene, req SceneUpdateRequest) {
//scene.Conditions = req.Conditions
var modelConditions models.Conditions
for _, condition := range req.Conditions {
modelConditions = append(modelConditions, models.Condition{
ConditionType: condition.ConditionType,
Option: condition.Option,
})
}
scene.Conditions = modelConditions
var modelAction models.Actions2
for _, action := range req.Actions {
modelAction = append(modelAction, models.Action{
ProductName: action.ProductName,
ProductID: action.ProductID,
DeviceName: action.DeviceName,
DeviceID: action.DeviceID,
Code: action.Code,
DataType: action.DataType,
Value: action.Value,
})
}
scene.Actions = modelAction
}
type Condition struct {
ConditionType string `json:"condition_type"`
Option map[string]string `json:"option"`
}
type Action struct {
ProductID string `json:"product_id"`
ProductName string `json:"product_name"`
DeviceID string `json:"device_id"`
DeviceName string `json:"device_name"`
Code string `json:"code"`
DataType string `json:"data_type"`
Value string `json:"value"`
}
type SceneSearchQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"`
Name string `json:"name"`
Status string `json:"status"`
}
type SceneLogSearchQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"`
StartAt int64 `schema:"start_time"`
EndAt int64 `schema:"end_time"`
SceneId string `json:"scene_id"`
}

View File

@ -1,371 +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 dataresource
import (
"context"
"database/sql"
"fmt"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/mitchellh/mapstructure"
"github.com/winc-link/hummingbird/internal/dtos"
resourceContainer "github.com/winc-link/hummingbird/internal/hummingbird/core/container"
interfaces "github.com/winc-link/hummingbird/internal/hummingbird/core/interface"
"github.com/winc-link/hummingbird/internal/models"
"github.com/winc-link/hummingbird/internal/pkg/constants"
"github.com/winc-link/hummingbird/internal/pkg/container"
"github.com/winc-link/hummingbird/internal/pkg/di"
"github.com/winc-link/hummingbird/internal/pkg/errort"
"github.com/winc-link/hummingbird/internal/pkg/logger"
"net/url"
"time"
_ "github.com/influxdata/influxdb1-client/v2"
client "github.com/influxdata/influxdb1-client/v2"
//_ "github.com/taosdata/driver-go/v2/taosSql"
)
type dataResourceApp struct {
dic *di.Container
dbClient interfaces.DBClient
lc logger.LoggingClient
}
func NewDataResourceApp(ctx context.Context, dic *di.Container) interfaces.DataResourceApp {
lc := container.LoggingClientFrom(dic.Get)
dbClient := resourceContainer.DBClientFrom(dic.Get)
app := &dataResourceApp{
dic: dic,
dbClient: dbClient,
lc: lc,
}
return app
}
func (p dataResourceApp) AddDataResource(ctx context.Context, req dtos.AddDataResourceReq) (string, error) {
var insertDataResource models.DataResource
insertDataResource.Name = req.Name
insertDataResource.Type = constants.DataResourceType(req.Type)
insertDataResource.Option = req.Option
insertDataResource.Option["sendSingle"] = true
id, err := p.dbClient.AddDataResource(insertDataResource)
if err != nil {
return "", err
}
return id, nil
}
func (p dataResourceApp) DataResourceById(ctx context.Context, id string) (models.DataResource, error) {
if id == "" {
return models.DataResource{}, errort.NewCommonEdgeX(errort.DefaultReqParamsError, "req id is required", nil)
}
dataResource, edgeXErr := p.dbClient.DataResourceById(id)
if edgeXErr != nil {
return models.DataResource{}, edgeXErr
}
return dataResource, nil
}
func (p dataResourceApp) UpdateDataResource(ctx context.Context, req dtos.UpdateDataResource) error {
if req.Id == "" {
return errort.NewCommonEdgeX(errort.DefaultReqParamsError, "update req id is required", nil)
}
dataResource, edgeXErr := p.dbClient.DataResourceById(req.Id)
if edgeXErr != nil {
return edgeXErr
}
ruleEngines, _, err := p.dbClient.RuleEngineSearch(0, -1, dtos.RuleEngineSearchQueryRequest{
Status: string(constants.RuleEngineStart),
})
if err != nil {
return err
}
for _, engine := range ruleEngines {
if engine.DataResourceId == req.Id {
return errort.NewCommonErr(errort.RuleEngineIsStartingNotAllowUpdate, fmt.Errorf("please stop this rule engine (%s) before editing it", req.Id))
}
}
dtos.ReplaceDataResourceModelFields(&dataResource, req)
edgeXErr = p.dbClient.UpdateDataResource(dataResource)
if edgeXErr != nil {
return edgeXErr
}
return nil
}
func (p dataResourceApp) DelDataResourceById(ctx context.Context, id string) error {
ruleEngines, _, err := p.dbClient.RuleEngineSearch(0, -1, dtos.RuleEngineSearchQueryRequest{
Status: string(constants.RuleEngineStart),
})
if err != nil {
return err
}
for _, engine := range ruleEngines {
if engine.DataResourceId == id {
return errort.NewCommonErr(errort.RuleEngineIsStartingNotAllowUpdate, fmt.Errorf("please stop this rule engine (%s) before editing it", id))
}
}
err = p.dbClient.DelDataResource(id)
if err != nil {
return err
}
return nil
}
func (p dataResourceApp) DataResourceSearch(ctx context.Context, req dtos.DataResourceSearchQueryRequest) ([]models.DataResource, uint32, error) {
offset, limit := req.BaseSearchConditionQuery.GetPage()
resp, total, err := p.dbClient.SearchDataResource(offset, limit, req)
if err != nil {
return []models.DataResource{}, 0, err
}
return resp, total, nil
}
func (p dataResourceApp) DataResourceType(ctx context.Context) []constants.DataResourceType {
return constants.DataResources
}
func (p dataResourceApp) DataResourceHealth(ctx context.Context, resourceId string) error {
dataResource, err := p.dbClient.DataResourceById(resourceId)
if err != nil {
return err
}
//return p.dbClient.UpdateDataResourceHealth(dataResource.Id, true)
switch dataResource.Type {
case constants.HttpResource:
err = p.checkHttpResourceHealth(dataResource)
case constants.MQTTResource:
err = p.checkMQTTResourceHealth(dataResource)
case constants.KafkaResource:
err = p.checkKafkaResourceHealth(dataResource)
case constants.InfluxDBResource:
err = p.checkInfluxDBResourceHealth(dataResource)
case constants.TDengineResource:
//err = p.checkTdengineResourceHealth(dataResource)
default:
return errort.NewCommonErr(errort.DefaultReqParamsError, fmt.Errorf("resource type not much"))
}
if err != nil {
return err
}
return p.dbClient.UpdateDataResourceHealth(dataResource.Id, true)
}
func (p dataResourceApp) checkHttpResourceHealth(resource models.DataResource) error {
urlAddr := resource.Option["url"].(string)
_, err := url.Parse(urlAddr)
if err != nil {
return err
}
return nil
}
func (p dataResourceApp) checkMQTTResourceHealth(resource models.DataResource) error {
var (
server, topic string
clientId, username, password string
//certificationPath,
//privateKeyPath, rootCaPath, insecureSkipVerify, retained, compression, connectionSelector string
)
server = resource.Option["server"].(string)
topic = resource.Option["topic"].(string)
clientId = resource.Option["clientId"].(string)
//protocolVersion = resource.Option["protocolVersion"]
//qos = resource.Option["qos"].(int)
username = resource.Option["username"].(string)
password = resource.Option["password"].(string)
//certificationPath = resource.Option["certificationPath"]
//privateKeyPath = resource.Option["privateKeyPath"]
//rootCaPath = resource.Option["rootCaPath"]
//insecureSkipVerify = resource.Option["insecureSkipVerify"]
//retained = resource.Option["retained"]
//compression = resource.Option["compression"]
//connectionSelector = resource.Option["connectionSelector"]
if server == "" || topic == "" || clientId == "" || username == "" || password == "" {
}
opts := mqtt.NewClientOptions()
opts.AddBroker(server)
opts.SetUsername(username)
opts.SetPassword(password)
opts.SetClientID(clientId)
client := mqtt.NewClient(opts)
token := client.Connect()
// 如果连接失败,则终止程序
if token.WaitTimeout(3*time.Second) && token.Error() != nil {
return token.Error()
}
defer client.Disconnect(250)
return nil
}
func (p dataResourceApp) checkKafkaResourceHealth(resource models.DataResource) error {
return nil
}
func (p dataResourceApp) checkInfluxDBResourceHealth(resource models.DataResource) error {
type influxSink struct {
addr string
username string
password string
measurement string
databaseName string
tagKey string
tagValue string
fields string
cli client.Client
fieldMap map[string]interface{}
hasTransform bool
}
var m influxSink
if i, ok := resource.Option["addr"]; ok {
if i, ok := i.(string); ok {
m.addr = i
}
}
if i, ok := resource.Option["username"]; ok {
if i, ok := i.(string); ok {
m.username = i
}
}
if i, ok := resource.Option["password"]; ok {
if i, ok := i.(string); ok {
m.password = i
}
}
if i, ok := resource.Option["measurement"]; ok {
if i, ok := i.(string); ok {
m.measurement = i
}
}
if i, ok := resource.Option["databasename"]; ok {
if i, ok := i.(string); ok {
m.databaseName = i
}
}
if i, ok := resource.Option["tagkey"]; ok {
if i, ok := i.(string); ok {
m.tagKey = i
}
}
if i, ok := resource.Option["tagvalue"]; ok {
if i, ok := i.(string); ok {
m.tagValue = i
}
}
if i, ok := resource.Option["fields"]; ok {
if i, ok := i.(string); ok {
m.fields = i
}
}
if i, ok := resource.Option["dataTemplate"]; ok {
if i, ok := i.(string); ok && i != "" {
m.hasTransform = true
}
}
_, err := client.NewHTTPClient(client.HTTPConfig{
Addr: m.addr,
Username: m.username,
Password: m.password,
})
if err != nil {
return err
}
return nil
}
func (p dataResourceApp) checkTdengineResourceHealth(resource models.DataResource) error {
type taosConfig struct {
ProvideTs bool `json:"provideTs"`
Port int `json:"port"`
Ip string `json:"ip"` // To be deprecated
Host string `json:"host"`
User string `json:"user"`
Password string `json:"password"`
Database string `json:"database"`
Table string `json:"table"`
TsFieldName string `json:"tsFieldName"`
Fields []string `json:"fields"`
STable string `json:"sTable"`
TagFields []string `json:"tagFields"`
DataTemplate string `json:"dataTemplate"`
TableDataField string `json:"tableDataField"`
}
cfg := &taosConfig{
User: "root",
Password: "taosdata",
}
err := MapToStruct(resource.Option, cfg)
if err != nil {
return fmt.Errorf("read properties %v fail with error: %v", resource.Option, err)
}
if cfg.Ip != "" {
fmt.Errorf("Deprecated: Tdengine sink ip property is deprecated, use host instead.")
if cfg.Host == "" {
cfg.Host = cfg.Ip
}
}
if cfg.Host == "" {
cfg.Host = "localhost"
}
if cfg.User == "" {
return fmt.Errorf("propert user is required.")
}
if cfg.Password == "" {
return fmt.Errorf("propert password is required.")
}
if cfg.Database == "" {
return fmt.Errorf("property database is required")
}
if cfg.Table == "" {
return fmt.Errorf("property table is required")
}
if cfg.TsFieldName == "" {
return fmt.Errorf("property TsFieldName is required")
}
if cfg.STable != "" && len(cfg.TagFields) == 0 {
return fmt.Errorf("property tagFields is required when sTable is set")
}
url := fmt.Sprintf(`%s:%s@tcp(%s:%d)/%s`, cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.Database)
//m.conf = cfg
_, err = sql.Open("taosSql", url)
if err != nil {
return err
}
return nil
}
func MapToStruct(input, output interface{}) error {
config := &mapstructure.DecoderConfig{
TagName: "json",
Result: output,
}
decoder, err := mapstructure.NewDecoder(config)
if err != nil {
return err
}
return decoder.Decode(input)
}

View File

@ -226,13 +226,6 @@ func (p *deviceApp) DeleteDeviceById(ctx context.Context, id string) error {
if edgeXErr != nil {
return edgeXErr
}
sceneApp := resourceContainer.SceneAppNameFrom(p.dic.Get)
edgeXErr = sceneApp.CheckSceneByDeviceId(ctx, id)
if edgeXErr != nil {
return edgeXErr
}
err = p.dbClient.DeleteDeviceById(id)
if err != nil {
return err
@ -267,12 +260,6 @@ func (p *deviceApp) DeviceUpdate(ctx context.Context, req dtos.DeviceUpdateReque
return edgeXErr
}
sceneApp := resourceContainer.SceneAppNameFrom(p.dic.Get)
edgeXErr = sceneApp.CheckSceneByDeviceId(ctx, req.Id)
if edgeXErr != nil {
return edgeXErr
}
dtos.ReplaceDeviceModelFields(&device, req)
edgeXErr = p.dbClient.UpdateDevice(device)
if edgeXErr != nil {

View File

@ -1,59 +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 ruleengine
import (
"context"
"github.com/winc-link/hummingbird/internal/dtos"
resourceContainer "github.com/winc-link/hummingbird/internal/hummingbird/core/container"
"github.com/winc-link/hummingbird/internal/pkg/constants"
"time"
)
func (p ruleEngineApp) monitor() {
tickTime := time.Second * 5
timeTickerChan := time.Tick(tickTime)
for {
select {
case <-timeTickerChan:
p.checkRuleStatus()
}
}
}
func (p ruleEngineApp) checkRuleStatus() {
ruleEngines, _, err := p.dbClient.RuleEngineSearch(0, -1, dtos.RuleEngineSearchQueryRequest{})
if err != nil {
p.lc.Errorf("get engines err:", err)
}
ekuiperApp := resourceContainer.EkuiperAppFrom(p.dic.Get)
for _, ruleEngine := range ruleEngines {
resp, err := ekuiperApp.GetRuleStats(context.Background(), ruleEngine.Id)
if err != nil {
p.lc.Errorf("error:", err)
continue
}
status, ok := resp["status"]
if ok {
if status != string(ruleEngine.Status) {
if status == string(constants.RuleEngineStop) {
p.dbClient.RuleEngineStop(ruleEngine.Id)
} else if status == string(constants.RuleEngineStart) {
p.dbClient.RuleEngineStart(ruleEngine.Id)
}
}
}
}
}

View File

@ -1,245 +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 ruleengine
import (
"context"
"fmt"
"github.com/winc-link/hummingbird/internal/dtos"
resourceContainer "github.com/winc-link/hummingbird/internal/hummingbird/core/container"
interfaces "github.com/winc-link/hummingbird/internal/hummingbird/core/interface"
"github.com/winc-link/hummingbird/internal/models"
"github.com/winc-link/hummingbird/internal/pkg/constants"
"github.com/winc-link/hummingbird/internal/pkg/container"
"github.com/winc-link/hummingbird/internal/pkg/di"
"github.com/winc-link/hummingbird/internal/pkg/errort"
"github.com/winc-link/hummingbird/internal/pkg/logger"
"github.com/winc-link/hummingbird/internal/pkg/utils"
)
type ruleEngineApp struct {
dic *di.Container
dbClient interfaces.DBClient
lc logger.LoggingClient
}
func (p ruleEngineApp) AddRuleEngine(ctx context.Context, req dtos.RuleEngineRequest) (string, error) {
dataResource, err := p.dbClient.DataResourceById(req.DataResourceId)
if err != nil {
return "", err
}
randomId := utils.RandomNum()
ekuiperApp := resourceContainer.EkuiperAppFrom(p.dic.Get)
sql := req.BuildEkuiperSql()
var actions []dtos.Actions
switch dataResource.Type {
case constants.HttpResource:
actions = append(actions, dtos.Actions{
Rest: dataResource.Option,
})
case constants.MQTTResource:
actions = append(actions, dtos.Actions{
MQTT: dataResource.Option,
})
case constants.KafkaResource:
actions = append(actions, dtos.Actions{
Kafka: dataResource.Option,
})
case constants.InfluxDBResource:
actions = append(actions, dtos.Actions{
Influx: dataResource.Option,
})
case constants.TDengineResource:
actions = append(actions, dtos.Actions{
Tdengine: dataResource.Option,
})
default:
return "", errort.NewCommonErr(errort.DefaultReqParamsError, fmt.Errorf("rule engine action not much"))
}
if err = ekuiperApp.CreateRule(ctx, actions, randomId, sql); err != nil {
return "", err
}
var insertRuleEngine models.RuleEngine
insertRuleEngine.Name = req.Name
insertRuleEngine.Id = randomId
insertRuleEngine.Description = req.Description
insertRuleEngine.Filter = models.Filter(req.Filter)
insertRuleEngine.DataResourceId = req.DataResourceId
insertRuleEngine.Status = constants.RuleEngineStop
id, err := p.dbClient.AddRuleEngine(insertRuleEngine)
if err != nil {
return "", err
}
return id, nil
}
func (p ruleEngineApp) UpdateRuleEngine(ctx context.Context, req dtos.RuleEngineUpdateRequest) error {
dataResource, err := p.dbClient.DataResourceById(*req.DataResourceId)
if err != nil {
return err
}
ruleEngine, err := p.dbClient.RuleEngineById(req.Id)
if err != nil {
return err
}
sql := req.BuildEkuiperSql()
var actions []dtos.Actions
switch dataResource.Type {
case constants.HttpResource:
actions = append(actions, dtos.Actions{
Rest: dataResource.Option,
})
case constants.MQTTResource:
actions = append(actions, dtos.Actions{
MQTT: dataResource.Option,
})
case constants.KafkaResource:
actions = append(actions, dtos.Actions{
Kafka: dataResource.Option,
})
case constants.InfluxDBResource:
actions = append(actions, dtos.Actions{
Influx: dataResource.Option,
})
case constants.TDengineResource:
actions = append(actions, dtos.Actions{
Tdengine: dataResource.Option,
})
default:
return errort.NewCommonErr(errort.DefaultReqParamsError, fmt.Errorf("rule engine action not much"))
}
ekuiperApp := resourceContainer.EkuiperAppFrom(p.dic.Get)
if err = ekuiperApp.UpdateRule(ctx, actions, req.Id, sql); err != nil {
return err
}
dtos.ReplaceRuleEngineModelFields(&ruleEngine, req)
err = p.dbClient.UpdateRuleEngine(ruleEngine)
if err != nil {
return err
}
return nil
}
func (p ruleEngineApp) UpdateRuleEngineField(ctx context.Context, req dtos.RuleEngineFieldUpdateRequest) error {
//TODO implement me
panic("implement me")
}
func (p ruleEngineApp) RuleEngineById(ctx context.Context, id string) (dtos.RuleEngineResponse, error) {
ruleEngine, err := p.dbClient.RuleEngineById(id)
var ruleEngineResponse dtos.RuleEngineResponse
if err != nil {
return ruleEngineResponse, err
}
ruleEngineResponse.Id = ruleEngine.Id
ruleEngineResponse.Name = ruleEngine.Name
ruleEngineResponse.Description = ruleEngine.Description
ruleEngineResponse.Created = ruleEngine.Created
ruleEngineResponse.Filter = dtos.Filter(ruleEngine.Filter)
ruleEngineResponse.DataResourceId = ruleEngine.DataResourceId
ruleEngineResponse.DataResource = dtos.DataResourceInfo{
Name: ruleEngine.DataResource.Name,
Type: string(ruleEngine.DataResource.Type),
Option: ruleEngine.DataResource.Option,
}
return ruleEngineResponse, nil
}
func (p ruleEngineApp) RuleEngineSearch(ctx context.Context, req dtos.RuleEngineSearchQueryRequest) ([]dtos.RuleEngineSearchQueryResponse, uint32, error) {
offset, limit := req.BaseSearchConditionQuery.GetPage()
resp, total, err := p.dbClient.RuleEngineSearch(offset, limit, req)
if err != nil {
return []dtos.RuleEngineSearchQueryResponse{}, 0, err
}
ruleEngines := make([]dtos.RuleEngineSearchQueryResponse, len(resp))
for i, p := range resp {
ruleEngines[i] = dtos.RuleEngineSearchQueryResponseFromModel(p)
}
return ruleEngines, total, nil
}
func (p ruleEngineApp) RuleEngineDelete(ctx context.Context, id string) error {
_, err := p.dbClient.RuleEngineById(id)
if err != nil {
return err
}
ekuiperApp := resourceContainer.EkuiperAppFrom(p.dic.Get)
err = ekuiperApp.DeleteRule(ctx, id)
if err != nil {
return err
}
return p.dbClient.DeleteRuleEngineById(id)
}
func (p ruleEngineApp) RuleEngineStop(ctx context.Context, id string) error {
_, err := p.dbClient.RuleEngineById(id)
if err != nil {
return err
}
//if alertRule.EkuiperRule() {
ekuiperApp := resourceContainer.EkuiperAppFrom(p.dic.Get)
err = ekuiperApp.StopRule(ctx, id)
if err != nil {
return err
}
return p.dbClient.RuleEngineStop(id)
}
func (p ruleEngineApp) RuleEngineStart(ctx context.Context, id string) error {
ruleEngine, err := p.dbClient.RuleEngineById(id)
if err != nil {
return err
}
dataResource, err := p.dbClient.DataResourceById(ruleEngine.DataResourceId)
if err != nil {
return err
}
if dataResource.Health != true {
return errort.NewCommonErr(errort.InvalidSource, fmt.Errorf("invalid resource configuration, please check the resource configuration resource id (%s)", dataResource.Id))
}
ekuiperApp := resourceContainer.EkuiperAppFrom(p.dic.Get)
err = ekuiperApp.StartRule(ctx, id)
if err != nil {
return err
}
//}
return p.dbClient.RuleEngineStart(id)
}
func (p ruleEngineApp) RuleEngineStatus(ctx context.Context, id string) (map[string]interface{}, error) {
response := make(map[string]interface{}, 0)
_, err := p.dbClient.RuleEngineById(id)
if err != nil {
return response, err
}
ekuiperApp := resourceContainer.EkuiperAppFrom(p.dic.Get)
return ekuiperApp.GetRuleStats(ctx, id)
}
func NewRuleEngineApp(ctx context.Context, dic *di.Container) interfaces.RuleEngineApp {
lc := container.LoggingClientFrom(dic.Get)
dbClient := resourceContainer.DBClientFrom(dic.Get)
app := &ruleEngineApp{
dic: dic,
dbClient: dbClient,
lc: lc,
}
go app.monitor()
return app
}

View File

@ -1,65 +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 scene
import (
"context"
"github.com/winc-link/hummingbird/internal/dtos"
resourceContainer "github.com/winc-link/hummingbird/internal/hummingbird/core/container"
"github.com/winc-link/hummingbird/internal/pkg/constants"
"time"
)
func (p sceneApp) monitor() {
tickTime := time.Second * 9
timeTickerChan := time.Tick(tickTime)
for {
select {
case <-timeTickerChan:
p.checkSceneRuleStatus()
}
}
}
func (p sceneApp) checkSceneRuleStatus() {
scenes, _, err := p.dbClient.SceneSearch(0, -1, dtos.SceneSearchQueryRequest{})
if err != nil {
p.lc.Errorf("get engines err:", err)
}
ekuiperApp := resourceContainer.EkuiperAppFrom(p.dic.Get)
for _, scene := range scenes {
if len(scene.Conditions) != 1 {
continue
}
if scene.Conditions[0].ConditionType != "notify" {
continue
}
resp, err := ekuiperApp.GetRuleStats(context.Background(), scene.Id)
if err != nil {
p.lc.Errorf("error:", err)
continue
}
status, ok := resp["status"]
if ok {
if status != string(scene.Status) {
if status == string(constants.SceneStart) {
p.dbClient.SceneStart(scene.Id)
} else if status == string(constants.SceneStop) {
p.dbClient.SceneStop(scene.Id)
}
}
}
}
}

View File

@ -1,628 +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 scene
import (
"context"
"errors"
"fmt"
"github.com/winc-link/hummingbird/internal/dtos"
resourceContainer "github.com/winc-link/hummingbird/internal/hummingbird/core/container"
interfaces "github.com/winc-link/hummingbird/internal/hummingbird/core/interface"
"github.com/winc-link/hummingbird/internal/models"
"github.com/winc-link/hummingbird/internal/pkg/constants"
"github.com/winc-link/hummingbird/internal/pkg/container"
"github.com/winc-link/hummingbird/internal/pkg/di"
"github.com/winc-link/hummingbird/internal/pkg/errort"
"github.com/winc-link/hummingbird/internal/pkg/logger"
"strconv"
"strings"
)
type sceneApp struct {
dic *di.Container
dbClient interfaces.DBClient
lc logger.LoggingClient
}
func NewSceneApp(ctx context.Context, dic *di.Container) interfaces.SceneApp {
lc := container.LoggingClientFrom(dic.Get)
dbClient := resourceContainer.DBClientFrom(dic.Get)
app := &sceneApp{
dic: dic,
dbClient: dbClient,
lc: lc,
}
go app.monitor()
return app
}
func (p sceneApp) AddScene(ctx context.Context, req dtos.SceneAddRequest) (string, error) {
var scene models.Scene
scene.Name = req.Name
scene.Description = req.Description
resp, err := p.dbClient.AddScene(scene)
if err != nil {
return "", err
}
return resp.Id, nil
}
func (p sceneApp) UpdateScene(ctx context.Context, req dtos.SceneUpdateRequest) error {
if req.Id == "" {
return errort.NewCommonEdgeX(errort.DefaultReqParamsError, "update req id is required", nil)
}
scene, edgeXErr := p.dbClient.SceneById(req.Id)
if edgeXErr != nil {
return edgeXErr
}
if len(req.Conditions) != 1 {
return errort.NewCommonEdgeX(errort.DefaultReqParamsError, "conditions len not eq 1", nil)
}
switch req.Conditions[0].ConditionType {
case "timer":
if scene.Status == constants.SceneStart {
return errort.NewCommonEdgeX(errort.SceneTimerIsStartingNotAllowUpdate, "Please stop this scheduled"+
" tasks before editing it.", nil)
}
case "notify":
if req.Conditions[0].Option == nil {
return errort.NewCommonEdgeX(errort.DefaultReqParamsError, "condition option is null", nil)
}
actions, sql, err := p.buildEkuiperSqlAndAction(req)
if err != nil {
return err
}
p.lc.Infof("sql:", sql)
ekuiperApp := resourceContainer.EkuiperAppFrom(p.dic.Get)
exist, err := ekuiperApp.RuleExist(ctx, scene.Id)
if err != nil {
return err
}
if exist {
err = ekuiperApp.UpdateRule(ctx, actions, scene.Id, sql)
if err != nil {
return err
}
} else {
err = ekuiperApp.CreateRule(ctx, actions, scene.Id, sql)
if err != nil {
return err
}
}
}
dtos.ReplaceSceneModelFields(&scene, req)
edgeXErr = p.dbClient.UpdateScene(scene)
if edgeXErr != nil {
return edgeXErr
}
return nil
}
func (p sceneApp) SceneById(ctx context.Context, sceneId string) (models.Scene, error) {
return p.dbClient.SceneById(sceneId)
}
func (p sceneApp) SceneStartById(ctx context.Context, sceneId string) error {
scene, err := p.dbClient.SceneById(sceneId)
if err != nil {
return err
}
if len(scene.Conditions) == 0 {
return errort.NewCommonErr(errort.SceneRuleParamsError, fmt.Errorf("scene id(%s) conditionType param errror", scene.Id))
}
switch scene.Conditions[0].ConditionType {
case "timer":
tmpJob, errJob := scene.ToRuntimeJob()
if errJob != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, errJob.Error(), errJob)
}
p.lc.Infof("tmpJob: %v", tmpJob)
conJobApp := resourceContainer.ConJobAppNameFrom(p.dic.Get)
err = conJobApp.AddJobToRunQueue(tmpJob)
if err != nil {
return err
}
case "notify":
if scene.Conditions[0].Option == nil {
return errort.NewCommonEdgeX(errort.DefaultReqParamsError, "condition option is null", nil)
}
if err = p.checkAlertRuleParam(ctx, scene, "start"); err != nil {
return err
}
ekuiperApp := resourceContainer.EkuiperAppFrom(p.dic.Get)
err = ekuiperApp.StartRule(ctx, sceneId)
if err != nil {
return err
}
default:
return errort.NewCommonEdgeX(errort.DefaultReqParamsError, "condition Type value not much", nil)
}
return p.dbClient.SceneStart(sceneId)
}
func (p sceneApp) SceneStopById(ctx context.Context, sceneId string) error {
scene, err := p.dbClient.SceneById(sceneId)
if err != nil {
return err
}
switch scene.Conditions[0].ConditionType {
case "timer":
conJobApp := resourceContainer.ConJobAppNameFrom(p.dic.Get)
conJobApp.DeleteJob(scene.Id)
case "notify":
ekuiperApp := resourceContainer.EkuiperAppFrom(p.dic.Get)
err = ekuiperApp.StopRule(ctx, sceneId)
if err != nil {
return err
}
default:
return errort.NewCommonEdgeX(errort.DefaultReqParamsError, "condition Type value not much", nil)
}
return p.dbClient.SceneStop(sceneId)
}
func (p sceneApp) DelSceneById(ctx context.Context, sceneId string) error {
scene, err := p.dbClient.SceneById(sceneId)
if err != nil {
return err
}
if len(scene.Conditions) == 0 {
return p.dbClient.DeleteSceneById(sceneId)
//return errort.NewCommonEdgeX(errort.DefaultSystemError, "conditions param error", nil)
}
switch scene.Conditions[0].ConditionType {
case "timer":
conJobApp := resourceContainer.ConJobAppNameFrom(p.dic.Get)
conJobApp.DeleteJob(scene.Id)
case "notify":
ekuiperApp := resourceContainer.EkuiperAppFrom(p.dic.Get)
err = ekuiperApp.DeleteRule(ctx, sceneId)
if err != nil {
return err
}
default:
return errort.NewCommonEdgeX(errort.DefaultReqParamsError, "condition Type value not much", nil)
}
return p.dbClient.DeleteSceneById(sceneId)
}
func (p sceneApp) SceneSearch(ctx context.Context, req dtos.SceneSearchQueryRequest) ([]models.Scene, uint32, error) {
offset, limit := req.BaseSearchConditionQuery.GetPage()
resp, total, err := p.dbClient.SceneSearch(offset, limit, req)
if err != nil {
return []models.Scene{}, 0, err
}
return resp, total, nil
}
func (p sceneApp) SceneLogSearch(ctx context.Context, req dtos.SceneLogSearchQueryRequest) ([]models.SceneLog, uint32, error) {
offset, limit := req.BaseSearchConditionQuery.GetPage()
resp, total, err := p.dbClient.SceneLogSearch(offset, limit, req)
if err != nil {
return []models.SceneLog{}, 0, err
}
return resp, total, nil
}
func (p sceneApp) buildEkuiperSqlAndAction(req dtos.SceneUpdateRequest) (actions []dtos.Actions, sql string, err error) {
configapp := resourceContainer.ConfigurationFrom(p.dic.Get)
actions = dtos.GetRuleSceneEkuiperActions(configapp.Service.Url())
option := req.Conditions[0].Option
deviceId := option["device_id"]
deviceName := option["device_name"]
productId := option["product_id"]
productName := option["product_name"]
trigger := option["trigger"]
code := option["code"]
if deviceId == "" || deviceName == "" || productId == "" || productName == "" || code == "" || trigger == "" {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required parameter missing", nil)
return
}
device, err := p.dbClient.DeviceById(deviceId)
if err != nil {
return
}
product, err := p.dbClient.ProductById(productId)
if err != nil {
return
}
if device.ProductId != product.Id {
err = errort.NewCommonEdgeX(errort.DefaultSystemError, "", nil)
return
}
switch trigger {
case string(constants.DeviceDataTrigger):
var codeFind bool
for _, property := range product.Properties {
if code == property.Code {
codeFind = true
if !property.TypeSpec.Type.AllowSendInEkuiper() {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required parameter missing", nil)
}
var s int
switch option["value_cycle"] {
case "1分钟周期":
s = 60
case "5分钟周期":
s = 60 * 5
case "15分钟周期":
s = 60 * 15
case "30分钟周期":
s = 60 * 30
case "60分钟周期":
s = 60 * 60
default:
}
switch property.TypeSpec.Type {
case constants.SpecsTypeInt, constants.SpecsTypeFloat:
valueType := option["value_type"]
if valueType == "" {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required value_type parameter missing", nil)
return
}
switch valueType {
case constants.Original: //原始值
decideCondition := option["decide_condition"]
if decideCondition == "" {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required decide_condition parameter missing", nil)
return
}
originalTemp := `SELECT rule_id(),json_path_query(data, "$.%s.time") as report_time ,deviceId FROM mqtt_stream where deviceId = "%s" and messageType = "PROPERTY_REPORT" and json_path_exists(data, "$.%s") = true and json_path_query(data, "$.%s.value") %s`
sql = fmt.Sprintf(originalTemp, code, deviceId, code, code, decideCondition)
return
case constants.Max:
sqlTemp := `SELECT window_start(),window_end(),rule_id(),deviceId,max(json_path_query(data, "$.%s.value")) as max_%s FROM mqtt_stream where deviceId = "%s" and messageType = "PROPERTY_REPORT" and json_path_exists(data, "$.%s") = true GROUP BY %s HAVING max_%s %s`
valueCycle := s
if valueCycle == 0 {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required value_cycle parameter missing", nil)
return
}
decideCondition := option["decide_condition"]
if decideCondition == "" {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required decide_condition parameter missing", nil)
return
}
sql = fmt.Sprintf(sqlTemp, code, code, device.Id, code, fmt.Sprintf("TUMBLINGWINDOW(ss, %d)", valueCycle), code, decideCondition)
return
case constants.Min:
sqlTemp := `SELECT window_start(),window_end(),rule_id(),deviceId,min(json_path_query(data, "$.%s.value")) as min_%s FROM mqtt_stream where deviceId = "%s" and messageType = "PROPERTY_REPORT" and json_path_exists(data, "$.%s") = true GROUP BY %s HAVING min_%s %s`
valueCycle := s
if valueCycle == 0 {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required value_cycle parameter missing", nil)
return
}
decideCondition := option["decide_condition"]
if decideCondition == "" {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required decide_condition parameter missing", nil)
return
}
sql = fmt.Sprintf(sqlTemp, code, code, device.Id, code, fmt.Sprintf("TUMBLINGWINDOW(ss, %d)", valueCycle), code, decideCondition)
return
case constants.Sum:
sqlTemp := `SELECT window_start(),window_end(),rule_id(),deviceId,sum(json_path_query(data, "$.%s.value")) as sum_%s FROM mqtt_stream where deviceId = "%s" and messageType = "PROPERTY_REPORT" and json_path_exists(data, "$.%s") = true GROUP BY %s HAVING sum_%s %s`
valueCycle := s
if valueCycle == 0 {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required value_cycle parameter missing", nil)
return
}
decideCondition := option["decide_condition"]
if decideCondition == "" {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required decide_condition parameter missing", nil)
return
}
sql = fmt.Sprintf(sqlTemp, code, code, device.Id, code, fmt.Sprintf("TUMBLINGWINDOW(ss, %d)", valueCycle), code, decideCondition)
return
case constants.Avg:
sqlTemp := `SELECT window_start(),window_end(),rule_id(),deviceId,avg(json_path_query(data, "$.%s.value")) as avg_%s FROM mqtt_stream where deviceId = "%s" and messageType = "PROPERTY_REPORT" and json_path_exists(data, "$.%s") = true GROUP BY %s HAVING avg_%s %s`
valueCycle := s
if valueCycle == 0 {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required value_cycle parameter missing", nil)
return
}
decideCondition := option["decide_condition"]
if decideCondition == "" {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required decide_condition parameter missing", nil)
return
}
sql = fmt.Sprintf(sqlTemp, code, code, device.Id, code, fmt.Sprintf("TUMBLINGWINDOW(ss, %d)", valueCycle), code, decideCondition)
return
}
case constants.SpecsTypeText:
decideCondition := option["decide_condition"]
if decideCondition == "" {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required decide_condition parameter missing", nil)
return
}
st := strings.Split(decideCondition, " ")
if len(st) != 2 {
return
}
sqlTemp := `SELECT rule_id(),json_path_query(data, "$.%s.time") as report_time,deviceId FROM mqtt_stream where deviceId = "%s" and messageType = "PROPERTY_REPORT" and json_path_exists(data, "$.%s") = true and json_path_query(data, "$.%s.value") = "%s"`
sql = fmt.Sprintf(sqlTemp, code, deviceId, code, code, st[1])
return
case constants.SpecsTypeBool:
decideCondition := option["decide_condition"]
if decideCondition == "" {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required decide_condition parameter missing", nil)
return
}
st := strings.Split(decideCondition, " ")
if len(st) != 2 {
return
}
sqlTemp := `SELECT rule_id(),json_path_query(data, "$.%s.time") as report_time,deviceId FROM mqtt_stream where deviceId = "%s" and messageType = "PROPERTY_REPORT" and json_path_exists(data, "$.%s") = true and json_path_query(data, "$.%s.value") = "%s"`
if st[1] == "true" {
sql = fmt.Sprintf(sqlTemp, code, deviceId, code, code, "1")
} else if st[1] == "false" {
sql = fmt.Sprintf(sqlTemp, code, deviceId, code, code, "0")
}
return
case constants.SpecsTypeEnum:
decideCondition := option["decide_condition"]
if decideCondition == "" {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required decide_condition parameter missing", nil)
return
}
st := strings.Split(decideCondition, " ")
if len(st) != 2 {
return
}
sqlTemp := `SELECT rule_id(),json_path_query(data, "$.%s.time") as report_time,deviceId FROM mqtt_stream where deviceId = "%s" and messageType = "PROPERTY_REPORT" and json_path_exists(data, "$.%s") = true and json_path_query(data, "$.%s.value") = "%s"`
sql = fmt.Sprintf(sqlTemp, code, deviceId, code, code, st[1])
return
}
}
}
if !codeFind {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required code parameter missing", nil)
}
case string(constants.DeviceEventTrigger):
var codeFind bool
for _, event := range product.Events {
if code == event.Code {
codeFind = true
sqlTemp := `SELECT rule_id(),json_path_query(data, "$.eventTime") as report_time,deviceId FROM mqtt_stream where deviceId = "%s" and messageType = "EVENT_REPORT" and json_path_exists(data, "$.eventCode") = true and json_path_query(data, "$.eventCode") = "%s"`
sql = fmt.Sprintf(sqlTemp, device.Id, code)
return
}
}
if !codeFind {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required code parameter missing", nil)
}
case string(constants.DeviceStatusTrigger):
var status string
deviceStatus := option["status"]
if deviceStatus == "" {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required status parameter missing", nil)
return
}
if deviceStatus == "在线" {
status = constants.DeviceOnline
} else if deviceStatus == "离线" {
status = constants.DeviceOffline
} else {
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required status parameter missing", nil)
return
}
sqlTemp := `SELECT rule_id(),json_path_query(data, "$.time") as report_time,deviceId FROM mqtt_stream where deviceId = "%s" and messageType = "DEVICE_STATUS" and json_path_exists(data, "$.status") = true and json_path_query(data, "$.status") = "%s"`
sql = fmt.Sprintf(sqlTemp, device.Id, status)
return
default:
err = errort.NewCommonEdgeX(errort.DefaultReqParamsError, "required trigger parameter missing", nil)
return
}
return
}
func (p sceneApp) checkAlertRuleParam(ctx context.Context, scene models.Scene, operate string) error {
if operate == "start" {
if scene.Status == constants.SceneStart {
return errort.NewCommonErr(errort.AlertRuleStatusStarting, fmt.Errorf("scene id(%s) is runing ,not allow start", scene.Id))
}
}
var (
trigger string
)
if len(scene.Conditions) != 1 {
trigger = scene.Conditions[0].Option["trigger"]
switch scene.Conditions[0].ConditionType {
case "timer":
case "notify":
ekuiperApp := resourceContainer.EkuiperAppFrom(p.dic.Get)
exist, err := ekuiperApp.RuleExist(ctx, scene.Id)
if err != nil {
return err
}
if !exist {
}
trigger = scene.Conditions[0].Option["trigger"]
if trigger != string(constants.DeviceDataTrigger) || trigger != string(constants.DeviceEventTrigger) || trigger != string(constants.DeviceStatusTrigger) {
return errort.NewCommonErr(errort.SceneRuleParamsError, fmt.Errorf("scene id(%s) trigger param error", scene.Id))
}
option := scene.Conditions[0].Option
deviceId := option["device_id"]
deviceName := option["device_name"]
productId := option["product_id"]
productName := option["product_name"]
//trigger := option["trigger"]
code := option["code"]
if deviceId == "" || deviceName == "" || productId == "" || productName == "" || code == "" || trigger == "" {
return errort.NewCommonEdgeX(errort.SceneRuleParamsError, "required parameter missing", nil)
}
device, err := p.dbClient.DeviceById(deviceId)
if err != nil {
return errort.NewCommonErr(errort.SceneRuleParamsError, fmt.Errorf("scene id(%s) device not found", scene.Id))
}
product, err := p.dbClient.ProductById(productId)
if err != nil {
return errort.NewCommonErr(errort.SceneRuleParamsError, fmt.Errorf("scene id(%s) actions is null", scene.Id))
}
if device.ProductId != product.Id {
return errort.NewCommonErr(errort.SceneRuleParamsError, fmt.Errorf("scene id(%s) actions is null", scene.Id))
}
default:
return errort.NewCommonErr(errort.SceneRuleParamsError, fmt.Errorf("scene id(%s) conditionType param errror", scene.Id))
}
}
//-------------------------
if len(scene.Actions) == 0 {
return errort.NewCommonErr(errort.SceneRuleParamsError, fmt.Errorf("scene id(%s) actions is null", scene.Id))
}
for _, action := range scene.Actions {
//检查产品和设备是否存在
device, err := p.dbClient.DeviceById(action.DeviceID)
if err != nil {
return errort.NewCommonErr(errort.SceneRuleParamsError, fmt.Errorf("scene id(%s) device not found", scene.Id))
}
product, err := p.dbClient.ProductById(action.ProductID)
if err != nil {
return errort.NewCommonErr(errort.SceneRuleParamsError, fmt.Errorf("scene id(%s) product not found", scene.Id))
}
if device.ProductId != product.Id {
return errort.NewCommonErr(errort.SceneRuleParamsError, fmt.Errorf("scene id(%s) actions is null", scene.Id))
}
var find bool
if trigger == string(constants.DeviceDataTrigger) {
for _, property := range product.Properties {
if property.Code == action.Code {
find = true
break
}
}
}
if trigger == string(constants.DeviceEventTrigger) {
for _, event := range product.Events {
if event.Code == action.Code {
find = true
break
}
}
}
if !find {
return errort.NewCommonErr(errort.SceneRuleParamsError, fmt.Errorf("scene id(%s) code not found", scene.Id))
}
if action.Value == "" {
return errort.NewCommonErr(errort.SceneRuleParamsError, fmt.Errorf("scene id(%s) value is null", scene.Id))
}
}
return nil
}
func (p sceneApp) EkuiperNotify(ctx context.Context, req map[string]interface{}) error {
sceneId, ok := req["rule_id"]
if !ok {
return errort.NewCommonErr(errort.DefaultReqParamsError, errors.New(""))
}
var (
coverSceneId string
)
switch sceneId.(type) {
case string:
coverSceneId = sceneId.(string)
case int:
coverSceneId = strconv.Itoa(sceneId.(int))
case int64:
coverSceneId = strconv.Itoa(int(sceneId.(int64)))
case float64:
coverSceneId = fmt.Sprintf("%f", sceneId.(float64))
case float32:
coverSceneId = fmt.Sprintf("%f", sceneId.(float64))
}
if coverSceneId == "" {
return errort.NewCommonErr(errort.DefaultReqParamsError, errors.New(""))
}
scene, err := p.dbClient.SceneById(coverSceneId)
if err != nil {
return err
}
for _, action := range scene.Actions {
deviceApp := resourceContainer.DeviceItfFrom(p.dic.Get)
execRes := deviceApp.DeviceAction(dtos.JobAction{
ProductId: action.ProductID,
})
_, err := p.dbClient.AddSceneLog(models.SceneLog{
SceneId: scene.Id,
Name: scene.Name,
ExecRes: execRes.ToString(),
})
if err != nil {
p.lc.Errorf("add sceneLog err %v", err.Error())
}
}
return nil
}
func (p sceneApp) CheckSceneByDeviceId(ctx context.Context, deviceId string) error {
var req dtos.SceneSearchQueryRequest
req.Status = string(constants.SceneStart)
scenes, _, err := p.SceneSearch(ctx, req)
if err != nil {
return err
}
for _, scene := range scenes {
for _, condition := range scene.Conditions {
if condition.Option != nil && condition.Option["device_id"] == deviceId {
return errort.NewCommonEdgeX(errort.DeviceAssociationSceneRule, "This device has been bound to scene rules. Please stop reporting scene rules before proceeding with the operation", nil)
}
}
for _, action := range scene.Actions {
if action.DeviceID == deviceId {
return errort.NewCommonEdgeX(errort.DeviceAssociationSceneRule, "This device has been bound to scene rules. Please stop reporting scene rules before proceeding with the operation", nil)
}
}
}
return nil
}

View File

@ -1,288 +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 timerapp
import (
"context"
"github.com/winc-link/hummingbird/internal/dtos"
resourceContainer "github.com/winc-link/hummingbird/internal/hummingbird/core/container"
interfaces "github.com/winc-link/hummingbird/internal/hummingbird/core/interface"
"github.com/winc-link/hummingbird/internal/pkg/constants"
"github.com/winc-link/hummingbird/internal/pkg/container"
"github.com/winc-link/hummingbird/internal/pkg/di"
//"github.com/winc-link/hummingbird/internal/edge/sharp/module/timer/db"
//"github.com/winc-link/hummingbird/internal/pkg/timer/db"
"github.com/winc-link/hummingbird/internal/pkg/timer/jobrunner"
"github.com/winc-link/hummingbird/internal/pkg/timer/jobs"
"github.com/winc-link/hummingbird/internal/pkg/logger"
"sort"
"sync"
"time"
)
type EdgeTimer struct {
mutex sync.Mutex
logger logger.LoggingClient
db interfaces.DBClient
//db db.TimerDBClient
// job id map
jobMap map[string]struct{}
// 任务链表 有序
entries []*entry
// 停止信号
stop chan struct{}
// 添加任务channel
add chan *entry
// 更新任务
//update chan *jobs.UpdateJobStu
// 删除任务 uuid
rm chan string
// 启动标志
running bool
location *time.Location
f jobrunner.JobRunFunc
}
func NewCronTimer(ctx context.Context,
f jobrunner.JobRunFunc, dic *di.Container) *EdgeTimer {
dbClient := resourceContainer.DBClientFrom(dic.Get)
l := container.LoggingClientFrom(dic.Get)
et := &EdgeTimer{
logger: l,
db: dbClient,
rm: make(chan string),
add: make(chan *entry),
entries: nil,
jobMap: make(map[string]struct{}),
stop: make(chan struct{}),
running: false,
location: time.Local,
f: f,
}
// restore
et.restoreJobs()
go et.run()
return et
}
func (et *EdgeTimer) restoreJobs() {
scenes, _, _ := et.db.SceneSearch(0, -1, dtos.SceneSearchQueryRequest{})
if len(scenes) == 0 {
return
}
for _, scene := range scenes {
if len(scene.Conditions) > 0 && scene.Status == constants.SceneStart {
if scene.Conditions[0].ConditionType == "timer" {
job, err := scene.ToRuntimeJob()
if err != nil {
et.logger.Errorf("restore jobs runtime job err %v", err.Error())
continue
}
err = et.AddJobToRunQueue(job)
if err != nil {
et.logger.Errorf("restore jobs add job to queue err %v", err.Error())
}
}
}
}
return
}
func (et *EdgeTimer) Stop() {
et.mutex.Lock()
defer et.mutex.Unlock()
if et.running {
close(et.stop)
et.running = false
}
}
type (
// 任务
entry struct {
JobID string
Schedule *jobs.JobSchedule
Next time.Time
Prev time.Time
}
)
func (e entry) Valid() bool { return e.JobID != "" }
type byTime []*entry
func (s byTime) Len() int { return len(s) }
func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s byTime) Less(i, j int) bool {
if s[i].Next.IsZero() {
return false
}
if s[j].Next.IsZero() {
return true
}
return s[i].Next.Before(s[j].Next)
}
func (et *EdgeTimer) now() time.Time {
return time.Now().In(et.location)
}
func (et *EdgeTimer) run() {
et.mutex.Lock()
if et.running {
et.mutex.Unlock()
return
}
et.running = true
et.mutex.Unlock()
et.logger.Info("edge timer started...")
now := et.now()
for _, entry := range et.entries {
if next, b := entry.Schedule.Next(now); !b {
entry.Next = next
}
}
var timer = time.NewTimer(100000 * time.Hour)
for {
// Determine the next entry to run.
sort.Sort(byTime(et.entries))
if len(et.entries) == 0 || et.entries[0].Next.IsZero() {
// If there are no entries yet, just sleep - it still handles new entries
// and stop requests.
timer.Reset(100000 * time.Hour)
} else {
et.logger.Debugf("next wake time: %+v with jobID: %s", et.entries[0].Next, et.entries[0].JobID)
timer.Reset(et.entries[0].Next.Sub(now))
}
select {
case now = <-timer.C:
timer.Stop()
now = now.In(et.location)
et.logger.Infof("wake now: %+v with jobID: %s", now, et.entries[0].JobID)
var ()
for i, e := range et.entries {
if e.Next.After(now) || e.Next.IsZero() {
break
}
// async call
go et.f(e.JobID, *et.entries[i].Schedule)
//times := e.Schedule.ScheduleAdd1()
if false {
//finished = append(finished, i)
} else {
e.Prev = e.Next
if next, b := e.Schedule.Next(now); !b {
e.Next = next
et.logger.Infof("run now: %+v, entry: jobId: %s, jobName: %s, next: %+v", now, e.JobID, e.Schedule.JobName, e.Next)
}
//}
}
}
case newEntry := <-et.add:
timer.Stop()
now = et.now()
if next, b := newEntry.Schedule.Next(now); !b {
newEntry.Next = next
et.entries = append(et.entries, newEntry)
et.logger.Infof("added job now: %+v, next: %+v", now, newEntry.Next)
}
et.logger.Infof("added job: %v, now: %+v, next: %+v", newEntry.JobID, now, newEntry.Next)
case entryID := <-et.rm:
timer.Stop()
now = et.now()
et.removeEntry(entryID)
case <-et.stop:
timer.Stop()
et.logger.Info("tedge timer stopped...")
return
}
}
}
func (et *EdgeTimer) schedule(schedule *jobs.JobSchedule) {
et.mutex.Lock()
defer et.mutex.Unlock()
entry := &entry{
JobID: schedule.GetJobId(),
Schedule: schedule,
}
if !et.running {
et.entries = append(et.entries, entry)
} else {
et.add <- entry
}
}
func (et *EdgeTimer) remove(id string) {
if et.running {
et.rm <- id
} else {
et.removeEntry(id)
}
}
func (et *EdgeTimer) removeEntry(id string) {
var b bool
et.mutex.Lock()
defer et.mutex.Unlock()
for i, e := range et.entries {
if e.JobID == id {
et.entries[i], et.entries[len(et.entries)-1] = et.entries[len(et.entries)-1], et.entries[i]
b = true
break
}
}
if b {
et.entries[len(et.entries)-1] = nil
et.entries = et.entries[:len(et.entries)-1]
delete(et.jobMap, id)
et.logger.Debugf("entry length: %d, deleted job id: %s", len(et.entries), id)
} else {
et.logger.Warnf("unknown jobs,id: %s", id)
}
}
func (et *EdgeTimer) DeleteJob(id string) {
et.remove(id)
}
func (et *EdgeTimer) AddJobToRunQueue(j *jobs.JobSchedule) error {
if _, ok := et.jobMap[j.JobID]; ok {
et.logger.Warnf("job is already in map: %s", j.JobID)
return nil
}
if _, err := jobs.ParseStandard(j.TimeData.Expression); err != nil {
return err
}
et.schedule(j)
et.mutex.Lock()
defer et.mutex.Unlock()
et.jobMap[j.JobID] = struct{}{}
return nil
}

View File

@ -26,11 +26,3 @@ var (
func AlertRuleAppNameFrom(get di.Get) interfaces.AlertRuleApp {
return get(AlertRuleAppName).(interfaces.AlertRuleApp)
}
var (
RuleEngineAppName = di.TypeInstanceToName((*interfaces.RuleEngineApp)(nil))
)
func RuleEngineAppNameFrom(get di.Get) interfaces.RuleEngineApp {
return get(RuleEngineAppName).(interfaces.RuleEngineApp)
}

View File

@ -1,26 +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 container
import (
interfaces "github.com/winc-link/hummingbird/internal/hummingbird/core/interface"
"github.com/winc-link/hummingbird/internal/pkg/di"
)
var DataResourceName = di.TypeInstanceToName((*interfaces.DataResourceApp)(nil))
func DataResourceFrom(get di.Get) interfaces.DataResourceApp {
return get(DataResourceName).(interfaces.DataResourceApp)
}

View File

@ -19,14 +19,6 @@ import (
"github.com/winc-link/hummingbird/internal/pkg/di"
)
var (
SceneAppName = di.TypeInstanceToName((*interfaces.SceneApp)(nil))
)
func SceneAppNameFrom(get di.Get) interfaces.SceneApp {
return get(SceneAppName).(interfaces.SceneApp)
}
var (
ConJobAppName = di.TypeInstanceToName((*interfaces.ConJob)(nil))
)

View File

@ -83,16 +83,12 @@ func (ctl *controller) getThingModelApp() interfaces.ThingModelCtlItf {
return container.ThingModelAppNameFrom(ctl.dic.Get)
}
func (ctl *controller) getUnitModelApp() interfaces.UnitApp {
return container.UnitTemplateAppFrom(ctl.dic.Get)
}
func (ctl *controller) getAlertRuleApp() interfaces.AlertRuleApp {
return container.AlertRuleAppNameFrom(ctl.dic.Get)
}
func (ctl *controller) getRuleEngineApp() interfaces.RuleEngineApp {
return container.RuleEngineAppNameFrom(ctl.dic.Get)
func (ctl *controller) getUnitModelApp() interfaces.UnitApp {
return container.UnitTemplateAppFrom(ctl.dic.Get)
}
func (ctl *controller) getHomePageApp() interfaces.HomePageItf {
@ -106,11 +102,3 @@ func (ctl *controller) getDocsApp() interfaces.DocsApp {
func (ctl *controller) getQuickNavigationApp() interfaces.QuickNavigation {
return container.QuickNavigationAppTemplateAppFrom(ctl.dic.Get)
}
func (ctl *controller) getDataResourceApp() interfaces.DataResourceApp {
return container.DataResourceFrom(ctl.dic.Get)
}
func (ctl *controller) getSceneApp() interfaces.SceneApp {
return container.SceneAppNameFrom(ctl.dic.Get)
}

View File

@ -1,139 +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
// @Param request query dtos.AddDataResourceReq true "参数"
// @Success 200 {object} httphelper.CommonResponse
// @Router /api/v1/typeresource [get]
func (ctl *controller) DataResourceType(c *gin.Context) {
lc := ctl.lc
types := ctl.getDataResourceApp().DataResourceType(c)
httphelper.ResultSuccess(types, c.Writer, lc)
}
// @Tags 资源管理
// @Summary 添加资源管理
// @Produce json
// @Param request query dtos.AddDataResourceReq true "参数"
// @Success 200 {object} httphelper.CommonResponse
// @Router /api/v1/dataresource [post]
func (ctl *controller) DataResourceAdd(c *gin.Context) {
lc := ctl.lc
var req dtos.AddDataResourceReq
if err := c.ShouldBind(&req); err != nil {
httphelper.RenderFail(c, errort.NewCommonErr(errort.DefaultReqParamsError, err), c.Writer, lc)
return
}
_, edgeXErr := ctl.getDataResourceApp().AddDataResource(c, req)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}
// @Tags 资源管理
// @Summary 添加资源管理
// @Produce json
// @Param request query dtos.AddDataResourceReq true "参数"
// @Success 200 {object} httphelper.CommonResponse
// @Router /api/v1/dataresource/:resourceId [get]
func (ctl *controller) DataResourceById(c *gin.Context) {
lc := ctl.lc
id := c.Param(UrlDataResourceId)
dataSource, edgeXErr := ctl.getDataResourceApp().DataResourceById(c, id)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(dataSource, c.Writer, lc)
}
// @Tags 资源管理
// @Summary 修改资源管理
// @Produce json
// @Param request query dtos.AddDataResourceReq true "参数"
// @Success 200 {object} httphelper.CommonResponse
// @Router /api/v1/dataresource [put]
func (ctl *controller) UpdateDataResource(c *gin.Context) {
lc := ctl.lc
var req dtos.UpdateDataResource
if err := c.ShouldBind(&req); err != nil {
httphelper.RenderFail(c, errort.NewCommonErr(errort.DefaultReqParamsError, err), c.Writer, lc)
return
}
edgeXErr := ctl.getDataResourceApp().UpdateDataResource(c, req)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}
// @Tags 资源管理
// @Summary 删除资源管理
// @Produce json
// @Success 200 {object} httphelper.CommonResponse
// @Router /api/v1/dataresource/:resourceId [delete]
func (ctl *controller) DataResourceDel(c *gin.Context) {
lc := ctl.lc
id := c.Param(UrlDataResourceId)
edgeXErr := ctl.getDataResourceApp().DelDataResourceById(c, id)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}
// @Tags 资源管理
// @Summary 资源管理查询
// @Produce json
// @Success 200 {object} httphelper.CommonResponse
// @Router /api/v1/dataresource [get]
func (ctl *controller) DataResourceSearch(c *gin.Context) {
lc := ctl.lc
var req dtos.DataResourceSearchQueryRequest
urlDecodeParam(&req, c.Request, lc)
dtos.CorrectionPageParam(&req.BaseSearchConditionQuery)
data, total, edgeXErr := ctl.getDataResourceApp().DataResourceSearch(c, req)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
pageResult := httphelper.NewPageResult(data, total, req.Page, req.PageSize)
httphelper.ResultSuccess(pageResult, c.Writer, lc)
}
func (ctl *controller) DataResourceHealth(c *gin.Context) {
lc := ctl.lc
id := c.Param(UrlDataResourceId)
edgeXErr := ctl.getDataResourceApp().DataResourceHealth(c, id)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}

View File

@ -1,38 +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"
)
func (ctl *controller) EkuiperScene(c *gin.Context) {
lc := ctl.lc
req := make(map[string]interface{})
if err := c.ShouldBind(&req); err != nil {
httphelper.RenderFail(c, errort.NewCommonErr(errort.DefaultReqParamsError, err), c.Writer, lc)
return
}
lc.Info("scene req....", req)
edgeXErr := ctl.getSceneApp().EkuiperNotify(c, req)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}

View File

@ -1,169 +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
// @Param request query dtos.RuleEngineRequest true "参数"
// @Success 200 {object} httphelper.CommonResponse
// @Router /api/v1/rule-engine [post]
func (ctl *controller) RuleEngineAdd(c *gin.Context) {
lc := ctl.lc
var req dtos.RuleEngineRequest
if err := c.ShouldBind(&req); err != nil {
httphelper.RenderFail(c, errort.NewCommonErr(errort.DefaultReqParamsError, err), c.Writer, lc)
return
}
_, edgeXErr := ctl.getRuleEngineApp().AddRuleEngine(c, req)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}
// @Tags 规则引擎
// @Summary 编辑规则引擎
// @Produce json
// @Param request query dtos.RuleEngineUpdateRequest true "参数"
// @Success 200 {object} httphelper.CommonResponse
// @Router /api/v1/rule-engine [put]
func (ctl *controller) RuleEngineUpdate(c *gin.Context) {
lc := ctl.lc
var req dtos.RuleEngineUpdateRequest
if err := c.ShouldBind(&req); err != nil {
httphelper.RenderFail(c, errort.NewCommonErr(errort.DefaultReqParamsError, err), c.Writer, lc)
return
}
edgeXErr := ctl.getRuleEngineApp().UpdateRuleEngine(c, req)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}
// @Tags 规则引擎
// @Summary 规则引擎详情
// @Produce json
// @Param ruleEngineId path string true "ruleEngineId"
// @Success 200 {object} httphelper.CommonResponse
// @Router /api/v1/rule-engine/:ruleEngineId [get]
func (ctl *controller) RuleEngineById(c *gin.Context) {
lc := ctl.lc
id := c.Param(RuleEngineId)
data, edgeXErr := ctl.getRuleEngineApp().RuleEngineById(c, id)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(data, c.Writer, lc)
}
// @Tags 规则引擎
// @Summary 规则引擎列表
// @Produce json
// @Param request query dtos.RuleEngineSearchQueryRequest true "参数"
// @Success 200 {array} []dtos.RuleEngineSearchQueryResponse
// @Router /api/v1/rule-engine [get]
func (ctl *controller) RuleEngineSearch(c *gin.Context) {
lc := ctl.lc
var req dtos.RuleEngineSearchQueryRequest
urlDecodeParam(&req, c.Request, lc)
dtos.CorrectionPageParam(&req.BaseSearchConditionQuery)
data, total, edgeXErr := ctl.getRuleEngineApp().RuleEngineSearch(c, req)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
pageResult := httphelper.NewPageResult(data, total, req.Page, req.PageSize)
httphelper.ResultSuccess(pageResult, c.Writer, lc)
}
// @Tags 规则引擎
// @Summary 规则引擎启动
// @Produce json
// @Param ruleEngineId path string true "ruleEngineId"
// @Success 200 {object} httphelper.CommonResponse
// @Router /api/v1/rule-engine/:ruleEngineId/start [post]
func (ctl *controller) RuleEngineStart(c *gin.Context) {
lc := ctl.lc
id := c.Param(RuleEngineId)
edgeXErr := ctl.getRuleEngineApp().RuleEngineStart(c, id)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}
// @Tags 规则引擎
// @Summary 规则引擎停止
// @Produce json
// @Param ruleEngineId path string true "ruleEngineId"
// @Success 200 {object} httphelper.CommonResponse
// @Router /api/v1/rule-engine/:ruleEngineId/stop [post]
func (ctl *controller) RuleEngineStop(c *gin.Context) {
lc := ctl.lc
id := c.Param(RuleEngineId)
edgeXErr := ctl.getRuleEngineApp().RuleEngineStop(c, id)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}
// @Tags 规则引擎
// @Summary 规则引擎删除
// @Produce json
// @Param ruleEngineId path string true "ruleEngineId"
// @Success 200 {object} httphelper.CommonResponse
// @Router /api/v1/rule-engine/:ruleEngineId/delete [delete]
func (ctl *controller) RuleEngineDelete(c *gin.Context) {
lc := ctl.lc
id := c.Param(RuleEngineId)
edgeXErr := ctl.getRuleEngineApp().RuleEngineDelete(c, id)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}
// @Tags 规则引擎
// @Summary 规则引擎状态
// @Produce json
// @Param ruleEngineId path string true "ruleEngineId"
// @Success 200 {object} httphelper.CommonResponse
// @Router /api/v1/rule-engine/:ruleEngineId/status [get]
func (ctl *controller) RuleEngineStatus(c *gin.Context) {
lc := ctl.lc
id := c.Param(RuleEngineId)
r, edgeXErr := ctl.getRuleEngineApp().RuleEngineStatus(c, id)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(r, c.Writer, lc)
}

View File

@ -1,140 +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"
)
func (ctl *controller) SceneAdd(c *gin.Context) {
lc := ctl.lc
var req dtos.SceneAddRequest
if err := c.ShouldBind(&req); err != nil {
httphelper.RenderFail(c, errort.NewCommonErr(errort.DefaultReqParamsError, err), c.Writer, lc)
return
}
_, edgeXErr := ctl.getSceneApp().AddScene(c, req)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}
func (ctl *controller) SceneUpdate(c *gin.Context) {
lc := ctl.lc
var req dtos.SceneUpdateRequest
if err := c.ShouldBind(&req); err != nil {
httphelper.RenderFail(c, errort.NewCommonErr(errort.DefaultReqParamsError, err), c.Writer, lc)
return
}
edgeXErr := ctl.getSceneApp().UpdateScene(c, req)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}
func (ctl *controller) SceneById(c *gin.Context) {
lc := ctl.lc
id := c.Param(UrlParamSceneId)
scene, edgeXErr := ctl.getSceneApp().SceneById(c, id)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(scene, c.Writer, lc)
}
func (ctl *controller) SearchScene(c *gin.Context) {
lc := ctl.lc
var req dtos.SceneSearchQueryRequest
urlDecodeParam(&req, c.Request, lc)
dtos.CorrectionPageParam(&req.BaseSearchConditionQuery)
list, total, edgeXErr := ctl.getSceneApp().SceneSearch(c, req)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
pageResult := httphelper.NewPageResult(list, total, req.Page, req.PageSize)
httphelper.ResultSuccess(pageResult, c.Writer, lc)
}
func (ctl *controller) SceneLogSearch(c *gin.Context) {
lc := ctl.lc
sceneId := c.Param(UrlParamSceneId)
var req dtos.SceneLogSearchQueryRequest
urlDecodeParam(&req, c.Request, lc)
dtos.CorrectionPageParam(&req.BaseSearchConditionQuery)
req.SceneId = sceneId
ctl.lc.Info("sceneLogSearch log:", req)
list, total, edgeXErr := ctl.getSceneApp().SceneLogSearch(c, req)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
pageResult := httphelper.NewPageResult(list, total, req.Page, req.PageSize)
httphelper.ResultSuccess(pageResult, c.Writer, lc)
}
func (ctl *controller) SceneStart(c *gin.Context) {
lc := ctl.lc
id := c.Param(UrlParamSceneId)
edgeXErr := ctl.getSceneApp().SceneStartById(c, id)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}
func (ctl *controller) SceneStop(c *gin.Context) {
lc := ctl.lc
id := c.Param(UrlParamSceneId)
edgeXErr := ctl.getSceneApp().SceneStopById(c, id)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}
func (ctl *controller) DeleteScene(c *gin.Context) {
lc := ctl.lc
id := c.Param(UrlParamSceneId)
edgeXErr := ctl.getSceneApp().DelSceneById(c, id)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}
func (ctl *controller) SceneLog(c *gin.Context) {
lc := ctl.lc
id := c.Param(UrlParamSceneId)
edgeXErr := ctl.getSceneApp().DelSceneById(c, id)
if edgeXErr != nil {
httphelper.RenderFail(c, edgeXErr, c.Writer, lc)
return
}
httphelper.ResultSuccess(nil, c.Writer, lc)
}

View File

@ -568,108 +568,6 @@ func (c *Client) MsgGatherSearch(offset int, limit int, req dtos.MsgGatherSearch
return msgGatherSearch(c, offset, limit, req)
}
func (c *Client) AddDataResource(dateResource models.DataResource) (string, error) {
if len(dateResource.Id) == 0 {
dateResource.Id = utils.RandomNum()
}
return addDataResource(c, dateResource)
}
func (c *Client) UpdateDataResource(dateResource models.DataResource) error {
return updateDataResource(c, dateResource)
}
func (c *Client) DelDataResource(id string) error {
return deleteDataResourceById(c, id)
}
func (c *Client) UpdateDataResourceHealth(id string, health bool) error {
return updateDataResourceHealth(c, id, health)
}
func (c *Client) SearchDataResource(offset int, limit int, req dtos.DataResourceSearchQueryRequest) (dataResource []models.DataResource, count uint32, edgeXErr error) {
return dataResourceSearch(c, offset, limit, req)
}
func (c *Client) DataResourceById(id string) (models.DataResource, error) {
return dataResourceById(c, id)
}
func (c *Client) AddRuleEngine(ruleEngine models.RuleEngine) (string, error) {
if len(ruleEngine.Id) == 0 {
ruleEngine.Id = utils.RandomNum()
}
return addRuleEngine(c, ruleEngine)
}
func (c *Client) UpdateRuleEngine(ruleEngine models.RuleEngine) error {
return updateRuleEngine(c, ruleEngine)
}
func (c *Client) RuleEngineById(id string) (ruleEngine models.RuleEngine, edgeXErr error) {
return ruleEngineById(c, id)
}
func (c *Client) RuleEngineSearch(offset int, limit int, req dtos.RuleEngineSearchQueryRequest) (ruleEngine []models.RuleEngine, count uint32, edgeXErr error) {
return ruleEngineSearch(c, offset, limit, req)
}
func (c *Client) RuleEngineStart(id string) error {
return ruleEngineStart(c, id)
}
func (c *Client) RuleEngineStop(id string) error {
return ruleEngineStop(c, id)
}
func (c *Client) DeleteRuleEngineById(id string) error {
return deleteRuleEngineById(c, id)
}
func (c *Client) AddScene(scene models.Scene) (models.Scene, error) {
if len(scene.Id) == 0 {
scene.Id = utils.RandomNum()
}
return addScene(c, scene)
}
func (c *Client) UpdateScene(scene models.Scene) error {
if len(scene.Id) == 0 {
scene.Id = utils.RandomNum()
}
return updateScene(c, scene)
}
func (c *Client) SceneById(id string) (models.Scene, error) {
return sceneById(c, id)
}
func (c *Client) SceneStart(id string) error {
return sceneStart(c, id)
}
func (c *Client) SceneStop(id string) error {
return sceneStop(c, id)
}
func (c *Client) DeleteSceneById(id string) error {
return deleteSceneById(c, id)
}
func (c *Client) SceneSearch(offset int, limit int, req dtos.SceneSearchQueryRequest) (scenes []models.Scene, total uint32, edgeXErr error) {
return sceneSearch(c, offset, limit, req)
}
func (c *Client) AddSceneLog(sceneLog models.SceneLog) (models.SceneLog, error) {
if len(sceneLog.Id) == 0 {
sceneLog.Id = utils.RandomNum()
}
return addSceneLog(c, sceneLog)
}
func (c *Client) SceneLogSearch(offset int, limit int, req dtos.SceneLogSearchQueryRequest) (sceneLogs []models.SceneLog, total uint32, edgeXErr error) {
return sceneLogSearch(c, offset, limit, req)
}
func (c *Client) LanguageSdkByName(name string) (cloudService models.LanguageSdk, edgeXErr error) {
return languageByName(c, name)
}

View File

@ -1,117 +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 mysql
import (
"fmt"
"github.com/winc-link/hummingbird/internal/dtos"
"github.com/winc-link/hummingbird/internal/models"
"github.com/winc-link/hummingbird/internal/pkg/errort"
"github.com/winc-link/hummingbird/internal/pkg/utils"
"github.com/winc-link/hummingbird/internal/tools/sqldb/sqlite"
"gorm.io/gorm"
)
func dataResourceById(c *Client, id string) (dateResource models.DataResource, edgeXErr error) {
if id == "" {
return dateResource, errort.NewCommonEdgeX(errort.DefaultIdEmpty, "dateResource id is empty", nil)
}
err := c.Pool.Table(dateResource.TableName()).First(&dateResource, id).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return dateResource, errort.NewCommonErr(errort.DefaultResourcesNotFound, fmt.Errorf("dateResource id(%s) not found", id))
}
return dateResource, errort.NewCommonErr(errort.DefaultSystemError, fmt.Errorf("query dateResource fail (Id:%s), %s", dateResource.Id, err))
}
return
}
func addDataResource(c *Client, ds models.DataResource) (id string, edgeXErr error) {
ts := utils.MakeTimestamp()
if ds.Created == 0 {
ds.Created = ts
}
ds.Modified = ts
err := c.client.CreateObject(&ds)
if err != nil {
edgeXErr = errort.NewCommonEdgeX(errort.DefaultSystemError, "data resourced creation failed", err)
}
return ds.Id, edgeXErr
}
func updateDataResource(c *Client, dl models.DataResource) error {
dl.Modified = utils.MakeTimestamp()
err := c.client.UpdateObject(&dl)
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "data resource update failed", err)
}
return nil
}
func deleteDataResourceById(c *Client, id string) error {
if id == "" {
return errort.NewCommonEdgeX(errort.DefaultIdEmpty, "id is empty", nil)
}
err := c.client.DeleteObject(&models.DataResource{Id: id})
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "data resourced deletion failed", err)
}
return nil
}
func updateDataResourceHealth(c *Client, id string, health bool) error {
if id == "" {
return errort.NewCommonEdgeX(errort.DefaultIdEmpty, "id is empty", nil)
}
d := models.DataResource{}
tx := c.Pool.Table(d.TableName())
err := tx.Where("id = ?", id).Updates(map[string]interface{}{"health": health}).Error
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "update data resource failed", err)
}
return nil
}
func dataResourceSearch(c *Client, offset int, limit int, req dtos.DataResourceSearchQueryRequest) (dataResource []models.DataResource, count uint32, edgeXErr error) {
dl := models.DataResource{}
var total int64
tx := c.Pool.Table(dl.TableName())
tx = sqlite.BuildCommonCondition(tx, dl, req.BaseSearchConditionQuery)
// 特殊条件
if req.Type != "" {
tx = tx.Where("`type` = ?", req.Type)
}
if req.Health != "" {
isHealth := true
if req.Health == SearchReqBoolTrue {
isHealth = true
} else {
isHealth = false
}
tx = tx.Where("`health` = ?", isHealth)
}
err := tx.Count(&total).Error
if err != nil {
return []models.DataResource{}, 0, errort.NewCommonEdgeX(errort.DefaultSystemError, "data resource failed query from the database", err)
}
err = tx.Offset(offset).Limit(limit).Find(&dataResource).Error
if err != nil {
return []models.DataResource{}, 0, errort.NewCommonEdgeX(errort.DefaultSystemError, "data resource failed query from the database", err)
}
return dataResource, uint32(total), nil
}

View File

@ -1,120 +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 mysql
import (
"fmt"
"github.com/winc-link/hummingbird/internal/dtos"
"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/utils"
"github.com/winc-link/hummingbird/internal/tools/sqldb/sqlite"
"gorm.io/gorm"
)
func addRuleEngine(c *Client, ds models.RuleEngine) (id string, edgeXErr error) {
ts := utils.MakeTimestamp()
if ds.Created == 0 {
ds.Created = ts
}
ds.Modified = ts
err := c.client.CreateObject(&ds)
if err != nil {
edgeXErr = errort.NewCommonEdgeX(errort.DefaultSystemError, "rule engine creation failed", err)
}
return ds.Id, edgeXErr
}
func ruleEngineById(c *Client, id string) (ruleEngine models.RuleEngine, edgeXErr error) {
if id == "" {
return ruleEngine, errort.NewCommonEdgeX(errort.DefaultIdEmpty, "rule engine id is empty", nil)
}
err := c.Pool.Table(ruleEngine.TableName()).Preload("DataResource").First(&ruleEngine, id).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return ruleEngine, errort.NewCommonErr(errort.DefaultSystemError, fmt.Errorf("rule engine id id(%s) not found", id))
}
return ruleEngine, errort.NewCommonErr(errort.DefaultSystemError, fmt.Errorf("query rule engine id fail (Id:%s), %s", ruleEngine.Id, err))
}
return
}
func ruleEngineSearch(c *Client, offset int, limit int, req dtos.RuleEngineSearchQueryRequest) (ruleEngine []models.RuleEngine, count uint32, edgeXErr error) {
dp := models.RuleEngine{}
var total int64
tx := c.Pool.Table(dp.TableName())
tx = sqlite.BuildCommonCondition(tx, dp, req.BaseSearchConditionQuery)
if req.Name != "" {
tx = tx.Where("`name` LIKE ?", sqlite.MakeLikeParams(req.Name))
}
if req.Status != "" {
tx = tx.Where("`status` = ?", req.Status)
}
err := tx.Count(&total).Error
if err != nil {
return ruleEngine, 0, errort.NewCommonEdgeX(errort.DefaultSystemError, "rules engine failed query from the database", err)
}
err = tx.Offset(offset).Limit(limit).Preload("DataResource").Find(&ruleEngine).Error
if err != nil {
return ruleEngine, 0, errort.NewCommonEdgeX(errort.DefaultSystemError, "rules engine failed query from the database", err)
}
return ruleEngine, uint32(total), nil
}
func ruleEngineStart(c *Client, id string) error {
d := models.RuleEngine{}
tx := c.Pool.Table(d.TableName())
err := tx.Where("id = ?", id).Updates(map[string]interface{}{"status": constants.RuleStart}).Error
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "start alert rule failed", err)
}
return nil
}
func ruleEngineStop(c *Client, id string) error {
d := models.RuleEngine{}
tx := c.Pool.Table(d.TableName())
err := tx.Where("id = ?", id).Updates(map[string]interface{}{"status": constants.RuleStop}).Error
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "stop alert rule failed", err)
}
return nil
}
func deleteRuleEngineById(c *Client, id string) error {
if id == "" {
return errort.NewCommonEdgeX(errort.DefaultIdEmpty, "rule engine id is empty", nil)
}
err := c.client.DeleteObject(&models.RuleEngine{Id: id})
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "rule engine deletion failed", err)
}
return nil
}
func updateRuleEngine(c *Client, ruleEngine models.RuleEngine) error {
ruleEngine.Modified = utils.MakeTimestamp()
err := c.client.UpdateObject(&ruleEngine)
if err != nil {
return err
}
return nil
}

View File

@ -1,159 +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 mysql
import (
"fmt"
"github.com/winc-link/hummingbird/internal/dtos"
"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/utils"
"github.com/winc-link/hummingbird/internal/tools/sqldb/sqlite"
"gorm.io/gorm"
)
func addScene(c *Client, ds models.Scene) (scene models.Scene, edgeXErr error) {
ts := utils.MakeTimestamp()
if ds.Created == 0 {
ds.Created = ts
}
ds.Modified = ts
err := c.client.CreateObject(&ds)
if err != nil {
edgeXErr = errort.NewCommonEdgeX(errort.DefaultSystemError, "scene creation failed", err)
}
return ds, edgeXErr
}
func updateScene(c *Client, dl models.Scene) error {
dl.Modified = utils.MakeTimestamp()
err := c.client.UpdateObject(&dl)
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "scene update failed", err)
}
return nil
}
func sceneById(c *Client, id string) (scene models.Scene, err error) {
if id == "" {
return scene, errort.NewCommonEdgeX(errort.DefaultIdEmpty, "scene id is empty", nil)
}
err = c.client.GetObject(&models.Scene{Id: id}, &scene)
if err != nil {
if err == gorm.ErrRecordNotFound {
return scene, errort.NewCommonErr(errort.DefaultResourcesNotFound, fmt.Errorf("scene id(%s) not found", id))
}
return scene, err
}
return
}
func sceneStart(c *Client, id string) error {
d := models.Scene{}
tx := c.Pool.Table(d.TableName())
err := tx.Where("id = ?", id).Updates(map[string]interface{}{"status": constants.SceneStart}).Error
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "start scene rule failed", err)
}
return nil
}
func sceneStop(c *Client, id string) error {
d := models.Scene{}
tx := c.Pool.Table(d.TableName())
err := tx.Where("id = ?", id).Updates(map[string]interface{}{"status": constants.SceneStop}).Error
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "start scene rule failed", err)
}
return nil
}
func deleteSceneById(c *Client, id string) error {
if id == "" {
return errort.NewCommonEdgeX(errort.DefaultIdEmpty, "del scene id is empty", nil)
}
err := c.client.DeleteObject(&models.Scene{Id: id})
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "del scene deletion failed", err)
}
return nil
}
func sceneSearch(c *Client, offset int, limit int, req dtos.SceneSearchQueryRequest) (scene []models.Scene, count uint32, edgeXErr error) {
dp := models.Scene{}
var total int64
tx := c.Pool.Table(dp.TableName())
tx = sqlite.BuildCommonCondition(tx, dp, req.BaseSearchConditionQuery)
if req.Name != "" {
tx = tx.Where("`name` LIKE ?", sqlite.MakeLikeParams(req.Name))
}
if req.Status != "" {
tx = tx.Where("`status` = ?", req.Status)
}
err := tx.Count(&total).Error
if err != nil {
return scene, 0, errort.NewCommonEdgeX(errort.DefaultSystemError, "scene search failed query from the database", err)
}
err = tx.Offset(offset).Limit(limit).Find(&scene).Error
if err != nil {
return scene, 0, errort.NewCommonEdgeX(errort.DefaultSystemError, "scene search failed query from the database", err)
}
return scene, uint32(total), nil
}
func addSceneLog(c *Client, ds models.SceneLog) (sceneLog models.SceneLog, edgeXErr error) {
ts := utils.MakeTimestamp()
if ds.Created == 0 {
ds.Created = ts
}
ds.Modified = ts
err := c.client.CreateObject(&ds)
if err != nil {
edgeXErr = errort.NewCommonEdgeX(errort.DefaultSystemError, "scene log creation failed", err)
}
return ds, edgeXErr
}
func sceneLogSearch(c *Client, offset int, limit int, req dtos.SceneLogSearchQueryRequest) (sceneLogs []models.SceneLog, count uint32, edgeXErr error) {
dp := models.SceneLog{}
var total int64
tx := c.Pool.Table(dp.TableName())
tx = sqlite.BuildCommonCondition(tx, dp, req.BaseSearchConditionQuery)
if req.StartAt > 0 && req.EndAt > 0 && req.EndAt-req.StartAt > 0 {
tx.Where("created > ?", req.StartAt).Where("created < ?", req.EndAt)
}
if req.SceneId != "" {
tx = tx.Where("`scene_id` = ?", req.SceneId)
}
err := tx.Count(&total).Error
if err != nil {
return sceneLogs, 0, errort.NewCommonEdgeX(errort.DefaultSystemError, "scene log search failed query from the database", err)
}
err = tx.Offset(offset).Limit(limit).Find(&sceneLogs).Error
if err != nil {
return sceneLogs, 0, errort.NewCommonEdgeX(errort.DefaultSystemError, "scene log search failed query from the database", err)
}
return sceneLogs, uint32(total), nil
}

View File

@ -581,108 +581,6 @@ func (c *Client) MsgGatherSearch(offset int, limit int, req dtos.MsgGatherSearch
return msgGatherSearch(c, offset, limit, req)
}
func (c *Client) AddDataResource(dateResource models.DataResource) (string, error) {
if len(dateResource.Id) == 0 {
dateResource.Id = utils.RandomNum()
}
return addDataResource(c, dateResource)
}
func (c *Client) UpdateDataResource(dateResource models.DataResource) error {
return updateDataResource(c, dateResource)
}
func (c *Client) DelDataResource(id string) error {
return deleteDataResourceById(c, id)
}
func (c *Client) UpdateDataResourceHealth(id string, health bool) error {
return updateDataResourceHealth(c, id, health)
}
func (c *Client) SearchDataResource(offset int, limit int, req dtos.DataResourceSearchQueryRequest) (dataResource []models.DataResource, count uint32, edgeXErr error) {
return dataResourceSearch(c, offset, limit, req)
}
func (c *Client) DataResourceById(id string) (models.DataResource, error) {
return dataResourceById(c, id)
}
func (c *Client) AddRuleEngine(ruleEngine models.RuleEngine) (string, error) {
if len(ruleEngine.Id) == 0 {
ruleEngine.Id = utils.RandomNum()
}
return addRuleEngine(c, ruleEngine)
}
func (c *Client) UpdateRuleEngine(ruleEngine models.RuleEngine) error {
return updateRuleEngine(c, ruleEngine)
}
func (c *Client) RuleEngineById(id string) (ruleEngine models.RuleEngine, edgeXErr error) {
return ruleEngineById(c, id)
}
func (c *Client) RuleEngineSearch(offset int, limit int, req dtos.RuleEngineSearchQueryRequest) (ruleEngine []models.RuleEngine, count uint32, edgeXErr error) {
return ruleEngineSearch(c, offset, limit, req)
}
func (c *Client) RuleEngineStart(id string) error {
return ruleEngineStart(c, id)
}
func (c *Client) RuleEngineStop(id string) error {
return ruleEngineStop(c, id)
}
func (c *Client) DeleteRuleEngineById(id string) error {
return deleteRuleEngineById(c, id)
}
func (c *Client) AddScene(scene models.Scene) (models.Scene, error) {
if len(scene.Id) == 0 {
scene.Id = utils.RandomNum()
}
return addScene(c, scene)
}
func (c *Client) UpdateScene(scene models.Scene) error {
if len(scene.Id) == 0 {
scene.Id = utils.RandomNum()
}
return updateScene(c, scene)
}
func (c *Client) SceneById(id string) (models.Scene, error) {
return sceneById(c, id)
}
func (c *Client) SceneStart(id string) error {
return sceneStart(c, id)
}
func (c *Client) SceneStop(id string) error {
return sceneStop(c, id)
}
func (c *Client) DeleteSceneById(id string) error {
return deleteSceneById(c, id)
}
func (c *Client) SceneSearch(offset int, limit int, req dtos.SceneSearchQueryRequest) (scenes []models.Scene, total uint32, edgeXErr error) {
return sceneSearch(c, offset, limit, req)
}
func (c *Client) AddSceneLog(sceneLog models.SceneLog) (models.SceneLog, error) {
if len(sceneLog.Id) == 0 {
sceneLog.Id = utils.RandomNum()
}
return addSceneLog(c, sceneLog)
}
func (c *Client) SceneLogSearch(offset int, limit int, req dtos.SceneLogSearchQueryRequest) (sceneLogs []models.SceneLog, total uint32, edgeXErr error) {
return sceneLogSearch(c, offset, limit, req)
}
func (c *Client) LanguageSdkByName(name string) (cloudService models.LanguageSdk, edgeXErr error) {
return languageByName(c, name)
}

View File

@ -1,117 +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 sqlite
import (
"fmt"
"github.com/winc-link/hummingbird/internal/dtos"
"github.com/winc-link/hummingbird/internal/models"
"github.com/winc-link/hummingbird/internal/pkg/errort"
"github.com/winc-link/hummingbird/internal/pkg/utils"
"github.com/winc-link/hummingbird/internal/tools/sqldb/sqlite"
"gorm.io/gorm"
)
func dataResourceById(c *Client, id string) (dateResource models.DataResource, edgeXErr error) {
if id == "" {
return dateResource, errort.NewCommonEdgeX(errort.DefaultIdEmpty, "dateResource id is empty", nil)
}
err := c.Pool.Table(dateResource.TableName()).First(&dateResource, id).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return dateResource, errort.NewCommonErr(errort.DefaultResourcesNotFound, fmt.Errorf("dateResource id(%s) not found", id))
}
return dateResource, errort.NewCommonErr(errort.DefaultSystemError, fmt.Errorf("query dateResource fail (Id:%s), %s", dateResource.Id, err))
}
return
}
func addDataResource(c *Client, ds models.DataResource) (id string, edgeXErr error) {
ts := utils.MakeTimestamp()
if ds.Created == 0 {
ds.Created = ts
}
ds.Modified = ts
err := c.client.CreateObject(&ds)
if err != nil {
edgeXErr = errort.NewCommonEdgeX(errort.DefaultSystemError, "data resourced creation failed", err)
}
return ds.Id, edgeXErr
}
func updateDataResource(c *Client, dl models.DataResource) error {
dl.Modified = utils.MakeTimestamp()
err := c.client.UpdateObject(&dl)
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "data resource update failed", err)
}
return nil
}
func deleteDataResourceById(c *Client, id string) error {
if id == "" {
return errort.NewCommonEdgeX(errort.DefaultIdEmpty, "id is empty", nil)
}
err := c.client.DeleteObject(&models.DataResource{Id: id})
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "data resourced deletion failed", err)
}
return nil
}
func updateDataResourceHealth(c *Client, id string, health bool) error {
if id == "" {
return errort.NewCommonEdgeX(errort.DefaultIdEmpty, "id is empty", nil)
}
d := models.DataResource{}
tx := c.Pool.Table(d.TableName())
err := tx.Where("id = ?", id).Updates(map[string]interface{}{"health": health}).Error
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "update data resource failed", err)
}
return nil
}
func dataResourceSearch(c *Client, offset int, limit int, req dtos.DataResourceSearchQueryRequest) (dataResource []models.DataResource, count uint32, edgeXErr error) {
dl := models.DataResource{}
var total int64
tx := c.Pool.Table(dl.TableName())
tx = sqlite.BuildCommonCondition(tx, dl, req.BaseSearchConditionQuery)
// 特殊条件
if req.Type != "" {
tx = tx.Where("`type` = ?", req.Type)
}
if req.Health != "" {
isHealth := true
if req.Health == SearchReqBoolTrue {
isHealth = true
} else {
isHealth = false
}
tx = tx.Where("`health` = ?", isHealth)
}
err := tx.Count(&total).Error
if err != nil {
return []models.DataResource{}, 0, errort.NewCommonEdgeX(errort.DefaultSystemError, "data resource failed query from the database", err)
}
err = tx.Offset(offset).Limit(limit).Find(&dataResource).Error
if err != nil {
return []models.DataResource{}, 0, errort.NewCommonEdgeX(errort.DefaultSystemError, "data resource failed query from the database", err)
}
return dataResource, uint32(total), nil
}

View File

@ -1,120 +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 sqlite
import (
"fmt"
"github.com/winc-link/hummingbird/internal/dtos"
"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/utils"
"github.com/winc-link/hummingbird/internal/tools/sqldb/sqlite"
"gorm.io/gorm"
)
func addRuleEngine(c *Client, ds models.RuleEngine) (id string, edgeXErr error) {
ts := utils.MakeTimestamp()
if ds.Created == 0 {
ds.Created = ts
}
ds.Modified = ts
err := c.client.CreateObject(&ds)
if err != nil {
edgeXErr = errort.NewCommonEdgeX(errort.DefaultSystemError, "rule engine creation failed", err)
}
return ds.Id, edgeXErr
}
func ruleEngineById(c *Client, id string) (ruleEngine models.RuleEngine, edgeXErr error) {
if id == "" {
return ruleEngine, errort.NewCommonEdgeX(errort.DefaultIdEmpty, "rule engine id is empty", nil)
}
err := c.Pool.Table(ruleEngine.TableName()).Preload("DataResource").First(&ruleEngine, id).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return ruleEngine, errort.NewCommonErr(errort.DefaultSystemError, fmt.Errorf("rule engine id id(%s) not found", id))
}
return ruleEngine, errort.NewCommonErr(errort.DefaultSystemError, fmt.Errorf("query rule engine id fail (Id:%s), %s", ruleEngine.Id, err))
}
return
}
func ruleEngineSearch(c *Client, offset int, limit int, req dtos.RuleEngineSearchQueryRequest) (ruleEngine []models.RuleEngine, count uint32, edgeXErr error) {
dp := models.RuleEngine{}
var total int64
tx := c.Pool.Table(dp.TableName())
tx = sqlite.BuildCommonCondition(tx, dp, req.BaseSearchConditionQuery)
if req.Name != "" {
tx = tx.Where("`name` LIKE ?", sqlite.MakeLikeParams(req.Name))
}
if req.Status != "" {
tx = tx.Where("`status` = ?", req.Status)
}
err := tx.Count(&total).Error
if err != nil {
return ruleEngine, 0, errort.NewCommonEdgeX(errort.DefaultSystemError, "rules engine failed query from the database", err)
}
err = tx.Offset(offset).Limit(limit).Preload("DataResource").Find(&ruleEngine).Error
if err != nil {
return ruleEngine, 0, errort.NewCommonEdgeX(errort.DefaultSystemError, "rules engine failed query from the database", err)
}
return ruleEngine, uint32(total), nil
}
func ruleEngineStart(c *Client, id string) error {
d := models.RuleEngine{}
tx := c.Pool.Table(d.TableName())
err := tx.Where("id = ?", id).Updates(map[string]interface{}{"status": constants.RuleStart}).Error
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "start alert rule failed", err)
}
return nil
}
func ruleEngineStop(c *Client, id string) error {
d := models.RuleEngine{}
tx := c.Pool.Table(d.TableName())
err := tx.Where("id = ?", id).Updates(map[string]interface{}{"status": constants.RuleStop}).Error
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "stop alert rule failed", err)
}
return nil
}
func deleteRuleEngineById(c *Client, id string) error {
if id == "" {
return errort.NewCommonEdgeX(errort.DefaultIdEmpty, "rule engine id is empty", nil)
}
err := c.client.DeleteObject(&models.RuleEngine{Id: id})
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "rule engine deletion failed", err)
}
return nil
}
func updateRuleEngine(c *Client, ruleEngine models.RuleEngine) error {
ruleEngine.Modified = utils.MakeTimestamp()
err := c.client.UpdateObject(&ruleEngine)
if err != nil {
return err
}
return nil
}

View File

@ -1,159 +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 sqlite
import (
"fmt"
"github.com/winc-link/hummingbird/internal/dtos"
"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/utils"
"github.com/winc-link/hummingbird/internal/tools/sqldb/sqlite"
"gorm.io/gorm"
)
func addScene(c *Client, ds models.Scene) (scene models.Scene, edgeXErr error) {
ts := utils.MakeTimestamp()
if ds.Created == 0 {
ds.Created = ts
}
ds.Modified = ts
err := c.client.CreateObject(&ds)
if err != nil {
edgeXErr = errort.NewCommonEdgeX(errort.DefaultSystemError, "scene creation failed", err)
}
return ds, edgeXErr
}
func updateScene(c *Client, dl models.Scene) error {
dl.Modified = utils.MakeTimestamp()
err := c.client.UpdateObject(&dl)
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "scene update failed", err)
}
return nil
}
func sceneById(c *Client, id string) (scene models.Scene, err error) {
if id == "" {
return scene, errort.NewCommonEdgeX(errort.DefaultIdEmpty, "scene id is empty", nil)
}
err = c.client.GetObject(&models.Scene{Id: id}, &scene)
if err != nil {
if err == gorm.ErrRecordNotFound {
return scene, errort.NewCommonErr(errort.DefaultResourcesNotFound, fmt.Errorf("scene id(%s) not found", id))
}
return scene, err
}
return
}
func sceneStart(c *Client, id string) error {
d := models.Scene{}
tx := c.Pool.Table(d.TableName())
err := tx.Where("id = ?", id).Updates(map[string]interface{}{"status": constants.SceneStart}).Error
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "start scene rule failed", err)
}
return nil
}
func sceneStop(c *Client, id string) error {
d := models.Scene{}
tx := c.Pool.Table(d.TableName())
err := tx.Where("id = ?", id).Updates(map[string]interface{}{"status": constants.SceneStop}).Error
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "start scene rule failed", err)
}
return nil
}
func deleteSceneById(c *Client, id string) error {
if id == "" {
return errort.NewCommonEdgeX(errort.DefaultIdEmpty, "del scene id is empty", nil)
}
err := c.client.DeleteObject(&models.Scene{Id: id})
if err != nil {
return errort.NewCommonEdgeX(errort.DefaultSystemError, "del scene deletion failed", err)
}
return nil
}
func sceneSearch(c *Client, offset int, limit int, req dtos.SceneSearchQueryRequest) (scene []models.Scene, count uint32, edgeXErr error) {
dp := models.Scene{}
var total int64
tx := c.Pool.Table(dp.TableName())
tx = sqlite.BuildCommonCondition(tx, dp, req.BaseSearchConditionQuery)
if req.Name != "" {
tx = tx.Where("`name` LIKE ?", sqlite.MakeLikeParams(req.Name))
}
if req.Status != "" {
tx = tx.Where("`status` = ?", req.Status)
}
err := tx.Count(&total).Error
if err != nil {
return scene, 0, errort.NewCommonEdgeX(errort.DefaultSystemError, "scene search failed query from the database", err)
}
err = tx.Offset(offset).Limit(limit).Find(&scene).Error
if err != nil {
return scene, 0, errort.NewCommonEdgeX(errort.DefaultSystemError, "scene search failed query from the database", err)
}
return scene, uint32(total), nil
}
func addSceneLog(c *Client, ds models.SceneLog) (sceneLog models.SceneLog, edgeXErr error) {
ts := utils.MakeTimestamp()
if ds.Created == 0 {
ds.Created = ts
}
ds.Modified = ts
err := c.client.CreateObject(&ds)
if err != nil {
edgeXErr = errort.NewCommonEdgeX(errort.DefaultSystemError, "scene log creation failed", err)
}
return ds, edgeXErr
}
func sceneLogSearch(c *Client, offset int, limit int, req dtos.SceneLogSearchQueryRequest) (sceneLogs []models.SceneLog, count uint32, edgeXErr error) {
dp := models.SceneLog{}
var total int64
tx := c.Pool.Table(dp.TableName())
tx = sqlite.BuildCommonCondition(tx, dp, req.BaseSearchConditionQuery)
if req.StartAt > 0 && req.EndAt > 0 && req.EndAt-req.StartAt > 0 {
tx.Where("created > ?", req.StartAt).Where("created < ?", req.EndAt)
}
if req.SceneId != "" {
tx = tx.Where("`scene_id` = ?", req.SceneId)
}
err := tx.Count(&total).Error
if err != nil {
return sceneLogs, 0, errort.NewCommonEdgeX(errort.DefaultSystemError, "scene log search failed query from the database", err)
}
err = tx.Offset(offset).Limit(limit).Find(&sceneLogs).Error
if err != nil {
return sceneLogs, 0, errort.NewCommonEdgeX(errort.DefaultSystemError, "scene log search failed query from the database", err)
}
return sceneLogs, uint32(total), nil
}

View File

@ -21,7 +21,6 @@ import (
"github.com/winc-link/hummingbird/internal/hummingbird/core/application"
"github.com/winc-link/hummingbird/internal/hummingbird/core/application/alertcentreapp"
"github.com/winc-link/hummingbird/internal/hummingbird/core/application/categorytemplate"
"github.com/winc-link/hummingbird/internal/hummingbird/core/application/dataresource"
"github.com/winc-link/hummingbird/internal/hummingbird/core/application/deviceapp"
"github.com/winc-link/hummingbird/internal/hummingbird/core/application/dmi"
"github.com/winc-link/hummingbird/internal/hummingbird/core/application/docapp"
@ -35,11 +34,8 @@ import (
"github.com/winc-link/hummingbird/internal/hummingbird/core/application/persistence"
"github.com/winc-link/hummingbird/internal/hummingbird/core/application/productapp"
"github.com/winc-link/hummingbird/internal/hummingbird/core/application/quicknavigationapp"
"github.com/winc-link/hummingbird/internal/hummingbird/core/application/ruleengine"
"github.com/winc-link/hummingbird/internal/hummingbird/core/application/scene"
"github.com/winc-link/hummingbird/internal/hummingbird/core/application/thingmodelapp"
"github.com/winc-link/hummingbird/internal/hummingbird/core/application/thingmodeltemplate"
"github.com/winc-link/hummingbird/internal/hummingbird/core/application/timerapp"
"github.com/winc-link/hummingbird/internal/hummingbird/core/application/unittemplate"
"github.com/winc-link/hummingbird/internal/hummingbird/core/application/userapp"
"github.com/winc-link/hummingbird/internal/hummingbird/core/config"
@ -55,7 +51,6 @@ import (
"github.com/winc-link/hummingbird/internal/pkg/handlers"
"github.com/winc-link/hummingbird/internal/pkg/logger"
"github.com/winc-link/hummingbird/internal/pkg/startup"
"github.com/winc-link/hummingbird/internal/pkg/timer/jobrunner"
"github.com/winc-link/hummingbird/internal/tools/ekuiperclient"
"github.com/winc-link/hummingbird/internal/tools/hpcloudclient"
"github.com/winc-link/hummingbird/internal/tools/notify/sms"
@ -204,34 +199,6 @@ func (b *Bootstrap) initClient(ctx context.Context, wg *sync.WaitGroup, dic *di.
},
})
ruleEngineApp := ruleengine.NewRuleEngineApp(ctx, dic)
dic.Update(di.ServiceConstructorMap{
container.RuleEngineAppName: func(get di.Get) interface{} {
return ruleEngineApp
},
})
sceneApp := scene.NewSceneApp(ctx, dic)
dic.Update(di.ServiceConstructorMap{
container.SceneAppName: func(get di.Get) interface{} {
return sceneApp
},
})
conJobApp := timerapp.NewCronTimer(ctx, jobrunner.NewJobRunFunc(dic), dic)
dic.Update(di.ServiceConstructorMap{
container.ConJobAppName: func(get di.Get) interface{} {
return conJobApp
},
})
dataResourceApp := dataresource.NewDataResourceApp(ctx, dic)
dic.Update(di.ServiceConstructorMap{
container.DataResourceName: func(get di.Get) interface{} {
return dataResourceApp
},
})
cosApp := cos.NewCos("", "", "")
dic.Update(di.ServiceConstructorMap{
container.CosAppName: func(get di.Get) interface{} {

View File

@ -1,52 +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 interfaces
import (
"context"
"github.com/winc-link/hummingbird/internal/dtos"
//"github.com/winc-link/hummingbird/internal/dtos"
)
type AlertRuleApp interface {
AddAlertRule(ctx context.Context, req dtos.RuleAddRequest) (string, error)
UpdateAlertRule(ctx context.Context, req dtos.RuleUpdateRequest) error
UpdateAlertField(ctx context.Context, req dtos.RuleFieldUpdate) error
AlertRuleById(ctx context.Context, id string) (dtos.RuleResponse, error)
AlertRulesSearch(ctx context.Context, req dtos.AlertRuleSearchQueryRequest) ([]dtos.AlertRuleSearchQueryResponse, uint32, error)
AlertRulesDelete(ctx context.Context, id string) error
AlertRulesStop(ctx context.Context, id string) error
AlertRulesStart(ctx context.Context, id string) error
AlertRulesRestart(ctx context.Context, id string) error
AlertIgnore(ctx context.Context, id string) error
TreatedIgnore(ctx context.Context, id, message string) error
AlertPlate(ctx context.Context, beforeTime int64) ([]dtos.AlertPlateQueryResponse, error)
AlertSearch(ctx context.Context, req dtos.AlertSearchQueryRequest) ([]dtos.AlertSearchQueryResponse, uint32, error)
AddAlert(ctx context.Context, req map[string]interface{}) error
CheckRuleByProductId(ctx context.Context, productId string) error
CheckRuleByDeviceId(ctx context.Context, deviceId string) error
}
type RuleEngineApp interface {
AddRuleEngine(ctx context.Context, req dtos.RuleEngineRequest) (string, error)
UpdateRuleEngine(ctx context.Context, req dtos.RuleEngineUpdateRequest) error
UpdateRuleEngineField(ctx context.Context, req dtos.RuleEngineFieldUpdateRequest) error
RuleEngineById(ctx context.Context, id string) (dtos.RuleEngineResponse, error)
RuleEngineSearch(ctx context.Context, req dtos.RuleEngineSearchQueryRequest) ([]dtos.RuleEngineSearchQueryResponse, uint32, error)
RuleEngineDelete(ctx context.Context, id string) error
RuleEngineStop(ctx context.Context, id string) error
RuleEngineStart(ctx context.Context, id string) error
RuleEngineStatus(ctx context.Context, id string) (map[string]interface{}, error)
}

View File

@ -1,32 +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 interfaces
import (
"context"
"github.com/winc-link/hummingbird/internal/dtos"
"github.com/winc-link/hummingbird/internal/models"
"github.com/winc-link/hummingbird/internal/pkg/constants"
)
type DataResourceApp interface {
AddDataResource(ctx context.Context, req dtos.AddDataResourceReq) (string, error)
DataResourceById(ctx context.Context, id string) (models.DataResource, error)
UpdateDataResource(ctx context.Context, req dtos.UpdateDataResource) error
DelDataResourceById(ctx context.Context, id string) error
DataResourceSearch(ctx context.Context, req dtos.DataResourceSearchQueryRequest) ([]models.DataResource, uint32, error)
DataResourceType(ctx context.Context) []constants.DataResourceType
DataResourceHealth(ctx context.Context, resourceId string) error
}

View File

@ -117,22 +117,6 @@ type DBClient interface {
AddMsgGather(msgGather models.MsgGather) error
MsgGatherSearch(offset int, limit int, req dtos.MsgGatherSearchQueryRequest) (msgGather []models.MsgGather, count uint32, edgeXErr error)
AddDataResource(dateResource models.DataResource) (string, error)
UpdateDataResource(dateResource models.DataResource) error
DelDataResource(id string) error
//DataResourceById(id string) models.DataResource
UpdateDataResourceHealth(id string, health bool) error
SearchDataResource(offset int, limit int, req dtos.DataResourceSearchQueryRequest) (dataResource []models.DataResource, count uint32, edgeXErr error)
DataResourceById(id string) (models.DataResource, error)
AddRuleEngine(ruleEngine models.RuleEngine) (string, error)
UpdateRuleEngine(ruleEngine models.RuleEngine) error
RuleEngineById(id string) (ruleEngine models.RuleEngine, edgeXErr error)
RuleEngineSearch(offset int, limit int, req dtos.RuleEngineSearchQueryRequest) (ruleEngine []models.RuleEngine, count uint32, edgeXErr error)
RuleEngineStart(id string) error
RuleEngineStop(id string) error
DeleteRuleEngineById(id string) error
LanguageSdkByName(name string) (cloudService models.LanguageSdk, edgeXErr error)
LanguageSearch(offset int, limit int, req dtos.LanguageSDKSearchQueryRequest) (languages []models.LanguageSdk, count uint32, edgeXErr error)
AddLanguageSdk(cs models.LanguageSdk) (language models.LanguageSdk, edgeXErr error)
@ -140,7 +124,6 @@ type DBClient interface {
DeviceAlert
UserDB
Scene
SystemMonitor
}
@ -172,16 +155,3 @@ type DeviceAlert interface {
AlertIgnore(id string) (edgeXErr error)
TreatedIgnore(id, message string) (edgeXErr error)
}
type Scene interface {
AddScene(scene models.Scene) (models.Scene, error)
SceneById(id string) (models.Scene, error)
UpdateScene(scene models.Scene) error
SceneStart(id string) error
SceneStop(id string) error
DeleteSceneById(id string) error
SceneSearch(offset int, limit int, req dtos.SceneSearchQueryRequest) (scenes []models.Scene, total uint32, edgeXErr error)
AddSceneLog(sceneLog models.SceneLog) (models.SceneLog, error)
SceneLogSearch(offset int, limit int, req dtos.SceneLogSearchQueryRequest) (sceneLogs []models.SceneLog, total uint32, edgeXErr error)
}

View File

@ -15,25 +15,9 @@
package interfaces
import (
"context"
"github.com/winc-link/hummingbird/internal/dtos"
"github.com/winc-link/hummingbird/internal/models"
"github.com/winc-link/hummingbird/internal/pkg/timer/jobs"
)
type SceneApp interface {
AddScene(ctx context.Context, req dtos.SceneAddRequest) (string, error)
UpdateScene(ctx context.Context, req dtos.SceneUpdateRequest) error
SceneById(ctx context.Context, sceneId string) (models.Scene, error)
SceneStartById(ctx context.Context, sceneId string) error
SceneStopById(ctx context.Context, sceneId string) error
DelSceneById(ctx context.Context, sceneId string) error
SceneSearch(ctx context.Context, req dtos.SceneSearchQueryRequest) ([]models.Scene, uint32, error)
CheckSceneByDeviceId(ctx context.Context, deviceId string) error
SceneLogSearch(ctx context.Context, req dtos.SceneLogSearchQueryRequest) ([]models.SceneLog, uint32, error)
EkuiperNotify(ctx context.Context, req map[string]interface{}) error
}
type ConJob interface {
AddJobToRunQueue(j *jobs.JobSchedule) error
DeleteJob(id string)

View File

@ -36,7 +36,6 @@ func RegisterGateway(engine *gin.Engine, dic *di.Container) {
v1.POST("auth/init-password", ctl.InitPassword)
v1.POST("ekuiper/alert", ctl.EkuiperAlert)
v1.POST("ekuiper/scene", ctl.EkuiperScene) //ekuiper 服务调用
v1.GET("ws/", websocket.NewServer(dic).Handle)
v1Auth := v1.Group("", jwt.JWTAuth(false))
@ -150,41 +149,7 @@ func RegisterGateway(engine *gin.Engine, dic *di.Container) {
v1Auth.POST("alert-treated", ctl.AlertTreated)
}
/*******规则引擎 *******/
{
v1Auth.POST("rule-engine", ctl.RuleEngineAdd)
v1Auth.PUT("rule-engine", ctl.RuleEngineUpdate)
v1Auth.GET("rule-engine/:ruleEngineId", ctl.RuleEngineById)
v1Auth.GET("rule-engine", ctl.RuleEngineSearch)
v1Auth.POST("rule-engine/:ruleEngineId/start", ctl.RuleEngineStart)
v1Auth.POST("rule-engine/:ruleEngineId/stop", ctl.RuleEngineStop)
v1Auth.DELETE("rule-engine/:ruleEngineId/delete", ctl.RuleEngineDelete)
v1Auth.GET("rule-engine/:ruleEngineId/status", ctl.RuleEngineStatus)
}
/*******资源管理 *******/
{
v1Auth.GET("typeresource", ctl.DataResourceType)
v1Auth.PUT("dataresource", ctl.UpdateDataResource)
v1Auth.POST("dataresource", ctl.DataResourceAdd)
v1Auth.DELETE("dataresource/:dataResourceId", ctl.DataResourceDel)
v1Auth.GET("dataresource", ctl.DataResourceSearch)
v1Auth.GET("dataresource/:dataResourceId", ctl.DataResourceById)
v1Auth.POST("dataresource/:dataResourceId/health", ctl.DataResourceHealth)
}
/*******场景联动 *******/
{
v1Auth.POST("scene", ctl.SceneAdd)
v1Auth.PUT("scene", ctl.SceneUpdate)
v1Auth.GET("scene/:sceneId", ctl.SceneById)
v1Auth.GET("scene", ctl.SearchScene)
v1Auth.POST("scene/:sceneId/start", ctl.SceneStart)
v1Auth.POST("scene/:sceneId/stop", ctl.SceneStop)
v1Auth.DELETE("scene/:sceneId", ctl.DeleteScene)
v1Auth.GET("scene/:sceneId/log", ctl.SceneLogSearch)
}
/*******文档中心sdk *******/
{

View File

@ -1,34 +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 models
import "github.com/winc-link/hummingbird/internal/pkg/constants"
type DataResource struct {
Timestamps `gorm:"embedded"`
Id string `json:"id" gorm:"id;primaryKey;not null;type:string;size:255;comment:主键"`
Name string `json:"name" gorm:"type:string;size:255;comment:名字"`
Type constants.DataResourceType `json:"type" gorm:"type:string;size:50;comment:类型"`
Health bool `json:"health" gorm:"comment:验证"`
Option MapStringInterface `json:"option" gorm:"type:text;comment:资源内容"`
}
func (d *DataResource) TableName() string {
return "data_resource"
}
func (d *DataResource) Get() interface{} {
return *d
}

View File

@ -1,54 +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 models
import (
"database/sql/driver"
"github.com/winc-link/hummingbird/internal/pkg/constants"
)
type RuleEngine struct {
Timestamps `gorm:"embedded"`
Id string `gorm:"id;primaryKey;not null;type:string;size:255;comment:主键"`
Name string `gorm:"type:string;size:255;comment:名字"`
Description string `gorm:"type:text;comment:描述"`
Status constants.RuleEngineStatus `gorm:"type:string;size:50;comment:状态"`
Filter Filter
DataResourceId string `gorm:"type:string;size:255;comment:资源ID"`
DataResource DataResource `gorm:"foreignKey:DataResourceId"`
}
func (d *RuleEngine) TableName() string {
return "rule_engine"
}
func (d *RuleEngine) Get() interface{} {
return *d
}
type Filter struct {
MessageSource string `json:"message_source" gorm:"type:string;size:255;comment:消息源"`
SelectName string `json:"select_name" gorm:"type:string;size:255;comment:选择字段"`
Condition string `json:"condition" gorm:"type:string;size:255;comment:条件"`
Sql string `json:"sql" gorm:"type:string;size:255;comment:sql"`
}
func (c Filter) Value() (driver.Value, error) {
return GormValueWrap(c)
}
func (c *Filter) Scan(value interface{}) error {
return GormScanWrap(value, c)
}

View File

@ -1,103 +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 models
import (
"database/sql/driver"
"github.com/winc-link/hummingbird/internal/pkg/constants"
"github.com/winc-link/hummingbird/internal/pkg/timer/jobs"
)
type Scene struct {
Timestamps `gorm:"embedded"`
Id string `json:"id" gorm:"id;primaryKey;not null;type:string;size:255;comment:主键"`
Name string `json:"name" gorm:"type:string;size:255;comment:名字"`
Description string `json:"description" gorm:"type:text;comment:描述"`
Status constants.SceneStatus `json:"status" gorm:"type:string;size:50;comment:状态"`
Conditions Conditions `json:"conditions" gorm:"type:text;comment:条件"`
Actions Actions2 `json:"actions" gorm:"type:text;comment:动作"`
}
func (d *Scene) TableName() string {
return "scene"
}
func (d *Scene) Get() interface{} {
return *d
}
func (d *Scene) ToRuntimeJob() (schedule *jobs.JobSchedule, err error) {
var (
rj = jobs.RuntimeJobStu{
JobID: d.Id,
JobName: d.Name,
Description: d.Description,
Status: string(d.Status),
//Runtimes: d.ScheduleTimes,
}
)
rj.TimeData = jobs.TimeData{
Expression: d.Conditions[0].Option["cron_expression"],
}
for _, action := range d.Actions {
rj.JobData.ActionData = append(rj.JobData.ActionData, jobs.DeviceMeta{
ProductId: action.ProductID,
ProductName: action.ProductName,
DeviceId: action.DeviceID,
DeviceName: action.DeviceName,
Code: action.Code,
DateType: action.DataType,
Value: action.Value,
})
}
return jobs.NewJobSchedule(&rj)
}
type Conditions []Condition
type Condition struct {
ConditionType string `json:"condition_type"`
Option MapStringString `json:"option"`
}
func (c Conditions) Value() (driver.Value, error) {
return GormValueWrap(c)
}
func (c *Conditions) Scan(value interface{}) error {
return GormScanWrap(value, c)
}
type Actions2 []Action
type Action struct {
ProductID string `json:"product_id"`
ProductName string `json:"product_name"`
DeviceID string `json:"device_id"`
DeviceName string `json:"device_name"`
Code string `json:"code"`
DataType string `json:"data_type"`
Value string `json:"value"`
}
func (c Actions2) Value() (driver.Value, error) {
return GormValueWrap(c)
}
func (c *Actions2) Scan(value interface{}) error {
return GormScanWrap(value, c)
}

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 models
type (
SceneLog struct {
Timestamps `gorm:"embedded"`
Id string `gorm:"id;primaryKey;not null;type:string;size:255;comment:主键"`
SceneId string `gorm:"index;type:string;size:255;comment:场景ID" json:"scene_id"`
Name string `json:"name" gorm:"type:string;size:255;comment:名字"`
ExecRes string `json:"exec_res" gorm:"type:text;comment:执行结果"`
}
)
func (pj *SceneLog) TableName() string {
return "scene_log"
}
func (pj *SceneLog) Get() interface{} {
return *pj
}

View File

@ -1,52 +0,0 @@
package jobrunner
import (
"github.com/winc-link/hummingbird/internal/dtos"
coreContainer "github.com/winc-link/hummingbird/internal/hummingbird/core/container"
"github.com/winc-link/hummingbird/internal/models"
"github.com/winc-link/hummingbird/internal/pkg/container"
"github.com/winc-link/hummingbird/internal/pkg/timer/jobs"
"time"
"github.com/winc-link/hummingbird/internal/pkg/di"
)
type JobRunFunc func(jobId string, job jobs.JobSchedule)
func NewJobRunFunc(dic *di.Container) JobRunFunc {
logger := container.LoggingClientFrom(dic.Get)
return func(jobId string, job jobs.JobSchedule) {
start := time.Now()
defer func() {
logger.Infof("JobRunFunc cost: %v ms", time.Since(start).Milliseconds())
}()
logger.Infof("JobId: %v, job in: %+v", jobId, job.RuntimeJobStu)
//调用驱动
s := job.JobData
deviceApp := coreContainer.DeviceItfFrom(dic.Get)
res := deviceApp.DeviceAction(dtos.JobAction{
ProductId: s.ActionData[0].ProductId,
ProductName: s.ActionData[0].ProductName,
DeviceId: s.ActionData[0].DeviceId,
DeviceName: s.ActionData[0].DeviceName,
Code: s.ActionData[0].Code,
DateType: s.ActionData[0].DateType,
Value: s.ActionData[0].Value,
})
dbClient := coreContainer.DBClientFrom(dic.Get)
_, err := dbClient.AddSceneLog(models.SceneLog{
SceneId: job.JobID,
Name: job.JobName,
ExecRes: res.ToString(),
})
if err != nil {
logger.Errorf("add sceneLog err %v", err.Error())
}
}
}

View File

@ -37,10 +37,12 @@ DataSource = 'hummingbird/db-data/core-data/core.db?_timeout=5000'
[Databases.Data]
[Databases.Data.Primary]
Type = 'leveldb'
DataSource = 'hummingbird/db-data/leveldb-core-data/'
#Type = 'tstorage'
#DataSource = 'manifest/docker/db-data/tstorage-data/'
#Type = 'tdengine'
#Dsn = 'root:taosdata@ws(127.0.0.1:6041)/hummingbird'
Type = 'leveldb'
DataSource = 'manifest/docker/db-data/leveldb-core-data/'
[MessageQueue]
Protocol = 'tcp'

View File

@ -0,0 +1 @@
{"minTimestamp":0,"maxTimestamp":0,"numDataPoints":0,"metrics":{},"createdAt":"2025-04-01T10:39:08.093705+08:00"}