init project

master
winc-link 2023-08-28 14:49:44 +08:00
parent 9651abf31c
commit c2761600e0
299 changed files with 38312 additions and 0 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

7
.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
.idea
vendor
logs
edge-db-data
hummingbird
mqtt-broker
go.sum

13
Makefile Normal file
View File

@ -0,0 +1,13 @@
.PHONY: build clean test docker run
GO=CGO_ENABLED=0 GOOS=linux go
GOCGO=CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go
cmd/hummingbird-core/hummingbird-core:
$(GOCGO) build -ldflags "-s -w" -o $@ ./cmd/hummingbird-core
cmd/mqtt-broker/mqtt-broker:
$(GO) build -ldflags "-s -w" -o $@ ./cmd/mqtt-broker
generate/api:
cd cmd/hummingbird-core && swag init --parseDependency --parseInternal --parseDepth 10

98
README.md Normal file
View File

@ -0,0 +1,98 @@
<p align="center">
<img src="manifest/image/logo.png" width="100">
<br>
<a href='https://gitee.com/winc-link/hummingbird/stargazers'>
<img src='https://gitee.com/winc-link/hummingbird/badge/star.svg?theme=gvp' alt='star'></img>
</a>
<a href='https://gitee.com/winc-link/hummingbird/members'>
<img src='https://gitee.com/winc-link/hummingbird/badge/fork.svg?theme=gvp' alt='fork'></img>
</a>
<br>
</p>
# 产品简介
蜂鸟HummingBird 是Golang语言实现的超轻量级物联网开发平台他的核心服务完全由团队自行研发从这个平台设计之初轻量级、性能优异当作我们的一条开发准则。所以它服务都是采用Golang语言编写占用内存极低。在数据存储上我们创新的使用了SQLite和LevelDB当作了我们存储数据库得益于SQLite的轻量级和LevelDB对数据的高吞吐和高压缩的特点 经过实际测试在1C/1G 100G存储的物理机上可实现数千设备的连接和8000W条的消息存储。
当然如果您对数据有可靠行、海量存储等要求您完全可以把SQLite和LevelDB换为MySQL和TDengine蜂鸟物联网平台兼容多种数据库连接用户可以根据自己的业务需要选择适合自己的数据库。
“麻雀(蜂鸟)虽小,五脏俱全” 虽然蜂鸟作为一个超轻量级物联网平台,但是他的核心功能并不会消减。设备接入、产品管理、物模型、告警中心、规则引擎...这些所有物联网平台的标配功能,都可以在本平台中找到。
![](manifest/image/architecture.png)
# 部分页面展示
| ![](manifest/image/1.png) | ![](manifest/image/2.png) |
|:------------------------------------------------------------------------|:----------------------------------------------------------------------------|
| ![](manifest/image/3.png)) | ![](manifest/image/4.png) |
| ![](manifest/image/5.png) | ![](manifest/image/6.png) |
| ![](manifest/image/7.png) | ![](manifest/image/8.png) |
# 在线演示
演示地址https://demo.winc-link.com
账号admin
密码123456
# 官方文档
官方文档地址https://doc.hummingbird.winc-link.com/
# 主要功能
- 产品管理
- 设备管理
- 镜像管理
- 驱动管理
- 驱动市场
- 系统监控
- 告警中心
- 资源管理
- 规则引擎
- 场景联动
- 插件市场(企业版本)
- 数据大屏(企业版本)
# 产品优势
- **免费开源**:我们源代码全部开源,可供个人学。
- **性能优异**经过实际测试在2C4G主机上可支持60k的设备连接。模拟4k设备以1000ms的间隔向服务端发送16kb长度的属性数据cpu使用率稳定在百分之60、内存使用率稳定在百分之16。
- **多数据支持**平台支持SQLite、LevelDB和MySQL、TDengine数据库用户可以根据自己的项目需要选择适合自己的数据库。
- **云插件**平台实现了阿里云、腾讯云、华为云、oneNet等物联网平台的对接支持把数据上报到各大物联网平台中。
- **支持可视化大屏**:用户只需要进行简单拖拽,无需写任何代码,即可完成可视化大屏开发设计。
- **内置产品模版库** 平台内部预置产品模版390条帮助用户一键创建产品。
- **文档清晰**:平台文档清晰完整,文档内部有大量使用案例和视频教程,帮助用户快速理解产品和使用产品。
- **部署简单**平台所有服务都是以docker形式运行支持docker-compose命令一键启动。
- **成本优势**:在中小型物联网项目(设备数<=5000只需要2C4G主机即可并且还可以支持本地部署。
# 讨论区
我们正在使用讨论作为与我们社区其他成员联系的地方。您可以在([Gitee](https://gitee.com/winc-link/hummingbird/issues/I7WC1A)
下方发表你的评论,告诉大家你要讨论的问题、关于 Hummingbird 好的发展建议、一些奇思妙想 🚀🛸🚤!
# 联系我们
如果你在使用或者部署过程遇到任何问题,请在 QQ 群讨论或者联系作者微信。
🌟 请记住我们不收费,代码完全开源,如果你想把蜂鸟物联网平台进行商用,请提前找作者授权!最后请点个 Start 鼓励我们吧!🌟
<p align="center">
<img src="manifest/image/jietu.png" width="600">
<br>
# 开源贡献
- 从 `master` 分支 `checkout` 一个新分支(**注**:请务必保证 `master` 代码是最新的)
- 新分支命名格式:`feature/username/description`,例如:`feature/pick/mqtt_driver`
- 在新分支上编辑文档、代码,并提交代码
- 提交 `PR` 合并到 `develop` 分支,等待作者合并即可
# 开源协议
`Hummingbird` 开源平台遵循 [Apache 2.0 协议](https://www.apache.org/licenses/LICENSE-2.0.html) 如果你想把蜂鸟物联网平台进行商用,请提前找作者授权!

BIN
cmd/.DS_Store vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,44 @@
# ----------------------------------------------------------------------------------
# Copyright 2018 Dell Technologies, Inc.
# Copyright 2018 Cavium
#
# 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.
#
# ----------------------------------------------------------------------------------
ARG BUILDER_BASE=registry.cn-shanghai.aliyuncs.com/winc-edgex/edgex:1.18.8-alpine3.16
FROM ${BUILDER_BASE} AS builder
WORKDIR /edge
COPY . .
RUN make cmd/hummingbird-core/hummingbird-core
#Next image - Copy built Go binary into new workspace
FROM alpine:3.16
ENV APP_PORT=58081
ENV WEB_PORT=3000
EXPOSE $APP_PORT
EXPOSE $WEB_PORT
WORKDIR /var/bin/
COPY --from=builder /edge/cmd/hummingbird-core/hummingbird-core /bin/
COPY --from=builder /edge/cmd/hummingbird-core/res/configuration.toml.dist /etc/hummingbird-core/configuration.toml
COPY --from=builder /edge/cmd/hummingbird-ui/build /var/bin/cmd/hummingbird-ui/build
CMD ["/bin/sh", "-c", "/bin/hummingbird-core --confdir=/etc/hummingbird-core/configuration.toml"]

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,40 @@
/*******************************************************************************
* Copyright 2018 Dell Inc.
*
* 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 main
import (
"context"
"github.com/winc-link/hummingbird/internal/hummingbird/core"
"github.com/gin-gonic/gin"
)
// @title 赢创万联(蜂鸟) API
// @version 1.0
// @description Swagger API for Golang Project hummingbird.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.email email@winc-link.com
// @BasePath /api/v1
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name x-token
func main() {
ctx, cancel := context.WithCancel(context.Background())
gin.SetMode(gin.ReleaseMode)
core.Main(ctx, cancel, gin.Default())
}

View File

@ -0,0 +1,50 @@
[Writable]
LogLevel = 'INFO'
LogPath = 'hummingbird/logs/hummingbird-core.log'
[Service]
BootTimeout = 30000
CheckInterval = '10s'
Host = '0.0.0.0'
ServerBindAddr = '' # Leave blank so default to Host value unless different value is needed.
Port = 58081
Protocol = 'http'
MaxResultCount = 50000
StartupMsg = 'This is the Core Resource Microservice'
Timeout = 45000
[RpcServer]
Address = '0.0.0.0:57081'
UseTLS = false
CertFile = ''
KeyFile = ''
[Clients]
[Clients.Ekuiper]
Protocol = 'http'
Host = '127.0.0.1'
Port = 9081
[WebServer]
Host = '0.0.0.0'
Port = 3000
Timeout = 120
[Databases]
[Databases.Metadata]
[Databases.Metadata.Primary]
Type = 'sqlite'
DataSource = 'hummingbird/db-data/core-data/core.db?_timeout=5000'
[Databases.Data]
[Databases.Data.Primary]
Type = 'leveldb'
DataSource = 'hummingbird/db-data/leveldb-core-data/'
[MessageQueue]
Protocol = 'tcp'
Host = '127.0.0.1'
Port = 58090
Type = 'mqtt'
PublishTopicPrefix = 'eventbus/in'

View File

@ -0,0 +1,49 @@
[Writable]
LogLevel = 'INFO'
LogPath = 'hummingbird/logs/hummingbird-core.log'
[Service]
BootTimeout = 30000
CheckInterval = '10s'
Host = '0.0.0.0'
ServerBindAddr = '' # Leave blank so default to Host value unless different value is needed.
Port = 58081
Protocol = 'http'
MaxResultCount = 50000
StartupMsg = 'This is the Core Resource Microservice'
Timeout = 45000
[RpcServer]
Address = '0.0.0.0:57081'
UseTLS = false
CertFile = ''
KeyFile = ''
[Clients]
[Clients.Ekuiper]
Protocol = 'http'
Host = 'ekuiper'
Port = 9081
[WebServer]
Host = '0.0.0.0'
Port = 3000
Timeout = 120
[Databases]
[Databases.Metadata]
[Databases.Metadata.Primary]
Type = 'sqlite'
DataSource = 'hummingbird/db-data/core-data/core.db?_timeout=5000'
[Databases.Data]
[Databases.Data.Primary]
Type = 'leveldb'
DataSource = 'hummingbird/db-data/leveldb-core-data/'
[MessageQueue]
Protocol = 'tcp'
Host = 'mqtt-broker'
Port = 58090
Type = 'mqtt'
PublishTopicPrefix = 'eventbus/in'

View File

@ -0,0 +1,33 @@
{
"files": {
"main.css": "/static/css/main.21abe5ff.css",
"main.js": "/static/js/main.4ec9d86b.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",
"static/js/258.efff4014.chunk.js": "/static/js/258.efff4014.chunk.js",
"static/js/787.d3befce1.chunk.js": "/static/js/787.d3befce1.chunk.js",
"ts.worker.js": "/ts.worker.js",
"json.worker.js": "/json.worker.js",
"editor.worker.js": "/editor.worker.js",
"static/media/head-bg.8b029587.png": "/static/media/head-bg.8b029587.60f3a93d8a581efd4c49.png",
"static/media/bg.ad187fed.png": "/static/media/bg.ad187fed.a47d112f49f56eb1cfa5.png",
"static/media/codicon.ttf": "/static/media/codicon.b797181c93b3755f4fa1.ttf",
"static/media/bg-1.7f3acdfb.png": "/static/media/bg-1.7f3acdfb.aad6275b1801455a76c0.png",
"static/media/newlogo.png": "/static/media/newlogo.e2ad3c36f34a1c2c10d1.png",
"static/media/default.32752796.png": "/static/media/default.32752796.9e3b4c5313ccb5060485.png",
"static/media/background.png": "/static/media/background.8ed5e5404edf817e15f5.png",
"index.html": "/index.html",
"main.21abe5ff.css.map": "/static/css/main.21abe5ff.css.map",
"main.4ec9d86b.js.map": "/static/js/main.4ec9d86b.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",
"258.efff4014.chunk.js.map": "/static/js/258.efff4014.chunk.js.map",
"787.d3befce1.chunk.js.map": "/static/js/787.d3befce1.chunk.js.map"
},
"entrypoints": [
"static/css/main.21abe5ff.css",
"static/js/main.4ec9d86b.js"
]
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

@ -0,0 +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.4ec9d86b.js"></script><link href="/static/css/main.21abe5ff.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,8 @@
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
/*!-----------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Version: 0.34.1(547870b6881302c5b4ff32173c16d06009e3588f)
* Released under the MIT license
* https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
*-----------------------------------------------------------------------------*/

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "logo.png",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/png"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,6 @@
/*!-----------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Version: 0.34.1(547870b6881302c5b4ff32173c16d06009e3588f)
* Released under the MIT license
* https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
*-----------------------------------------------------------------------------*/

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,2 @@
"use strict";(self.webpackChunkmyapp=self.webpackChunkmyapp||[]).push([[787],{787:function(e,t,n){n.r(t),n.d(t,{getCLS:function(){return y},getFCP:function(){return g},getFID:function(){return C},getLCP:function(){return P},getTTFB:function(){return D}});var i,r,a,o,u=function(e,t){return{name:e,value:void 0===t?-1:t,delta:0,entries:[],id:"v2-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12)}},c=function(e,t){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){if("first-input"===e&&!("PerformanceEventTiming"in self))return;var n=new PerformanceObserver((function(e){return e.getEntries().map(t)}));return n.observe({type:e,buffered:!0}),n}}catch(e){}},f=function(e,t){var n=function n(i){"pagehide"!==i.type&&"hidden"!==document.visibilityState||(e(i),t&&(removeEventListener("visibilitychange",n,!0),removeEventListener("pagehide",n,!0)))};addEventListener("visibilitychange",n,!0),addEventListener("pagehide",n,!0)},s=function(e){addEventListener("pageshow",(function(t){t.persisted&&e(t)}),!0)},m=function(e,t,n){var i;return function(r){t.value>=0&&(r||n)&&(t.delta=t.value-(i||0),(t.delta||void 0===i)&&(i=t.value,e(t)))}},v=-1,p=function(){return"hidden"===document.visibilityState?0:1/0},d=function(){f((function(e){var t=e.timeStamp;v=t}),!0)},l=function(){return v<0&&(v=p(),d(),s((function(){setTimeout((function(){v=p(),d()}),0)}))),{get firstHiddenTime(){return v}}},g=function(e,t){var n,i=l(),r=u("FCP"),a=function(e){"first-contentful-paint"===e.name&&(f&&f.disconnect(),e.startTime<i.firstHiddenTime&&(r.value=e.startTime,r.entries.push(e),n(!0)))},o=window.performance&&performance.getEntriesByName&&performance.getEntriesByName("first-contentful-paint")[0],f=o?null:c("paint",a);(o||f)&&(n=m(e,r,t),o&&a(o),s((function(i){r=u("FCP"),n=m(e,r,t),requestAnimationFrame((function(){requestAnimationFrame((function(){r.value=performance.now()-i.timeStamp,n(!0)}))}))})))},h=!1,T=-1,y=function(e,t){h||(g((function(e){T=e.value})),h=!0);var n,i=function(t){T>-1&&e(t)},r=u("CLS",0),a=0,o=[],v=function(e){if(!e.hadRecentInput){var t=o[0],i=o[o.length-1];a&&e.startTime-i.startTime<1e3&&e.startTime-t.startTime<5e3?(a+=e.value,o.push(e)):(a=e.value,o=[e]),a>r.value&&(r.value=a,r.entries=o,n())}},p=c("layout-shift",v);p&&(n=m(i,r,t),f((function(){p.takeRecords().map(v),n(!0)})),s((function(){a=0,T=-1,r=u("CLS",0),n=m(i,r,t)})))},E={passive:!0,capture:!0},w=new Date,L=function(e,t){i||(i=t,r=e,a=new Date,F(removeEventListener),S())},S=function(){if(r>=0&&r<a-w){var e={entryType:"first-input",name:i.type,target:i.target,cancelable:i.cancelable,startTime:i.timeStamp,processingStart:i.timeStamp+r};o.forEach((function(t){t(e)})),o=[]}},b=function(e){if(e.cancelable){var t=(e.timeStamp>1e12?new Date:performance.now())-e.timeStamp;"pointerdown"==e.type?function(e,t){var n=function(){L(e,t),r()},i=function(){r()},r=function(){removeEventListener("pointerup",n,E),removeEventListener("pointercancel",i,E)};addEventListener("pointerup",n,E),addEventListener("pointercancel",i,E)}(t,e):L(t,e)}},F=function(e){["mousedown","keydown","touchstart","pointerdown"].forEach((function(t){return e(t,b,E)}))},C=function(e,t){var n,a=l(),v=u("FID"),p=function(e){e.startTime<a.firstHiddenTime&&(v.value=e.processingStart-e.startTime,v.entries.push(e),n(!0))},d=c("first-input",p);n=m(e,v,t),d&&f((function(){d.takeRecords().map(p),d.disconnect()}),!0),d&&s((function(){var a;v=u("FID"),n=m(e,v,t),o=[],r=-1,i=null,F(addEventListener),a=p,o.push(a),S()}))},k={},P=function(e,t){var n,i=l(),r=u("LCP"),a=function(e){var t=e.startTime;t<i.firstHiddenTime&&(r.value=t,r.entries.push(e),n())},o=c("largest-contentful-paint",a);if(o){n=m(e,r,t);var v=function(){k[r.id]||(o.takeRecords().map(a),o.disconnect(),k[r.id]=!0,n(!0))};["keydown","click"].forEach((function(e){addEventListener(e,v,{once:!0,capture:!0})})),f(v,!0),s((function(i){r=u("LCP"),n=m(e,r,t),requestAnimationFrame((function(){requestAnimationFrame((function(){r.value=performance.now()-i.timeStamp,k[r.id]=!0,n(!0)}))}))}))}},D=function(e){var t,n=u("TTFB");t=function(){try{var t=performance.getEntriesByType("navigation")[0]||function(){var e=performance.timing,t={entryType:"navigation",startTime:0};for(var n in e)"navigationStart"!==n&&"toJSON"!==n&&(t[n]=Math.max(e[n]-e.navigationStart,0));return t}();if(n.value=n.delta=t.responseStart,n.value<0||n.value>performance.now())return;n.entries=[t],e(n)}catch(e){}},"complete"===document.readyState?setTimeout(t,0):addEventListener("load",(function(){return setTimeout(t,0)}))}}}]);
//# sourceMappingURL=787.d3befce1.chunk.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,117 @@
/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/*! @license DOMPurify 2.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.3.1/LICENSE */
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
/*!-----------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Version: 0.34.1(547870b6881302c5b4ff32173c16d06009e3588f)
* Released under the MIT license
* https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
*-----------------------------------------------------------------------------*/
/**
* @license
* Lodash <https://lodash.com/>
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* use-sync-external-store-shim.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @remix-run/router v1.0.3
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
/**
* React Router DOM v6.4.3
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
/**
* React Router v6.4.3
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
/** @license React v16.13.1
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,8 @@
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
/*!-----------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Version: 0.34.1(547870b6881302c5b4ff32173c16d06009e3588f)
* Released under the MIT license
* https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
*-----------------------------------------------------------------------------*/

File diff suppressed because one or more lines are too long

157
go.mod Normal file
View File

@ -0,0 +1,157 @@
module github.com/winc-link/hummingbird
go 1.18
require (
github.com/BurntSushi/toml v1.1.0
github.com/alexmullins/zip v0.0.0-20180717182244-4affb64b04d0
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/docker/distribution v2.8.1+incompatible
github.com/docker/docker v20.10.17+incompatible
github.com/docker/go-connections v0.4.0
github.com/eclipse/paho.mqtt.golang v1.4.2
github.com/gin-contrib/pprof v1.4.0
github.com/gin-contrib/static v0.0.1
github.com/gin-gonic/gin v1.8.1
github.com/go-gormigrate/gormigrate/v2 v2.0.0
github.com/gogf/gf/v2 v2.5.0
github.com/golang/mock v1.5.0
github.com/golang/protobuf v1.5.2
github.com/gomodule/redigo v1.8.9
github.com/google/uuid v1.3.0
github.com/gorilla/schema v1.2.0
github.com/gorilla/websocket v1.5.0
github.com/grpc-ecosystem/go-grpc-middleware v1.3.0
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0
github.com/grpc-ecosystem/grpc-gateway v1.16.0
github.com/hashicorp/go-sockaddr v1.0.0
github.com/hashicorp/logutils v1.0.0
github.com/hashicorp/serf v0.8.2
github.com/hpcloud/tail v1.0.0
github.com/influxdata/influxdb1-client v0.0.0-20220302092344-a9ab5670611c
github.com/jinzhu/gorm v1.9.16
github.com/kirinlabs/HttpRequest v1.1.1
github.com/mitchellh/mapstructure v1.4.3
github.com/nicksnyder/go-i18n/v2 v2.2.0
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pelletier/go-toml v1.9.5
github.com/pelletier/go-toml/v2 v2.0.5
github.com/pkg/errors v0.9.1
github.com/robfig/cron/v3 v3.0.1
github.com/shirou/gopsutil/v3 v3.22.2
github.com/spf13/cobra v1.5.0
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.8.0
github.com/swaggo/files v0.0.0-20220728132757-551d4a08d97a
github.com/swaggo/gin-swagger v1.5.3
github.com/swaggo/swag v1.8.7
github.com/syndtr/goleveldb v1.0.0
github.com/taosdata/driver-go/v3 v3.5.0
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.617
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms v1.0.617
github.com/tencentyun/cos-go-sdk-v5 v0.7.39
github.com/winc-link/edge-driver-proto v0.0.0-20230208100708-287ba270a685
github.com/xuri/excelize/v2 v2.5.0
go.uber.org/atomic v1.9.0
go.uber.org/zap v1.21.0
golang.org/x/crypto v0.5.0
golang.org/x/sys v0.4.0
golang.org/x/text v0.6.0
golang.org/x/time v0.0.0-20220609170525-579cf78fd858
google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c
google.golang.org/grpc v1.49.0
google.golang.org/protobuf v1.28.1
gopkg.in/natefinch/lumberjack.v2 v2.0.0
gopkg.in/yaml.v2 v2.4.0
gopkg.in/yaml.v3 v3.0.1
gorm.io/driver/mysql v1.0.1
gorm.io/driver/sqlite v1.3.6
gorm.io/gorm v1.23.8
)
require (
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/Microsoft/go-winio v0.5.2 // indirect
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/clbanning/mxj v1.8.4 // indirect
github.com/clbanning/mxj/v2 v2.5.5 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/docker/go-units v0.4.0 // indirect
github.com/fatih/color v1.13.0 // indirect
github.com/fsnotify/fsnotify v1.5.4 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-logr/logr v1.2.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/jsonreference v0.20.0 // indirect
github.com/go-openapi/spec v0.20.7 // indirect
github.com/go-openapi/swag v0.22.3 // indirect
github.com/go-playground/locales v0.14.0 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/go-playground/validator/v10 v10.11.1 // indirect
github.com/go-sql-driver/mysql v1.5.0 // indirect
github.com/goccy/go-json v0.9.11 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db // indirect
github.com/google/btree v1.0.0 // indirect
github.com/google/go-querystring v1.0.0 // indirect
github.com/grokify/html-strip-tags-go v0.0.1 // indirect
github.com/hashicorp/errwrap v1.0.0 // indirect
github.com/hashicorp/go-immutable-radix v1.0.0 // indirect
github.com/hashicorp/go-msgpack v0.5.3 // indirect
github.com/hashicorp/go-multierror v1.0.0 // indirect
github.com/hashicorp/golang-lru v0.5.1 // indirect
github.com/hashicorp/memberlist v0.1.3 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-colorable v0.1.9 // indirect
github.com/mattn/go-isatty v0.0.16 // indirect
github.com/mattn/go-runewidth v0.0.9 // indirect
github.com/mattn/go-sqlite3 v1.14.12 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/miekg/dns v1.0.14 // indirect
github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/morikuni/aec v1.0.0 // indirect
github.com/mozillazg/go-httpheader v0.2.1 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.0.2 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
github.com/prometheus/client_golang v1.13.0 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.37.0 // indirect
github.com/prometheus/procfs v0.8.0 // indirect
github.com/richardlehane/mscfb v1.0.3 // indirect
github.com/richardlehane/msoleps v1.0.1 // indirect
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 // indirect
github.com/sirupsen/logrus v1.9.0 // indirect
github.com/tklauser/go-sysconf v0.3.9 // indirect
github.com/tklauser/numcpus v0.3.0 // indirect
github.com/ugorji/go/codec v1.2.7 // indirect
github.com/xuri/efp v0.0.0-20210322160811-ab561f5b45e3 // indirect
github.com/yusufpapurcu/wmi v1.2.2 // indirect
go.opentelemetry.io/otel v1.7.0 // indirect
go.opentelemetry.io/otel/sdk v1.7.0 // indirect
go.opentelemetry.io/otel/trace v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
golang.org/x/net v0.5.0 // indirect
golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f // indirect
golang.org/x/tools v0.2.0 // indirect
gopkg.in/fsnotify.v1 v1.4.7 // indirect
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
gotest.tools/v3 v3.3.0 // indirect
)

130
internal/dtos/agent.go Normal file
View File

@ -0,0 +1,130 @@
//
// Copyright (C) 2021 IOTech Ltd
//
// SPDX-License-Identifier: Apache-2.0
package dtos
import (
"encoding/json"
"github.com/winc-link/hummingbird/internal/models"
//"gitlab.com/tedge/edgex/internal/models"
)
// swagger:response ServicesStats
type ServicesStats []ServiceStats
func (s ServicesStats) Len() int {
return len(s)
}
func (s ServicesStats) Less(i, j int) bool {
return s[i].Name < s[j].Name
}
func (s ServicesStats) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
type ServiceStats struct {
Id string `json:"id" binding:"required"` //
Name string `json:"name" binding:"required"`
Healthy bool `json:"healthy"` // 健康状态
Created string `json:"created"`
LogPath string `json:"log_path"` // 日志地址, 宿主主机日志路径
Started string `json:"started"` // 服务最近启动时间
ServiceType string `json:"service_type" binding:"required"`
}
func FromModelsServiceStatsToDTO(s models.ServiceStats) ServiceStats {
return ServiceStats{
Id: s.Id,
Name: s.Name,
Healthy: s.Healthy,
Created: s.Created,
Started: s.Started,
LogPath: s.LogPath,
ServiceType: s.ServiceType,
}
}
func FromDTOServiceStatsToModel(s ServiceStats) models.ServiceStats {
return models.ServiceStats{
Id: s.Id,
Name: s.Name,
Healthy: s.Healthy,
Created: s.Created,
Started: s.Started,
LogPath: s.LogPath,
ServiceType: s.ServiceType,
}
}
type Logging struct {
Log string `json:"log"`
}
type MetricsQuery struct {
Service string `form:"service" binding:"required"` // 服务ID
MetricsType string `form:"metrics_type" binding:"oneof=minute hour halfday day"` // 监控类型,范围: minute hour halfday day
MetricsRangeQuery
}
type SystemMetricsQuery struct {
Iface string `form:"iface"`
MetricsType string `form:"metrics_type" binding:"oneof=hour halfday day"`
}
type MetricsRangeQuery struct {
Start int64 `form:"start" binding:"gt=0"` // 开始时间戳
End int64 `form:"end" binding:"gt=0"` // 结束时间戳
}
// swagger:response MetricsResult
type MetricsResult struct {
Total int `json:"total"`
Metrics []Metrics `json:"metrics"` // 性能点列表
}
type Metrics struct {
Timestamp int64 `json:"timestamp"` // 时间戳
CpuUsedPercent float64 `json:"cpuUsedPercent"` // cpu 使用率百分比
MemoryUsed int64 `json:"memoryUsed"` // 内存使用大小,单位:字节
}
func FromModelsMetricsToDTO(m models.Metrics) Metrics {
return Metrics{
Timestamp: m.Timestamp,
CpuUsedPercent: m.CpuUsedPercent,
MemoryUsed: m.MemoryUsed,
}
}
func (m Metrics) ToJSON() string {
marshal, _ := json.Marshal(m)
return string(marshal)
}
type LogParam struct {
Line int `form:"line"`
}
type TerminalParams struct {
Cmd string `json:"cmd" binding:"required"`
Args []string `json:"args" binding:"required"`
TimeoutSeconds int `json:"timeout_seconds" binding:"min=1,max=60"`
}
type AgentRequest struct {
Cmd string `json:"cmd"`
Args []string `json:"args"`
TimeoutSeconds int `json:"timeout_seconds"`
}
type AgentResponse struct {
Operation string `json:"operation"`
Service string `json:"service"`
Executor string `json:"executor"`
Success bool `json:"success"`
ErrorMessage string `json:"errorMessage"`
}

106
internal/dtos/alert.go Normal file
View File

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

308
internal/dtos/alertrule.go Normal file
View File

@ -0,0 +1,308 @@
/*******************************************************************************
* 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 (
"fmt"
"github.com/winc-link/hummingbird/internal/models"
"github.com/winc-link/hummingbird/internal/pkg/constants"
"strings"
)
type RuleAddRequest struct {
Name string `json:"name"` //名字
AlertType constants.AlertType `json:"alert_type"` //告警类型
AlertLevel constants.AlertLevel `json:"alert_level"` //告警级别
Description string `json:"description"` //描述
}
type RuleFieldUpdate struct {
Id string `json:"id"`
Name string `json:"name"`
AlertLevel constants.AlertLevel `json:"alert_level"`
Description string `json:"description"`
}
type RuleUpdateRequest struct {
Id string `json:"id"`
Condition constants.WorkerCondition `json:"condition"` //执行条件
SubRule []SubRule `json:"sub_rule"`
Notify []Notify `json:"notify"`
SilenceTime int64 `json:"silence_time"` //静默时间
}
type AlertTreatedRequest struct {
Id string `json:"id"`
Message string `json:"message"`
}
type Notify struct {
Name constants.AlertWay `json:"name"` //告警方式
Option map[string]string `json:"option"`
StartEffectTime string `json:"start_effect_time"` //生效开始时间
EndEffectTime string `json:"end_effect_time"` //生效结束时间
}
func (b *RuleUpdateRequest) BuildEkuiperSql(deviceId string, specsType constants.SpecsType) string {
var sql string
switch specsType {
case constants.SpecsTypeInt, constants.SpecsTypeFloat:
var s int
switch b.SubRule[0].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:
if b.SubRule[0].Option["value_type"] != constants.Original {
return ""
}
}
switch b.SubRule[0].Option["value_type"] {
case constants.Original:
code := b.SubRule[0].Option["code"]
decideCondition := b.SubRule[0].Option["decide_condition"]
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)
case constants.Avg:
code := b.SubRule[0].Option["code"]
decideCondition := b.SubRule[0].Option["decide_condition"]
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`
sql = fmt.Sprintf(sqlTemp, code, code, deviceId, code, fmt.Sprintf("TUMBLINGWINDOW(ss, %d)", s), code, decideCondition)
case constants.Max:
code := b.SubRule[0].Option["code"]
decideCondition := b.SubRule[0].Option["decide_condition"]
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`
sql = fmt.Sprintf(sqlTemp, code, code, deviceId, code, fmt.Sprintf("TUMBLINGWINDOW(ss, %d)", s), code, decideCondition)
case constants.Min:
code := b.SubRule[0].Option["code"]
decideCondition := b.SubRule[0].Option["decide_condition"]
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`
sql = fmt.Sprintf(sqlTemp, code, code, deviceId, code, fmt.Sprintf("TUMBLINGWINDOW(ss, %d)", s), code, decideCondition)
case constants.Sum:
code := b.SubRule[0].Option["code"]
decideCondition := b.SubRule[0].Option["decide_condition"]
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`
sql = fmt.Sprintf(sqlTemp, code, code, deviceId, code, fmt.Sprintf("TUMBLINGWINDOW(ss, %d)", s), code, decideCondition)
}
return sql
case constants.SpecsTypeText:
code := b.SubRule[0].Option["code"]
decideCondition := b.SubRule[0].Option["decide_condition"]
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])
case constants.SpecsTypeEnum:
code := b.SubRule[0].Option["code"]
decideCondition := b.SubRule[0].Option["decide_condition"]
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])
case constants.SpecsTypeBool:
code := b.SubRule[0].Option["code"]
decideCondition := b.SubRule[0].Option["decide_condition"]
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 sql
}
func ReplaceRuleFields(ds *models.AlertRule, patch RuleFieldUpdate) {
if patch.Name != "" {
ds.Name = patch.Name
}
if patch.AlertLevel != "" {
ds.AlertLevel = patch.AlertLevel
}
if patch.Description != "" {
ds.Description = patch.Description
}
}
func ReplaceRuleModelFields(ds *models.AlertRule, patch RuleUpdateRequest) {
if patch.Condition != "" {
ds.Condition = patch.Condition
}
if patch.SilenceTime > 0 {
ds.SilenceTime = patch.SilenceTime
}
if len(patch.SubRule) > 0 {
var newSubRule models.SubRule
for _, rule := range patch.SubRule {
newSubRule = append(newSubRule, models.Rule{
Trigger: rule.Trigger,
ProductId: rule.ProductId,
DeviceId: rule.DeviceId,
Option: rule.Option,
})
}
ds.SubRule = newSubRule
} else {
ds.SubRule = nil
}
if len(patch.Notify) > 0 {
var newNotify models.Notify
for _, notify := range patch.Notify {
newNotify = append(newNotify, models.SubNotify{
Name: notify.Name,
Option: notify.Option,
StartEffectTime: notify.StartEffectTime,
EndEffectTime: notify.EndEffectTime,
})
}
ds.Notify = newNotify
}
}
type SubRule struct {
Trigger constants.Trigger `json:"trigger"`
ProductId string `json:"product_id"`
DeviceId string `json:"device_id"`
Option map[string]string `json:"option"`
}
type RuleResponse struct {
Id string `json:"id"`
Name string `json:"name"`
AlertType constants.AlertType `json:"alert_type"`
AlertLevel constants.AlertLevel `json:"alert_level"`
Status constants.RuleStatus `json:"status"`
Condition constants.WorkerCondition `json:"condition"`
SubRule RuleSubRules `json:"sub_rule"`
Notify models.Notify `json:"notify"`
SilenceTime int64 `json:"silence_time"`
Description string `json:"description"`
Created int64 `json:"created"`
Modified int64 `json:"modified"`
}
type RuleSubRules []RuleSubRule
type RuleSubRule struct {
Trigger constants.Trigger `json:"trigger"` //触发方式
ProductId string `json:"product_id"`
ProductName string `json:"product_name"`
DeviceId string `json:"device_id"`
DeviceName string `json:"device_name"`
Code string `json:"code"`
Condition string `json:"condition"`
Option map[string]string `json:"option"`
}
//type RuleNotifys []RuleNotify
//
//type RuleNotify struct {
// Name constants.AlertWay `json:"name"` //告警方式
// Option map[string]string `json:"option"`
// StartEffectTime string `json:"start_effect_time"` //生效开始时间
// EndEffectTime string `json:"end_effect_time"` //生效结束时间
//}
type AlertRuleSearchQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"`
Name string `schema:"name,omitempty"`
Status string `schema:"status,omitempty"`
Msg string `schema:"msg,omitempty"`
}
type AlertRuleSearchQueryResponse struct {
Id string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
AlertType constants.AlertType `json:"alert_type"`
AlertLevel constants.AlertLevel `json:"alert_level"`
Created int64 `json:"created"`
Status constants.RuleStatus `json:"status"`
SubRule []SubRule `json:"sub_rule"`
}
func RuleSearchQueryResponseFromModel(p models.AlertRule) AlertRuleSearchQueryResponse {
var subRule []SubRule
for _, rule := range p.SubRule {
subRule = append(subRule, SubRule{
Trigger: rule.Trigger,
ProductId: rule.ProductId,
DeviceId: rule.DeviceId,
Option: rule.Option,
})
}
return AlertRuleSearchQueryResponse{
Id: p.Id,
Name: p.Name,
Description: p.Description,
AlertType: p.AlertType,
AlertLevel: p.AlertLevel,
Status: p.Status,
Created: p.Created,
SubRule: subRule,
}
}
type AlertSearchQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"`
Name string `schema:"name,omitempty"`
AlertLevel string `schema:"alert_level,omitempty"`
Status string `schema:"status,omitempty"`
TriggerStartTime int `schema:"trigger_start_time,omitempty"`
TriggerEndTime int `schema:"trigger_end_time,omitempty"`
}
type AlertSearchQueryResponse struct {
Id string `json:"id"`
Name string `json:"name"`
//Description string `json:"description"`
AlertResult string `json:"alert_result"`
AlertLevel constants.AlertLevel `json:"alert_level"`
TriggerTime int64 `json:"trigger_time"`
TreatedTime int64 `json:"treated_time"`
Status string `json:"status"`
Message string `json:"message"`
IsSend bool `json:"is_send"`
}
type AlertAddRequest struct {
DeviceId string `json:"device_id"`
TriggerTime int64 `json:"trigger_time"` //触发时间
RuleId string `json:"rule_id"`
Content string `json:"content"`
}
type AlertPlateQueryResponse struct {
Count int `json:"count"`
AlertLevel constants.AlertLevel `json:"alert_level"`
}

33
internal/dtos/backup.go Normal file
View File

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

70
internal/dtos/base.go Normal file
View File

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

View File

@ -0,0 +1,87 @@
/*******************************************************************************
* Copyright 2017 Dell Inc.
* Copyright (c) 2019 Intel Corporation
*
* 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 CategoryTemplateRequest struct {
BaseSearchConditionQuery `schema:",inline"`
CategoryName string `schema:"category_name"`
Scene string `schema:"scene"`
}
type CategoryTemplateSyncRequest struct {
VersionName string `json:"version_name"`
}
type ThingModelTemplateSyncRequest struct {
VersionName string `json:"version_name"`
}
func CategoryTemplateResponseFromModel(m models.CategoryTemplate) CategoryTemplateResponse {
return CategoryTemplateResponse{
Id: m.Id,
CategoryName: m.CategoryName,
CategoryKey: m.CategoryKey,
Scene: m.Scene,
}
}
type CategoryTemplateResponse struct {
Id string `json:"id"`
CategoryName string `json:"category_name"` //品类名称
CategoryKey string `json:"category_key"`
Scene string `json:"scene"` //所属场景
}
type CosCategoryTemplateResponse struct {
CategoryName string `json:"category_name"`
CategoryKey string `json:"category_key"`
Scene string `json:"scene"`
}
type ThingModelTemplateRequest struct {
BaseSearchConditionQuery `schema:",inline"`
CategoryKey string `schema:"category_key"`
CategoryName string `schema:"category_name"`
}
type ThingModelTemplateResponse struct {
Id string `json:"id"`
CategoryName string `json:"category_name"` //品类名称
CategoryKey string `json:"category_key"`
ThingModelJSON string `json:"thing_model_json"`
//models.Properties
Properties interface{} `json:"properties"`
Events interface{} `json:"events"`
Actions interface{} `json:"actions"`
}
func ThingModelTemplateResponseFromModel(m models.ThingModelTemplate) ThingModelTemplateResponse {
p, e, a := GetModelPropertyEventActionByThingModelTemplate(m.ThingModelJSON)
return ThingModelTemplateResponse{
CategoryKey: m.CategoryKey,
CategoryName: m.CategoryName,
Properties: p,
Events: e,
Actions: a,
}
}
type CosThingModelTemplateResponse struct {
CategoryName string `json:"category_name"`
CategoryKey string `json:"category_key"`
ThingModelJSON string `json:"thing_model_json"`
}

61
internal/dtos/command.go Normal file
View File

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

109
internal/dtos/common.go Normal file
View File

@ -0,0 +1,109 @@
/*******************************************************************************
* Copyright 2017 Dell Inc.
* Copyright (c) 2019 Intel Corporation
*
* 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 "strings"
type PageRequest struct {
NameLike string `json:"nameLike" form:"nameLike"`
Page int `json:"page" form:"page"`
PageSize int `json:"pageSize" form:"pageSize"`
}
//func (p *PageRequest) ToRpc() *common.PageRequest {
// return &common.PageRequest{
// NameLike: p.NameLike,
// Page: int64(p.Page),
// PageSize: int64(p.PageSize),
// }
//}
type BaseSearchConditionQuery struct {
Page int `schema:"page,omitempty" form:"page"`
PageSize int `schema:"pageSize,omitempty" form:"pageSize" json:"pageSize"`
Id string `schema:"id,omitempty" form:"id"`
Ids string `schema:"ids,omitempty" form:"ids"`
LikeId string `schema:"likeId,omitempty" form:"likeId"`
Name string `schema:"name,omitempty" form:"name"`
NameLike string `schema:"nameLike,omitempty" form:"nameLike"`
IsAll bool `schema:"isAll,omitempty" form:"isAll"`
OrderBy string `schema:"orderBy,omitempty" form:"orderBy"`
}
func (req BaseSearchConditionQuery) GetPage() (int, int) {
var (
offset = (req.Page - 1) * req.PageSize
limit = req.PageSize
)
if req.Page == 0 && req.PageSize == 0 {
offset = 0
limit = -1
}
if req.IsAll {
offset = 0
limit = -1
}
return offset, limit
}
func ApiParamsStringToArray(str string) []string {
return strings.Split(str, ",")
}
/**
/order bykeymodels
models.Device.ProductName key ProductName product_name pn
*/
type ApiOrderBy struct {
Key string
IsDesc bool
}
func ApiParamsStringToOrderBy(str string) []ApiOrderBy {
orderBys := make([]ApiOrderBy, 0)
arr := strings.Split(str, ",")
if len(arr) <= 0 {
return nil
}
for _, v := range arr {
vArr := strings.Split(v, ":")
if len(vArr) <= 1 {
continue
}
switch vArr[1] {
case "desc":
orderBys = append(orderBys, ApiOrderBy{
Key: vArr[0],
IsDesc: true,
})
case "asc":
orderBys = append(orderBys, ApiOrderBy{
Key: vArr[0],
IsDesc: false,
})
default:
continue
}
}
return orderBys
}
func ApiParamsArrayToString(arr []string) string {
return strings.Join(arr, ",")
}

34
internal/dtos/config.go Normal file
View File

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

View File

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

View File

@ -0,0 +1,60 @@
/*******************************************************************************
* 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
}

31
internal/dtos/db.go Normal file
View File

@ -0,0 +1,31 @@
/*******************************************************************************
* Copyright 2018 Dell Inc.
*
* 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
type Configuration struct {
DbType string
Host string
Port string
Timeout int
DatabaseName string
Username string
Password string
BatchSize int
Dsn string
// 添加sqlite数据库存储地址
DataSource string
// 添加tqlite集群地址
Cluster []string
}

324
internal/dtos/device.go Normal file
View File

@ -0,0 +1,324 @@
/*******************************************************************************
* Copyright 2017 Dell Inc.
* Copyright (c) 2019 Intel Corporation
*
* 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 (
"encoding/json"
"github.com/winc-link/hummingbird/internal/models"
"github.com/winc-link/hummingbird/internal/pkg/constants"
"github.com/winc-link/hummingbird/internal/pkg/utils"
)
type DeviceSyncRequest struct {
CloudInstanceId string `json:"cloud_instance_id"`
DriveInstanceId string `json:"driver_instance_id"`
//Extra struct{
//
//} `json:"extra"`
//Aliyun *struct {
// ResourceGroupId string `json:"resource_group_id"`
//} `json:"ali_yun"`
//HuaweiYun *struct {
// ProjectId string `json:"project_id"`
// AppId string `json:"app_id"`
//} `json:"huawei_yun"`
}
type DeviceSyncByIdRequest struct {
DeviceId string `json:"device_id"`
}
type DeviceStatusRequest struct {
DeviceId string `json:"device_id"`
}
type DeviceSearchQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"`
Platform string `schema:"platform,omitempty"`
Name string `schema:"name,omitempty"`
ProductId string `schema:"product_id,omitempty"`
CloudProductId string `schema:"cloud_product_id,omitempty"`
CloudInstanceId string `schema:"cloud_instance_id,omitempty"`
DriveInstanceId string `schema:"drive_instance_id,omitempty"`
Status string `schema:"status,omitempty"`
}
type DeviceSearchQueryResponse struct {
Id string `json:"id"`
Name string `json:"name"`
ProductId string `json:"product_id"`
Status constants.DeviceStatus `json:"status"`
Platform constants.IotPlatform `json:"platform"`
CloudInstanceId string `json:"cloud_instance_id"`
CloudProductId string `json:"cloud_product_id"`
DriverServiceName string `json:"driver_service_name"`
ProductName string `json:"product_name"`
LastSyncTime int64 `json:"last_sync_time"`
LastOnlineTime int64 `json:"last_online_time"`
DriveInstanceId string `json:"drive_instance_id"`
Created int64 `json:"created"`
Description string `json:"description"`
}
func DeviceResponseFromModel(p models.Device, deviceServiceName string) DeviceSearchQueryResponse {
return DeviceSearchQueryResponse{
Id: p.Id,
ProductId: p.ProductId,
Name: p.Name,
Platform: p.Platform,
Status: p.Status,
DriverServiceName: deviceServiceName,
CloudInstanceId: p.CloudInstanceId,
CloudProductId: p.CloudProductId,
ProductName: p.Product.Name,
LastSyncTime: p.LastSyncTime,
LastOnlineTime: p.LastOnlineTime,
DriveInstanceId: p.DriveInstanceId,
Created: p.Created,
Description: p.Description,
}
}
type OpenApiDeviceStatus struct {
Status constants.DeviceStatus `json:"status"`
}
type OpenApiDeviceInfoResponse struct {
Id string `json:"id"`
Name string `json:"name"`
Platform constants.IotPlatform `json:"platform"`
Status constants.DeviceStatus `json:"status"`
Description string `json:"description"`
ProductId string `json:"product_id"`
ProductName string `json:"product_name"`
//Secret string `json:"secret"`
LastOnlineTime int64 `json:"last_online_time"`
Created int64 `json:"created_at"`
}
func OpenApiDeviceInfoResponseFromModel(p models.Device) OpenApiDeviceInfoResponse {
return OpenApiDeviceInfoResponse{
Id: p.Id,
Name: p.Name,
Platform: p.Platform,
Status: p.Status,
Description: p.Description,
ProductId: p.ProductId,
ProductName: p.Product.Name,
//Secret: p.Secret,
LastOnlineTime: p.LastOnlineTime,
Created: p.Created,
}
}
type DeviceInfoResponse struct {
Id string `json:"id"`
CloudDeviceId string `json:"cloud_device_id"`
CloudProductId string `json:"cloud_product_id"`
CloudInstanceId string `json:"cloud_instance_id"`
Name string `json:"name"`
Status constants.DeviceStatus `json:"status"`
Description string `json:"description"`
ProductId string `json:"product_id"`
ProductName string `json:"product_name"`
Secret string `json:"secret"`
Platform constants.IotPlatform `json:"platform"`
DeviceServiceName string `json:"device_service_name"`
LastSyncTime int64 `json:"last_sync_time"`
LastOnlineTime int64 `json:"last_online_time"`
Created int64 `json:"create_at"`
}
func DeviceInfoResponseFromModel(p models.Device, deviceServiceName string) DeviceInfoResponse {
return DeviceInfoResponse{
Id: p.Id,
CloudDeviceId: p.CloudDeviceId,
CloudProductId: p.CloudProductId,
Name: p.Name,
Status: p.Status,
Description: p.Description,
ProductId: p.ProductId,
ProductName: p.Product.Name,
Secret: p.Secret,
Platform: p.Platform,
DeviceServiceName: deviceServiceName,
LastSyncTime: p.LastSyncTime,
LastOnlineTime: p.LastOnlineTime,
Created: p.Created,
CloudInstanceId: p.CloudInstanceId,
}
}
type DeviceReportPropertiesValueSearchRequest struct {
DeviceId string `json:"device_id"`
}
type PropertyInfo struct {
Code string `json:"code,omitempty"`
Value string `json:"value,omitempty"`
DataType string `json:"dataType,omitempty"`
Time string `json:"time,omitempty"`
Unit string `json:"unit,omitempty"`
Name string `json:"name,omitempty"`
}
type DeviceReportPropertiesValueSearchResponse struct {
PropertyInfoList []PropertyInfo `json:"property_info_list"`
}
type DeviceAddRequest struct {
DeviceId string `json:"device_id"`
Name string `json:"name"`
ProductId string `json:"product_id"`
Description string `json:"description"`
Platform constants.IotPlatform `json:"platform"`
DriverInstanceId string `json:"driver_instance_id"`
//CloudDeviceId string `json:"cloud_device_id"`
//CloudProductId string `json:"cloud_product_id"`
//CloudInstanceId string `gorm:"index"`
//Status constants.DeviceStatus `json:"status"`
//Secret string `json:"secret"`
}
type DeviceAuthInfoResponse struct {
ClientId string `json:"clientId"`
UserName string `json:"username"`
Password string `json:"password"`
Host string `json:"mqttHostUrl"`
Port int `json:"port"`
}
func DeviceAuthInfoResponseFromModel(p models.MqttAuth) DeviceAuthInfoResponse {
ip, _ := utils.GetOutBoundIP()
return DeviceAuthInfoResponse{
ClientId: p.ClientId,
UserName: p.UserName,
Password: p.Password,
Host: ip,
Port: 58090,
}
}
type DeviceUpdateRequest struct {
Id string `json:"id"`
Description *string `json:"description"`
//Ip *string `json:"ip"`
//Lat *string `json:"lat"`
//Lon *string `json:"lon"`
Name *string `json:"name"`
InstallLocation *string `json:"install_location"`
DriveInstanceId *string `json:"drive_instance_id"`
}
func ReplaceDeviceModelFields(ds *models.Device, patch DeviceUpdateRequest) {
if patch.Description != nil {
ds.Description = *patch.Description
}
if patch.Name != nil {
ds.Name = *patch.Name
}
//
//if patch.Lat != nil {
// ds.Lat = *patch.Lat
//}
//
//if patch.Lon != nil {
// ds.Lon = *patch.Lon
//}
if patch.DriveInstanceId != nil {
ds.DriveInstanceId = *patch.DriveInstanceId
}
if patch.InstallLocation != nil {
ds.InstallLocation = *patch.InstallLocation
}
}
type DeviceUpdateOrCreateCallBack struct {
Id string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
ProductId string `json:"product_id"`
Status constants.DeviceStatus `json:"status"`
Platform constants.IotPlatform `json:"platform"`
DriveInstanceId string `json:"drive_instance_id"`
}
type DeviceDeleteCallBack struct {
Id string `json:"id"`
DriveInstanceId string `json:"drive_instance_id"`
}
type DeviceImportTemplateRequest struct {
}
type DevicesImport struct {
ProductId string `schema:"product_id,omitempty"`
DriverInstanceId string `schema:"driver_instance_id,omitempty"`
}
type DeviceBatchDelete struct {
DeviceIds []string `json:"device_ids"`
}
type DevicesBindDriver struct {
DeviceIds []string `json:"device_ids"`
DriverInstanceId string `json:"driver_instance_id,omitempty"`
}
type DevicesBindProductId struct {
ProductId string `json:"product_id"`
DriverInstanceId string `json:"driver_instance_id,omitempty"`
}
type DevicesUnBindDriver struct {
DeviceIds []string `json:"device_ids"`
}
type AddMqttAuthInfoRequest struct {
Id string `json:"id"`
ClientId string `json:"client_id"`
UserName string `json:"username"`
Password string `json:"password"`
ResourceId string `json:"resource_id"`
ResourceType string `json:"resource_type"`
}
type DeviceExecRes struct {
Result bool `json:"result"`
Message string `json:"message"`
}
func (d *DeviceExecRes) ToString() string {
b, _ := json.Marshal(d)
return string(b)
}
type JobAction struct {
ActionType string `json:"actionType"`
ProductId string `json:"productId"`
ProductName string `json:"product_name"`
DeviceId string `json:"deviceId"`
DeviceName string `json:"deviceName"`
Code string `json:"code"`
DateType string `json:"dateType"`
Value interface{} `json:"value"`
}
type InvokeDeviceServiceReq struct {
DeviceId string `json:"deviceId"`
Code string `json:"code"`
Items map[string]interface{} `json:"inputParams"`
}

View File

@ -0,0 +1,205 @@
package dtos
import (
"github.com/winc-link/hummingbird/internal/models"
)
type DeviceLibrary struct {
Id string
Name string // 容器名/软件名
Alias string
Description string
Protocol string
Version string
LibFile string
ConfigFile string
Config string
DockerConfigId string
DockerRepoName string
DockerImageId string
//SupportVersions []DeviceLibrarySupportVersion
IsInternal bool
OperateStatus string // 下载状态
}
func DeviceLibraryFromModel(d models.DeviceLibrary) DeviceLibrary {
return DeviceLibrary{
Id: d.Id,
Name: d.Name,
Description: d.Description,
Protocol: d.Protocol,
Version: d.Version,
//LibFile: d.LibFile,
//ConfigFile: d.ConfigFile,
DockerConfigId: d.DockerConfigId,
DockerRepoName: d.DockerRepoName,
DockerImageId: d.DockerImageId,
//SupportVersions: SupperVersionsFromModel(d.SupportVersions),
}
}
type DeviceLibraryAddRequest struct {
Id string `json:"id,omitempty"`
Name string `json:"name" binding:"required"`
Description string `json:"description,omitempty"`
Protocol string `json:"protocol"`
Version string `json:"version" binding:"required"`
ContainerName string `json:"container_name" binding:"required"`
DockerConfigId string `json:"docker_config_id" binding:"required"`
DockerRepoName string `json:"docker_repo_name" binding:"required"`
Language string `json:"language"` //代码语言
SupportVersion struct {
IsDefault bool `json:"is_default"`
DockerParamsSwitch bool `json:"docker_params_switch"`
DockerParams string `json:"docker_params"`
ExpertMode bool `json:"expert_mode"`
ExpertModeContent string `json:"expert_mode_content"`
ConfigJson string `json:"config_json"`
} `json:"support_version"`
}
func FromDeviceLibraryRpcToModel(p *DeviceLibraryAddRequest) models.DeviceLibrary {
dl := models.DeviceLibrary{
Id: p.Id,
Name: p.Name,
Description: p.Description,
Protocol: p.Protocol,
Version: p.Version,
ContainerName: p.ContainerName,
DockerRepoName: p.DockerRepoName,
DockerConfigId: p.DockerConfigId,
Language: p.Language,
}
//dl.SupportVersions = append(dl.SupportVersions, models.SupportVersion{
// Version: p.Version,
// IsDefault: p.IsDefault,
// ConfigJson: p.ConfigJson,
// ConfigFile: p.ConfigFile,
// DockerParamsSwitch: p.DockerParamsSwitch,
// DockerParams: s.DockerParams,
// ExpertMode: s.ExpertMode,
// ExpertModeContent: s.ExpertModeContent,
//})
return dl
}
type DeviceLibrarySearchQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"`
DockerConfigId string `form:"docker_config_id" json:"docker_config_id"`
IsInternal string `form:"is_internal" json:"is_internal"`
ClassifyId int `form:"classify_id" json:"classify_id"`
DockerRepoName string `form:"docker_repo_name" json:"docker_repo_name"`
NameAliasLike string `form:"name_alias_like" json:"name_alias_like"`
DownloadStatus string `form:"download_status" json:"download_status"`
DriverType int `form:"driver_type" json:"driver_type" binding:"omitempty,oneof=1 2"` // 驱动库类型1驱动2三方应用
NoInIds string // 约定没有from的为 内置查询条件
ImageIds string // 内置条件
NoInImageIds string // 内置条件
}
type DeviceLibraryResponse struct {
Id string `json:"id"`
Name string `json:"name"`
//Alias string `json:"alias"`
Description string `json:"description"`
//Manufacturer string `json:"manufacturer"`
Protocol string `json:"protocol"`
Version string `json:"version"`
ContainerName string `json:"container_name"`
//ConfigFile string `json:"config_file"`
DockerConfigId string `json:"docker_config_id"`
DockerRepoName string `json:"docker_repo_name"`
OperateStatus string `json:"operate_status"`
IsInternal bool `json:"is_internal"`
Manual string `json:"manual"`
Icon string `json:"icon"`
ClassifyId int `json:"classify_id"`
Created int64 `json:"created"`
Language string `json:"language"`
SupportVersions []DeviceLibrarySupportVersionSimple `json:"support_versions"` // 用于前端展示可供下载/更新的版本号 key:value == 版本号:配置文件
}
func DeviceLibraryResponseFromModel(dl models.DeviceLibrary) DeviceLibraryResponse {
// 如果docker镜像id为空那么返回给前端的版本为 `-`
if dl.DockerImageId == "" {
dl.Version = "-"
}
//if dl.ConfigFile != "" {
// dl.ConfigFile = path.Base(dl.ConfigFile)
//}
return DeviceLibraryResponse{
Id: dl.Id,
Name: dl.Name,
Description: dl.Description,
Protocol: dl.Protocol,
Version: dl.Version,
ContainerName: dl.ContainerName,
//ConfigFile: dl.ConfigFile,
IsInternal: dl.IsInternal,
DockerConfigId: dl.DockerConfigId,
DockerRepoName: dl.DockerRepoName,
OperateStatus: dl.OperateStatus,
Icon: dl.Icon,
Manual: dl.Manual,
ClassifyId: dl.ClassifyId,
Created: dl.Created,
Language: dl.Language,
SupportVersions: DeviceLibrarySupportVersionSimpleFromModel(dl.SupportVersions),
}
}
type DeviceLibraryUpgradeRequest struct {
Id string `json:"id" binding:"required"`
Version string `json:"version" binding:"required"`
}
type DeviceLibraryUpgradeResponse struct {
Id string `json:"id"`
Version string `json:"version"`
OperateStatus string `json:"operate_status"`
}
func GetLibrarySimpleBaseConfig() string {
return `{"deviceServer": {},"deviceProtocols": {},"deviceDpAttrs": []}`
}
type UpdateDeviceLibrary struct {
Id string `json:"id" binding:"required"`
Name *string `json:"name"`
Description *string `json:"description"`
DockerConfigId *string `json:"docker_config_id"`
Protocol *string `json:"protocol"`
Language *string `json:"language"`
Manual *string `json:"manual"`
Icon *string `json:"icon"`
}
func ReplaceDeviceLibraryModelFieldsWithDTO(deviceLibrary *models.DeviceLibrary, patch UpdateDeviceLibrary) {
if patch.Name != nil {
deviceLibrary.Name = *patch.Name
}
if patch.DockerConfigId != nil {
deviceLibrary.DockerConfigId = *patch.DockerConfigId
}
if patch.Description != nil {
deviceLibrary.Description = *patch.Description
}
if patch.Protocol != nil {
deviceLibrary.Protocol = *patch.Protocol
}
if patch.Language != nil {
deviceLibrary.Language = *patch.Language
}
if patch.Manual != nil {
deviceLibrary.Manual = *patch.Manual
}
if patch.Icon != nil {
deviceLibrary.Icon = *patch.Icon
}
}

View File

@ -0,0 +1,343 @@
package dtos
import (
"github.com/winc-link/hummingbird/internal/models"
"github.com/winc-link/hummingbird/internal/pkg/constants"
//"gitlab.com/tedge/edgex/internal/models"
//devicelibraryProto "gitlab.com/tedge/edgex/proto/devicelibrary"
//deviceserviceProto "gitlab.com/tedge/edgex/proto/deviceservice"
"gopkg.in/yaml.v3"
)
type DeviceService struct {
Id string `json:"id,omitempty"`
Name string `json:"name"`
Created int64 `json:"created,omitempty"`
Modified int64 `json:"modified,omitempty"`
BaseAddress string `json:"baseAddress"`
DeviceLibraryId string `json:"deviceLibraryId"`
Config map[string]interface{} `json:"config"`
DockerContainerId string `json:"dockerContainerId"`
ExpertMode bool `json:"isExpertMode"`
ExpertModeContent string `json:"expertModeContent"`
DockerParamsSwitch bool `json:"dockerParamsSwitch"`
DockerParams string `json:"dockerParams"`
ContainerName string `json:"container_name"`
}
// 启动实例时对应的配置
type RunServiceCfg struct {
ImageRepo string
RunConfig string
DockerMountDevices []string
DockerParams string
DriverName string // 驱动名
}
func DeviceServiceFromModel(ds models.DeviceService) DeviceService {
var dto DeviceService
dto.Id = ds.Id
dto.Name = ds.Name
dto.BaseAddress = ds.BaseAddress
dto.DeviceLibraryId = ds.DeviceLibraryId
dto.Config = ds.Config
dto.DockerContainerId = ds.DockerContainerId
dto.ExpertMode = ds.ExpertMode
dto.ExpertModeContent = ds.ExpertModeContent
dto.DockerParamsSwitch = ds.DockerParamsSwitch
dto.DockerParams = ds.DockerParams
dto.ContainerName = ds.ContainerName
return dto
}
//func FromDeviceServiceModelToRPC(mds models.DeviceService) *deviceserviceProto.DeviceService {
// byteConfig, _ := json.Marshal(mds.Config)
// var ds deviceserviceProto.DeviceService
// ds.Id = mds.Id
// ds.Name = mds.Name
// ds.BaseAddress = mds.BaseAddress
// ds.DeviceLibraryId = mds.DeviceLibraryId
// ds.DockerContainerId = mds.DockerContainerId
// ds.Config = byteConfig
// ds.ExpertMode = mds.ExpertMode
// ds.ExpertModeContent = mds.ExpertModeContent
// ds.DockerParamsSwitch = mds.DockerParamsSwitch
// ds.DockerParams = mds.DockerParams
// ds.LogLevel = int64(mds.LogLevel)
// ds.RunStatus = int32(mds.RunStatus)
// ds.ImageExist = mds.ImageExist
// return &ds
//}
//func FromDeviceServiceRpcToModel(ds *deviceserviceProto.DeviceService) models.DeviceService {
// var config map[string]interface{}
// if ds.Config != nil {
// _ = json.Unmarshal(ds.Config, &config)
// }
//
// var mds models.DeviceService
// mds.Id = ds.Id
// mds.Name = ds.Name
// mds.BaseAddress = ds.BaseAddress
// mds.DeviceLibraryId = ds.DeviceLibraryId
// mds.DockerContainerId = ds.DockerContainerId
// mds.RunStatus = int(ds.RunStatus)
// mds.Config = config
// mds.ExpertMode = ds.ExpertMode
// mds.ExpertModeContent = ds.ExpertModeContent
// mds.DockerParamsSwitch = ds.DockerParamsSwitch
// mds.DockerParams = ds.DockerParams
// mds.ImageExist = ds.ImageExist
// mds.DriverType = int(ds.DriverType)
// return mds
//}
type DeviceServiceAddRequest struct {
Id string `json:"id,omitempty" binding:"omitempty,t-special-char"`
Name string `json:"name"`
DeviceLibraryId string `json:"deviceLibraryId" binding:"required"`
Config map[string]interface{} `json:"config" binding:"required"`
ExpertMode bool `json:"expertMode"`
ExpertModeContent string `json:"expertModeContent"`
DockerParamsSwitch bool `json:"dockerParamsSwitch"`
DockerParams string `json:"dockerParams"`
DriverType int `json:"driverType" binding:"omitempty,oneof=1 2"` //驱动库类型1驱动2三方应用
}
//func FromDeviceServiceAddToRpc(req DeviceServiceAddRequest) *deviceserviceProto.DeviceService {
// byteConfig, _ := json.Marshal(req.Config)
// return &deviceserviceProto.DeviceService{
// Id: req.Id,
// Name: req.Name,
// DeviceLibraryId: req.DeviceLibraryId,
// Config: byteConfig,
// ExpertMode: req.ExpertMode,
// ExpertModeContent: req.ExpertModeContent,
// DockerParamsSwitch: req.DockerParamsSwitch,
// DockerParams: req.DockerParams,
// DriverType: int32(req.DriverType),
// }
//}
func DeviceServiceFromDeviceServiceAddRequest(ds DeviceServiceAddRequest) models.DeviceService {
var mds models.DeviceService
mds.Id = ds.Id
mds.Name = ds.Name
mds.Config = ds.Config
mds.DeviceLibraryId = ds.DeviceLibraryId
mds.ExpertMode = ds.ExpertMode
mds.ExpertModeContent = ds.ExpertModeContent
mds.DockerParamsSwitch = ds.DockerParamsSwitch
mds.DockerParams = ds.DockerParams
mds.DriverType = ds.DriverType
return mds
}
type DeviceServiceUpdateRequest struct {
Id string `json:"id" binding:"required"`
DeviceLibraryId *string `json:"deviceLibraryId"`
Name *string `json:"name"`
Config *map[string]interface{} `json:"config"`
ExpertMode *bool `json:"expertMode"`
ExpertModeContent *string `json:"expertModeContent"`
DockerParamsSwitch *bool `json:"docker_params_switch"`
DockerParams *string `json:"docker_params"`
Platform constants.IotPlatform `json:"platform"`
//IsIgnoreRunStatus bool
}
//func FromRpcToUpdateDeviceService(rpc *deviceserviceProto.UpdateDeviceService) DeviceServiceUpdateRequest {
// var config map[string]interface{}
// if rpc.Config != nil {
// _ = json.Unmarshal(rpc.Config, &config)
// }
// return DeviceServiceUpdateRequest{
// Id: rpc.Id,
// Name: rpc.Name,
// DeviceLibraryId: rpc.DeviceLibraryId,
// Config: &config,
// ExpertMode: rpc.ExpertMode,
// ExpertModeContent: rpc.ExpertModeContent,
// DockerParamsSwitch: rpc.DockerParamsSwitch,
// DockerParams: rpc.DockerParams,
// }
//}
type UpdateDeviceServiceRunStatusRequest struct {
Id string `json:"id"`
RunStatus int `json:"run_status" binding:"required,oneof=1 2"`
}
type DeviceServiceRunLogRequest struct {
Id string `json:"id"`
Operate int `json:"operate" binding:"required,oneof=1 2"`
}
type DeviceServiceDeleteRequest struct {
Id string `json:"id" binding:"required"`
}
//func FromUpdateDeviceServiceRunStatusToRpc(req UpdateDeviceServiceRunStatusRequest) *deviceserviceProto.UpdateDeviceServiceRunStatusRequest {
// return &deviceserviceProto.UpdateDeviceServiceRunStatusRequest{
// Id: req.Id,
// RunStatus: int32(req.RunStatus),
// }
//}
//
//func FromDeviceServiceSearchQueryRequestToRpc(req DeviceServiceSearchQueryRequest) *deviceserviceProto.DeviceServiceSearchRequest {
// return &deviceserviceProto.DeviceServiceSearchRequest{
// BaseSearchConditionQuery: FromBaseSearchConditionQueryToRpc(req.BaseSearchConditionQuery),
// DeviceLibraryId: req.DeviceLibraryId,
// DriverType: int32(req.DriverType),
// }
//}
//func FromRpcToUpdateDeviceServiceRunStatus(rpc *deviceserviceProto.UpdateDeviceServiceRunStatusRequest) UpdateDeviceServiceRunStatusRequest {
// return UpdateDeviceServiceRunStatusRequest{
// Id: rpc.Id,
// RunStatus: int(rpc.RunStatus),
// }
//}
func ReplaceDeviceServiceModelFieldsWithDTO(ds *models.DeviceService, patch DeviceServiceUpdateRequest) {
if patch.Config != nil {
ds.Config = *patch.Config
}
if patch.DeviceLibraryId != nil {
ds.DeviceLibraryId = *patch.DeviceLibraryId
}
if patch.ExpertMode != nil {
ds.ExpertMode = *patch.ExpertMode
}
if patch.ExpertModeContent != nil {
ds.ExpertModeContent = *patch.ExpertModeContent
}
if patch.DockerParamsSwitch != nil {
ds.DockerParamsSwitch = *patch.DockerParamsSwitch
}
if patch.DockerParams != nil {
ds.DockerParams = *patch.DockerParams
}
if patch.Platform != "" {
ds.Platform = patch.Platform
}
}
type DeviceServiceSearchQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"`
ProductId string `form:"productId"`
CloudProductId string `form:"cloudProductId"`
DeviceLibraryId string `form:"deviceLibraryId"` // 驱动库ID
DeviceLibraryIds string `form:"deviceLibraryIds"` // 驱动库IDs
Platform string `form:"platform"`
DriverType int `form:"driver_type" binding:"omitempty,oneof=1 2"` //驱动库类型1驱动2三方应用
}
//func ToDeviceServiceSearchQueryRequestDTO(req *deviceserviceProto.DeviceServiceSearchRequest) DeviceServiceSearchQueryRequest {
//
// if req.BaseSearchConditionQuery == nil {
// return DeviceServiceSearchQueryRequest{
// DeviceLibraryId: req.DeviceLibraryId,
// DriverType: int(req.DriverType),
// }
// } else {
// return DeviceServiceSearchQueryRequest{
// BaseSearchConditionQuery: ToBaseSearchConditionQueryDTO(req.BaseSearchConditionQuery),
// DeviceLibraryId: req.DeviceLibraryId,
// DriverType: int(req.DriverType),
// }
// }
//}
//func FromDeviceServiceUpdateToRpc(req DeviceServiceUpdateRequest) *deviceserviceProto.UpdateDeviceService {
// var byteConfig []byte
// if req.Config != nil {
// byteConfig, _ = json.Marshal(&req.Config)
// } else {
// byteConfig = nil
// }
//
// return &deviceserviceProto.UpdateDeviceService{
// Id: req.Id,
// Name: req.Name,
// DeviceLibraryId: req.DeviceLibraryId,
// Config: byteConfig,
// ExpertMode: req.ExpertMode,
// ExpertModeContent: req.ExpertModeContent,
// DockerParamsSwitch: req.DockerParamsSwitch,
// DockerParams: req.DockerParams,
// }
//}
/************** Response **************/
type DeviceServiceResponse struct {
Id string `json:"id"`
Name string `json:"name"`
DeviceLibrary DeviceLibraryResponse `json:"deviceLibrary"`
//Version string `json:"version"`
RunStatus int `json:"runStatus"`
Config interface{} `json:"config"`
ExpertMode bool `json:"expertMode"`
ExpertModeContent string `json:"expertModeContent"`
DockerParamsSwitch bool `json:"dockerParamsSwitch"`
DockerParams string `json:"dockerParams"`
CreateAt int64 `json:"create_at"`
ImageExist bool `json:"imageExist"`
Platform string `json:"platform"`
}
func DeviceServiceResponseFromModel(ds models.DeviceService, dl models.DeviceLibrary) DeviceServiceResponse {
return DeviceServiceResponse{
Id: ds.Id,
Name: ds.Name,
//Version: DeviceLibraryResponseFromModel(dl).Version,
DeviceLibrary: DeviceLibraryResponseFromModel(dl),
RunStatus: ds.RunStatus,
Config: ds.Config,
ExpertMode: ds.ExpertMode,
ExpertModeContent: ds.ExpertModeContent,
DockerParamsSwitch: ds.DockerParamsSwitch,
DockerParams: ds.DockerParams,
ImageExist: ds.ImageExist,
CreateAt: ds.Created,
Platform: string(ds.Platform),
}
}
//func FromDeviceServiceRpcToResponse(ds *deviceserviceProto.DeviceService, dl *devicelibraryProto.DeviceLibrary) DeviceServiceResponse {
// var cfg map[string]interface{}
// _ = json.Unmarshal(ds.Config, &cfg)
// return DeviceServiceResponse{
// Id: ds.Id,
// Name: ds.Name,
// RunStatus: int(ds.RunStatus),
// DeviceLibrary: FromDeviceLibraryRpcToResponse(dl),
// Config: cfg,
// ExpertMode: ds.ExpertMode,
// ExpertModeContent: ds.ExpertModeContent,
// DockerParamsSwitch: ds.DockerParamsSwitch,
// DockerParams: ds.DockerParams,
// ImageExist: ds.ImageExist,
// }
//}
func FromYamlStrToMap(yamlStr string) (m map[string]interface{}, err error) {
err = yaml.Unmarshal([]byte(yamlStr), &m)
if err != nil {
return nil, err
}
return m, nil
}
type UpdateDeviceServiceRunStatusResponse struct {
Id string `json:"id"`
RunStatus int `json:"run_status"`
}
type UpdateServiceLogLevelConfigRequest struct {
Id string `json:"id"` // 驱动或应用ID
LogLevel int64 `json:"logLevel"`
}

View File

@ -0,0 +1,93 @@
/*******************************************************************************
* Copyright 2017 Dell Inc.
* Copyright (c) 2019 Intel Corporation
*
* 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 DockerConfig struct {
Id string
Address string
Account string
Password string
SaltKey string
}
func DockerConfigFromModel(dc models.DockerConfig) DockerConfig {
return DockerConfig{
Id: dc.Id,
Address: dc.Address,
Account: dc.Account,
Password: dc.Password,
SaltKey: dc.SaltKey,
}
}
func WincLinkDockerConfig() DockerConfig {
return DockerConfig{
Address: constants.Address,
Password: constants.Password,
Account: constants.Account,
SaltKey: constants.SaltKey,
}
}
type DockerConfigAddRequest struct {
Id string `json:"id"`
Address string `json:"address" binding:"required"` // 仓库地址 true
Account string `json:"account,omitempty"` // 账户
Password string `json:"password,omitempty"` // 密码
}
type DockerConfigSearchQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"`
Address string `schema:"address"`
Account string `schema:"account"`
}
type DockerConfigResponse struct {
Id string `json:"id"`
Address string `json:"address"`
Account string `json:"account"`
}
func DockerConfigResponseFromModel(dc models.DockerConfig) DockerConfigResponse {
return DockerConfigResponse{
Id: dc.Id,
Address: dc.Address,
Account: dc.Account,
}
}
type DockerConfigUpdateRequest struct {
Id string `json:"id" binding:"required"`
Address *string `json:"address"`
Account *string `json:"account"`
Password *string `json:"password"`
}
func ReplaceDockerConfigModelFieldsWithDTO(ds *models.DockerConfig, patch DockerConfigUpdateRequest) {
if patch.Address != nil {
ds.Address = *patch.Address
}
if patch.Account != nil {
ds.Account = *patch.Account
}
if patch.Password != nil {
ds.Password = *patch.Password
}
}

View File

@ -0,0 +1,26 @@
/*******************************************************************************
* Copyright 2017 Dell Inc.
* Copyright (c) 2019 Intel Corporation
*
* 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
type DriverClassifyResponse struct {
Id string `json:"id"`
Name string `json:"name"`
}
type DriverClassifyQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"`
Name string `schema:"name"`
}

View File

@ -0,0 +1,93 @@
/*******************************************************************************
* Copyright 2017 Dell Inc.
* Copyright (c) 2019 Intel Corporation
*
* 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/pkg/constants"
"github.com/winc-link/hummingbird/internal/pkg/utils"
"sync"
)
var dcMutex sync.Mutex
type DriverConfigManage struct {
HostRootDir string // 宿主主机dir
NetWorkName string
DockerManageConfig
}
type DockerManageConfig struct {
ContainerConfigPath string // 容器内部驱动运行启动的配置文件路径
DockerApiVersion string // docker 版本号
DockerRunMode string // 默认运行模式 默认是host
DockerSelfName string // edge启动的容器名
Privileged bool // 容器特权
}
func (m *DriverConfigManage) SetHostRootDir(dir string) {
dcMutex.Lock()
defer dcMutex.Unlock()
m.HostRootDir = dir
}
func (m *DriverConfigManage) SetNetworkName(networkName string) {
dcMutex.Lock()
defer dcMutex.Unlock()
m.NetWorkName = networkName
}
// 存储驱动上传配置定义文件目录 /var/tedge/edgex-driver-data/driver-library/
func (m *DriverConfigManage) GetLibraryDir() string {
return utils.GetPwdDir() + "/" + constants.DriverLibraryDir + "/"
}
// 驱动二进制文件路径 /var/tedge/edgex-driver-data/bin/modbus-1234
func (m *DriverConfigManage) GetBinPath(serverName string) string {
return utils.GetPwdDir() + "/" + constants.DriverBinDir + "/" + serverName
}
// 驱动启动的配置文件路径 /var/edge/run-config/modbus-1234.toml
func (m *DriverConfigManage) GetRunConfigPath(serviceName string) string {
return constants.DockerHummingbirdRootDir + "/" + constants.DriverRunConfigDir + "/" + serviceName + constants.ConfigSuffix
}
// docker挂载
func (m *DriverConfigManage) GetHostRunConfigPath(serviceName string) string {
return m.HostRootDir + "/" + constants.DriverRunConfigDir + "/" + serviceName + constants.ConfigSuffix
}
// 二进制版本路径
// 驱动启动的配置文件路径 /var/edge/mnt/modbus-1234.toml
func (m *DriverConfigManage) GetMntDir(serviceName string) string {
return constants.DockerHummingbirdRootDir + "/" + constants.DriverMntDir + "/" + serviceName
}
// docker挂载 的日志只针对docker版本二进制版本需要改动日志存储地址 /var/edge/mnt/modbus-1234.toml
func (m *DriverConfigManage) GetHostMntDir(serviceName string) string {
return m.HostRootDir + "/" + constants.DriverMntDir + "/" + serviceName
}
// 二进制版本 驱动运行日志文件 /var/tedge/mnt/modbus-1234/logs/driver.log
func (m *DriverConfigManage) GetLogFilePath(serviceName string) string {
return utils.GetPwdDir() + "/" + constants.DriverMntDir + "/" + serviceName + "/" + constants.DriverDefaultLogPath
}
// docker挂载
//logfilePath = "/var/edge/edge-driver-data/mnt/aliyun-iot/edgex-aliyun-cloud.log"
///var/edge/edge-driver-data/mnt/aliyun-iot
func (m *DriverConfigManage) GetHostLogFilePath(serviceName string) string {
return constants.DockerHummingbirdRootDir + "/" + constants.DriverMntDir + "/" + serviceName + "/" + constants.DriverDefaultLogPath
}

120
internal/dtos/ekuiper.go Normal file
View File

@ -0,0 +1,120 @@
/*******************************************************************************
* 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
type GetRuleInfoResponse struct {
Triggered bool `json:"triggered"`
Id string `json:"id"`
Name string `json:"name"`
Sql string `json:"sql"`
Actions []map[string]interface{} `json:"actions"`
Options map[string]interface{} `json:"options"`
}
type GetRuleStatusResponse struct {
Status string `json:"status"`
}
type CreateRule struct {
Triggered bool `json:"triggered"`
Id string `json:"id"`
Name string `json:"name"`
Sql string `json:"sql"`
Actions []Actions `json:"actions"`
}
type Actions struct {
Rest map[string]interface{} `json:"rest,omitempty"`
MQTT map[string]interface{} `json:"mqtt,omitempty"`
Kafka map[string]interface{} `json:"kafka,omitempty"`
Zmq map[string]interface{} `json:"zmq,omitempty"`
Redis map[string]interface{} `json:"redis,omitempty"`
Influx map[string]interface{} `json:"influx,omitempty"`
Tdengine map[string]interface{} `json:"tdengine,omitempty"`
}
type Rest struct {
Method string `json:"method,omitempty"`
Url string `json:"url,omitempty"`
BodyType string `json:"bodyType,omitempty"`
Timeout int `json:"timeout,omitempty"`
RunAsync bool `json:"runAsync,omitempty"`
OmitIfEmpty bool `json:"omitIfEmpty,omitempty"`
SendSingle bool `json:"sendSingle,omitempty"`
BufferLength int `json:"bufferLength,omitempty"`
EnableCache bool `json:"enableCache,omitempty"`
Format string `json:"format,omitempty"`
}
type MQTT struct {
Server string `json:"server,omitempty"`
Topic string `json:"topic,omitempty"`
ClientId string `json:"clientId,omitempty"`
ProtocolVersion string `json:"protocolVersion,omitempty"`
Qos int `json:"qos,omitempty"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
CertificationPath string `json:"certificationPath,omitempty"`
PrivateKeyPath string `json:"privateKeyPath,omitempty"`
RootCaPath string `json:"rootCaPath,omitempty"`
InsecureSkipVerify string `json:"insecureSkipVerify,omitempty"`
Retained bool `json:"retained,omitempty"`
//compression string `json:"compression"`
}
func (b CreateRule) BuildCreateRuleParam(actions []Actions, ruleId, sql string) CreateRule {
b.Triggered = false
b.Id = ruleId
b.Name = ruleId
b.Sql = sql
b.Actions = actions
return b
}
func GetRuleAlertEkuiperActions(actionUrl string) []Actions {
var a []Actions
rest := make(map[string]interface{})
rest["method"] = "POST"
rest["url"] = "http://hummingbird-core:58081" + "/api/v1/ekuiper/alert"
rest["bodyType"] = "json"
rest["timeout"] = 5000
rest["runAsync"] = false
rest["omitIfEmpty"] = false
rest["sendSingle"] = true
rest["enableCache"] = false
rest["format"] = "json"
a = append(a, Actions{
Rest: rest,
})
return a
}
func GetRuleSceneEkuiperActions(actionUrl string) []Actions {
var a []Actions
rest := make(map[string]interface{})
rest["method"] = "POST"
rest["url"] = actionUrl + "/api/v1/ekuiper/scene"
rest["bodyType"] = "json"
rest["timeout"] = 5000
rest["runAsync"] = false
rest["omitIfEmpty"] = false
rest["sendSingle"] = true
rest["enableCache"] = false
rest["format"] = "json"
a = append(a, Actions{
Rest: rest,
})
return a
}

View File

@ -0,0 +1,47 @@
package dtos
import (
"fmt"
"strconv"
"time"
"github.com/xuri/excelize/v2"
)
const (
DevicesFilename = "Devices"
)
var (
FuncPointImmutableHeader = []string{"DP ID", "Name", "DataType", "TransferType"}
FuncPointIntegerHeader = []string{"Scale", "ValueType"}
)
type ExportFile struct {
Excel *excelize.File
FileName string
}
func NewExportFile(filename string) (*ExportFile, error) {
ef := &ExportFile{
FileName: newFileName(filename),
Excel: excelize.NewFile(),
}
return ef, nil
}
func newFileName(name string) string {
date := time.Now().Format("2006-01-02")
unix := strconv.FormatInt(time.Now().Unix(), 10)
return fmt.Sprintf("%s_%s_%s.xlsx", name, date, unix)
}
func (f *ExportFile) GetCenterStyle() int {
style, _ := f.Excel.NewStyle(`{"alignment":{"horizontal": "center","vertical": "center"}}`)
return style
}
func (f *ExportFile) GetRequiredStyle() int {
style, _ := f.Excel.NewStyle(`{"alignment":{"horizontal": "center","vertical": "center"},"font":{"color": "#ea4335"}}`)
return style
}

53
internal/dtos/gateway.go Normal file
View File

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

12
internal/dtos/gps.go Normal file
View File

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

88
internal/dtos/homepage.go Normal file
View File

@ -0,0 +1,88 @@
/*******************************************************************************
* 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
type HomePageRequest struct {
}
type HomePageResponse struct {
PageInfo struct {
Product struct {
Total uint32 `json:"total"`
Self uint32 `json:"self"`
Other uint32 `json:"other"`
} `json:"product"`
Device struct {
Total uint32 `json:"total"`
Self uint32 `json:"self"`
Other uint32 `json:"other"`
} `json:"device"`
CloudInstance struct {
Count uint32 `json:"count"`
RunCount uint32 `json:"run_count"`
StopCount uint32 `json:"stop_count"`
//InstanceName string `json:"instanceName"`
//Status string `json:"status"`
} `json:"cloudInstance"`
Alert struct {
Total uint32 `json:"total"`
} `json:"alert"`
} `json:"pageInfo"`
QuickNavigation []QuickNavigation `json:"quickNavigation"`
Docs Docs `json:"docs"`
AlertPlate []AlertPlateQueryResponse `json:"alertPlate"`
MsgGather []MsgGather `json:"msg_gather"`
}
type PlatformInfo struct {
VersionName string `json:"version_name"`
DbName string `json:"db_name"`
}
type NetWorkInfo struct {
NewWork []NewWork `json:"newWork"`
Dns string `json:"dns"`
}
type NewWork struct {
NcId string `json:"ncId"`
LocalIp string `json:"localIp,omitempty"`
GwIp string `json:"gwIp,omitempty"`
SmIp string `json:"smIp,omitempty"`
Netlink bool `json:"netlink"`
}
type QuickNavigation struct {
Id string `json:"id"`
Name string `json:"name"`
Icon string `json:"icon"`
//JumpLink string `json:"jumpLink,omitempty"`
}
type Doc struct {
Name string `json:"name"`
JumpLink string `json:"jumpLink,omitempty"`
}
type Docs struct {
More string `json:"more"`
Doc []Doc `json:"info"`
}
type Alert struct {
Count int `json:"count"`
AlertLevel string `json:"alert_level"`
}
type MsgGather struct {
Count int `json:"count"`
Date string `json:"date"`
}

View File

@ -0,0 +1,35 @@
package dtos
import (
"io"
"github.com/xuri/excelize/v2"
)
type ImportFile struct {
Excel *excelize.File
}
func NewImportFile(f io.Reader) (*ImportFile, error) {
file, err := excelize.OpenReader(f)
if err != nil {
return nil, err
}
return &ImportFile{
Excel: file,
}, nil
}
type DeviceAddResponse struct {
List []DeviceAddResult `json:"list"`
ProcessNum int `json:"processNum"`
SuccessNum int `json:"successNum"`
FailNum int `json:"failNum"`
}
type DeviceAddResult struct {
Id string `json:"id"`
Name string `json:"name"`
Status bool `json:"status"`
Message string `json:"message"`
}

View File

@ -0,0 +1,38 @@
/*******************************************************************************
* Copyright 2017 Dell Inc.
* Copyright (c) 2019 Intel Corporation
*
* 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
type LanguageSDK struct {
Name string `json:"name"`
Icon string `json:"icon"`
Sort int `json:"sort"`
Addr string `json:"addr"`
Description string `json:"description"`
}
type LanguageSDKSyncRequest struct {
VersionName string `json:"version_name"`
}
type LanguageSDKSearchQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"`
}
type LanguageSDKSearchResponse struct {
Name string `json:"name"`
Icon string `json:"icon"`
Addr string `json:"addr"`
Description string `json:"description"`
}

22
internal/dtos/mqtt.go Normal file
View File

@ -0,0 +1,22 @@
package dtos
import (
"context"
)
type ConnectHandler func(ctx context.Context)
type CallbackHandler func(context.Context, CallbackMessage)
type CallbackMessage struct {
Error error
}
type NewMQTTClient struct {
Broker string `json:"broker"`
ClientId string `json:"client_id"`
Username string `json:"username"`
Password string `json:"password"`
PubTopic string `json:"pub_topic"`
SubTopics []string `json:"sub_topics"`
}

View File

@ -0,0 +1,20 @@
/*******************************************************************************
* 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
type MsgGatherSearchQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"`
Date []string `schema:"date"`
}

View File

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

View File

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

289
internal/dtos/product.go Normal file
View File

@ -0,0 +1,289 @@
/*******************************************************************************
* Copyright 2017 Dell Inc.
* Copyright (c) 2019 Intel Corporation
*
* 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 ProductSearchQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"`
Platform string `schema:"platform,omitempty"`
Name string `schema:"name,omitempty"`
ProductId string `schema:"product_id,omitempty"`
CloudInstanceId string `schema:"cloud_instance_id,omitempty"`
//DeviceLibraryId string `schema:"deviceLibraryId,omitempty"`
}
type ProductSearchQueryResponse struct {
Id string `json:"id"`
ProductId string `json:"product_id"`
Name string `json:"name"`
Key string `json:"key"`
NodeType string `json:"node_type"`
Platform string `json:"platform"`
Status string `json:"status"`
CreatedAt int64 `json:"created_at"`
CategoryName string `json:"category_name"`
}
func ProductResponseFromModel(p models.Product) ProductSearchQueryResponse {
return ProductSearchQueryResponse{
Id: p.Id,
ProductId: p.CloudProductId,
Name: p.Name,
Key: p.Key,
NodeType: string(p.NodeType),
Platform: string(p.Platform),
Status: string(p.Status),
CreatedAt: p.Created,
}
}
type ProductSearchByIdResponse struct {
Id string `json:"id"`
Name string `json:"name"`
Key string `json:"key"`
CloudProductId string `json:"cloud_product_id"`
CloudInstanceId string `json:"cloud_instance_id"`
Platform string `json:"platform"`
Protocol string `json:"protocol"`
NodeType string `json:"node_type"`
NetType string `json:"net_type"`
DataFormat string `json:"data_format"`
Factory string `json:"factory"`
Description string `json:"description"`
Status string `json:"status"`
CreatedAt int64 `json:"created_at"`
LastSyncTime int64 `json:"last_sync_time"`
Properties interface{} `json:"properties"`
Events interface{} `json:"events"`
Actions interface{} `json:"actions"`
}
func ProductSearchByIdFromModel(p models.Product) ProductSearchByIdResponse {
return ProductSearchByIdResponse{
Id: p.Id,
Name: p.Name,
CloudProductId: p.CloudProductId,
CloudInstanceId: p.CloudInstanceId,
Platform: string(p.Platform),
Protocol: p.Protocol,
Key: p.Key,
NodeType: string(p.NodeType),
NetType: string(p.NetType),
DataFormat: p.DataFormat,
Factory: p.Factory,
Description: p.Description,
CreatedAt: p.Created,
LastSyncTime: p.LastSyncTime,
Status: string(p.Status),
Properties: p.Properties,
Events: p.Events,
Actions: p.Actions,
}
}
type ProductSearchByIdOpenApiResponse struct {
Id string `json:"id"`
Name string `json:"name"`
Key string `json:"key"`
Platform string `json:"platform"`
Protocol string `json:"protocol"`
NodeType string `json:"node_type"`
NetType string `json:"net_type"`
DataFormat string `json:"data_format"`
Factory string `json:"factory"`
Status string `json:"status"`
Description string `json:"description"`
CreatedAt int64 `json:"created_at"`
//Properties []OpenApiProperties `json:"properties"`
//Events []OpenApiEvents `json:"events"`
//Actions []OpenApiActions `json:"services"`
}
type OpenApiProperties struct {
Id string `json:"id"`
ProductId string `json:"product_id"` // 产品ID
Name string `json:"name"` // 属性名称
Code string `json:"code"` // 标识符
AccessMode string `json:"access_mode"` // 数据传输类型
Required bool `json:"required"`
TypeSpec OpenApiTypeSpec `json:"type_spec"` // 数据属性
Description string `json:"description"`
CreatedAt int64 `json:"created_at"`
}
type OpenApiEvents struct {
Id string `json:"id"`
ProductId string `json:"product_id"`
Name string `json:"name"` // 功能名称
Code string `json:"code"` // 标识符
EventType string `json:"event_type"`
Required bool `json:"required"`
OutputParams []OpenApiOutPutParams `json:"output_params"`
Description string `json:"description"`
CreatedAt int64 `json:"created_at"`
}
//
//func (t *OpenApiEvents) TransformModelInPutParams() (inPutParams models.InPutParams) {
// for _, datum := range t.OutputParams {
// var inputOutput models.InputOutput
// inputOutput.Code = datum.Code
// inputOutput.Name = datum.Name
// inputOutput.TypeSpec = getThingModelTemplateTypeSpec(string(datum.TypeSpec.Type), datum.TypeSpec.Specs, nil)
// inPutParams = append(inPutParams, inputOutput)
// }
// return
//}
type OpenApiOutPutParams struct {
Code string `json:"code"`
Name string `json:"name"`
TypeSpec OpenApiTypeSpec `json:"type_spec"`
}
type OpenApiInPutParams struct {
Code string `json:"code"`
Name string `json:"name"`
TypeSpec OpenApiTypeSpec `json:"type_spec"`
}
type OpenApiActions struct {
Id string `json:"id"`
ProductId string `json:"product_id"`
Name string `json:"name"` // 功能名称
Code string `json:"code"` // 标识符
Required bool `json:"required"`
CallType constants.CallType `json:"call_type"`
InputParams []OpenApiInPutParams `json:"input_params"` // 输入参数
OutputParams []OpenApiOutPutParams `json:"output_params"` // 输出参数
CreatedAt int64 `json:"created_at"`
Description string `json:"description"`
}
type OpenApiTypeSpec struct {
Type constants.SpecsType `json:"type,omitempty"`
Specs string `json:"specs,omitempty"`
}
func ProductSearchByIdOpenApiFromModel(p models.Product) ProductSearchByIdOpenApiResponse {
return ProductSearchByIdOpenApiResponse{
Id: p.Id,
Name: p.Name,
Key: p.Key,
Platform: string(p.Platform),
Protocol: p.Protocol,
NodeType: string(p.NodeType),
NetType: string(p.NetType),
DataFormat: p.DataFormat,
Factory: p.Factory,
Status: string(p.Status),
Description: p.Description,
CreatedAt: p.Created,
}
}
type ProductSearchOpenApiResponse struct {
Id string `json:"id"`
Name string `json:"name"`
Key string `json:"key"`
Platform string `json:"platform"`
Protocol string `json:"protocol"`
NodeType string `json:"node_type"`
NetType string `json:"net_type"`
DataFormat string `json:"data_format"`
Factory string `json:"factory"`
Status string `json:"status"`
Description string `json:"description"`
CreatedAt int64 `json:"created_at"`
}
func ProductSearchOpenApiFromModel(p models.Product) ProductSearchOpenApiResponse {
return ProductSearchOpenApiResponse{
Id: p.Id,
Name: p.Name,
Key: p.Key,
Platform: string(p.Platform),
Protocol: p.Protocol,
NodeType: string(p.NodeType),
NetType: string(p.NetType),
DataFormat: p.DataFormat,
Factory: p.Factory,
Status: string(p.Status),
Description: p.Description,
CreatedAt: p.Created,
}
}
type ProductSyncRequest struct {
CloudInstanceId string `json:"cloud_instance_id"`
//Extra struct{
//
//} `json:"extra"`
//Aliyun *struct {
// ResourceGroupId string `json:"resource_group_id"`
//} `json:"ali_yun"`
//HuaweiYun *struct {
// ProjectId string `json:"project_id"`
// AppId string `json:"app_id"`
//} `json:"huawei_yun"`
}
type ProductSyncByIdRequest struct {
ProductId string `json:"product_id"`
}
type ProductAddRequest struct {
Name string `json:"name"` //产品名字
//Platform string `json:"platform"`
Key string `json:"key"`
CategoryTemplateId string `json:"category_template_id"` //如果是自定义 id固定传递"1"
Protocol string `json:"protocol"` //协议
NodeType string `json:"node_type"` //节点类型
NetType string `json:"net_type"` //联网模式
DataFormat string `json:"data_format"` //数据类型
Factory string `json:"factory"` //厂家
Description string `json:"description"` //描述
}
type OpenApiAddProductRequest struct {
Name string `json:"name"` //产品名字
Protocol string `json:"protocol"` //协议
NodeType string `json:"node_type"` //节点类型
NetType string `json:"net_type"` //联网模式
DataFormat string `json:"data_format"` //数据类型
Factory string `json:"factory"` //厂家
Description string `json:"description"` //描述
//Properties []OpenApiProperties `json:"properties"`
//Events []OpenApiEvents `json:"events"`
//Actions []OpenApiActions `json:"services"`
}
type OpenApiUpdateProductRequest struct {
Id string `json:"id"`
Name *string `json:"name"` //产品名字
Protocol *string `json:"protocol"` //协议
NodeType *string `json:"node_type"` //节点类型
NetType *string `json:"net_type"` //联网模式
DataFormat *string `json:"data_format"` //数据类型
Factory *string `json:"factory"` //厂家
Description *string `json:"description"` //描述
//Properties []OpenApiProperties `json:"properties"`
//Events []OpenApiEvents `json:"events"`
//Actions []OpenApiActions `json:"services"`
}

View File

@ -0,0 +1,35 @@
/*******************************************************************************
* 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
type QuickNavigationSearchQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"`
Name string `schema:"name,omitempty"`
}
type DocsSearchQueryRequest struct {
BaseSearchConditionQuery `schema:",inline"`
Name string `schema:"name,omitempty"`
}
type CosQuickNavigationTemplateResponse struct {
Name string `json:"Name"`
Sort int `json:"Sort"`
Icon string `json:"Icon"`
JumpLink string `json:"JumpLink"`
}
type CosDocTemplateResponse struct {
Name string `json:"Name"`
Sort int `json:"Sort"`
JumpLink string `json:"JumpLink"`
}

31
internal/dtos/rpclog.go Normal file
View File

@ -0,0 +1,31 @@
package dtos
import "encoding/json"
type InvokeLog struct {
Req interface{} `json:"req"`
Reply interface{} `json:"reply"`
Success bool `json:"success"`
Method string `json:"method"`
Duration string `json:"duration"`
Error string `json:"error"`
}
func (il InvokeLog) ToString() string {
data, _ := json.Marshal(il)
return string(data)
}
type HandleLog struct {
Req interface{} `json:"req"`
Reply interface{} `json:"reply"`
Success bool `json:"success"`
Method string `json:"method"`
Duration string `json:"duration"`
Error string `json:"error"`
}
func (hl HandleLog) ToString() string {
data, _ := json.Marshal(hl)
return string(data)
}

View File

@ -0,0 +1,29 @@
/*******************************************************************************
* Copyright 2017 Dell Inc.
* Copyright (c) 2019 Intel Corporation
*
* 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 "encoding/json"
type RpcData struct {
Code WsCode
ReqId string
ErrCode uint32
Data interface{}
}
func (rd *RpcData) String() string {
str, _ := json.Marshal(rd)
return string(str)
}

114
internal/dtos/ruleengine.go Normal file
View File

@ -0,0 +1,114 @@
/*******************************************************************************
* 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

@ -0,0 +1,94 @@
package dtos
type (
// LogConfig logger common
LogConfig struct {
FileName string
LogLevel string
}
CloudInstanceLogConfig struct {
FileName string
LogSwitch bool
LogFilter []string
}
// RPCConfig internal grpc server common
RPCConfig struct {
Address string
UseTLS bool
CertFile string
KeyFile string
}
// ClientInfo provides the host and port of another service in tedge.
ClientInfo struct {
Address string
// 是否启用tls
UseTLS bool
// ca cert
CertFilePath string
// mqtt clientId
ClientId string
// mqtt username
Username string
// mqtt password
Password string
}
ServiceInfo struct {
// ID 驱动实例化后生成的唯一ID驱动管理服务自动生成。
// 驱动实例启动后会通过该ID去元数据服务同步设备和更新驱动配置。
ID string
Name string
Server RPCConfig
// ProductList 驱动对应的产品ID列表
//ProductList []string
//GwId string
//LocalKey string
// 跳过激活检查
Activated bool
}
DriverConfig struct {
Logger LogConfig
Clients map[string]ClientInfo
Service ServiceInfo
CustomParam string
}
CloudInstanceConfig struct {
Logger CloudInstanceLogConfig
Clients map[string]ClientInfo
Authorization AuthorizationInfo
Service ServiceInfo
}
AuthorizationInfo struct {
AK string
SK string
Regions string
ProjectId string
InstanceId string
Endpoint string
MqttHost string
MqttPort string
}
AppServiceConfig struct {
Log struct {
LogLevel string
LogPath string
}
Tedge struct {
Host string
Port int32
}
Server struct {
ID string
Name string
Host string
Port int32
}
//应用私有配置
CustomConfig map[string]interface{}
}
)

88
internal/dtos/scene.go Normal file
View File

@ -0,0 +1,88 @@
/*******************************************************************************
* 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"`
//Condition constants.WorkerCondition `json:"condition"` //执行条件
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"`
//CronExpression string `json:"cron_expression"`
}
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"`
//Name string `schema:"name,omitempty"`
StartAt int64 `schema:"start_time"`
EndAt int64 `schema:"end_time"`
SceneId string `json:"scene_id"`
}

149
internal/dtos/stats.go Normal file
View File

@ -0,0 +1,149 @@
/*******************************************************************************
* Copyright 2017 Dell Inc.
*
* 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 (
"encoding/json"
"github.com/winc-link/hummingbird/internal/models"
)
type StatsResp struct {
MemoryStats MemoryStats `json:"memory_stats"`
CpuStats CpuStats `json:"cpu_stats"`
PrecpuStats CpuStats `json:"precpu_stats"`
}
type CpuStats struct {
CpuUsage CpuUsage `json:"cpu_usage"`
SystemCpuUsage int64 `json:"system_cpu_usage"`
OnlineCpus int64 `json:"online_cpus"`
}
type CpuUsage struct {
PercpuUsage []int64 `json:"percpu_usage"`
TotalUsage int64 `json:"total_usage"`
}
type MemoryStats struct {
Usage int64 `json:"usage"`
Limit int64 `json:"limit"`
MaxUsage int64 `json:"max_usage"`
Stats MemoryStatsDetail `json:"stats"`
}
type MemoryStatsDetail struct {
Cache int64 `json:"cache"`
Rss int64 `json:"rss"`
}
func (s StatsResp) UsedMemory() int64 {
return s.MemoryStats.Usage - s.MemoryStats.Stats.Cache
}
// MemoryUsage %
func (s StatsResp) MemoryUsage() float64 {
if s.MemoryStats.Limit <= 0 {
return 0
}
return float64(s.UsedMemory()/s.MemoryStats.Limit) * 100.0
}
func (s StatsResp) CpuDelta() float64 {
return float64(s.CpuStats.CpuUsage.TotalUsage - s.PrecpuStats.CpuUsage.TotalUsage)
}
func (s StatsResp) SystemCpuDelta() float64 {
return float64(s.CpuStats.SystemCpuUsage - s.PrecpuStats.SystemCpuUsage)
}
// CpuUsage %
func (s StatsResp) CpuUsage() float64 {
scd := s.SystemCpuDelta()
if scd <= 0 {
return 0
}
return (s.CpuDelta() / scd) * float64(s.CpuStats.OnlineCpus) * 100.0
}
type SystemMetrics struct {
Timestamp int64 `json:"timestamp"` // 时间戳
CpuUsedPercent float64 `json:"cpu_used_percent"` // cpu 使用率百分比
CpuAvg float64 `json:"cpu_avg"` // cpu 负载1分钟
Memory SystemMemory `json:"memory"` // 内存
Disk SystemDisk `json:"disk"` // 磁盘使用率
Network map[string]SystemNetwork `json:"network"` // 网卡en/eth的IO
Openfiles int `json:"openfiles"` // 文件数linux 才有
}
type SystemMemory struct {
Total uint64 `json:"total"` // 大小
Used uint64 `json:"used"` // 使用大小 bytes
UsedPercent float64 `json:"used_percent"` // 百分比
}
type SystemDisk struct {
Path string `json:"path"` // 获取 / 目录信息
Total uint64 `json:"total"` // 大小 bytes
Used uint64 `json:"used"` // 使用值
UsedPercent float64 `json:"used_percent"` // 使用百分比
}
type SystemNetwork struct {
Name string `json:"name"`
BytesSent uint64 `json:"bytes_sent"` // 总发送字节
BytesRecv uint64 `json:"bytes_recv"` // 总接收字节
BytesSentPre uint64 `json:"bytes_sent_pre"` // 单位时间内发送的字节1分钟
BytesRecvPre uint64 `json:"bytes_recv_pre"` // 单位时间内接收的字节1分钟
Last int64 `json:"-"` // 采集时记录,不做输出
}
func FromModelsSystemMetricsToDTO(m models.SystemMetrics) (SystemMetrics, error) {
var s SystemMetrics
if err := json.Unmarshal([]byte(m.Data), &s); err != nil {
return SystemMetrics{}, err
}
return s, nil
}
func (s SystemNetwork) String() string {
bytes, _ := json.Marshal(s)
return string(bytes)
}
func (s SystemMetrics) String() string {
bytes, _ := json.Marshal(s)
return string(bytes)
}
// Response
type SystemMetricsResponse struct {
Total int `json:"total"`
Metrics []SystemStatResponse `json:"metrics"`
}
type SystemStatResponse struct {
Timestamp int64 `json:"timestamp"` // 时间戳
CpuUsedPercent float64 `json:"cpu_used_percent"` // cpu 使用率百分比
MemoryTotal uint64 `json:"memory_total"` // 内存使用
MemoryUsed uint64 `json:"memory_used"` // 内存使用
MemoryUsedPercent float64 `json:"memory_used_percent"` // 内存使用率
DiskTotal uint64 `json:"disk_total"`
DiskUsed uint64 `json:"disk_used"`
DiskUsedPercent float64 `json:"disk_used_percent"` // 磁盘使用率
NetSentBytes uint64 `json:"net_sent_bytes"` // 网卡发送字节
NetRecvBytes uint64 `json:"net_recv_bytes"` // 网卡接收字节
Openfiles int `json:"openfiles"` // 文件句柄数linux 才有
}

View File

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

135
internal/dtos/thingmodel.go Normal file
View File

@ -0,0 +1,135 @@
/*******************************************************************************
* Copyright 2017 Dell Inc.
* Copyright (c) 2019 Intel Corporation
*
* 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 ThingModelAddOrUpdateReq struct {
Id string `json:"id"`
ProductId string `json:"product_id"`
ThingModelType string `json:"thing_model_type"`
//ModelName string `json:"model_name"`
Name string `json:"name"`
Code string `json:"code"`
Description string `json:"description"`
Tag string `json:"tag"`
Property *ThingModelProperties `json:"property"`
Event *ThingModelEvents `json:"event"`
Action *ThingModelActions `json:"action"`
}
type ThingModelProperties struct {
AccessModel string `json:"access_model"`
Require bool `json:"require"`
DataType constants.SpecsType `json:"type"`
TypeSpec interface{} `json:"specs"`
}
type ThingModelEventAction struct {
Code string `json:"code"`
Name string `json:"name"`
DataType constants.SpecsType `json:"type"`
TypeSpec interface{} `json:"specs"`
}
type ThingModelEvents struct {
EventType string `json:"event_type"`
OutPutParam []ThingModelEventAction `json:"output_param"`
}
type ThingModelActions struct {
CallType constants.CallType `json:"call_type"`
InPutParam []ThingModelEventAction `json:"input_param"`
OutPutParam []ThingModelEventAction `json:"output_param"`
}
type ThingModelDeleteReq struct {
ThingModelId string `json:"thing_model_id"`
ThingModelType string `json:"thing_model_type"`
}
type SystemThingModelSearchReq struct {
ModelName string `schema:"modelName"`
ThingModelType string `schema:"thingModelType"`
}
type OpenApiThingModelProperties struct {
Id string `json:"id"`
//ProductId string `json:"product_id"` // 产品ID
Name string `json:"name"` // 属性名称
Code string `json:"code"` // 标识符
AccessMode string `json:"access_mode"` // 数据传输类型
Require bool `json:"require"`
TypeSpec models.TypeSpec `json:"type_spec"` // 数据属性
Description string `json:"description"`
}
type OpenApiThingModelEvents struct {
Id string `json:"id"`
//ProductId string `json:"product_id"`
EventType string `json:"event_type"`
Name string `json:"name"` // 功能名称
Code string `json:"code"` // 标识符
Description string `json:"description"`
Require bool `json:"require"`
OutputParams models.OutPutParams `json:"output_params"`
}
type OpenApiThingModelServices struct {
Id string `json:"id"`
//ProductId string `json:"product_id"`
Name string `json:"name"` // 功能名称
Code string `json:"code"` // 标识符
Description string `json:"description"`
Require bool `json:"require"`
CallType constants.CallType `json:"call_type"`
InputParams models.InPutParams `json:"input_params"` // 输入参数
OutputParams models.OutPutParams `json:"output_params"` // 输出参数
}
type OpenApiThingModelAddOrUpdateReq struct {
ProductId string `json:"product_id"`
Properties []OpenApiThingModelProperties `json:"properties"`
Events []OpenApiThingModelEvents `json:"events"`
Services []OpenApiThingModelServices `json:"services"`
}
type OpenApiQueryThingModelReq struct {
ProductId string `schema:"product_id,omitempty"`
}
type OpenApiQueryThingModel struct {
Properties []OpenApiThingModelProperties `json:"properties"`
Events []OpenApiThingModelEvents `json:"events"`
Services []OpenApiThingModelServices `json:"services"`
}
type OpenApiThingModelDeleteReq struct {
ProductId string `json:"product_id"`
PropertyIds []string `json:"property_ids"`
EventIds []string `json:"event_ids"`
ServiceIds []string `json:"service_ids"`
}
type OpenApiSetDeviceThingModel struct {
DeviceId string `json:"deviceId"`
Item map[string]interface{} `json:"item"`
}
type OpenApiQueryDevicePropertyData struct {
}

View File

@ -0,0 +1,107 @@
/*******************************************************************************
* Copyright 2017 Dell Inc.
*
* 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
type ThingModelDataBaseRequest struct {
First bool `json:"first"`
Last bool `json:"last"`
//Page int `json:"page"`
//PageSize int `json:"pageSize"`
Range []int64 `json:"range"`
}
type ThingModelPropertyDataRequest struct {
BaseSearchConditionQuery `schema:",inline"`
ThingModelDataBaseRequest
DeviceId string ` json:"deviceId"`
Code string `json:"code"`
}
type ThingModelEventDataRequest struct {
BaseSearchConditionQuery `schema:",inline"`
ThingModelDataBaseRequest
DeviceId string ` json:"deviceId"`
EventCode string `json:"eventCode"`
EventType string `json:"eventType"`
}
type ThingModelEventDataResponse struct {
EventCode string `json:"event_code"`
EventType string `json:"event_type"`
OutputData map[string]interface{} `json:"output_data"`
ReportTime int64 `json:"report_time"`
Name string `json:"name"`
}
type ThingModelEventDataResponseArray []ThingModelEventDataResponse
func (array ThingModelEventDataResponseArray) Len() int {
return len(array)
}
func (array ThingModelEventDataResponseArray) Less(i, j int) bool {
return array[i].ReportTime > array[j].ReportTime //从小到大, 若为大于号,则从大到小
}
func (array ThingModelEventDataResponseArray) Swap(i, j int) {
array[i], array[j] = array[j], array[i]
}
type ThingModelServiceDataResponse struct {
ReportTime int64 `json:"report_time"`
Code string `json:"code"`
ServiceName string `json:"service_name"`
InputData map[string]interface{} `json:"input_data"`
OutputData map[string]interface{} `json:"output_data"`
}
type ThingModelServiceDataResponseArray []ThingModelServiceDataResponse
func (array ThingModelServiceDataResponseArray) Len() int {
return len(array)
}
func (array ThingModelServiceDataResponseArray) Less(i, j int) bool {
return array[i].ReportTime > array[j].ReportTime //从小到大, 若为大于号,则从大到小
}
func (array ThingModelServiceDataResponseArray) Swap(i, j int) {
array[i], array[j] = array[j], array[i]
}
type ThingModelDataResponse struct {
ReportData
Code string `json:"code"`
DataType string `json:"data_type"`
Unit string `json:"unit"`
Name string `json:"name"`
AccessMode string `json:"access_mode"`
}
type ThingModelPropertyDataResponse struct {
ReportData interface{} `json:"report_data"`
Code string `json:"code"`
DataType string `json:"data_type"`
Unit string `json:"unit"`
Name string `json:"name"`
AccessMode string `json:"access_mode"`
}
type ThingModelServiceDataRequest struct {
BaseSearchConditionQuery `schema:",inline"`
ThingModelDataBaseRequest
DeviceId string ` json:"deviceId"`
Code string `json:"code"`
}

View File

@ -0,0 +1,576 @@
/*******************************************************************************
* Copyright 2017 Dell Inc.
* Copyright (c) 2019 Intel Corporation
*
* 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 (
"encoding/json"
"github.com/winc-link/hummingbird/internal/models"
"github.com/winc-link/hummingbird/internal/pkg/constants"
"github.com/winc-link/hummingbird/internal/pkg/utils"
"strconv"
"strings"
"time"
)
type ThingModelTemplate struct {
Properties []ThingModelTemplateProperties `json:"properties"`
Events []ThingModelTemplateEvents `json:"events"`
Services []ThingModelTemplateServices `json:"services"`
}
//------------------------------------------------------------
//array
//{
//"childDataType":"TEXT",
//"customFlag":true,
//"dataType":"ARRAY",
//"size":128
//}
type ThingModelTemplateArray struct {
ChildDataType string `json:"childDataType"`
Size int `json:"size"`
}
//------------------------------------------------------------
//{
// "dataType":"DOUBLE",
// "max":"23",
// "min":"16",
// "precise":7,
// "step":"0.01",
// "unit":"°C",
// "unitName":"摄氏度"
//}
type ThingModelTemplateIntOrFloat struct {
Max string `json:"max"`
Min string `json:"min"`
Step string `json:"step"`
Unit string `json:"unit"`
UnitName string `json:"unitName"`
}
//------------------------------------------------------------
//[
//{
//"dataType":"BOOL",
//"name":"未查询",
//"value":0
//},
//{
//"dataType":"BOOL",
//"name":"查询",
//"value":1
//}
//]
type ThingModelTemplateBool struct {
Name string `json:"name"`
Value int `json:"value"`
}
//------------------------------------------------------------
//{
//"dataType":"TEXT",
//"length":255
//}
type ThingModelTemplateText struct {
Length int `json:"length"`
}
//------------------------------------------------------------
//{
//"dataType":"Date",
//"length":255
//}
type ThingModelTemplateDate struct {
Length string `json:"length"`
}
//------------------------------------------------------------
//[
//{
//"dataType":"ENUM",
//"name":"电源",
//"value":0
//},
//{
//"dataType":"ENUM",
//"name":"电池",
//"value":1
//}
//]
type ThingModelTemplateEnum struct {
Name string `json:"name"`
Value int `json:"value"`
}
type ThingModelTemplateStruct struct {
ChildDataType string `json:"childDataType"`
ChildName string `json:"childName"`
Identifier string `json:"identifier"`
ChildSpecsDTO interface{} `json:"childSpecsDTO"`
}
//------------------------------------------------------------
// INT DOUBLE FLOAT TEXT ARRAY=> dataSpecs
//BOOL ENUM STRUCT=> dataSpecsList
type ThingModelTemplateProperties struct {
Name string `json:"name"`
Identifier string `json:"identifier"`
DataType string `json:"dataType"`
Description string `json:"description"`
Required bool `json:"required"`
RwFlag string `json:"rwFlag"`
DataSpecs interface{} `json:"dataSpecs"`
DataSpecsList interface{} `json:"dataSpecsList"`
}
func (t *ThingModelTemplateProperties) TransformModelTypeSpec() (typeSpec models.TypeSpec) {
return getThingModelTemplateTypeSpec(t.DataType, t.DataSpecs, t.DataSpecsList)
}
func getModelSpecByDataType(specType constants.SpecsType, dto interface{}) string {
switch specType {
case constants.SpecsTypeInt, constants.SpecsTypeFloat:
thingModelTemplateIntOrFloat := new(ThingModelTemplateIntOrFloat)
b, _ := json.Marshal(dto)
err := json.Unmarshal(b, thingModelTemplateIntOrFloat)
if err != nil {
return ""
}
var modelTypeSpecIntOrFloat models.TypeSpecIntOrFloat
modelTypeSpecIntOrFloat.Max = thingModelTemplateIntOrFloat.Max
modelTypeSpecIntOrFloat.Min = thingModelTemplateIntOrFloat.Min
modelTypeSpecIntOrFloat.Step = thingModelTemplateIntOrFloat.Step
modelTypeSpecIntOrFloat.Unit = thingModelTemplateIntOrFloat.Unit
modelTypeSpecIntOrFloat.UnitName = thingModelTemplateIntOrFloat.UnitName
return modelTypeSpecIntOrFloat.TransformTostring()
case constants.SpecsTypeText:
thingModelTemplateText := new(ThingModelTemplateText)
b, _ := json.Marshal(dto)
err := json.Unmarshal(b, thingModelTemplateText)
if err != nil {
return ""
}
var modelTypeSpecText models.TypeSpecText
modelTypeSpecText.Length = strconv.Itoa(thingModelTemplateText.Length)
return modelTypeSpecText.TransformTostring()
case constants.SpecsTypeDate:
var modelTypeSpecText models.TypeSpecDate
return modelTypeSpecText.TransformTostring()
case constants.SpecsTypeBool:
thingModelTemplateBool := new([]ThingModelTemplateBool)
b, _ := json.Marshal(dto)
err := json.Unmarshal(b, thingModelTemplateBool)
if err != nil {
return ""
}
var modelTypeSpecBool models.TypeSpecBool
modelTypeSpecBool = make(map[string]string)
if thingModelTemplateBool != nil {
for _, templateBool := range *thingModelTemplateBool {
modelTypeSpecBool[strconv.Itoa(templateBool.Value)] = templateBool.Name
}
}
return modelTypeSpecBool.TransformTostring()
case constants.SpecsTypeEnum:
thingModelTemplateEnum := new([]ThingModelTemplateEnum)
b, _ := json.Marshal(dto)
err := json.Unmarshal(b, thingModelTemplateEnum)
if err != nil {
return ""
}
var modelTypeSpecEunm models.TypeSpecEnum
modelTypeSpecEunm = make(map[string]string)
if thingModelTemplateEnum != nil {
for _, templateEunm := range *thingModelTemplateEnum {
modelTypeSpecEunm[strconv.Itoa(templateEunm.Value)] = templateEunm.Name
}
}
return modelTypeSpecEunm.TransformTostring()
case constants.SpecsTypeArray:
thingModelTemplateArray := new(ThingModelTemplateArray)
b, _ := json.Marshal(dto)
err := json.Unmarshal(b, thingModelTemplateArray)
if err != nil {
return ""
}
var modelTypeSpecArray models.TypeSpecArray
modelTypeSpecArray.Size = strconv.Itoa(thingModelTemplateArray.Size)
modelTypeSpecArray.Item = models.Item{
Type: thingModelTemplateArray.ChildDataType,
}
return modelTypeSpecArray.TransformTostring()
}
return ""
}
func transformSpecType(specType string) constants.SpecsType {
var specs constants.SpecsType
switch specType {
case "INT":
specs = constants.SpecsTypeInt
case "DOUBLE", "FLOAT":
specs = constants.SpecsTypeFloat
case "TEXT":
specs = constants.SpecsTypeText
case "ARRAY":
specs = constants.SpecsTypeArray
case "BOOL":
specs = constants.SpecsTypeBool
case "ENUM":
specs = constants.SpecsTypeEnum
case "STRUCT":
specs = constants.SpecsTypeStruct
case "DATE":
specs = constants.SpecsTypeDate
}
return specs
}
//ASYNC SYNC
type ThingModelTemplateServices struct {
ServiceName string `json:"serviceName"`
Identifier string `json:"identifier"`
Description string `json:"description"`
Required bool `json:"required"`
CallType constants.CallType `json:"callType"`
InputParams []ThingModelTemplateServicesInputParam `json:"inputParams"`
OutParams []ThingModelTemplateServicesOutParam `json:"outParams"`
}
type ThingModelTemplateServicesInputParam struct {
Name string `json:"name"`
Identifier string `json:"identifier"`
DataType string `json:"dataType"`
DataSpecs interface{} `json:"dataSpecs"`
DataSpecsList interface{} `json:"dataSpecsList"`
}
type ThingModelTemplateServicesOutParam struct {
Name string `json:"name"`
Identifier string `json:"identifier"`
DataType string `json:"dataType"`
DataSpecs interface{} `json:"dataSpecs"`
DataSpecsList interface{} `json:"dataSpecsList"`
}
func (t *ThingModelTemplateServices) TransformModelInPutParams() (inPutParams models.InPutParams) {
for _, datum := range t.InputParams {
var inputOutput models.InputOutput
inputOutput.Code = datum.Identifier
inputOutput.Name = datum.Name
inputOutput.TypeSpec = getThingModelTemplateTypeSpec(datum.DataType, datum.DataSpecs, datum.DataSpecsList)
inPutParams = append(inPutParams, inputOutput)
}
return
}
func (t *ThingModelTemplateServices) TransformModelOutPutParams() (outPutParams models.OutPutParams) {
for _, datum := range t.OutParams {
var inputOutput models.InputOutput
inputOutput.Code = datum.Identifier
inputOutput.Name = datum.Name
inputOutput.TypeSpec = getThingModelTemplateTypeSpec(datum.DataType, datum.DataSpecs, datum.DataSpecsList)
outPutParams = append(outPutParams, inputOutput)
}
return
}
type ThingModelTemplateEvents struct {
EventName string `json:"eventName"`
EventType string `json:"eventType"`
Identifier string `json:"identifier"`
Description string `json:"description"`
Required bool `json:"required"`
OutputData []ThingModelTemplateEventsOutputData `json:"outputData"`
}
type ThingModelTemplateEventsOutputData struct {
Name string `json:"name"`
Identifier string `json:"identifier"`
DataType string `json:"dataType"`
Required bool `json:"required"`
DataSpecs interface{} `json:"dataSpecs"`
DataSpecsList interface{} `json:"dataSpecsList"`
}
func (t *ThingModelTemplateEvents) TransformModelOutputParams() (outPutParams models.OutPutParams) {
for _, datum := range t.OutputData {
var inputOutput models.InputOutput
inputOutput.Code = datum.Identifier
inputOutput.Name = datum.Name
inputOutput.TypeSpec = getThingModelTemplateTypeSpec(datum.DataType, datum.DataSpecs, datum.DataSpecsList)
outPutParams = append(outPutParams, inputOutput)
}
return outPutParams
}
func getThingModelTemplateTypeSpec(dataType string, dataSpecs, dataSpecsList interface{}) (typeSpec models.TypeSpec) {
typeSpec.Type = transformSpecType(dataType)
switch typeSpec.Type {
case constants.SpecsTypeInt, constants.SpecsTypeFloat:
thingModelTemplateIntOrFloat := new(ThingModelTemplateIntOrFloat)
b, _ := json.Marshal(dataSpecs)
err := json.Unmarshal(b, thingModelTemplateIntOrFloat)
if err != nil {
return
}
var modelTypeSpecIntOrFloat models.TypeSpecIntOrFloat
modelTypeSpecIntOrFloat.Max = thingModelTemplateIntOrFloat.Max
modelTypeSpecIntOrFloat.Min = thingModelTemplateIntOrFloat.Min
modelTypeSpecIntOrFloat.Step = thingModelTemplateIntOrFloat.Step
modelTypeSpecIntOrFloat.Unit = thingModelTemplateIntOrFloat.Unit
modelTypeSpecIntOrFloat.UnitName = thingModelTemplateIntOrFloat.UnitName
typeSpec.Specs = modelTypeSpecIntOrFloat.TransformTostring()
case constants.SpecsTypeText:
thingModelTemplateText := new(ThingModelTemplateText)
b, _ := json.Marshal(dataSpecs)
err := json.Unmarshal(b, thingModelTemplateText)
if err != nil {
return
}
var modelTypeSpecText models.TypeSpecText
modelTypeSpecText.Length = strconv.Itoa(thingModelTemplateText.Length)
typeSpec.Specs = modelTypeSpecText.TransformTostring()
case constants.SpecsTypeDate:
var modelTypeSpecText models.TypeSpecDate
typeSpec.Specs = modelTypeSpecText.TransformTostring()
case constants.SpecsTypeBool:
thingModelTemplateBool := new([]ThingModelTemplateBool)
b, _ := json.Marshal(dataSpecsList)
err := json.Unmarshal(b, thingModelTemplateBool)
if err != nil {
return
}
var modelTypeSpecBool models.TypeSpecBool
modelTypeSpecBool = make(map[string]string)
if thingModelTemplateBool != nil {
for _, templateBool := range *thingModelTemplateBool {
modelTypeSpecBool[strconv.Itoa(templateBool.Value)] = templateBool.Name
}
}
typeSpec.Specs = modelTypeSpecBool.TransformTostring()
case constants.SpecsTypeEnum:
thingModelTemplateEnum := new([]ThingModelTemplateEnum)
b, _ := json.Marshal(dataSpecsList)
err := json.Unmarshal(b, thingModelTemplateEnum)
if err != nil {
return
}
var modelTypeSpecEunm models.TypeSpecEnum
modelTypeSpecEunm = make(map[string]string)
if thingModelTemplateEnum != nil {
for _, templateEunm := range *thingModelTemplateEnum {
modelTypeSpecEunm[strconv.Itoa(templateEunm.Value)] = templateEunm.Name
}
}
typeSpec.Specs = modelTypeSpecEunm.TransformTostring()
case constants.SpecsTypeArray:
thingModelTemplateArray := new(ThingModelTemplateArray)
b, _ := json.Marshal(dataSpecs)
err := json.Unmarshal(b, thingModelTemplateArray)
if err != nil {
return
}
var modelTypeSpecArray models.TypeSpecArray
modelTypeSpecArray.Size = strconv.Itoa(thingModelTemplateArray.Size)
modelTypeSpecArray.Item = models.Item{
Type: strings.ToLower(thingModelTemplateArray.ChildDataType),
}
typeSpec.Specs = modelTypeSpecArray.TransformTostring()
case constants.SpecsTypeStruct:
thingModelTemplateStruct := new([]ThingModelTemplateStruct)
b, _ := json.Marshal(dataSpecsList)
err := json.Unmarshal(b, thingModelTemplateStruct)
if err != nil {
return
}
var modelTypeSpecStruct []models.TypeSpecStruct
if thingModelTemplateStruct != nil {
for _, templateStruct := range *thingModelTemplateStruct {
modelTypeSpecStruct = append(modelTypeSpecStruct, models.TypeSpecStruct{
Code: templateStruct.Identifier,
Name: templateStruct.ChildName,
DataType: models.TypeSpec{
Type: transformSpecType(templateStruct.ChildDataType),
Specs: getModelSpecByDataType(transformSpecType(templateStruct.ChildDataType), templateStruct.ChildSpecsDTO),
},
})
}
}
bm, _ := json.Marshal(modelTypeSpecStruct)
typeSpec.Specs = string(bm)
}
return
}
func GetModelPropertyEventActionByThingModelTemplate(thingModelJSON string) (properties []models.Properties, events []models.Events, actions []models.Actions) {
thingModelTemplate := new(ThingModelTemplate)
err := json.Unmarshal([]byte(thingModelJSON), thingModelTemplate)
if err == nil {
for _, property := range thingModelTemplate.Properties {
var accessMode string
if property.RwFlag == "READ_ONLY" {
accessMode = "R"
} else if property.RwFlag == "READ_WRITE" {
accessMode = "RW"
} else if property.RwFlag == "WRITE_ONLY" {
accessMode = "W"
}
properties = append(properties, models.Properties{
Id: utils.RandomNum(),
Name: property.Name,
Code: property.Identifier,
AccessMode: accessMode,
Require: property.Required,
Description: property.Description,
TypeSpec: property.TransformModelTypeSpec(),
Tag: string(constants.TagNameSystem),
Timestamps: models.Timestamps{
Created: time.Now().UnixMilli(),
},
})
}
for _, event := range thingModelTemplate.Events {
var eventType constants.EventType
if event.EventType == "ALERT_EVENT_TYPE" {
eventType = constants.EventTypeAlert
} else if event.EventType == "INFO_EVENT_TYPE" {
eventType = constants.EventTypeInfo
} else if event.EventType == "ERROR_EVENT_TYPE" {
eventType = constants.EventTypeError
}
events = append(events, models.Events{
Id: utils.RandomNum(),
Name: event.EventName,
EventType: string(eventType),
Code: event.Identifier,
Require: event.Required,
Description: event.Description,
OutputParams: event.TransformModelOutputParams(),
Tag: string(constants.TagNameSystem),
Timestamps: models.Timestamps{
Created: time.Now().UnixMilli(),
},
})
}
for _, service := range thingModelTemplate.Services {
actions = append(actions, models.Actions{
Id: utils.RandomNum(),
Name: service.ServiceName,
Code: service.Identifier,
CallType: service.CallType,
Require: service.Required,
Description: service.Description,
InputParams: service.TransformModelInPutParams(),
OutputParams: service.TransformModelOutPutParams(),
Tag: string(constants.TagNameSystem),
Timestamps: models.Timestamps{
Created: time.Now().UnixMilli(),
},
})
}
}
return
}
//func OpenApiGetModelPropertyEventActionByThingModelTemplate(req OpenApiAddRequest) (properties []models.Properties, events []models.Events, actions []models.Actions) {
// for _, property := range req.Properties {
// properties = append(properties, models.Properties{
// Id: utils.RandomNum(),
// Name: property.Name,
// Code: property.Code,
// AccessMode: property.AccessMode,
// Require: property.Required,
// Description: property.Description,
// TypeSpec: models.TypeSpec(property.TypeSpec),
// Tag: string(constants.TagNameCustom),
// Timestamps: models.Timestamps{
// Created: time.Now().UnixMilli(),
// },
// })
// }
//
// for _, event := range req.Events {
// var outPutParams models.OutPutParams
// for _, param := range event.OutputParams {
// outPutParams = append(outPutParams, models.InputOutput{
// Code: param.Code,
// Name: param.Name,
// TypeSpec: models.TypeSpec{
// Type: param.TypeSpec.Type,
// Specs: param.TypeSpec.Specs,
// },
// })
// }
// events = append(events, models.Events{
// Id: utils.RandomNum(),
// Name: event.Name,
// EventType: event.EventType,
// Code: event.Code,
// Require: event.Required,
// Description: event.Description,
// OutputParams: outPutParams,
// Tag: string(constants.TagNameCustom),
// Timestamps: models.Timestamps{
// Created: time.Now().UnixMilli(),
// },
// })
// }
//
// for _, action := range req.Actions {
// var inPutParams models.InPutParams
// var outPutParams models.OutPutParams
// for _, param := range action.InputParams {
// inPutParams = append(inPutParams, models.InputOutput{
// Code: param.Code,
// Name: param.Name,
// TypeSpec: models.TypeSpec{
// Type: param.TypeSpec.Type,
// Specs: param.TypeSpec.Specs,
// },
// })
// }
// for _, param := range action.OutputParams {
// outPutParams = append(outPutParams, models.InputOutput{
// Code: param.Code,
// Name: param.Name,
// TypeSpec: models.TypeSpec{
// Type: param.TypeSpec.Type,
// Specs: param.TypeSpec.Specs,
// },
// })
// }
// actions = append(actions, models.Actions{
// Id: utils.RandomNum(),
// Name: action.Name,
// Code: action.Code,
// CallType: action.CallType,
// Require: action.Required,
// Description: action.Description,
// InputParams: inPutParams,
// OutputParams: outPutParams,
// Tag: string(constants.TagNameCustom),
// Timestamps: models.Timestamps{
// Created: time.Now().UnixMilli(),
// },
// })
// }
// return
//}

View File

@ -0,0 +1,227 @@
/*******************************************************************************
* Copyright 2017 Dell Inc.
*
* 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 (
"encoding/json"
"github.com/winc-link/edge-driver-proto/drivercommon"
"github.com/winc-link/edge-driver-proto/thingmodel"
)
type ThingModelMessage struct {
BaseRequest *drivercommon.BaseRequestMessage
Cid string `json:"cid"` // 下发的目标设备id
OpType int32 `json:"op_type"` // 消息类型
Data string `json:"data"` // 云端下发消息内容
}
func (m *ThingModelMessage) String() string {
b, _ := json.Marshal(m)
return string(b)
}
type MessageBus struct {
DeviceId string `json:"deviceId"`
MessageType string `json:"messageType"`
Data interface{} `json:"data"`
}
func (m *ThingModelMessage) TransformMessageBus() []byte {
var messageBus MessageBus
messageBus.DeviceId = m.Cid
messageBus.MessageType = thingmodel.OperationType_name[m.OpType]
data := make(map[string]interface{})
err := json.Unmarshal([]byte(m.Data), &data)
if err != nil {
return nil
}
messageBus.Data = data["data"]
b, _ := json.Marshal(messageBus)
return b
}
func (m *ThingModelMessage) GetOpType() thingmodel.OperationType {
return thingmodel.OperationType(m.OpType)
}
func (m *ThingModelMessage) IsPersistent() bool {
var isPersistent bool
switch m.GetOpType() {
case thingmodel.OperationType_PROPERTY_REPORT, thingmodel.OperationType_EVENT_REPORT:
isPersistent = true
default:
return isPersistent
}
return isPersistent
}
func (m *ThingModelMessage) TransformMessageDataByProperty() (EdgeXDevicePropertyReport, error) {
var dataMsg EdgeXDevicePropertyReport
err := json.Unmarshal([]byte(m.Data), &dataMsg)
return dataMsg, err
}
func (m *ThingModelMessage) TransformMessageDataByEvent() (EdgeXDeviceEventReport, error) {
var dataMsg EdgeXDeviceEventReport
err := json.Unmarshal([]byte(m.Data), &dataMsg)
return dataMsg, err
}
func (m *ThingModelMessage) TransformMessageDataByService() (SaveServiceIssueData, error) {
var dataMsg SaveServiceIssueData
err := json.Unmarshal([]byte(m.Data), &dataMsg)
return dataMsg, err
}
func (m *ThingModelMessage) TransformMessageDataByServiceExec() (ServiceExecResponse, error) {
var dataMsg ServiceExecResponse
err := json.Unmarshal([]byte(m.Data), &dataMsg)
return dataMsg, err
}
func (m *ThingModelMessage) TransformMessageDataByBatchReport() (DeviceBatchReport, error) {
var dataMsg DeviceBatchReport
err := json.Unmarshal([]byte(m.Data), &dataMsg)
return dataMsg, err
}
func ThingModelMessageFromThingModelMsg(msg *thingmodel.ThingModelMsg) ThingModelMessage {
return ThingModelMessage{
BaseRequest: msg.BaseRequest,
Cid: msg.DeviceId,
OpType: int32(msg.OperationType),
Data: msg.Data,
}
}
type EdgeXDevicePropertyReport struct {
MsgId string `json:"msgId"`
Version string `json:"version"`
//Time int64 `json:"time"`
Sys struct {
Ack int `json:"ack"`
} `json:"sys"`
Data map[string]ReportData `json:"data"`
}
type DeviceBatchReport struct {
MsgId string `json:"msgId"`
Version string `json:"version"`
Time int64 `json:"time"`
Sys struct {
Ack int `json:"ack"`
} `json:"sys"`
Data BatchData `json:"data"`
}
type BatchData struct {
Properties map[string]BatchProperty `json:"properties"`
Events map[string]BatchEvent `json:"events"`
}
type BatchProperty struct {
Value interface{} `json:"value"`
//Time int64 `json:"time"`
}
type BatchEvent struct {
//EventTime int64 `json:"eventTime"`
OutputParams map[string]interface{} `json:"outputParams"`
}
type ReportData struct {
Value interface{} `json:"value"`
Time int64 `json:"time"`
}
func (r *ReportData) Marshal() ([]byte, error) {
return json.Marshal(r)
}
type EdgeXDeviceEventReport struct {
MsgId string `json:"msgId"`
Version string `json:"version"`
Sys struct {
Ack int `json:"ack"`
} `json:"sys"`
Data EventData `json:"data"`
}
type EventData struct {
EventCode string `json:"eventCode"`
EventTime int64 `json:"eventTime"`
OutputParams map[string]interface{} `json:"outputParams"`
}
func (r *EventData) Marshal() ([]byte, error) {
return json.Marshal(r)
}
//operationType:SERVICE_EXECUTE data:"topic:\"/sys/hq85KDcqGI6/test_008/thing/service/DeleteAlgorithmModel\"
//message:\"{\\\"id\\\":\\\"2130175210\\\",\\\"version\\\":\\\"1.0.0\\\",\\\"code\\\":\\\"DeleteAlgorithmModel\\\",\\\"params\\\":{\\\"ForceDelete\\\":3}}\""
type InvokeDeviceService struct {
MsgId string `json:"msgId"`
Version string `json:"version"`
Time int64 `json:"time"`
Data ServiceData `json:"data"`
}
type ServiceData struct {
Code string `json:"code"`
InputParams map[string]interface{} `json:"inputParams"`
}
func (r *ServiceData) Marshal() ([]byte, error) {
return json.Marshal(r)
}
func (r *InvokeDeviceService) ToString() string {
s, _ := json.Marshal(r)
return string(s)
}
type SaveServiceIssueData struct {
MsgId string `json:"msgId"`
Code string `json:"code"`
Time int64 `json:"time"`
InputParams map[string]interface{} `json:"inputParams"`
OutputParams map[string]interface{} `json:"outputParams"`
}
func (r *SaveServiceIssueData) Marshal() ([]byte, error) {
return json.Marshal(r)
}
type ServiceExecResponse struct {
MsgId string `json:"msgId"`
Code string `json:"code"`
Time int64 `json:"time"`
OutputParams map[string]interface{} `json:"outputParams"`
}
func (r *ServiceExecResponse) Marshal() ([]byte, error) {
return json.Marshal(r)
}
type PropertySet struct {
Version string `json:"version"`
MsgId string `json:"msgId"`
Time int64 `json:"time"`
Params map[string]interface{} `json:"data"`
}
func (r *PropertySet) ToString() string {
s, _ := json.Marshal(r)
return string(s)
}

45
internal/dtos/unit.go Normal file
View File

@ -0,0 +1,45 @@
/*******************************************************************************
* Copyright 2017 Dell Inc.
* Copyright (c) 2019 Intel Corporation
*
* 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 UnitRequest struct {
BaseSearchConditionQuery `schema:",inline"`
UnitName string `schema:"unitName" json:"unitName"`
}
type UnitResponse struct {
Id string `json:"id"`
Symbol string `json:"symbol"`
UnitName string `json:"unit_name"`
}
type CosUnitTemplateResponse struct {
UnitName string `json:"Name"`
Symbol string `json:"Symbol"`
}
func UnitTemplateResponseFromModel(unitModel models.Unit) UnitResponse {
return UnitResponse{
Id: unitModel.Id,
Symbol: unitModel.Symbol,
UnitName: unitModel.UnitName,
}
}
type UnitTemplateSyncRequest struct {
VersionName string `json:"version_name"`
}

45
internal/dtos/user.go Normal file
View File

@ -0,0 +1,45 @@
package dtos
type LoginRequest struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
type UpdatePasswordRequest struct {
CurrentPassword string `json:"currentPassword" binding:"required"`
NewPassword string `json:"newPassword" binding:"required"`
}
type UpdateLangRequest struct {
Lang string `json:"lang" binding:"required"`
}
type InitPasswordRequest struct {
NewPassword string `json:"newPassword" binding:"required"`
}
/************** Response **************/
type LoginResponse struct {
User UserResponse `json:"user"`
Token string `json:"token"`
ExpiresAt int64 `json:"expiresAt"`
}
type UserResponse struct {
Username string `json:"username"`
Lang string `json:"lang"`
}
type InitInfoResponse struct {
IsInit bool `json:"isInit"`
}
type TokenDetail struct {
AccessId string `json:"access_id"`
RefreshId string `json:"refresh_id"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
AtExpires int64 `json:"at_expires"`
RtExpires int64 `json:"rt_expires"`
}

39
internal/dtos/ws.go Normal file
View File

@ -0,0 +1,39 @@
/*******************************************************************************
* Copyright 2017 Dell Inc.
* Copyright (c) 2019 Intel Corporation
*
* 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
type WsCode uint32
const (
WsCodeDeviceLibraryUpgrade WsCode = 10001 // 驱动下载/升级
WsCodeDeviceServiceRunStatus WsCode = 10002 // 驱动重启
WsCodeDeviceLibraryDelete WsCode = 10003 // 驱动删除
WsCodeDeviceServiceLog WsCode = 10004 // 驱动日志
WsCodeCloudServiceDownload WsCode = 20001 // 云服务下载
WsCodeCloudServiceRunStatus WsCode = 20002 // 云服务重启/停止
WsCodeCloudServiceRunDelete WsCode = 20003 // 云服务删除
WsCodeCloudServiceRunLog WsCode = 20004 // 云服务日志
WsCodeCheckLang WsCode = 30001 // 切换语言
// 云端网络情况
WsCodeCloudState WsCode = 10007 // 云端网络情况
//OTA
WsCodeOTAUpgradeProgress WsCode = 10100 // OTA升级进度
WsCodeOTAFirmwareUpgrade WsCode = 10101 // OTA升级
// 严重警告
WsCodeSeriousAlert WsCode = 10200
)

191
internal/models/ability.go Normal file
View File

@ -0,0 +1,191 @@
package models
import (
"database/sql/driver"
"encoding/json"
"github.com/winc-link/hummingbird/internal/pkg/constants"
)
// TypeSpec 物模型的属性、事件、动作的基础信息字段
type TypeSpec struct {
Type constants.SpecsType `json:"type,omitempty"`
Specs string `json:"specs,omitempty"`
}
type TypeSpecIntOrFloat struct {
Min string `json:"min,omitempty"`
Max string `json:"max,omitempty"`
Step string `json:"step,omitempty"`
Unit string `json:"unit,omitempty"`
UnitName string `json:"unitName,omitempty"`
}
func (t *TypeSpecIntOrFloat) TransformTostring() string {
b, _ := json.Marshal(t)
return string(b)
}
type TypeSpecText struct {
Length string `json:"length,omitempty"`
}
func (t *TypeSpecText) TransformTostring() string {
b, _ := json.Marshal(t)
return string(b)
}
type TypeSpecBool map[string]string
func (t *TypeSpecBool) TransformTostring() string {
b, _ := json.Marshal(t)
return string(b)
}
type TypeSpecArray struct {
Size string `json:"size,omitempty"`
Item Item `json:"item,omitempty"`
}
func (t *TypeSpecArray) TransformTostring() string {
b, _ := json.Marshal(t)
return string(b)
}
type TypeSpecEnum map[string]string
func (t *TypeSpecEnum) TransformTostring() string {
b, _ := json.Marshal(t)
return string(b)
}
type TypeSpecStruct struct {
Code string `json:"code"`
Name string `json:"name"`
DataType TypeSpec `json:"data_type"`
}
func (t *TypeSpecStruct) TransformTostring() string {
b, _ := json.Marshal(t)
return string(b)
}
type TypeSpecDate struct {
}
func (t *TypeSpecDate) TransformTostring() string {
b, _ := json.Marshal(t)
return string(b)
}
type Item struct {
Type string `json:"type,omitempty"`
}
func (c Item) Value() (driver.Value, error) {
return GormValueWrap(c)
}
func (c *Item) Scan(value interface{}) error {
return GormScanWrap(value, c)
}
type Properties struct {
Id string `json:"id" gorm:"id;primaryKey;not null;type:string;size:255;comment:主键"`
ProductId string `json:"product_id" gorm:"type:string;size:255;comment:产品ID"`
Name string `json:"name" gorm:"type:string;size:255;comment:名字"`
Code string `json:"code" gorm:"type:string;size:255;comment:标识符"`
AccessMode string `json:"access_mode" gorm:"type:string;size:50;comment:读写模型"`
Require bool `json:"require" gorm:"comment:是否必须"`
TypeSpec TypeSpec `json:"type_spec" gorm:"type:text;comment:属性物模型详情"`
Description string `json:"description" gorm:"type:text;comment:描述"`
Tag string `json:"tag" gorm:"type:string;size:50;comment:标签"`
System bool `json:"system" gorm:"comment:系统内置"`
Timestamps
}
func (c TypeSpec) Value() (driver.Value, error) {
return GormValueWrap(c)
}
func (c *TypeSpec) Scan(value interface{}) error {
return GormScanWrap(value, c)
}
func (p *Properties) TableName() string {
return "properties"
}
func (p *Properties) Get() interface{} {
return *p
}
type Actions struct {
Id string `json:"id" gorm:"id;primaryKey;not null;type:string;size:255;comment:主键"`
ProductId string `json:"product_id" gorm:"type:string;size:255;comment:产品ID"`
Code string `json:"code" gorm:"type:string;size:255;comment:标识符"`
Name string `json:"name" gorm:"type:string;size:255;comment:名字"`
Description string `json:"description" gorm:"type:text;comment:描述"`
Require bool `json:"require" gorm:"comment:是否必须"`
CallType constants.CallType `json:"call_type" gorm:"type:string;size:50;comment:调用方式"`
InputParams InPutParams `json:"input_params" gorm:"type:text;comment:输入参数"` // 输入参数
OutputParams OutPutParams `json:"output_params" gorm:"type:text;comment:输入参数"` // 输出参数
Tag string `json:"tag" gorm:"type:string;size:50;comment:标签"`
System bool `json:"system" gorm:"comment:系统内置"`
Timestamps
}
type InPutParams []InputOutput
type InputOutput struct {
Code string `json:"code"`
Name string `json:"name"`
TypeSpec TypeSpec `json:"type_spec"`
}
func (c InPutParams) Value() (driver.Value, error) {
return GormValueWrap(c)
}
func (c *InPutParams) Scan(value interface{}) error {
return GormScanWrap(value, c)
}
type OutPutParams []InputOutput
func (c OutPutParams) Value() (driver.Value, error) {
return GormValueWrap(c)
}
func (c *OutPutParams) Scan(value interface{}) error {
return GormScanWrap(value, c)
}
func (table *Actions) TableName() string {
return "actions"
}
func (table *Actions) Get() interface{} {
return *table
}
type Events struct {
Id string `json:"id" gorm:"id;primaryKey;not null;type:string;size:255;comment:主键"`
ProductId string `json:"product_id" gorm:"type:string;size:255;comment:产品ID"`
EventType string `json:"event_type" gorm:"type:string;size:255;comment:事件类型"`
Code string `json:"code" gorm:"type:string;size:255;comment:标识符"`
Name string `json:"name" gorm:"type:string;size:255;comment:名字"`
Description string `json:"description" gorm:"type:text;comment:描述"`
Require bool `json:"require" gorm:"comment:是否必须"`
OutputParams OutPutParams `json:"output_params" gorm:"type:text;comment:输入参数"`
Tag string `json:"tag" gorm:"type:string;size:50;comment:标签"`
System bool `json:"system" gorm:"comment:系统内置"`
Timestamps
}
func (table *Events) TableName() string {
return "events"
}
func (table *Events) Get() interface{} {
return *table
}

View File

@ -0,0 +1,32 @@
/*******************************************************************************
* 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 AdvanceConfig struct {
ID int `json:"id" gorm:"id;primaryKey;not null;type:string;size:255;comment:主键"`
LogLevel constants.LogLevel `gorm:"default:1;comment:日志等级"` // 日志级别 默认为INFO
PersistStorage bool `gorm:"default:0;comment:存储开关"`
StorageHour int32 `gorm:"default:24;comment:存储时长"`
}
func (table *AdvanceConfig) TableName() string {
return "advance_config"
}
func (table *AdvanceConfig) Get() interface{} {
return *table
}

Some files were not shown because too many files have changed in this diff Show More