From a408ac66c12cddb1013bc05532386d4b7f4d3943 Mon Sep 17 00:00:00 2001 From: anlworke <978080633@qq.com> Date: Wed, 27 Dec 2023 17:37:22 +0800 Subject: [PATCH 01/35] =?UTF-8?q?fix=EF=BC=9A=E4=BF=AE=E6=94=B9=E4=BB=A3?= =?UTF-8?q?=E7=90=86=E5=9C=B0=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../.env_20221121185243.development | 11 ++ .../.env_20231012170233.development | 12 ++ .../.env_20231012170414.development | 12 ++ .../.env_20231012173152.development | 12 ++ .../vue.config_20231012165327.js | 126 ++++++++++++++++++ .../vue.config_20231012170036.js | 125 +++++++++++++++++ .../vue.config_20231012170400.js | 125 +++++++++++++++++ .../vue.config_20231012170401.js | 125 +++++++++++++++++ .../vue.config_20231012170409.js | 125 +++++++++++++++++ thinglinks-ui/.env.development | 3 +- thinglinks-ui/vue.config.js | 7 +- 11 files changed, 678 insertions(+), 5 deletions(-) create mode 100644 .history/thinglinks-ui/.env_20221121185243.development create mode 100644 .history/thinglinks-ui/.env_20231012170233.development create mode 100644 .history/thinglinks-ui/.env_20231012170414.development create mode 100644 .history/thinglinks-ui/.env_20231012173152.development create mode 100644 .history/thinglinks-ui/vue.config_20231012165327.js create mode 100644 .history/thinglinks-ui/vue.config_20231012170036.js create mode 100644 .history/thinglinks-ui/vue.config_20231012170400.js create mode 100644 .history/thinglinks-ui/vue.config_20231012170401.js create mode 100644 .history/thinglinks-ui/vue.config_20231012170409.js diff --git a/.history/thinglinks-ui/.env_20221121185243.development b/.history/thinglinks-ui/.env_20221121185243.development new file mode 100644 index 00000000..ab110dcc --- /dev/null +++ b/.history/thinglinks-ui/.env_20221121185243.development @@ -0,0 +1,11 @@ +# 页面标题 +VUE_APP_TITLE = ThingLinks物联网一体化平台 + +# 开发环境配置 +ENV = 'development' + +# ThingLinks物联网一体化平台/开发环境 +VUE_APP_BASE_API = '/dev-api' + +# 路由懒加载 +VUE_CLI_BABEL_TRANSPILE_MODULES = true diff --git a/.history/thinglinks-ui/.env_20231012170233.development b/.history/thinglinks-ui/.env_20231012170233.development new file mode 100644 index 00000000..dff48828 --- /dev/null +++ b/.history/thinglinks-ui/.env_20231012170233.development @@ -0,0 +1,12 @@ +# 页面标题 +VUE_APP_TITLE = ThingLinks物联网一体化平台 + +# 开发环境配置 +ENV = 'development' + +# ThingLinks物联网一体化平台/开发环境 +#VUE_APP_BASE_API = '/dev-api' +VUE_APP_BASE_API = '/prod-api' + +# 路由懒加载 +VUE_CLI_BABEL_TRANSPILE_MODULES = true diff --git a/.history/thinglinks-ui/.env_20231012170414.development b/.history/thinglinks-ui/.env_20231012170414.development new file mode 100644 index 00000000..20456fbf --- /dev/null +++ b/.history/thinglinks-ui/.env_20231012170414.development @@ -0,0 +1,12 @@ +# 页面标题 +VUE_APP_TITLE = ThingLinks物联网一体化平台 + +# 开发环境配置 +ENV = 'development' + +# ThingLinks物联网一体化平台/开发环境 +#VUE_APP_BASE_API = '/dev-api' +VUE_APP_BASE_API = '/' + +# 路由懒加载 +VUE_CLI_BABEL_TRANSPILE_MODULES = true diff --git a/.history/thinglinks-ui/.env_20231012173152.development b/.history/thinglinks-ui/.env_20231012173152.development new file mode 100644 index 00000000..20456fbf --- /dev/null +++ b/.history/thinglinks-ui/.env_20231012173152.development @@ -0,0 +1,12 @@ +# 页面标题 +VUE_APP_TITLE = ThingLinks物联网一体化平台 + +# 开发环境配置 +ENV = 'development' + +# ThingLinks物联网一体化平台/开发环境 +#VUE_APP_BASE_API = '/dev-api' +VUE_APP_BASE_API = '/' + +# 路由懒加载 +VUE_CLI_BABEL_TRANSPILE_MODULES = true diff --git a/.history/thinglinks-ui/vue.config_20231012165327.js b/.history/thinglinks-ui/vue.config_20231012165327.js new file mode 100644 index 00000000..b29d553c --- /dev/null +++ b/.history/thinglinks-ui/vue.config_20231012165327.js @@ -0,0 +1,126 @@ +'use strict' +const path = require('path') + +function resolve(dir) { + return path.join(__dirname, dir) +} + +const name = process.env.VUE_APP_TITLE || 'ThingLinks物联网一体化平台' // 网页标题 + +const port = process.env.port || process.env.npm_config_port || 3000 // 端口 + +// vue.config.js 配置说明 +//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions +// 这里只列一部分,具体配置参考文档 +module.exports = { + // 部署生产环境和开发环境下的URL。 + // 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上 + // 例如 https://thinglinks.mqttsnet.com/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://thinglinks.mqttsnet.com/admin/,则设置 baseUrl 为 /admin/。 + publicPath: process.env.NODE_ENV === "production" ? "/" : "/", + // 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist) + outputDir: 'dist', + // 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下) + assetsDir: 'static', + // 是否开启eslint保存检测,有效值:ture | false | 'error' + lintOnSave: process.env.NODE_ENV === 'development', + // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。 + productionSourceMap: false, + // webpack-dev-server 相关配置 + devServer: { + host: '127.0.0.1', + port: port, + open: true, + proxy: { + // detail: https://cli.vuejs.org/config/#devserver-proxy + [process.env.VUE_APP_BASE_API]: { + target: `http://localhost:19100`, + // target: `http://124.223.113.139:19100`, + changeOrigin: true, + pathRewrite: { + ['^' + process.env.VUE_APP_BASE_API]: '' + } + }, + [process.env.VUE_APP_BASE_SOCKETIP]: { + target: `ws://localhost:19100`, + // target: `ws://frp1.xiaonannet.com:6901`, + changeOrigin: true, + pathRewrite: { + ['^' + process.env.VUE_APP_BASE_SOCKETIP]: '' + } + } + }, + disableHostCheck: true + }, + configureWebpack: { + name: name, + resolve: { + alias: { + '@': resolve('src') + } + } + }, + chainWebpack(config) { + config.plugins.delete('preload') // TODO: need test + config.plugins.delete('prefetch') // TODO: need test + + // set svg-sprite-loader + config.module + .rule('svg') + .exclude.add(resolve('src/assets/icons')) + .end() + config.module + .rule('icons') + .test(/\.svg$/) + .include.add(resolve('src/assets/icons')) + .end() + .use('svg-sprite-loader') + .loader('svg-sprite-loader') + .options({ + symbolId: 'icon-[name]' + }) + .end() + + config + .when(process.env.NODE_ENV !== 'development', + config => { + config + .plugin('ScriptExtHtmlWebpackPlugin') + .after('html') + .use('script-ext-html-webpack-plugin', [{ + // `runtime` must same as runtimeChunk name. default is `runtime` + inline: /runtime\..*\.js$/ + }]) + .end() + config + .optimization.splitChunks({ + chunks: 'all', + cacheGroups: { + libs: { + name: 'chunk-libs', + test: /[\\/]node_modules[\\/]/, + priority: 10, + chunks: 'initial' // only package third parties that are initially dependent + }, + elementUI: { + name: 'chunk-elementUI', // split elementUI into a single package + priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app + test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm + }, + commons: { + name: 'chunk-commons', + test: resolve('src/components'), // can customize your rules + minChunks: 3, // minimum common number + priority: 5, + reuseExistingChunk: true + } + } + }) + config.optimization.runtimeChunk('single'), + { + from: path.resolve(__dirname, './public/robots.txt'), //防爬虫文件 + to: './', //到根目录下 + } + } + ) + } +} diff --git a/.history/thinglinks-ui/vue.config_20231012170036.js b/.history/thinglinks-ui/vue.config_20231012170036.js new file mode 100644 index 00000000..29f4f75b --- /dev/null +++ b/.history/thinglinks-ui/vue.config_20231012170036.js @@ -0,0 +1,125 @@ +'use strict' +const path = require('path') + +function resolve(dir) { + return path.join(__dirname, dir) +} + +const name = process.env.VUE_APP_TITLE || 'ThingLinks物联网一体化平台' // 网页标题 + +const port = process.env.port || process.env.npm_config_port || 3000 // 端口 + +// vue.config.js 配置说明 +//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions +// 这里只列一部分,具体配置参考文档 +module.exports = { + // 部署生产环境和开发环境下的URL。 + // 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上 + // 例如 https://thinglinks.mqttsnet.com/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://thinglinks.mqttsnet.com/admin/,则设置 baseUrl 为 /admin/。 + publicPath: process.env.NODE_ENV === "production" ? "/" : "/", + // 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist) + outputDir: 'dist', + // 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下) + assetsDir: 'static', + // 是否开启eslint保存检测,有效值:ture | false | 'error' + lintOnSave: process.env.NODE_ENV === 'development', + // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。 + productionSourceMap: false, + // webpack-dev-server 相关配置 + devServer: { + host: '127.0.0.1', + port: port, + open: true, + proxy: { + // detail: https://cli.vuejs.org/config/#devserver-proxy + [process.env.VUE_APP_BASE_API]: { + // target: `http://localhost:19100`, + target: `http://thinglinks.mqttsnet.com`, + changeOrigin: true, + pathRewrite: { + ['^' + process.env.VUE_APP_BASE_API]: '' + } + }, + [process.env.VUE_APP_BASE_SOCKETIP]: { + target: `ws://localhost:19100`, + // target: `ws://frp1.xiaonannet.com:6901`, + changeOrigin: true, + pathRewrite: { + ['^' + process.env.VUE_APP_BASE_SOCKETIP]: '' + } + } + }, + disableHostCheck: true + }, + configureWebpack: { + name: name, + resolve: { + alias: { + '@': resolve('src') + } + } + }, + chainWebpack(config) { + config.plugins.delete('preload') // TODO: need test + config.plugins.delete('prefetch') // TODO: need test + + // set svg-sprite-loader + config.module + .rule('svg') + .exclude.add(resolve('src/assets/icons')) + .end() + config.module + .rule('icons') + .test(/\.svg$/) + .include.add(resolve('src/assets/icons')) + .end() + .use('svg-sprite-loader') + .loader('svg-sprite-loader') + .options({ + symbolId: 'icon-[name]' + }) + .end() + + config + .when(process.env.NODE_ENV !== 'development', + config => { + config + .plugin('ScriptExtHtmlWebpackPlugin') + .after('html') + .use('script-ext-html-webpack-plugin', [{ + // `runtime` must same as runtimeChunk name. default is `runtime` + inline: /runtime\..*\.js$/ + }]) + .end() + config + .optimization.splitChunks({ + chunks: 'all', + cacheGroups: { + libs: { + name: 'chunk-libs', + test: /[\\/]node_modules[\\/]/, + priority: 10, + chunks: 'initial' // only package third parties that are initially dependent + }, + elementUI: { + name: 'chunk-elementUI', // split elementUI into a single package + priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app + test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm + }, + commons: { + name: 'chunk-commons', + test: resolve('src/components'), // can customize your rules + minChunks: 3, // minimum common number + priority: 5, + reuseExistingChunk: true + } + } + }) + config.optimization.runtimeChunk('single'), { + from: path.resolve(__dirname, './public/robots.txt'), //防爬虫文件 + to: './', //到根目录下 + } + } + ) + } +} diff --git a/.history/thinglinks-ui/vue.config_20231012170400.js b/.history/thinglinks-ui/vue.config_20231012170400.js new file mode 100644 index 00000000..29f4f75b --- /dev/null +++ b/.history/thinglinks-ui/vue.config_20231012170400.js @@ -0,0 +1,125 @@ +'use strict' +const path = require('path') + +function resolve(dir) { + return path.join(__dirname, dir) +} + +const name = process.env.VUE_APP_TITLE || 'ThingLinks物联网一体化平台' // 网页标题 + +const port = process.env.port || process.env.npm_config_port || 3000 // 端口 + +// vue.config.js 配置说明 +//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions +// 这里只列一部分,具体配置参考文档 +module.exports = { + // 部署生产环境和开发环境下的URL。 + // 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上 + // 例如 https://thinglinks.mqttsnet.com/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://thinglinks.mqttsnet.com/admin/,则设置 baseUrl 为 /admin/。 + publicPath: process.env.NODE_ENV === "production" ? "/" : "/", + // 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist) + outputDir: 'dist', + // 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下) + assetsDir: 'static', + // 是否开启eslint保存检测,有效值:ture | false | 'error' + lintOnSave: process.env.NODE_ENV === 'development', + // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。 + productionSourceMap: false, + // webpack-dev-server 相关配置 + devServer: { + host: '127.0.0.1', + port: port, + open: true, + proxy: { + // detail: https://cli.vuejs.org/config/#devserver-proxy + [process.env.VUE_APP_BASE_API]: { + // target: `http://localhost:19100`, + target: `http://thinglinks.mqttsnet.com`, + changeOrigin: true, + pathRewrite: { + ['^' + process.env.VUE_APP_BASE_API]: '' + } + }, + [process.env.VUE_APP_BASE_SOCKETIP]: { + target: `ws://localhost:19100`, + // target: `ws://frp1.xiaonannet.com:6901`, + changeOrigin: true, + pathRewrite: { + ['^' + process.env.VUE_APP_BASE_SOCKETIP]: '' + } + } + }, + disableHostCheck: true + }, + configureWebpack: { + name: name, + resolve: { + alias: { + '@': resolve('src') + } + } + }, + chainWebpack(config) { + config.plugins.delete('preload') // TODO: need test + config.plugins.delete('prefetch') // TODO: need test + + // set svg-sprite-loader + config.module + .rule('svg') + .exclude.add(resolve('src/assets/icons')) + .end() + config.module + .rule('icons') + .test(/\.svg$/) + .include.add(resolve('src/assets/icons')) + .end() + .use('svg-sprite-loader') + .loader('svg-sprite-loader') + .options({ + symbolId: 'icon-[name]' + }) + .end() + + config + .when(process.env.NODE_ENV !== 'development', + config => { + config + .plugin('ScriptExtHtmlWebpackPlugin') + .after('html') + .use('script-ext-html-webpack-plugin', [{ + // `runtime` must same as runtimeChunk name. default is `runtime` + inline: /runtime\..*\.js$/ + }]) + .end() + config + .optimization.splitChunks({ + chunks: 'all', + cacheGroups: { + libs: { + name: 'chunk-libs', + test: /[\\/]node_modules[\\/]/, + priority: 10, + chunks: 'initial' // only package third parties that are initially dependent + }, + elementUI: { + name: 'chunk-elementUI', // split elementUI into a single package + priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app + test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm + }, + commons: { + name: 'chunk-commons', + test: resolve('src/components'), // can customize your rules + minChunks: 3, // minimum common number + priority: 5, + reuseExistingChunk: true + } + } + }) + config.optimization.runtimeChunk('single'), { + from: path.resolve(__dirname, './public/robots.txt'), //防爬虫文件 + to: './', //到根目录下 + } + } + ) + } +} diff --git a/.history/thinglinks-ui/vue.config_20231012170401.js b/.history/thinglinks-ui/vue.config_20231012170401.js new file mode 100644 index 00000000..29f4f75b --- /dev/null +++ b/.history/thinglinks-ui/vue.config_20231012170401.js @@ -0,0 +1,125 @@ +'use strict' +const path = require('path') + +function resolve(dir) { + return path.join(__dirname, dir) +} + +const name = process.env.VUE_APP_TITLE || 'ThingLinks物联网一体化平台' // 网页标题 + +const port = process.env.port || process.env.npm_config_port || 3000 // 端口 + +// vue.config.js 配置说明 +//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions +// 这里只列一部分,具体配置参考文档 +module.exports = { + // 部署生产环境和开发环境下的URL。 + // 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上 + // 例如 https://thinglinks.mqttsnet.com/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://thinglinks.mqttsnet.com/admin/,则设置 baseUrl 为 /admin/。 + publicPath: process.env.NODE_ENV === "production" ? "/" : "/", + // 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist) + outputDir: 'dist', + // 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下) + assetsDir: 'static', + // 是否开启eslint保存检测,有效值:ture | false | 'error' + lintOnSave: process.env.NODE_ENV === 'development', + // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。 + productionSourceMap: false, + // webpack-dev-server 相关配置 + devServer: { + host: '127.0.0.1', + port: port, + open: true, + proxy: { + // detail: https://cli.vuejs.org/config/#devserver-proxy + [process.env.VUE_APP_BASE_API]: { + // target: `http://localhost:19100`, + target: `http://thinglinks.mqttsnet.com`, + changeOrigin: true, + pathRewrite: { + ['^' + process.env.VUE_APP_BASE_API]: '' + } + }, + [process.env.VUE_APP_BASE_SOCKETIP]: { + target: `ws://localhost:19100`, + // target: `ws://frp1.xiaonannet.com:6901`, + changeOrigin: true, + pathRewrite: { + ['^' + process.env.VUE_APP_BASE_SOCKETIP]: '' + } + } + }, + disableHostCheck: true + }, + configureWebpack: { + name: name, + resolve: { + alias: { + '@': resolve('src') + } + } + }, + chainWebpack(config) { + config.plugins.delete('preload') // TODO: need test + config.plugins.delete('prefetch') // TODO: need test + + // set svg-sprite-loader + config.module + .rule('svg') + .exclude.add(resolve('src/assets/icons')) + .end() + config.module + .rule('icons') + .test(/\.svg$/) + .include.add(resolve('src/assets/icons')) + .end() + .use('svg-sprite-loader') + .loader('svg-sprite-loader') + .options({ + symbolId: 'icon-[name]' + }) + .end() + + config + .when(process.env.NODE_ENV !== 'development', + config => { + config + .plugin('ScriptExtHtmlWebpackPlugin') + .after('html') + .use('script-ext-html-webpack-plugin', [{ + // `runtime` must same as runtimeChunk name. default is `runtime` + inline: /runtime\..*\.js$/ + }]) + .end() + config + .optimization.splitChunks({ + chunks: 'all', + cacheGroups: { + libs: { + name: 'chunk-libs', + test: /[\\/]node_modules[\\/]/, + priority: 10, + chunks: 'initial' // only package third parties that are initially dependent + }, + elementUI: { + name: 'chunk-elementUI', // split elementUI into a single package + priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app + test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm + }, + commons: { + name: 'chunk-commons', + test: resolve('src/components'), // can customize your rules + minChunks: 3, // minimum common number + priority: 5, + reuseExistingChunk: true + } + } + }) + config.optimization.runtimeChunk('single'), { + from: path.resolve(__dirname, './public/robots.txt'), //防爬虫文件 + to: './', //到根目录下 + } + } + ) + } +} diff --git a/.history/thinglinks-ui/vue.config_20231012170409.js b/.history/thinglinks-ui/vue.config_20231012170409.js new file mode 100644 index 00000000..9b3e03f2 --- /dev/null +++ b/.history/thinglinks-ui/vue.config_20231012170409.js @@ -0,0 +1,125 @@ +'use strict' +const path = require('path') + +function resolve(dir) { + return path.join(__dirname, dir) +} + +const name = process.env.VUE_APP_TITLE || 'ThingLinks物联网一体化平台' // 网页标题 + +const port = process.env.port || process.env.npm_config_port || 3000 // 端口 + +// vue.config.js 配置说明 +//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions +// 这里只列一部分,具体配置参考文档 +module.exports = { + // 部署生产环境和开发环境下的URL。 + // 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上 + // 例如 https://thinglinks.mqttsnet.com/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://thinglinks.mqttsnet.com/admin/,则设置 baseUrl 为 /admin/。 + publicPath: process.env.NODE_ENV === "production" ? "/" : "/", + // 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist) + outputDir: 'dist', + // 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下) + assetsDir: 'static', + // 是否开启eslint保存检测,有效值:ture | false | 'error' + lintOnSave: process.env.NODE_ENV === 'development', + // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。 + productionSourceMap: false, + // webpack-dev-server 相关配置 + devServer: { + host: '127.0.0.1', + port: port, + open: true, + proxy: { + // detail: https://cli.vuejs.org/config/#devserver-proxy + [process.env.VUE_APP_BASE_API]: { + // target: `http://localhost:19100`, + target: `http://thinglinks.mqttsnet.com/prod-api`, + changeOrigin: true, + pathRewrite: { + ['^' + process.env.VUE_APP_BASE_API]: '' + } + }, + [process.env.VUE_APP_BASE_SOCKETIP]: { + target: `ws://localhost:19100`, + // target: `ws://frp1.xiaonannet.com:6901`, + changeOrigin: true, + pathRewrite: { + ['^' + process.env.VUE_APP_BASE_SOCKETIP]: '' + } + } + }, + disableHostCheck: true + }, + configureWebpack: { + name: name, + resolve: { + alias: { + '@': resolve('src') + } + } + }, + chainWebpack(config) { + config.plugins.delete('preload') // TODO: need test + config.plugins.delete('prefetch') // TODO: need test + + // set svg-sprite-loader + config.module + .rule('svg') + .exclude.add(resolve('src/assets/icons')) + .end() + config.module + .rule('icons') + .test(/\.svg$/) + .include.add(resolve('src/assets/icons')) + .end() + .use('svg-sprite-loader') + .loader('svg-sprite-loader') + .options({ + symbolId: 'icon-[name]' + }) + .end() + + config + .when(process.env.NODE_ENV !== 'development', + config => { + config + .plugin('ScriptExtHtmlWebpackPlugin') + .after('html') + .use('script-ext-html-webpack-plugin', [{ + // `runtime` must same as runtimeChunk name. default is `runtime` + inline: /runtime\..*\.js$/ + }]) + .end() + config + .optimization.splitChunks({ + chunks: 'all', + cacheGroups: { + libs: { + name: 'chunk-libs', + test: /[\\/]node_modules[\\/]/, + priority: 10, + chunks: 'initial' // only package third parties that are initially dependent + }, + elementUI: { + name: 'chunk-elementUI', // split elementUI into a single package + priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app + test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm + }, + commons: { + name: 'chunk-commons', + test: resolve('src/components'), // can customize your rules + minChunks: 3, // minimum common number + priority: 5, + reuseExistingChunk: true + } + } + }) + config.optimization.runtimeChunk('single'), { + from: path.resolve(__dirname, './public/robots.txt'), //防爬虫文件 + to: './', //到根目录下 + } + } + ) + } +} diff --git a/thinglinks-ui/.env.development b/thinglinks-ui/.env.development index ab110dcc..20456fbf 100644 --- a/thinglinks-ui/.env.development +++ b/thinglinks-ui/.env.development @@ -5,7 +5,8 @@ VUE_APP_TITLE = ThingLinks物联网一体化平台 ENV = 'development' # ThingLinks物联网一体化平台/开发环境 -VUE_APP_BASE_API = '/dev-api' +#VUE_APP_BASE_API = '/dev-api' +VUE_APP_BASE_API = '/' # 路由懒加载 VUE_CLI_BABEL_TRANSPILE_MODULES = true diff --git a/thinglinks-ui/vue.config.js b/thinglinks-ui/vue.config.js index b29d553c..9b3e03f2 100644 --- a/thinglinks-ui/vue.config.js +++ b/thinglinks-ui/vue.config.js @@ -33,8 +33,8 @@ module.exports = { proxy: { // detail: https://cli.vuejs.org/config/#devserver-proxy [process.env.VUE_APP_BASE_API]: { - target: `http://localhost:19100`, - // target: `http://124.223.113.139:19100`, + // target: `http://localhost:19100`, + target: `http://thinglinks.mqttsnet.com/prod-api`, changeOrigin: true, pathRewrite: { ['^' + process.env.VUE_APP_BASE_API]: '' @@ -115,8 +115,7 @@ module.exports = { } } }) - config.optimization.runtimeChunk('single'), - { + config.optimization.runtimeChunk('single'), { from: path.resolve(__dirname, './public/robots.txt'), //防爬虫文件 to: './', //到根目录下 } From 05b4cb53937bd3d58c9eba6e6a8f041ac073e5de Mon Sep 17 00:00:00 2001 From: xiaonan <13733918655@163.com> Date: Wed, 24 Jan 2024 17:38:29 +0800 Subject: [PATCH 02/35] fix sql --- doc/sql/changeRecord/1.2.0.RELEASE.sql | 65 ++ doc/sql/thinglinks.sql | 1014 +++++++++++------ docker/docker-compose.yml | 224 ++++ thinglinks-auth/Dockerfile | 28 +- thinglinks-gateway/Dockerfile | 28 +- .../thinglinks-modules-broker/Dockerfile | 28 +- .../thinglinks-modules-broker/pom.xml | 14 - .../thinglinks-modules-file/Dockerfile | 28 +- .../thinglinks-modules-gen/Dockerfile | 28 +- .../thinglinks-modules-job/Dockerfile | 28 +- .../thinglinks-modules-link/Dockerfile | 28 +- .../Dockerfile | 25 + .../thinglinks-modules-rule/Dockerfile | 28 +- .../thinglinks-modules-system/Dockerfile | 28 +- .../thinglinks-modules-tdengine/Dockerfile | 28 +- .../thinglinks-visual-monitor/Dockerfile | 28 +- 16 files changed, 1187 insertions(+), 463 deletions(-) create mode 100644 doc/sql/changeRecord/1.2.0.RELEASE.sql create mode 100644 docker/docker-compose.yml create mode 100644 thinglinks-modules/thinglinks-modules-protocolAnalysis/Dockerfile diff --git a/doc/sql/changeRecord/1.2.0.RELEASE.sql b/doc/sql/changeRecord/1.2.0.RELEASE.sql new file mode 100644 index 00000000..83f0b36d --- /dev/null +++ b/doc/sql/changeRecord/1.2.0.RELEASE.sql @@ -0,0 +1,65 @@ +CREATE TABLE `ota_upgrades` +( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', + `app_id` varchar(64) NOT NULL DEFAULT '' COMMENT '应用ID', + `package_name` varchar(100) NOT NULL DEFAULT '' COMMENT '包名称', + `package_type` smallint(1) NOT NULL DEFAULT '0' COMMENT '升级包类型(0:软件包、1:固件包)', + `product_identification` varchar(100) NOT NULL DEFAULT '' COMMENT '产品标识', + `version` varchar(255) NOT NULL DEFAULT '' COMMENT '升级包版本号', + `file_location` varchar(255) NOT NULL DEFAULT '' COMMENT '升级包的位置', + `status` smallint(1) NOT NULL DEFAULT '0' COMMENT '状态', + `description` varchar(255) DEFAULT '' COMMENT '升级包功能描述', + `custom_info` longtext COMMENT '自定义信息', + `remark` varchar(255) DEFAULT '' COMMENT '描述', + `created_by` bigint(20) DEFAULT NULL COMMENT '创建人', + `created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `updated_by` bigint(20) DEFAULT NULL COMMENT '更新人', + `updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `created_org_id` bigint(20) DEFAULT NULL COMMENT '创建人组织', + PRIMARY KEY (`id`) USING BTREE, + KEY `idx_app_id` (`app_id`) USING BTREE COMMENT '应用ID', + KEY `idx_product_identification` (`product_identification`) USING BTREE COMMENT '产品标识', + KEY `idx_version` (`version`) USING BTREE COMMENT '升级包版本号' +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='OTA升级包'; + +CREATE TABLE `ota_upgrade_tasks` +( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', + `upgrade_id` bigint(20) NOT NULL COMMENT '升级包ID,关联ota_upgrades表', + `task_name` varchar(100) NOT NULL DEFAULT '' COMMENT '任务名称', + `task_status` smallint(1) NOT NULL DEFAULT '0' COMMENT '任务状态(0:待发布、1:进行中、2:已完成、3:已取消)', + `scheduled_time` datetime DEFAULT NULL COMMENT '计划执行时间', + `description` varchar(255) DEFAULT '' COMMENT '任务描述', + `remark` varchar(255) DEFAULT '' COMMENT '描述', + `created_by` bigint(20) DEFAULT NULL COMMENT '创建人', + `created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `updated_by` bigint(20) DEFAULT NULL COMMENT '更新人', + `updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `created_org_id` bigint(20) DEFAULT NULL COMMENT '创建人组织', + PRIMARY KEY (`id`) USING BTREE, + KEY `idx_upgrade_id` (`upgrade_id`) USING BTREE COMMENT '升级包ID' +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='OTA升级任务表'; + +CREATE TABLE `ota_upgrade_records` +( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', + `task_id` bigint(20) NOT NULL COMMENT '任务ID,关联ota_upgrade_tasks表', + `device_identification` varchar(100) NOT NULL DEFAULT '' COMMENT '设备标识', + `upgrade_status` smallint(1) NOT NULL DEFAULT '0' COMMENT '升级状态(0:待升级、1:升级中、2:升级成功、3:升级失败)', + `progress` smallint(3) NOT NULL DEFAULT '0' COMMENT '升级进度(百分比)', + `error_code` varchar(100) DEFAULT NULL COMMENT '错误代码', + `error_message` varchar(255) DEFAULT NULL COMMENT '错误信息', + `start_time` datetime DEFAULT NULL COMMENT '升级开始时间', + `end_time` datetime DEFAULT NULL COMMENT '升级结束时间', + `success_details` longtext COMMENT '升级成功详细信息', + `failure_details` longtext COMMENT '升级失败详细信息', + `log_details` longtext COMMENT '升级过程日志', + `remark` varchar(255) DEFAULT '' COMMENT '描述', + `created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '记录创建时间', + `created_org_id` bigint(20) DEFAULT NULL COMMENT '创建人组织', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `idx_task_id_device_identification` (`task_id`,`device_identification`) USING BTREE, + KEY `idx_task_id` (`task_id`), + KEY `idx_device_identification` (`device_identification`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='OTA升级记录表'; + diff --git a/doc/sql/thinglinks.sql b/doc/sql/thinglinks.sql index afb012ed..270d2165 100644 --- a/doc/sql/thinglinks.sql +++ b/doc/sql/thinglinks.sql @@ -13,13 +13,17 @@ Date: 18/11/2022 21:10:02 */ -DROP DATABASE IF EXISTS `thinglinks`; +DROP +DATABASE IF EXISTS `thinglinks`; -CREATE DATABASE `thinglinks` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; +CREATE +DATABASE `thinglinks` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; SET NAMES utf8mb4; -SET FOREIGN_KEY_CHECKS = 0; -USE `thinglinks`; +SET +FOREIGN_KEY_CHECKS = 0; +USE +`thinglinks`; -- ---------------------------- -- Table structure for QRTZ_BLOB_TRIGGERS -- ---------------------------- @@ -116,9 +120,9 @@ CREATE TABLE `QRTZ_FIRED_TRIGGERS` `trigger_name` varchar(200) NOT NULL COMMENT 'qrtz_triggers表trigger_name的外键', `trigger_group` varchar(200) NOT NULL COMMENT 'qrtz_triggers表trigger_group的外键', `instance_name` varchar(200) NOT NULL COMMENT '调度器实例名', - `fired_time` bigint(13) NOT NULL COMMENT '触发的时间', - `sched_time` bigint(13) NOT NULL COMMENT '定时器制定的时间', - `priority` int(11) NOT NULL COMMENT '优先级', + `fired_time` bigint(13) NOT NULL COMMENT '触发的时间', + `sched_time` bigint(13) NOT NULL COMMENT '定时器制定的时间', + `priority` int(11) NOT NULL COMMENT '优先级', `state` varchar(16) NOT NULL COMMENT '状态', `job_name` varchar(200) DEFAULT NULL COMMENT '任务名称', `job_group` varchar(200) DEFAULT NULL COMMENT '任务组名', @@ -262,8 +266,8 @@ CREATE TABLE `QRTZ_SCHEDULER_STATE` ( `sched_name` varchar(120) NOT NULL COMMENT '调度名称', `instance_name` varchar(200) NOT NULL COMMENT '实例名称', - `last_checkin_time` bigint(13) NOT NULL COMMENT '上次检查时间', - `checkin_interval` bigint(13) NOT NULL COMMENT '检查间隔时间', + `last_checkin_time` bigint(13) NOT NULL COMMENT '上次检查时间', + `checkin_interval` bigint(13) NOT NULL COMMENT '检查间隔时间', PRIMARY KEY (`sched_name`, `instance_name`) USING BTREE ) ENGINE = InnoDB DEFAULT CHARSET = utf8 @@ -286,9 +290,9 @@ CREATE TABLE `QRTZ_SIMPLE_TRIGGERS` `sched_name` varchar(120) NOT NULL COMMENT '调度名称', `trigger_name` varchar(200) NOT NULL COMMENT 'qrtz_triggers表trigger_name的外键', `trigger_group` varchar(200) NOT NULL COMMENT 'qrtz_triggers表trigger_group的外键', - `repeat_count` bigint(7) NOT NULL COMMENT '重复的次数统计', - `repeat_interval` bigint(12) NOT NULL COMMENT '重复的间隔时间', - `times_triggered` bigint(10) NOT NULL COMMENT '已经触发的次数', + `repeat_count` bigint(7) NOT NULL COMMENT '重复的次数统计', + `repeat_interval` bigint(12) NOT NULL COMMENT '重复的间隔时间', + `times_triggered` bigint(10) NOT NULL COMMENT '已经触发的次数', PRIMARY KEY (`sched_name`, `trigger_name`, `trigger_group`) USING BTREE, CONSTRAINT `QRTZ_SIMPLE_TRIGGERS_ibfk_1` FOREIGN KEY (`sched_name`, `trigger_name`, `trigger_group`) REFERENCES `QRTZ_TRIGGERS` (`sched_name`, `trigger_name`, `trigger_group`) ) ENGINE = InnoDB @@ -313,10 +317,10 @@ CREATE TABLE `QRTZ_SIMPROP_TRIGGERS` `str_prop_1` varchar(512) DEFAULT NULL COMMENT 'String类型的trigger的第一个参数', `str_prop_2` varchar(512) DEFAULT NULL COMMENT 'String类型的trigger的第二个参数', `str_prop_3` varchar(512) DEFAULT NULL COMMENT 'String类型的trigger的第三个参数', - `int_prop_1` int(11) DEFAULT NULL COMMENT 'int类型的trigger的第一个参数', - `int_prop_2` int(11) DEFAULT NULL COMMENT 'int类型的trigger的第二个参数', - `long_prop_1` bigint(20) DEFAULT NULL COMMENT 'long类型的trigger的第一个参数', - `long_prop_2` bigint(20) DEFAULT NULL COMMENT 'long类型的trigger的第二个参数', + `int_prop_1` int(11) DEFAULT NULL COMMENT 'int类型的trigger的第一个参数', + `int_prop_2` int(11) DEFAULT NULL COMMENT 'int类型的trigger的第二个参数', + `long_prop_1` bigint(20) DEFAULT NULL COMMENT 'long类型的trigger的第一个参数', + `long_prop_2` bigint(20) DEFAULT NULL COMMENT 'long类型的trigger的第二个参数', `dec_prop_1` decimal(13, 4) DEFAULT NULL COMMENT 'decimal类型的trigger的第一个参数', `dec_prop_2` decimal(13, 4) DEFAULT NULL COMMENT 'decimal类型的trigger的第二个参数', `bool_prop_1` varchar(1) DEFAULT NULL COMMENT 'Boolean类型的trigger的第一个参数', @@ -345,18 +349,18 @@ CREATE TABLE `QRTZ_TRIGGERS` `job_name` varchar(200) NOT NULL COMMENT 'qrtz_job_details表job_name的外键', `job_group` varchar(200) NOT NULL COMMENT 'qrtz_job_details表job_group的外键', `description` varchar(250) DEFAULT NULL COMMENT '相关介绍', - `next_fire_time` bigint(13) DEFAULT NULL COMMENT '上一次触发时间(毫秒)', - `prev_fire_time` bigint(13) DEFAULT NULL COMMENT '下一次触发时间(默认为-1表示不触发)', - `priority` int(11) DEFAULT NULL COMMENT '优先级', + `next_fire_time` bigint(13) DEFAULT NULL COMMENT '上一次触发时间(毫秒)', + `prev_fire_time` bigint(13) DEFAULT NULL COMMENT '下一次触发时间(默认为-1表示不触发)', + `priority` int(11) DEFAULT NULL COMMENT '优先级', `trigger_state` varchar(16) NOT NULL COMMENT '触发器状态', `trigger_type` varchar(8) NOT NULL COMMENT '触发器的类型', - `start_time` bigint(13) NOT NULL COMMENT '开始时间', - `end_time` bigint(13) DEFAULT NULL COMMENT '结束时间', + `start_time` bigint(13) NOT NULL COMMENT '开始时间', + `end_time` bigint(13) DEFAULT NULL COMMENT '结束时间', `calendar_name` varchar(200) DEFAULT NULL COMMENT '日程表名称', - `misfire_instr` smallint(2) DEFAULT NULL COMMENT '补偿执行的策略', + `misfire_instr` smallint(2) DEFAULT NULL COMMENT '补偿执行的策略', `job_data` blob COMMENT '存放持久化job对象', PRIMARY KEY (`sched_name`, `trigger_name`, `trigger_group`) USING BTREE, - KEY `sched_name` (`sched_name`, `job_name`, `job_group`) USING BTREE, + KEY `sched_name` (`sched_name`, `job_name`, `job_group`) USING BTREE, CONSTRAINT `QRTZ_TRIGGERS_ibfk_1` FOREIGN KEY (`sched_name`, `job_name`, `job_group`) REFERENCES `QRTZ_JOB_DETAILS` (`sched_name`, `job_name`, `job_group`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8 @@ -424,7 +428,7 @@ COMMIT; DROP TABLE IF EXISTS `casbin_rule`; CREATE TABLE `casbin_rule` ( - `id` int(11) NOT NULL AUTO_INCREMENT, + `id` int(11) NOT NULL AUTO_INCREMENT, `ptype` varchar(100) NOT NULL, `v0` varchar(100) DEFAULT NULL, `v1` varchar(100) DEFAULT NULL, @@ -448,7 +452,7 @@ COMMIT; DROP TABLE IF EXISTS `device`; CREATE TABLE `device` ( - `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', + `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', `client_id` varchar(255) NOT NULL COMMENT '客户端标识', `user_name` varchar(255) NOT NULL COMMENT '用户名', `password` varchar(255) NOT NULL COMMENT '密码', @@ -471,8 +475,8 @@ CREATE TABLE `device` `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', `remark` varchar(500) DEFAULT NULL COMMENT '备注', PRIMARY KEY (`id`) USING BTREE, - KEY `device_id` (`device_identification`) USING BTREE COMMENT '设备标识', - KEY `client_id` (`client_id`) USING BTREE COMMENT '客户端标识' + KEY `device_id` (`device_identification`) USING BTREE COMMENT '设备标识', + KEY `client_id` (`client_id`) USING BTREE COMMENT '客户端标识' ) ENGINE = InnoDB AUTO_INCREMENT = 67 DEFAULT CHARSET = utf8 COMMENT ='边设备档案信息表'; @@ -490,13 +494,13 @@ DROP TABLE IF EXISTS `device_action`; CREATE TABLE `device_action` ( `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', - `device_identification` varchar(255) DEFAULT NULL COMMENT '设备标识', - `action_type` varchar(255) DEFAULT NULL COMMENT '动作类型', + `device_identification` varchar(255) DEFAULT NULL COMMENT '设备标识', + `action_type` varchar(255) DEFAULT NULL COMMENT '动作类型', `message` longtext COMMENT '内容信息', - `status` varchar(255) DEFAULT NULL COMMENT '状态', - `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `status` varchar(255) DEFAULT NULL COMMENT '状态', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', PRIMARY KEY (`id`) USING BTREE, - KEY `device_id` (`device_identification`) USING BTREE COMMENT '设备标识' + KEY `device_id` (`device_identification`) USING BTREE COMMENT '设备标识' ) ENGINE = InnoDB AUTO_INCREMENT = 1001 DEFAULT CHARSET = utf8 COMMENT ='设备动作数据'; @@ -514,15 +518,15 @@ DROP TABLE IF EXISTS `device_datas`; CREATE TABLE `device_datas` ( `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', - `device_identification` varchar(255) DEFAULT NULL COMMENT '设备标识', - `message_id` varchar(255) DEFAULT NULL COMMENT '消息ID', - `topic` varchar(255) DEFAULT NULL COMMENT 'topic', + `device_identification` varchar(255) DEFAULT NULL COMMENT '设备标识', + `message_id` varchar(255) DEFAULT NULL COMMENT '消息ID', + `topic` varchar(255) DEFAULT NULL COMMENT 'topic', `message` longtext COMMENT '内容信息', - `status` varchar(255) DEFAULT NULL COMMENT '状态', - `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `status` varchar(255) DEFAULT NULL COMMENT '状态', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', PRIMARY KEY (`id`) USING BTREE, UNIQUE KEY `message_id` (`message_id`) USING BTREE COMMENT '消息标识', - KEY `device_id` (`device_identification`) USING BTREE COMMENT '设备标识' + KEY `device_id` (`device_identification`) USING BTREE COMMENT '设备标识' ) ENGINE = InnoDB DEFAULT CHARSET = utf8 COMMENT ='设备消息'; @@ -538,8 +542,8 @@ COMMIT; DROP TABLE IF EXISTS `device_info`; CREATE TABLE `device_info` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', - `d_id` bigint(20) NOT NULL COMMENT '边设备档案主键', + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', + `d_id` bigint(20) NOT NULL COMMENT '边设备档案主键', `app_id` varchar(64) NOT NULL COMMENT '应用ID', `node_id` varchar(256) DEFAULT NULL COMMENT '设备节点ID', `node_name` varchar(256) DEFAULT NULL COMMENT '设备名称', @@ -548,7 +552,7 @@ CREATE TABLE `device_info` `manufacturer_id` varchar(256) DEFAULT NULL COMMENT '厂商ID', `model` varchar(256) DEFAULT NULL COMMENT '设备型号', `connect_status` varchar(20) DEFAULT NULL COMMENT '子设备连接状态 : 在线:ONLINE || 离线:OFFLINE || 未连接:INIT', - `shadow_enable` tinyint(1) DEFAULT '1' COMMENT '是否支持设备影子TRUE:1、FALSE :0', + `shadow_enable` tinyint(1) DEFAULT '1' COMMENT '是否支持设备影子TRUE:1、FALSE :0', `shadow_table_name` varchar(2048) DEFAULT NULL COMMENT '设备影子数据表名(多个英文逗号分割)', `status` varchar(10) NOT NULL DEFAULT '0' COMMENT '状态(字典值:0启用 1停用)', `create_by` varchar(64) DEFAULT 'ununited' COMMENT '创建者', @@ -574,7 +578,7 @@ COMMIT; DROP TABLE IF EXISTS `device_location`; CREATE TABLE `device_location` ( - `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT '主键', + `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT '主键', `device_identification` varchar(100) NOT NULL COMMENT '设备标识', `latitude` decimal(10, 7) NOT NULL COMMENT '纬度', `longitude` decimal(10, 7) NOT NULL COMMENT '经度', @@ -604,7 +608,7 @@ COMMIT; DROP TABLE IF EXISTS `device_topic`; CREATE TABLE `device_topic` ( - `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', + `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', `device_identification` varchar(100) NOT NULL COMMENT '设备标识', `type` varchar(255) DEFAULT NULL COMMENT '类型(0:基础Topic,1:自定义Topic)', `topic` varchar(100) DEFAULT NULL COMMENT 'topic', @@ -633,25 +637,25 @@ DROP TABLE IF EXISTS `gen_table`; CREATE TABLE `gen_table` ( `table_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号', - `table_name` varchar(200) DEFAULT '' COMMENT '表名称', - `table_comment` varchar(500) DEFAULT '' COMMENT '表描述', - `sub_table_name` varchar(64) DEFAULT NULL COMMENT '关联子表的表名', - `sub_table_fk_name` varchar(64) DEFAULT NULL COMMENT '子表关联的外键名', - `class_name` varchar(100) DEFAULT '' COMMENT '实体类名称', - `tpl_category` varchar(200) DEFAULT 'crud' COMMENT '使用的模板(crud单表操作 tree树表操作)', - `package_name` varchar(100) DEFAULT NULL COMMENT '生成包路径', - `module_name` varchar(30) DEFAULT NULL COMMENT '生成模块名', - `business_name` varchar(30) DEFAULT NULL COMMENT '生成业务名', - `function_name` varchar(50) DEFAULT NULL COMMENT '生成功能名', - `function_author` varchar(50) DEFAULT NULL COMMENT '生成功能作者', - `gen_type` char(1) DEFAULT '0' COMMENT '生成代码方式(0zip压缩包 1自定义路径)', - `gen_path` varchar(200) DEFAULT '/' COMMENT '生成路径(不填默认项目路径)', - `options` varchar(1000) DEFAULT NULL COMMENT '其它生成选项', - `create_by` varchar(64) DEFAULT '' COMMENT '创建者', - `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `update_by` varchar(64) DEFAULT '' COMMENT '更新者', - `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - `remark` varchar(500) DEFAULT NULL COMMENT '备注', + `table_name` varchar(200) DEFAULT '' COMMENT '表名称', + `table_comment` varchar(500) DEFAULT '' COMMENT '表描述', + `sub_table_name` varchar(64) DEFAULT NULL COMMENT '关联子表的表名', + `sub_table_fk_name` varchar(64) DEFAULT NULL COMMENT '子表关联的外键名', + `class_name` varchar(100) DEFAULT '' COMMENT '实体类名称', + `tpl_category` varchar(200) DEFAULT 'crud' COMMENT '使用的模板(crud单表操作 tree树表操作)', + `package_name` varchar(100) DEFAULT NULL COMMENT '生成包路径', + `module_name` varchar(30) DEFAULT NULL COMMENT '生成模块名', + `business_name` varchar(30) DEFAULT NULL COMMENT '生成业务名', + `function_name` varchar(50) DEFAULT NULL COMMENT '生成功能名', + `function_author` varchar(50) DEFAULT NULL COMMENT '生成功能作者', + `gen_type` char(1) DEFAULT '0' COMMENT '生成代码方式(0zip压缩包 1自定义路径)', + `gen_path` varchar(200) DEFAULT '/' COMMENT '生成路径(不填默认项目路径)', + `options` varchar(1000) DEFAULT NULL COMMENT '其它生成选项', + `create_by` varchar(64) DEFAULT '' COMMENT '创建者', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_by` varchar(64) DEFAULT '' COMMENT '更新者', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `remark` varchar(500) DEFAULT NULL COMMENT '备注', PRIMARY KEY (`table_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 14 @@ -672,14 +676,16 @@ INSERT INTO `gen_table` (`table_id`, `table_name`, `table_comment`, `sub_table_n `tpl_category`, `package_name`, `module_name`, `business_name`, `function_name`, `function_author`, `gen_type`, `gen_path`, `options`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (4, 'product', '产品管理', NULL, NULL, 'Product', 'crud', 'com.mqttsnet.thinglinks.link', 'link', 'product', '产品管理', +VALUES (4, 'product', '产品管理', NULL, NULL, 'Product', 'crud', 'com.mqttsnet.thinglinks.link', 'link', 'product', + '产品管理', 'thinglinks', '0', '/', '{\"parentMenuId\":1061}', 'admin', '2022-02-09 16:13:45', '', '2022-02-09 16:52:41', NULL); INSERT INTO `gen_table` (`table_id`, `table_name`, `table_comment`, `sub_table_name`, `sub_table_fk_name`, `class_name`, `tpl_category`, `package_name`, `module_name`, `business_name`, `function_name`, `function_author`, `gen_type`, `gen_path`, `options`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (5, 'device_info', '子设备档案表', '', '', 'DeviceInfo', 'crud', 'com.mqttsnet.thinglinks.link', 'link', 'deviceInfo', +VALUES (5, 'device_info', '子设备档案表', '', '', 'DeviceInfo', 'crud', 'com.mqttsnet.thinglinks.link', 'link', + 'deviceInfo', '子设备管理', 'thinglinks', '0', '/', '{\"treeCode\":\"d_id\",\"treeName\":\"d_id\",\"treeParentCode\":\"d_id\",\"parentMenuId\":\"1076\"}', 'admin', '2022-05-09 15:38:08', '', '2022-06-21 14:32:37', NULL); @@ -688,48 +694,58 @@ INSERT INTO `gen_table` (`table_id`, `table_name`, `table_comment`, `sub_table_n `function_author`, `gen_type`, `gen_path`, `options`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) VALUES (7, 'casbin_rule', 'CAS规则策略配置表', NULL, NULL, 'CasbinRule', 'crud', 'com.mqttsnet.thinglinks.link', 'link', - 'casbinRule', 'CAS规则管理', 'thinglinks', '0', '/', '{\"parentMenuId\":\"1061\"}', 'admin', '2022-06-16 17:19:58', + 'casbinRule', 'CAS规则管理', 'thinglinks', '0', '/', '{\"parentMenuId\":\"1061\"}', 'admin', + '2022-06-16 17:19:58', '', '2022-06-17 11:09:44', NULL); INSERT INTO `gen_table` (`table_id`, `table_name`, `table_comment`, `sub_table_name`, `sub_table_fk_name`, `class_name`, `tpl_category`, `package_name`, `module_name`, `business_name`, `function_name`, `function_author`, `gen_type`, `gen_path`, `options`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (8, 'device_topic', '设备Topic数据表', '', '', 'DeviceTopic', 'crud', 'com.mqttsnet.thinglinks.link', 'link', 'topic', - '设备Topic数据', 'thinglinks', '0', '/', '{\"treeCode\":\"device_identification\",\"parentMenuId\":1076}', 'admin', +VALUES (8, 'device_topic', '设备Topic数据表', '', '', 'DeviceTopic', 'crud', 'com.mqttsnet.thinglinks.link', 'link', + 'topic', + '设备Topic数据', 'thinglinks', '0', '/', '{\"treeCode\":\"device_identification\",\"parentMenuId\":1076}', + 'admin', '2022-06-17 16:41:13', '', '2022-06-17 16:57:24', NULL); INSERT INTO `gen_table` (`table_id`, `table_name`, `table_comment`, `sub_table_name`, `sub_table_fk_name`, `class_name`, `tpl_category`, `package_name`, `module_name`, `business_name`, `function_name`, `function_author`, `gen_type`, `gen_path`, `options`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) VALUES (9, 'device_action', '设备动作数据', NULL, NULL, 'DeviceAction', 'crud', 'com.mqttsnet.thinglinks.link', 'link', - 'action', '设备动作数据', 'thinglinks', '0', '/', '{\"parentMenuId\":\"1076\"}', 'admin', '2022-06-17 17:38:20', '', + 'action', '设备动作数据', 'thinglinks', '0', '/', '{\"parentMenuId\":\"1076\"}', 'admin', '2022-06-17 17:38:20', + '', '2022-06-17 17:46:18', NULL); INSERT INTO `gen_table` (`table_id`, `table_name`, `table_comment`, `sub_table_name`, `sub_table_fk_name`, `class_name`, `tpl_category`, `package_name`, `module_name`, `business_name`, `function_name`, `function_author`, `gen_type`, `gen_path`, `options`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (10, 'device_location', '设备位置表', NULL, NULL, 'DeviceLocation', 'crud', 'com.mqttsnet.thinglinks.link', 'link', - 'device_location', '设备位置', 'lvwshuai', '0', '/', '{\"parentMenuId\":\"1062\"}', 'admin', '2022-06-30 16:54:17', +VALUES (10, 'device_location', '设备位置表', NULL, NULL, 'DeviceLocation', 'crud', 'com.mqttsnet.thinglinks.link', + 'link', + 'device_location', '设备位置', 'lvwshuai', '0', '/', '{\"parentMenuId\":\"1062\"}', 'admin', + '2022-06-30 16:54:17', '', '2022-06-30 16:58:36', NULL); INSERT INTO `gen_table` (`table_id`, `table_name`, `table_comment`, `sub_table_name`, `sub_table_fk_name`, `class_name`, `tpl_category`, `package_name`, `module_name`, `business_name`, `function_name`, `function_author`, `gen_type`, `gen_path`, `options`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (11, 'product_template', '产品模板', NULL, NULL, 'ProductTemplate', 'crud', 'com.mqttsnet.thinglinks.link', 'link', - 'product_template', '产品模板', 'thinglinks', '0', '/', '{\"parentMenuId\":1061}', 'admin', '2022-06-30 20:03:00', +VALUES (11, 'product_template', '产品模板', NULL, NULL, 'ProductTemplate', 'crud', 'com.mqttsnet.thinglinks.link', + 'link', + 'product_template', '产品模板', 'thinglinks', '0', '/', '{\"parentMenuId\":1061}', 'admin', + '2022-06-30 20:03:00', '', '2022-07-08 18:33:57', NULL); INSERT INTO `gen_table` (`table_id`, `table_name`, `table_comment`, `sub_table_name`, `sub_table_fk_name`, `class_name`, `tpl_category`, `package_name`, `module_name`, `business_name`, `function_name`, `function_author`, `gen_type`, `gen_path`, `options`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (12, 'protocol', '协议信息表', NULL, NULL, 'Protocol', 'crud', 'com.mqttsnet.thinglinks.link', 'link', 'protocol', +VALUES (12, 'protocol', '协议信息表', NULL, NULL, 'Protocol', 'crud', 'com.mqttsnet.thinglinks.link', 'link', + 'protocol', '协议管理', 'thinglinks', '0', '/', '{\"parentMenuId\":\"1061\"}', 'admin', '2022-07-04 09:05:19', '', '2022-07-04 11:21:13', '协议管理'); INSERT INTO `gen_table` (`table_id`, `table_name`, `table_comment`, `sub_table_name`, `sub_table_fk_name`, `class_name`, `tpl_category`, `package_name`, `module_name`, `business_name`, `function_name`, `function_author`, `gen_type`, `gen_path`, `options`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (13, 'rule', '规则信息表', NULL, NULL, 'Rule', 'crud', 'com.mqttsnet.thinglinks.link', 'link', 'rule', '规则信息', +VALUES (13, 'rule', '规则信息表', NULL, NULL, 'Rule', 'crud', 'com.mqttsnet.thinglinks.link', 'link', 'rule', + '规则信息', 'thinglinks', '0', '/', NULL, 'admin', '2022-07-15 17:47:01', '', '2022-11-18 13:37:26', NULL); COMMIT; @@ -740,27 +756,27 @@ DROP TABLE IF EXISTS `gen_table_column`; CREATE TABLE `gen_table_column` ( `column_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号', - `table_id` varchar(64) DEFAULT NULL COMMENT '归属表编号', - `column_name` varchar(200) DEFAULT NULL COMMENT '列名称', - `column_comment` varchar(500) DEFAULT NULL COMMENT '列描述', - `column_type` varchar(100) DEFAULT NULL COMMENT '列类型', - `java_type` varchar(500) DEFAULT NULL COMMENT 'JAVA类型', - `java_field` varchar(200) DEFAULT NULL COMMENT 'JAVA字段名', - `is_pk` char(1) DEFAULT NULL COMMENT '是否主键(1是)', - `is_increment` char(1) DEFAULT NULL COMMENT '是否自增(1是)', - `is_required` char(1) DEFAULT NULL COMMENT '是否必填(1是)', - `is_insert` char(1) DEFAULT NULL COMMENT '是否为插入字段(1是)', - `is_edit` char(1) DEFAULT NULL COMMENT '是否编辑字段(1是)', - `is_list` char(1) DEFAULT NULL COMMENT '是否列表字段(1是)', - `is_query` char(1) DEFAULT NULL COMMENT '是否查询字段(1是)', - `query_type` varchar(200) DEFAULT 'EQ' COMMENT '查询方式(等于、不等于、大于、小于、范围)', - `html_type` varchar(200) DEFAULT NULL COMMENT '显示类型(文本框、文本域、下拉框、复选框、单选框、日期控件)', - `dict_type` varchar(200) DEFAULT '' COMMENT '字典类型', - `sort` int(11) DEFAULT NULL COMMENT '排序', - `create_by` varchar(64) DEFAULT '' COMMENT '创建者', - `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `update_by` varchar(64) DEFAULT '' COMMENT '更新者', - `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `table_id` varchar(64) DEFAULT NULL COMMENT '归属表编号', + `column_name` varchar(200) DEFAULT NULL COMMENT '列名称', + `column_comment` varchar(500) DEFAULT NULL COMMENT '列描述', + `column_type` varchar(100) DEFAULT NULL COMMENT '列类型', + `java_type` varchar(500) DEFAULT NULL COMMENT 'JAVA类型', + `java_field` varchar(200) DEFAULT NULL COMMENT 'JAVA字段名', + `is_pk` char(1) DEFAULT NULL COMMENT '是否主键(1是)', + `is_increment` char(1) DEFAULT NULL COMMENT '是否自增(1是)', + `is_required` char(1) DEFAULT NULL COMMENT '是否必填(1是)', + `is_insert` char(1) DEFAULT NULL COMMENT '是否为插入字段(1是)', + `is_edit` char(1) DEFAULT NULL COMMENT '是否编辑字段(1是)', + `is_list` char(1) DEFAULT NULL COMMENT '是否列表字段(1是)', + `is_query` char(1) DEFAULT NULL COMMENT '是否查询字段(1是)', + `query_type` varchar(200) DEFAULT 'EQ' COMMENT '查询方式(等于、不等于、大于、小于、范围)', + `html_type` varchar(200) DEFAULT NULL COMMENT '显示类型(文本框、文本域、下拉框、复选框、单选框、日期控件)', + `dict_type` varchar(200) DEFAULT '' COMMENT '字典类型', + `sort` int(11) DEFAULT NULL COMMENT '排序', + `create_by` varchar(64) DEFAULT '' COMMENT '创建者', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_by` varchar(64) DEFAULT '' COMMENT '更新者', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`column_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 189 @@ -780,13 +796,15 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (50, '3', 'client_id', '客户端标识', 'varchar(255)', 'String', 'clientId', '0', '0', '1', '1', '1', '1', '1', 'LIKE', +VALUES (50, '3', 'client_id', '客户端标识', 'varchar(255)', 'String', 'clientId', '0', '0', '1', '1', '1', '1', '1', + 'LIKE', 'input', '', 2, 'thinglinks', '2021-12-28 10:51:40', '', '2021-12-28 11:04:26'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (51, '3', 'user_name', '用户名', 'varchar(255)', 'String', 'userName', '0', '0', '1', '1', '1', '1', NULL, 'LIKE', +VALUES (51, '3', 'user_name', '用户名', 'varchar(255)', 'String', 'userName', '0', '0', '1', '1', '1', '1', NULL, + 'LIKE', 'input', '', 3, 'thinglinks', '2021-12-28 10:51:40', '', '2021-12-28 11:04:26'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -798,19 +816,22 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (53, '3', 'app_id', '应用ID', 'varchar(64)', 'String', 'appId', '0', '0', '1', '1', '1', NULL, NULL, 'EQ', 'input', +VALUES (53, '3', 'app_id', '应用ID', 'varchar(64)', 'String', 'appId', '0', '0', '1', '1', '1', NULL, NULL, 'EQ', + 'input', '', 5, 'thinglinks', '2021-12-28 10:51:40', '', '2021-12-28 11:04:26'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (54, '3', 'auth_mode', '认证方式', 'varchar(255)', 'String', 'authMode', '0', '0', '1', '1', '1', '1', NULL, 'EQ', +VALUES (54, '3', 'auth_mode', '认证方式', 'varchar(255)', 'String', 'authMode', '0', '0', '1', '1', '1', '1', NULL, + 'EQ', 'input', 'link_device_auth_mode', 6, 'thinglinks', '2021-12-28 10:51:40', '', '2021-12-28 11:04:26'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (55, '3', 'device_identification', '设备标识', 'varchar(100)', 'String', 'deviceIdentification', '0', '0', '1', '1', +VALUES (55, '3', 'device_identification', '设备标识', 'varchar(100)', 'String', 'deviceIdentification', '0', '0', '1', + '1', '1', '1', '1', 'LIKE', 'input', '', 7, 'thinglinks', '2021-12-28 10:51:40', '', '2021-12-28 11:04:26'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -822,25 +843,29 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (57, '3', 'connector', '连接实例', 'varchar(255)', 'String', 'connector', '0', '0', '1', '1', '1', '1', '1', 'EQ', +VALUES (57, '3', 'connector', '连接实例', 'varchar(255)', 'String', 'connector', '0', '0', '1', '1', '1', '1', '1', + 'EQ', 'input', 'link_device_connector', 9, 'thinglinks', '2021-12-28 10:51:40', '', '2021-12-28 11:04:26'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (58, '3', 'device_description', '设备描述', 'varchar(255)', 'String', 'deviceDescription', '0', '0', NULL, '1', '1', +VALUES (58, '3', 'device_description', '设备描述', 'varchar(255)', 'String', 'deviceDescription', '0', '0', NULL, '1', + '1', '1', NULL, 'EQ', 'input', '', 10, 'thinglinks', '2021-12-28 10:51:40', '', '2021-12-28 11:04:26'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (59, '3', 'device_status', '设备状态', 'varchar(255)', 'String', 'deviceStatus', '0', '0', '1', '1', '1', '1', '1', +VALUES (59, '3', 'device_status', '设备状态', 'varchar(255)', 'String', 'deviceStatus', '0', '0', '1', '1', '1', '1', + '1', 'EQ', 'radio', 'link_device_status', 11, 'thinglinks', '2021-12-28 10:51:41', '', '2021-12-28 11:04:26'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (60, '3', 'connect_status', '连接状态', 'varchar(255)', 'String', 'connectStatus', '0', '0', '1', '1', '1', '1', '1', +VALUES (60, '3', 'connect_status', '连接状态', 'varchar(255)', 'String', 'connectStatus', '0', '0', '1', '1', '1', '1', + '1', 'EQ', 'radio', 'link_device_connect_status', 12, 'thinglinks', '2021-12-28 10:51:41', '', '2021-12-28 11:04:26'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, @@ -853,13 +878,15 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (62, '3', 'device_tags', '设备标签', 'varchar(255)', 'String', 'deviceTags', '0', '0', '1', '1', '1', '1', '1', 'EQ', +VALUES (62, '3', 'device_tags', '设备标签', 'varchar(255)', 'String', 'deviceTags', '0', '0', '1', '1', '1', '1', '1', + 'EQ', 'input', '', 14, 'thinglinks', '2021-12-28 10:51:41', '', '2021-12-28 11:04:27'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (63, '3', 'product_id', '产品型号', 'varchar(255)', 'String', 'productId', '0', '0', '1', '1', '1', '1', '1', 'EQ', +VALUES (63, '3', 'product_id', '产品型号', 'varchar(255)', 'String', 'productId', '0', '0', '1', '1', '1', '1', '1', + 'EQ', 'input', '', 15, 'thinglinks', '2021-12-28 10:51:41', '', '2021-12-28 11:04:27'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -871,14 +898,16 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (65, '3', 'protocol_type', '产品协议类型', 'varchar(255)', 'String', 'protocolType', '0', '0', '1', '1', '1', '1', '1', +VALUES (65, '3', 'protocol_type', '产品协议类型', 'varchar(255)', 'String', 'protocolType', '0', '0', '1', '1', '1', + '1', '1', 'EQ', 'select', 'link_device_protocol_type', 17, 'thinglinks', '2021-12-28 10:51:41', '', '2021-12-28 11:04:27'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (66, '3', 'device_type', '设备类型', 'varchar(255)', 'String', 'deviceType', '0', '0', '1', '1', '1', '1', '1', 'EQ', +VALUES (66, '3', 'device_type', '设备类型', 'varchar(255)', 'String', 'deviceType', '0', '0', '1', '1', '1', '1', '1', + 'EQ', 'select', 'link_device_device_type', 18, 'thinglinks', '2021-12-28 10:51:41', '', '2021-12-28 11:04:27'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -926,13 +955,15 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (74, '4', 'template_id', '产品模型模板', 'bigint(19)', 'Long', 'templateId', '0', '0', NULL, '1', NULL, NULL, NULL, +VALUES (74, '4', 'template_id', '产品模型模板', 'bigint(19)', 'Long', 'templateId', '0', '0', NULL, '1', NULL, NULL, + NULL, 'EQ', 'input', '', 3, 'admin', '2022-02-09 16:13:46', '', '2022-02-09 16:52:41'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (75, '4', 'product_name', '产品名称:自定义,支持中文、英文大小写、数字、下划线和中划线', 'varchar(255)', 'String', 'productName', '0', '0', +VALUES (75, '4', 'product_name', '产品名称:自定义,支持中文、英文大小写、数字、下划线和中划线', 'varchar(255)', 'String', + 'productName', '0', '0', '1', '1', '1', '1', '1', 'LIKE', 'input', '', 4, 'admin', '2022-02-09 16:13:46', '', '2022-02-09 16:52:41'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -944,53 +975,61 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (77, '4', 'product_type', '支持以下两种产品类型•0:普通产品,需直连设备。\r\n•1:网关产品,可挂载子设备。\r\n', 'varchar(255)', 'String', +VALUES (77, '4', 'product_type', '支持以下两种产品类型•0:普通产品,需直连设备。\r\n•1:网关产品,可挂载子设备。\r\n', + 'varchar(255)', 'String', 'productType', '0', '0', '1', '1', NULL, NULL, NULL, 'EQ', 'select', 'link_device_device_type', 6, 'admin', '2022-02-09 16:13:46', '', '2022-02-09 16:52:41'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (78, '4', 'manufacturer_id', '厂商ID:支持英文大小写,数字,下划线和中划线', 'varchar(255)', 'String', 'manufacturerId', '0', '0', +VALUES (78, '4', 'manufacturer_id', '厂商ID:支持英文大小写,数字,下划线和中划线', 'varchar(255)', 'String', + 'manufacturerId', '0', '0', '1', '1', '1', '1', '1', 'EQ', 'input', '', 7, 'admin', '2022-02-09 16:13:46', '', '2022-02-09 16:52:41'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (79, '4', 'manufacturer_name', '厂商名称 :支持中文、英文大小写、数字、下划线和中划线', 'varchar(255)', 'String', 'manufacturerName', '0', +VALUES (79, '4', 'manufacturer_name', '厂商名称 :支持中文、英文大小写、数字、下划线和中划线', 'varchar(255)', 'String', + 'manufacturerName', '0', '0', '1', '1', '1', '1', '1', 'LIKE', 'input', '', 8, 'admin', '2022-02-09 16:13:46', '', '2022-02-09 16:52:41'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (80, '4', 'model', '产品型号,建议包含字母或数字来保证可扩展性。支持英文大小写、数字、下划线和中划线\r\n', 'varchar(255)', 'String', 'model', '0', '0', +VALUES (80, '4', 'model', '产品型号,建议包含字母或数字来保证可扩展性。支持英文大小写、数字、下划线和中划线\r\n', + 'varchar(255)', 'String', 'model', '0', '0', '1', '1', '1', '1', '1', 'EQ', 'input', '', 9, 'admin', '2022-02-09 16:13:46', '', '2022-02-09 16:52:42'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (81, '4', 'data_format', '数据格式,默认为JSON无需修改。', 'varchar(255)', 'String', 'dataFormat', '0', '0', '1', '1', NULL, +VALUES (81, '4', 'data_format', '数据格式,默认为JSON无需修改。', 'varchar(255)', 'String', 'dataFormat', '0', '0', '1', + '1', NULL, NULL, NULL, 'EQ', 'input', '', 10, 'admin', '2022-02-09 16:13:46', '', '2022-02-09 16:52:42'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (82, '4', 'device_type', '设备类型:支持英文大小写、数字、下划线和中划线\r\n', 'varchar(255)', 'String', 'deviceType', '0', '0', '1', +VALUES (82, '4', 'device_type', '设备类型:支持英文大小写、数字、下划线和中划线\r\n', 'varchar(255)', 'String', + 'deviceType', '0', '0', '1', '1', NULL, '1', NULL, 'EQ', 'select', 'link_protocol_device_type', 11, 'admin', '2022-02-09 16:13:46', '', '2022-02-09 16:52:42'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (83, '4', 'protocol_type', '设备接入平台的协议类型,默认为MQTT无需修改。\r\n ', 'varchar(255)', 'String', 'protocolType', '0', '0', +VALUES (83, '4', 'protocol_type', '设备接入平台的协议类型,默认为MQTT无需修改。\r\n ', 'varchar(255)', 'String', + 'protocolType', '0', '0', '1', '1', NULL, '1', NULL, 'EQ', 'select', 'link_device_protocol_type', 12, 'admin', '2022-02-09 16:13:46', '', '2022-02-09 16:52:42'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (84, '4', 'status', '状态(字典值:启用 停用)', 'varchar(10)', 'String', 'status', '0', '0', '1', '1', '1', '1', NULL, +VALUES (84, '4', 'status', '状态(字典值:启用 停用)', 'varchar(10)', 'String', 'status', '0', '0', '1', '1', '1', '1', + NULL, 'EQ', 'select', 'sys_normal_disable', 13, 'admin', '2022-02-09 16:13:46', '', '2022-02-09 16:52:42'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1002,13 +1041,15 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (86, '4', 'create_by', '创建者', 'varchar(64)', 'String', 'createBy', '0', '0', NULL, '1', NULL, NULL, NULL, 'EQ', +VALUES (86, '4', 'create_by', '创建者', 'varchar(64)', 'String', 'createBy', '0', '0', NULL, '1', NULL, NULL, NULL, + 'EQ', 'input', '', 15, 'admin', '2022-02-09 16:13:47', '', '2022-02-09 16:52:42'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (87, '4', 'create_time', '创建时间', 'datetime', 'Date', 'createTime', '0', '0', NULL, '1', NULL, NULL, NULL, 'EQ', +VALUES (87, '4', 'create_time', '创建时间', 'datetime', 'Date', 'createTime', '0', '0', NULL, '1', NULL, NULL, NULL, + 'EQ', 'datetime', '', 16, 'admin', '2022-02-09 16:13:47', '', '2022-02-09 16:52:42'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1020,7 +1061,8 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (89, '4', 'update_time', '更新时间', 'datetime', 'Date', 'updateTime', '0', '0', NULL, '1', '1', NULL, NULL, 'EQ', +VALUES (89, '4', 'update_time', '更新时间', 'datetime', 'Date', 'updateTime', '0', '0', NULL, '1', '1', NULL, NULL, + 'EQ', 'datetime', '', 18, 'admin', '2022-02-09 16:13:47', '', '2022-02-09 16:52:42'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1044,19 +1086,22 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (93, '5', 'node_id', '设备唯一标识', 'varchar(256)', 'String', 'nodeId', '0', '0', NULL, '1', '1', '1', '1', 'EQ', +VALUES (93, '5', 'node_id', '设备唯一标识', 'varchar(256)', 'String', 'nodeId', '0', '0', NULL, '1', '1', '1', '1', + 'EQ', 'input', '', 4, 'admin', '2022-05-09 15:38:08', '', '2022-06-21 14:32:37'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (94, '5', 'node_name', '设备名称', 'varchar(256)', 'String', 'nodeName', '0', '0', NULL, '1', '1', '1', '1', 'LIKE', +VALUES (94, '5', 'node_name', '设备名称', 'varchar(256)', 'String', 'nodeName', '0', '0', NULL, '1', '1', '1', '1', + 'LIKE', 'input', '', 5, 'admin', '2022-05-09 15:38:08', '', '2022-06-21 14:32:37'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (95, '5', 'device_id', '子设备标识', 'varchar(256)', 'String', 'deviceId', '0', '0', NULL, '1', '1', '1', '1', 'EQ', +VALUES (95, '5', 'device_id', '子设备标识', 'varchar(256)', 'String', 'deviceId', '0', '0', NULL, '1', '1', '1', '1', + 'EQ', 'input', '', 6, 'admin', '2022-05-09 15:38:09', '', '2022-06-21 14:32:37'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1074,7 +1119,8 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (98, '5', 'model', '设备型号', 'varchar(256)', 'String', 'model', '0', '0', NULL, '1', '1', '1', '1', 'EQ', 'input', +VALUES (98, '5', 'model', '设备型号', 'varchar(256)', 'String', 'model', '0', '0', NULL, '1', '1', '1', '1', 'EQ', + 'input', '', 9, 'admin', '2022-05-09 15:38:09', '', '2022-06-21 14:32:38'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1087,44 +1133,51 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (100, '5', 'shadow_enable', '是否支持设备影子', 'tinyint(1)', 'Integer', 'shadowEnable', '0', '0', NULL, '1', '1', '1', +VALUES (100, '5', 'shadow_enable', '是否支持设备影子', 'tinyint(1)', 'Integer', 'shadowEnable', '0', '0', NULL, '1', + '1', '1', '1', 'EQ', 'select', 'link_deviceInfo_shadow_enable', 11, 'admin', '2022-05-09 15:38:09', '', '2022-06-21 14:32:38'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (101, '5', 'shadow_table_name', '设备影子数据表名', 'varchar(2048)', 'String', 'shadowTableName', '0', '0', NULL, '1', +VALUES (101, '5', 'shadow_table_name', '设备影子数据表名', 'varchar(2048)', 'String', 'shadowTableName', '0', '0', NULL, + '1', '1', '1', '1', 'LIKE', 'input', '', 12, 'admin', '2022-05-09 15:38:09', '', '2022-06-21 14:32:38'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (102, '5', 'status', '状态(字典值:0启用 1停用)', 'varchar(10)', 'String', 'status', '0', '0', '1', '1', '1', '1', '1', +VALUES (102, '5', 'status', '状态(字典值:0启用 1停用)', 'varchar(10)', 'String', 'status', '0', '0', '1', '1', '1', + '1', '1', 'EQ', 'select', 'business_data_status', 13, 'admin', '2022-05-09 15:38:09', '', '2022-06-21 14:32:38'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (103, '5', 'create_by', '创建者', 'varchar(64)', 'String', 'createBy', '0', '0', NULL, '1', NULL, NULL, NULL, 'EQ', +VALUES (103, '5', 'create_by', '创建者', 'varchar(64)', 'String', 'createBy', '0', '0', NULL, '1', NULL, NULL, NULL, + 'EQ', 'input', '', 14, 'admin', '2022-05-09 15:38:09', '', '2022-06-21 14:32:38'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (104, '5', 'create_time', '创建时间', 'datetime', 'Date', 'createTime', '0', '0', NULL, '1', NULL, NULL, NULL, 'EQ', +VALUES (104, '5', 'create_time', '创建时间', 'datetime', 'Date', 'createTime', '0', '0', NULL, '1', NULL, NULL, NULL, + 'EQ', 'datetime', '', 15, 'admin', '2022-05-09 15:38:09', '', '2022-06-21 14:32:38'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (105, '5', 'update_by', '更新者', 'varchar(64)', 'String', 'updateBy', '0', '0', NULL, '1', '1', NULL, NULL, 'EQ', +VALUES (105, '5', 'update_by', '更新者', 'varchar(64)', 'String', 'updateBy', '0', '0', NULL, '1', '1', NULL, NULL, + 'EQ', 'input', '', 16, 'admin', '2022-05-09 15:38:09', '', '2022-06-21 14:32:38'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (106, '5', 'update_time', '更新时间', 'datetime', 'Date', 'updateTime', '0', '0', NULL, '1', '1', NULL, NULL, 'EQ', +VALUES (106, '5', 'update_time', '更新时间', 'datetime', 'Date', 'updateTime', '0', '0', NULL, '1', '1', NULL, NULL, + 'EQ', 'datetime', '', 17, 'admin', '2022-05-09 15:38:09', '', '2022-06-21 14:32:38'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1148,13 +1201,15 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (118, '7', 'v0', '规则名称', 'varchar(100)', 'String', 'v0', '0', '0', NULL, '1', '1', '1', '1', 'EQ', 'input', '', +VALUES (118, '7', 'v0', '规则名称', 'varchar(100)', 'String', 'v0', '0', '0', NULL, '1', '1', '1', '1', 'EQ', 'input', + '', 3, 'admin', '2022-06-16 17:19:58', '', '2022-06-17 11:09:45'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (119, '7', 'v1', '资源', 'varchar(100)', 'String', 'v1', '0', '0', NULL, '1', '1', '1', '1', 'EQ', 'input', '', 4, +VALUES (119, '7', 'v1', '资源', 'varchar(100)', 'String', 'v1', '0', '0', NULL, '1', '1', '1', '1', 'EQ', 'input', '', + 4, 'admin', '2022-06-16 17:19:58', '', '2022-06-17 11:09:45'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1190,13 +1245,15 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (125, '8', 'device_identification', '设备标识', 'varchar(100)', 'String', 'deviceIdentification', '0', '0', '1', '1', +VALUES (125, '8', 'device_identification', '设备标识', 'varchar(100)', 'String', 'deviceIdentification', '0', '0', '1', + '1', '1', '1', '1', 'EQ', 'input', '', 2, 'admin', '2022-06-17 16:41:14', '', '2022-06-17 16:57:24'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (126, '8', 'type', '类型(0:基础Topic,1:自定义Topic)', 'varchar(255)', 'String', 'type', '0', '0', NULL, '1', '1', '1', +VALUES (126, '8', 'type', '类型(0:基础Topic,1:自定义Topic)', 'varchar(255)', 'String', 'type', '0', '0', NULL, '1', '1', + '1', '1', 'EQ', 'select', '', 3, 'admin', '2022-06-17 16:41:14', '', '2022-06-17 16:57:24'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1208,37 +1265,43 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (128, '8', 'publisher', '发布者', 'varchar(255)', 'String', 'publisher', '0', '0', NULL, '1', '1', '1', '1', 'EQ', +VALUES (128, '8', 'publisher', '发布者', 'varchar(255)', 'String', 'publisher', '0', '0', NULL, '1', '1', '1', '1', + 'EQ', 'input', '', 5, 'admin', '2022-06-17 16:41:14', '', '2022-06-17 16:57:24'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (129, '8', 'subscriber', '订阅者', 'varchar(255)', 'String', 'subscriber', '0', '0', NULL, '1', '1', '1', '1', 'EQ', +VALUES (129, '8', 'subscriber', '订阅者', 'varchar(255)', 'String', 'subscriber', '0', '0', NULL, '1', '1', '1', '1', + 'EQ', 'input', '', 6, 'admin', '2022-06-17 16:41:14', '', '2022-06-17 16:57:24'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (130, '8', 'create_by', '创建者', 'varchar(64)', 'String', 'createBy', '0', '0', NULL, '1', NULL, NULL, NULL, 'EQ', +VALUES (130, '8', 'create_by', '创建者', 'varchar(64)', 'String', 'createBy', '0', '0', NULL, '1', NULL, NULL, NULL, + 'EQ', 'input', '', 7, 'admin', '2022-06-17 16:41:14', '', '2022-06-17 16:57:24'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (131, '8', 'create_time', '创建时间', 'datetime', 'Date', 'createTime', '0', '0', NULL, '1', NULL, NULL, NULL, 'EQ', +VALUES (131, '8', 'create_time', '创建时间', 'datetime', 'Date', 'createTime', '0', '0', NULL, '1', NULL, NULL, NULL, + 'EQ', 'datetime', '', 8, 'admin', '2022-06-17 16:41:14', '', '2022-06-17 16:57:25'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (132, '8', 'update_by', '更新者', 'varchar(64)', 'String', 'updateBy', '0', '0', NULL, '1', '1', NULL, NULL, 'EQ', +VALUES (132, '8', 'update_by', '更新者', 'varchar(64)', 'String', 'updateBy', '0', '0', NULL, '1', '1', NULL, NULL, + 'EQ', 'input', '', 9, 'admin', '2022-06-17 16:41:14', '', '2022-06-17 16:57:25'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (133, '8', 'update_time', '更新时间', 'datetime', 'Date', 'updateTime', '0', '0', NULL, '1', '1', NULL, NULL, 'EQ', +VALUES (133, '8', 'update_time', '更新时间', 'datetime', 'Date', 'updateTime', '0', '0', NULL, '1', '1', NULL, NULL, + 'EQ', 'datetime', '', 10, 'admin', '2022-06-17 16:41:14', '', '2022-06-17 16:57:25'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1274,19 +1337,22 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (139, '9', 'status', '状态', 'varchar(255)', 'String', 'status', '0', '0', NULL, '1', '1', '1', '1', 'EQ', 'radio', +VALUES (139, '9', 'status', '状态', 'varchar(255)', 'String', 'status', '0', '0', NULL, '1', '1', '1', '1', 'EQ', + 'radio', '', 5, 'admin', '2022-06-17 17:38:21', '', '2022-06-17 17:46:18'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (140, '9', 'create_time', '创建时间', 'datetime', 'Date', 'createTime', '0', '0', NULL, '1', NULL, NULL, NULL, 'EQ', +VALUES (140, '9', 'create_time', '创建时间', 'datetime', 'Date', 'createTime', '0', '0', NULL, '1', NULL, NULL, NULL, + 'EQ', 'datetime', '', 6, 'admin', '2022-06-17 17:38:21', '', '2022-06-17 17:46:19'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (141, '10', 'id', '主键', 'bigint(19)', 'Long', 'id', '1', '1', NULL, '1', NULL, NULL, NULL, 'EQ', 'input', '', 1, +VALUES (141, '10', 'id', '主键', 'bigint(19)', 'Long', 'id', '1', '1', NULL, '1', NULL, NULL, NULL, 'EQ', 'input', '', + 1, 'admin', '2022-06-30 16:54:17', '', '2022-06-30 16:58:36'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1298,7 +1364,8 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (143, '10', 'latitude', '纬度', 'decimal(10,7)', 'BigDecimal', 'latitude', '0', '0', '1', '1', '1', '1', '1', 'EQ', +VALUES (143, '10', 'latitude', '纬度', 'decimal(10,7)', 'BigDecimal', 'latitude', '0', '0', '1', '1', '1', '1', '1', + 'EQ', 'input', '', 3, 'admin', '2022-06-30 16:54:17', '', '2022-06-30 16:58:36'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1310,13 +1377,15 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (145, '10', 'full_name', '位置名称', 'varchar(500)', 'String', 'fullName', '0', '0', '1', '1', '1', '1', '1', 'LIKE', +VALUES (145, '10', 'full_name', '位置名称', 'varchar(500)', 'String', 'fullName', '0', '0', '1', '1', '1', '1', '1', + 'LIKE', 'textarea', '', 5, 'admin', '2022-06-30 16:54:17', '', '2022-06-30 16:58:36'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (146, '10', 'province_code', '省,直辖市编码', 'varchar(50)', 'String', 'provinceCode', '0', '0', '1', '1', '1', '1', +VALUES (146, '10', 'province_code', '省,直辖市编码', 'varchar(50)', 'String', 'provinceCode', '0', '0', '1', '1', '1', + '1', '1', 'EQ', 'input', '', 6, 'admin', '2022-06-30 16:54:17', '', '2022-06-30 16:58:36'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1328,31 +1397,36 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (148, '10', 'region_code', '区县', 'varchar(50)', 'String', 'regionCode', '0', '0', '1', '1', '1', '1', '1', 'EQ', +VALUES (148, '10', 'region_code', '区县', 'varchar(50)', 'String', 'regionCode', '0', '0', '1', '1', '1', '1', '1', + 'EQ', 'input', '', 8, 'admin', '2022-06-30 16:54:17', '', '2022-06-30 16:58:36'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (149, '10', 'create_by', '创建者', 'varchar(64)', 'String', 'createBy', '0', '0', NULL, '1', NULL, NULL, NULL, 'EQ', +VALUES (149, '10', 'create_by', '创建者', 'varchar(64)', 'String', 'createBy', '0', '0', NULL, '1', NULL, NULL, NULL, + 'EQ', 'input', '', 9, 'admin', '2022-06-30 16:54:17', '', '2022-06-30 16:58:37'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (150, '10', 'create_time', '创建时间', 'datetime', 'Date', 'createTime', '0', '0', NULL, '1', NULL, NULL, NULL, 'EQ', +VALUES (150, '10', 'create_time', '创建时间', 'datetime', 'Date', 'createTime', '0', '0', NULL, '1', NULL, NULL, NULL, + 'EQ', 'datetime', '', 10, 'admin', '2022-06-30 16:54:17', '', '2022-06-30 16:58:37'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (151, '10', 'update_by', '更新者', 'varchar(64)', 'String', 'updateBy', '0', '0', NULL, '1', '1', NULL, NULL, 'EQ', +VALUES (151, '10', 'update_by', '更新者', 'varchar(64)', 'String', 'updateBy', '0', '0', NULL, '1', '1', NULL, NULL, + 'EQ', 'input', '', 11, 'admin', '2022-06-30 16:54:17', '', '2022-06-30 16:58:37'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (152, '10', 'update_time', '更新时间', 'datetime', 'Date', 'updateTime', '0', '0', NULL, '1', '1', NULL, NULL, 'EQ', +VALUES (152, '10', 'update_time', '更新时间', 'datetime', 'Date', 'updateTime', '0', '0', NULL, '1', '1', NULL, NULL, + 'EQ', 'datetime', '', 12, 'admin', '2022-06-30 16:54:17', '', '2022-06-30 16:58:37'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1370,50 +1444,58 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (155, '11', 'app_id', '应用ID', 'varchar(64)', 'String', 'appId', '0', '0', '1', '1', '1', '1', '1', 'EQ', 'input', +VALUES (155, '11', 'app_id', '应用ID', 'varchar(64)', 'String', 'appId', '0', '0', '1', '1', '1', '1', '1', 'EQ', + 'input', '', 2, 'admin', '2022-06-30 20:03:01', '', '2022-07-08 18:33:58'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (156, '11', 'template_name', '产品模板名称:自定义,支持中文、英文大小写、数字、下划线和中划线', 'varchar(255)', 'String', 'templateName', '0', +VALUES (156, '11', 'template_name', '产品模板名称:自定义,支持中文、英文大小写、数字、下划线和中划线', 'varchar(255)', + 'String', 'templateName', '0', '0', '1', '1', '1', '1', '1', 'LIKE', 'input', '', 3, 'admin', '2022-06-30 20:03:01', '', '2022-07-08 18:33:58'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (157, '11', 'status', '状态(字典值:启用 停用)', 'varchar(10)', 'String', 'status', '0', '0', '1', '1', '1', '1', '1', +VALUES (157, '11', 'status', '状态(字典值:启用 停用)', 'varchar(10)', 'String', 'status', '0', '0', '1', '1', '1', '1', + '1', 'EQ', 'radio', '', 4, 'admin', '2022-06-30 20:03:01', '', '2022-07-08 18:33:58'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (158, '11', 'remark', '产品模型模板描述', 'varchar(255)', 'String', 'remark', '0', '0', NULL, '1', '1', '1', NULL, 'EQ', +VALUES (158, '11', 'remark', '产品模型模板描述', 'varchar(255)', 'String', 'remark', '0', '0', NULL, '1', '1', '1', + NULL, 'EQ', 'input', '', 5, 'admin', '2022-06-30 20:03:01', '', '2022-07-08 18:33:58'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (159, '11', 'create_by', '创建者', 'varchar(64)', 'String', 'createBy', '0', '0', NULL, '1', NULL, NULL, NULL, 'EQ', +VALUES (159, '11', 'create_by', '创建者', 'varchar(64)', 'String', 'createBy', '0', '0', NULL, '1', NULL, NULL, NULL, + 'EQ', 'input', '', 6, 'admin', '2022-06-30 20:03:01', '', '2022-07-08 18:33:58'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (160, '11', 'create_time', '创建时间', 'datetime', 'Date', 'createTime', '0', '0', NULL, '1', NULL, NULL, NULL, 'EQ', +VALUES (160, '11', 'create_time', '创建时间', 'datetime', 'Date', 'createTime', '0', '0', NULL, '1', NULL, NULL, NULL, + 'EQ', 'datetime', '', 7, 'admin', '2022-06-30 20:03:01', '', '2022-07-08 18:33:58'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (161, '11', 'update_by', '更新者', 'varchar(64)', 'String', 'updateBy', '0', '0', NULL, '1', '1', NULL, NULL, 'EQ', +VALUES (161, '11', 'update_by', '更新者', 'varchar(64)', 'String', 'updateBy', '0', '0', NULL, '1', '1', NULL, NULL, + 'EQ', 'input', '', 8, 'admin', '2022-06-30 20:03:01', '', '2022-07-08 18:33:58'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (162, '11', 'update_time', '更新时间', 'datetime', 'Date', 'updateTime', '0', '0', NULL, '1', '1', NULL, NULL, 'EQ', +VALUES (162, '11', 'update_time', '更新时间', 'datetime', 'Date', 'updateTime', '0', '0', NULL, '1', '1', NULL, NULL, + 'EQ', 'datetime', '', 9, 'admin', '2022-06-30 20:03:01', '', '2022-07-08 18:33:58'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1425,7 +1507,8 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (164, '12', 'product_identification', '产品标识', 'varchar(100)', 'String', 'productIdentification', '0', '0', '1', +VALUES (164, '12', 'product_identification', '产品标识', 'varchar(100)', 'String', 'productIdentification', '0', '0', + '1', '1', '1', '1', '1', 'EQ', 'input', '', 2, 'admin', '2022-07-04 09:05:19', '', '2022-07-04 11:21:13'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1443,20 +1526,23 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (167, '12', 'protocol_version', '协议版本', 'varchar(255)', 'String', 'protocolVersion', '0', '0', NULL, '1', '1', +VALUES (167, '12', 'protocol_version', '协议版本', 'varchar(255)', 'String', 'protocolVersion', '0', '0', NULL, '1', + '1', '1', '1', 'EQ', 'input', '', 5, 'admin', '2022-07-04 09:05:19', '', '2022-07-04 11:21:13'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (168, '12', 'protocol_type', '协议类型 :mqtt || coap || modbus || http', 'varchar(255)', 'String', 'protocolType', +VALUES (168, '12', 'protocol_type', '协议类型 :mqtt || coap || modbus || http', 'varchar(255)', 'String', + 'protocolType', '0', '0', NULL, '1', '1', '1', '1', 'EQ', 'select', 'link_device_protocol_type', 6, 'admin', '2022-07-04 09:05:19', '', '2022-07-04 11:21:13'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (169, '12', 'protocol_voice', '协议语言', 'varchar(255)', 'String', 'protocolVoice', '0', '0', NULL, '1', '1', '1', +VALUES (169, '12', 'protocol_voice', '协议语言', 'varchar(255)', 'String', 'protocolVoice', '0', '0', NULL, '1', '1', + '1', '1', 'EQ', 'select', 'link_ protocol_voice', 7, 'admin', '2022-07-04 09:05:19', '', '2022-07-04 11:21:13'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1468,7 +1554,8 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (171, '12', 'file_path', '文件地址', 'varchar(255)', 'String', 'filePath', '0', '0', NULL, '1', '1', '1', NULL, 'EQ', +VALUES (171, '12', 'file_path', '文件地址', 'varchar(255)', 'String', 'filePath', '0', '0', NULL, '1', '1', '1', NULL, + 'EQ', 'input', '', 9, 'admin', '2022-07-04 09:05:19', '', '2022-07-04 11:21:14'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1480,31 +1567,36 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (173, '12', 'status', '状态(字典值:0启用 1停用)', 'varchar(10)', 'String', 'status', '0', '0', '1', '1', '1', '1', '1', +VALUES (173, '12', 'status', '状态(字典值:0启用 1停用)', 'varchar(10)', 'String', 'status', '0', '0', '1', '1', '1', + '1', '1', 'EQ', 'select', 'business_data_status', 11, 'admin', '2022-07-04 09:05:20', '', '2022-07-04 11:21:14'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (174, '12', 'create_by', '创建者', 'varchar(64)', 'String', 'createBy', '0', '0', NULL, '1', NULL, '1', NULL, 'EQ', +VALUES (174, '12', 'create_by', '创建者', 'varchar(64)', 'String', 'createBy', '0', '0', NULL, '1', NULL, '1', NULL, + 'EQ', 'input', '', 12, 'admin', '2022-07-04 09:05:20', '', '2022-07-04 11:21:14'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (175, '12', 'create_time', '创建时间', 'datetime', 'Date', 'createTime', '0', '0', NULL, '1', NULL, '1', NULL, 'EQ', +VALUES (175, '12', 'create_time', '创建时间', 'datetime', 'Date', 'createTime', '0', '0', NULL, '1', NULL, '1', NULL, + 'EQ', 'datetime', '', 13, 'admin', '2022-07-04 09:05:20', '', '2022-07-04 11:21:14'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (176, '12', 'update_by', '更新者', 'varchar(64)', 'String', 'updateBy', '0', '0', NULL, '1', '1', '1', NULL, 'EQ', +VALUES (176, '12', 'update_by', '更新者', 'varchar(64)', 'String', 'updateBy', '0', '0', NULL, '1', '1', '1', NULL, + 'EQ', 'input', '', 14, 'admin', '2022-07-04 09:05:20', '', '2022-07-04 11:21:14'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (177, '12', 'update_time', '更新时间', 'datetime', 'Date', 'updateTime', '0', '0', NULL, '1', '1', '1', NULL, 'EQ', +VALUES (177, '12', 'update_time', '更新时间', 'datetime', 'Date', 'updateTime', '0', '0', NULL, '1', '1', '1', NULL, + 'EQ', 'datetime', '', 15, 'admin', '2022-07-04 09:05:20', '', '2022-07-04 11:21:14'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, @@ -1522,55 +1614,64 @@ INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_ `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (180, '13', 'app_id', '应用ID', 'varchar(64)', 'String', 'appId', '0', '0', '1', '1', '1', '1', '1', 'EQ', 'input', +VALUES (180, '13', 'app_id', '应用ID', 'varchar(64)', 'String', 'appId', '0', '0', '1', '1', '1', '1', '1', 'EQ', + 'input', '', 2, 'admin', '2022-07-15 17:47:02', '', '2022-11-18 13:38:26'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (181, '13', 'rule_name', '规则名称', 'varchar(255)', 'String', 'ruleName', '0', '0', '1', '1', '1', '1', '1', 'LIKE', +VALUES (181, '13', 'rule_name', '规则名称', 'varchar(255)', 'String', 'ruleName', '0', '0', '1', '1', '1', '1', '1', + 'LIKE', 'input', '', 3, 'admin', '2022-07-15 17:47:02', '', '2022-11-18 13:38:38'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (182, '13', 'cron_expression', '生效时间', 'varchar(50)', 'String', 'cronExpression', '0', '0', NULL, '1', '1', '1', +VALUES (182, '13', 'cron_expression', '生效时间', 'varchar(50)', 'String', 'cronExpression', '0', '0', NULL, '1', '1', + '1', '1', 'EQ', 'input', '', 4, 'admin', '2022-07-15 17:47:02', '', '2022-11-18 13:38:38'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (183, '13', 'status', '状态(字典值:0启用 1停用)', 'varchar(10)', 'String', 'status', '0', '0', '1', '1', '1', '1', '1', +VALUES (183, '13', 'status', '状态(字典值:0启用 1停用)', 'varchar(10)', 'String', 'status', '0', '0', '1', '1', '1', + '1', '1', 'EQ', 'radio', '', 5, 'admin', '2022-07-15 17:47:02', '', '2022-11-18 13:38:38'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (184, '13', 'remark', '规则描述,可以为空', 'varchar(255)', 'String', 'remark', '0', '0', NULL, '1', '1', '1', NULL, 'EQ', +VALUES (184, '13', 'remark', '规则描述,可以为空', 'varchar(255)', 'String', 'remark', '0', '0', NULL, '1', '1', '1', + NULL, 'EQ', 'input', '', 6, 'admin', '2022-07-15 17:47:02', '', '2022-11-18 13:38:38'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (185, '13', 'create_by', '创建人', 'varchar(64)', 'String', 'createBy', '0', '0', NULL, '1', NULL, NULL, NULL, 'EQ', +VALUES (185, '13', 'create_by', '创建人', 'varchar(64)', 'String', 'createBy', '0', '0', NULL, '1', NULL, NULL, NULL, + 'EQ', 'input', '', 7, 'admin', '2022-07-15 17:47:02', '', '2022-11-18 13:38:38'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (186, '13', 'create_time', '创建时间', 'datetime', 'Date', 'createTime', '0', '0', NULL, '1', NULL, NULL, NULL, 'EQ', +VALUES (186, '13', 'create_time', '创建时间', 'datetime', 'Date', 'createTime', '0', '0', NULL, '1', NULL, NULL, NULL, + 'EQ', 'datetime', '', 8, 'admin', '2022-07-15 17:47:03', '', '2022-11-18 13:38:38'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (187, '13', 'update_by', '更新人', 'varchar(64)', 'String', 'updateBy', '0', '0', NULL, '1', '1', NULL, NULL, 'EQ', +VALUES (187, '13', 'update_by', '更新人', 'varchar(64)', 'String', 'updateBy', '0', '0', NULL, '1', '1', NULL, NULL, + 'EQ', 'input', '', 9, 'admin', '2022-07-15 17:47:03', '', '2022-11-18 13:38:38'); INSERT INTO `gen_table_column` (`column_id`, `table_id`, `column_name`, `column_comment`, `column_type`, `java_type`, `java_field`, `is_pk`, `is_increment`, `is_required`, `is_insert`, `is_edit`, `is_list`, `is_query`, `query_type`, `html_type`, `dict_type`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (188, '13', 'update_time', '更新时间', 'datetime', 'Date', 'updateTime', '0', '0', NULL, '1', '1', NULL, NULL, 'EQ', +VALUES (188, '13', 'update_time', '更新时间', 'datetime', 'Date', 'updateTime', '0', '0', NULL, '1', '1', NULL, NULL, + 'EQ', 'datetime', '', 10, 'admin', '2022-07-15 17:47:03', '', '2022-11-18 13:38:38'); COMMIT; @@ -1580,7 +1681,7 @@ COMMIT; DROP TABLE IF EXISTS `product`; CREATE TABLE `product` ( - `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', + `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', `app_id` varchar(64) NOT NULL COMMENT '应用ID', `template_identification` varchar(100) DEFAULT NULL COMMENT '产品模版标识', `product_name` varchar(255) NOT NULL COMMENT '产品名称:自定义,支持中文、英文大小写、数字、下划线和中划线', @@ -1599,7 +1700,7 @@ CREATE TABLE `product` `update_by` varchar(64) DEFAULT '' COMMENT '更新者', `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`) USING BTREE, - KEY `manufacturer_id` (`manufacturer_id`) USING BTREE COMMENT '厂商ID索引' + KEY `manufacturer_id` (`manufacturer_id`) USING BTREE COMMENT '厂商ID索引' ) ENGINE = InnoDB AUTO_INCREMENT = 47 DEFAULT CHARSET = utf8 COMMENT ='产品模型'; @@ -1616,8 +1717,8 @@ COMMIT; DROP TABLE IF EXISTS `product_commands`; CREATE TABLE `product_commands` ( - `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT '命令id', - `service_id` bigint(19) NOT NULL COMMENT '服务ID', + `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT '命令id', + `service_id` bigint(19) NOT NULL COMMENT '服务ID', `name` varchar(255) NOT NULL COMMENT '指示命令的名字,如门磁的LOCK命令、摄像头的VIDEO_RECORD命令,命令名与参数共同构成一个完整的命令。\r\n支持英文大小写、数字及下划线,长度[2,50]。\r\n', `description` varchar(255) DEFAULT NULL COMMENT '命令描述。', `create_by` varchar(64) DEFAULT 'ununited' COMMENT '创建者', @@ -1625,7 +1726,7 @@ CREATE TABLE `product_commands` `update_by` varchar(64) DEFAULT '' COMMENT '更新者', `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`) USING BTREE, - KEY `service_id` (`service_id`) USING BTREE + KEY `service_id` (`service_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 6 DEFAULT CHARSET = utf8 COMMENT ='产品模型设备服务命令表'; @@ -1642,9 +1743,9 @@ COMMIT; DROP TABLE IF EXISTS `product_commands_requests`; CREATE TABLE `product_commands_requests` ( - `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', - `service_id` bigint(19) NOT NULL COMMENT '服务ID', - `commands_id` bigint(19) NOT NULL COMMENT '命令ID', + `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', + `service_id` bigint(19) NOT NULL COMMENT '服务ID', + `commands_id` bigint(19) NOT NULL COMMENT '命令ID', `datatype` varchar(255) NOT NULL COMMENT '指示数据类型。取值范围:string、int、decimal\r\n', `enumlist` varchar(255) DEFAULT NULL COMMENT '指示枚举值。\r\n如开关状态status可有如下取值\r\n"enumList" : ["OPEN","CLOSE"]\r\n目前本字段是非功能性字段,仅起到描述作用。建议准确定义。\r\n', `max` varchar(255) DEFAULT NULL COMMENT '指示最大值。\r\n仅当dataType为int、decimal时生效,逻辑小于等于。', @@ -1660,8 +1761,8 @@ CREATE TABLE `product_commands_requests` `update_by` varchar(64) DEFAULT '' COMMENT '更新者', `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`) USING BTREE, - KEY `commands_id` (`commands_id`) USING BTREE, - KEY `service_id` (`service_id`) USING BTREE + KEY `commands_id` (`commands_id`) USING BTREE, + KEY `service_id` (`service_id`) USING BTREE ) ENGINE = InnoDB DEFAULT CHARSET = utf8 COMMENT ='产品模型设备下发服务命令属性表'; @@ -1677,9 +1778,9 @@ COMMIT; DROP TABLE IF EXISTS `product_commands_response`; CREATE TABLE `product_commands_response` ( - `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', - `commands_id` bigint(19) NOT NULL COMMENT '命令ID', - `service_id` bigint(19) DEFAULT NULL COMMENT '服务ID', + `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', + `commands_id` bigint(19) NOT NULL COMMENT '命令ID', + `service_id` bigint(19) DEFAULT NULL COMMENT '服务ID', `datatype` varchar(255) NOT NULL COMMENT '指示数据类型。取值范围:string、int、decimal\r\n', `enumlist` varchar(255) DEFAULT NULL COMMENT '指示枚举值。\r\n如开关状态status可有如下取值\r\n"enumList" : ["OPEN","CLOSE"]\r\n目前本字段是非功能性字段,仅起到描述作用。建议准确定义。\r\n', `max` varchar(255) DEFAULT NULL COMMENT '指示最大值。\r\n仅当dataType为int、decimal时生效,逻辑小于等于。', @@ -1695,8 +1796,8 @@ CREATE TABLE `product_commands_response` `update_by` varchar(64) DEFAULT '' COMMENT '更新者', `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`) USING BTREE, - KEY `commands_id` (`commands_id`) USING BTREE, - KEY `service_id` (`service_id`) USING BTREE + KEY `commands_id` (`commands_id`) USING BTREE, + KEY `service_id` (`service_id`) USING BTREE ) ENGINE = InnoDB DEFAULT CHARSET = utf8 COMMENT ='产品模型设备响应服务命令属性表'; @@ -1712,25 +1813,25 @@ COMMIT; DROP TABLE IF EXISTS `product_properties`; CREATE TABLE `product_properties` ( - `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT '属性id', + `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT '属性id', `name` varchar(255) NOT NULL COMMENT '指示属性名称。', - `service_id` bigint(19) NOT NULL COMMENT '服务ID', + `service_id` bigint(19) NOT NULL COMMENT '服务ID', `datatype` varchar(255) NOT NULL COMMENT '指示数据类型:取值范围:string、int、decimal(float和double都可以使用此类型)、DateTime、jsonObject上报数据时,复杂类型数据格式如下:\r\n•DateTime:yyyyMMdd’T’HHmmss’Z’如:20151212T121212Z•jsonObject:自定义json结构体,平台不理解只透传\r\n', `description` varchar(255) DEFAULT NULL COMMENT '属性描述,不影响实际功能,可配置为空字符串""。', `enumlist` varchar(255) DEFAULT NULL COMMENT '指示枚举值:如开关状态status可有如下取值"enumList" : ["OPEN","CLOSE"]目前本字段是非功能性字段,仅起到描述作用。建议准确定义。\r\n', `max` varchar(255) DEFAULT NULL COMMENT '指示最大值。支持长度不超过50的数字。仅当dataType为int、decimal时生效,逻辑小于等于。\r\n', - `maxlength` bigint(19) DEFAULT NULL COMMENT '指示字符串长度。仅当dataType为string、DateTime时生效。\r\n', + `maxlength` bigint(19) DEFAULT NULL COMMENT '指示字符串长度。仅当dataType为string、DateTime时生效。\r\n', `method` varchar(255) DEFAULT NULL COMMENT '指示访问模式。R:可读;W:可写;E属性值更改时上报数据取值范围:R、RW、RE、RWE\r\n', `min` varchar(255) DEFAULT NULL COMMENT '指示最小值。支持长度不超过50的数字。仅当dataType为int、decimal时生效,逻辑大于等于。\r\n', - `required` int(2) DEFAULT NULL COMMENT '指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。(字典值link_product_isRequired:0非必填 1必填)\r\n', - `step` int(9) DEFAULT NULL COMMENT '指示步长。', + `required` int(2) DEFAULT NULL COMMENT '指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。(字典值link_product_isRequired:0非必填 1必填)\r\n', + `step` int(9) DEFAULT NULL COMMENT '指示步长。', `unit` varchar(255) DEFAULT NULL COMMENT '指示单位。支持长度不超过50。\r\n取值根据参数确定,如:\r\n•温度单位:“C”或“K”\r\n•百分比单位:“%”\r\n•压强单位:“Pa”或“kPa”\r\n', `create_by` varchar(64) DEFAULT 'ununited' COMMENT '创建者', `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `update_by` varchar(64) DEFAULT '' COMMENT '更新者', `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`) USING BTREE, - KEY `service_id` (`service_id`) USING BTREE COMMENT '服务ID' + KEY `service_id` (`service_id`) USING BTREE COMMENT '服务ID' ) ENGINE = InnoDB AUTO_INCREMENT = 142 DEFAULT CHARSET = utf8 COMMENT ='产品模型服务属性表'; @@ -1747,7 +1848,7 @@ COMMIT; DROP TABLE IF EXISTS `product_services`; CREATE TABLE `product_services` ( - `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT '服务id', + `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT '服务id', `service_name` varchar(255) NOT NULL COMMENT '服务名称:支持英文大小写、数字、下划线和中划线\r\n', `template_identification` varchar(100) DEFAULT NULL COMMENT '产品模版标识', `product_identification` varchar(100) DEFAULT NULL COMMENT '产品标识', @@ -1774,7 +1875,7 @@ COMMIT; DROP TABLE IF EXISTS `product_template`; CREATE TABLE `product_template` ( - `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', + `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', `app_id` varchar(64) NOT NULL COMMENT '应用ID', `template_identification` varchar(100) NOT NULL COMMENT '产品模版标识', `template_name` varchar(255) NOT NULL COMMENT '产品模板名称:自定义,支持中文、英文大小写、数字、下划线和中划线', @@ -1801,7 +1902,7 @@ COMMIT; DROP TABLE IF EXISTS `protocol`; CREATE TABLE `protocol` ( - `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', + `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', `app_id` varchar(64) NOT NULL COMMENT '应用ID', `product_identification` varchar(100) NOT NULL COMMENT '产品标识', `protocol_name` varchar(255) DEFAULT NULL COMMENT '协议名称', @@ -1830,7 +1931,8 @@ BEGIN; INSERT INTO `protocol` (`id`, `app_id`, `product_identification`, `protocol_name`, `protocol_identification`, `protocol_version`, `protocol_type`, `protocol_voice`, `class_name`, `file_path`, `content`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1, 'thinglinks', '82325a1de5e84ea88f332f3dbc10f6d5', '温湿度产品协议转换', '22', '22', 'MQTT', 'java', '222', '222', +VALUES (1, 'thinglinks', '82325a1de5e84ea88f332f3dbc10f6d5', '温湿度产品协议转换', '22', '22', 'MQTT', 'java', '222', + '222', 'import com.alibaba.fastjson.JSONArray;\nimport com.alibaba.fastjson.JSONObject;\n\nimport javax.xml.bind.annotation.adapters.HexBinaryAdapter;\nimport java.math.BigInteger;\nimport java.util.Date;\n\npublic class newtest {\n public static void main(String[] args) throws Exception {\n String injson = \"\";\n\n if (args != null && args.length != 0) {\n injson = args[0];\n }\n JSONObject parsejson = JSONObject.parseObject(injson);\n System.out.println(Convert2SystemJSON(parsejson));\n }\n public static String Convert2SystemJSON(JSONObject injsonobj) throws Exception {\n String hexdata = injsonobj.get(\"data\").toString();\n byte[] bt = java.util.Base64.getDecoder().decode(hexdata);\n JSONObject data = hex2wsdjsonobj(bt);\n\n JSONArray services = new JSONArray();\n JSONObject server = new JSONObject();\n server.put(\"serviceId\", \"serdsd123\");\n server.put(\"data\", data);\n server.put(\"eventTime\", new Date());\n services.add(server);\n\n JSONObject dev = new JSONObject();\n dev.put(\"deviceId\", injsonobj.get(\"devEui\"));\n dev.put(\"services\", services);\n JSONArray devices = new JSONArray();\n devices.add(dev);\n\n JSONObject root = new JSONObject();\n root.put(\"devices\", devices);\n return root.toJSONString();\n }\n\n /**\n * 十六进制转换成10进制 负数也能转换\n */\n public static int hex16convert2(String hex) throws Exception {\n if (hex.length() != 4) {\n throw new Exception(\"必须是4个长度\");\n }\n int bit1 = Integer.parseInt(hex.substring(0, 1), 16);\n if (bit1 < 8)\n {\n return Integer.parseInt(hex, 16);\n } else {\n return new BigInteger(\"FFFF\" + hex, 16).intValue();\n }\n }\n\n /**\n * 温湿度解码\n */\n private static JSONObject hex2wsdjsonobj(byte[] bt) throws Exception {\n javax.xml.bind.annotation.adapters.HexBinaryAdapter hexBinaryAdapter = new HexBinaryAdapter();\n JSONObject data = new JSONObject();\n String temp = hexBinaryAdapter.marshal(new byte[]{bt[2]});\n String temp2 = hexBinaryAdapter.marshal(new byte[]{bt[3]});\n String changtemp = change(temp, temp2);\n data.put(\"temperature\", hex16convert2(changtemp) * 0.01);\n temp = hexBinaryAdapter.marshal(new byte[]{bt[4]});\n temp2 = hexBinaryAdapter.marshal(new byte[]{bt[5]});\n changtemp = change(temp, temp2);\n data.put(\"humidity\", hex16convert2(changtemp) * 0.01);\n temp = hexBinaryAdapter.marshal(new byte[]{bt[8]});\n temp2 = hexBinaryAdapter.marshal(new byte[]{bt[9]});\n changtemp = change(temp, temp2);\n data.put(\"battery\", hex16convert2(changtemp));\n return data;\n }\n\n public static String change(String first, String end) {\n return end + first;\n }\n}\n', '0', 'admin', '2022-07-11 15:55:22', 'admin', '2022-08-17 17:29:02', '温湿度产品协议转换样例'); INSERT INTO `protocol` (`id`, `app_id`, `product_identification`, `protocol_name`, `protocol_identification`, @@ -1847,13 +1949,13 @@ COMMIT; DROP TABLE IF EXISTS `rule`; CREATE TABLE `rule` ( - `id` bigint(1) NOT NULL AUTO_INCREMENT COMMENT '主键', + `id` bigint(1) NOT NULL AUTO_INCREMENT COMMENT '主键', `app_id` varchar(64) NOT NULL COMMENT '应用ID', `rule_identification` varchar(100) NOT NULL COMMENT '规则标识', `rule_name` varchar(255) NOT NULL COMMENT '规则名称', - `job_identification` varchar(255) NOT NULL COMMENT '任务标识', + `job_identification` varchar(255) NOT NULL COMMENT '任务标识', `status` varchar(10) NOT NULL DEFAULT '0' COMMENT '状态(字典值:0启用 1停用)', - `triggering` smallint(20) DEFAULT NULL COMMENT '触发机制(0:全部,1:任意一个)', + `triggering` smallint(20) DEFAULT NULL COMMENT '触发机制(0:全部,1:任意一个)', `remark` varchar(255) DEFAULT NULL COMMENT '规则描述,可以为空', `create_by` varchar(64) DEFAULT NULL COMMENT '创建人', `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', @@ -1881,16 +1983,16 @@ DROP TABLE IF EXISTS `rule_alarm`; CREATE TABLE `rule_alarm` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '规则告警ID', - `rule_id` bigint(20) DEFAULT NULL COMMENT '规则ID', - `rule_alarm_name` varchar(255) DEFAULT NULL COMMENT '告警规则名称', - `rule_alarm_status` int(10) DEFAULT NULL COMMENT '告警状态0 未启动 1运行中', - `rule_alarm_remark` varchar(255) DEFAULT NULL COMMENT '告警规则描述', - `rule_level` int(10) DEFAULT NULL COMMENT '告警级别', - `notice_type` int(10) DEFAULT NULL COMMENT '通知方式', - `create_by` varchar(64) DEFAULT NULL COMMENT '创建人', - `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `update_by` varchar(64) DEFAULT NULL COMMENT '更新人', - `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `rule_id` bigint(20) DEFAULT NULL COMMENT '规则ID', + `rule_alarm_name` varchar(255) DEFAULT NULL COMMENT '告警规则名称', + `rule_alarm_status` int(10) DEFAULT NULL COMMENT '告警状态0 未启动 1运行中', + `rule_alarm_remark` varchar(255) DEFAULT NULL COMMENT '告警规则描述', + `rule_level` int(10) DEFAULT NULL COMMENT '告警级别', + `notice_type` int(10) DEFAULT NULL COMMENT '通知方式', + `create_by` varchar(64) DEFAULT NULL COMMENT '创建人', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_by` varchar(64) DEFAULT NULL COMMENT '更新人', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8 COMMENT ='规则告警表'; @@ -1910,9 +2012,9 @@ CREATE TABLE `rule_alarm_list` `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', `alarm_time` datetime DEFAULT NULL COMMENT '告警时间', `alarm_name` varchar(255) DEFAULT NULL COMMENT '告警名称', - `alarm_level` int(10) DEFAULT NULL COMMENT '告警级别', + `alarm_level` int(10) DEFAULT NULL COMMENT '告警级别', `alarm_describe` varchar(255) DEFAULT NULL COMMENT '告警描述', - `processing_result` int(10) DEFAULT NULL COMMENT '处理结果 0 未处理 1已处理', + `processing_result` int(10) DEFAULT NULL COMMENT '处理结果 0 未处理 1已处理', `processing_opinions` varchar(255) DEFAULT NULL COMMENT '处理意见', `alarm_content` varchar(500) DEFAULT NULL COMMENT '告警内容', `processing_people` varchar(64) DEFAULT NULL COMMENT '处理人', @@ -1933,19 +2035,19 @@ COMMIT; DROP TABLE IF EXISTS `rule_conditions`; CREATE TABLE `rule_conditions` ( - `id` bigint(20) NOT NULL COMMENT '主键', - `rule_id` bigint(20) NOT NULL COMMENT '规则ID', + `id` bigint(20) NOT NULL COMMENT '主键', + `rule_id` bigint(20) NOT NULL COMMENT '规则ID', `condition_type` smallint(20) NOT NULL COMMENT '条件类型(0:匹配设备触发、1:指定设备触发、2:按策略定时触发)', - `device_identification` varchar(2000) DEFAULT NULL COMMENT '设备标识(匹配设备设备类型存储一个产品下所有的设备标识逗号分隔,指定设备触发存储指定的设备标识)', - `product_identification` varchar(100) DEFAULT NULL COMMENT '产品标识', - `service_id` bigint(20) DEFAULT NULL COMMENT '服务ID', - `properties_id` bigint(20) DEFAULT NULL COMMENT '属性ID', - `comparison_mode` varchar(255) DEFAULT NULL COMMENT '比较模式\r\n<\r\n<=\r\n>\r\n>=\r\n==\r\n!=\r\nin\r\nbetween', - `comparison_value` varchar(255) DEFAULT NULL COMMENT '比较值\r\n\r\nbetween类型传值例子 [10,15] 必须是两位,且数字不能重复\r\n判断数据是否处于一个离散的取值范围内,例如输入[1,2,3,4],取值范围是1、2、3、4四个值,如果比较值类型为float(double),两个float(double)型数值相差在0.000001范围内即为相等', - `create_by` varchar(64) DEFAULT NULL COMMENT '创建人', - `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `update_by` varchar(64) DEFAULT NULL COMMENT '更新人', - `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `device_identification` varchar(2000) DEFAULT NULL COMMENT '设备标识(匹配设备设备类型存储一个产品下所有的设备标识逗号分隔,指定设备触发存储指定的设备标识)', + `product_identification` varchar(100) DEFAULT NULL COMMENT '产品标识', + `service_id` bigint(20) DEFAULT NULL COMMENT '服务ID', + `properties_id` bigint(20) DEFAULT NULL COMMENT '属性ID', + `comparison_mode` varchar(255) DEFAULT NULL COMMENT '比较模式\r\n<\r\n<=\r\n>\r\n>=\r\n==\r\n!=\r\nin\r\nbetween', + `comparison_value` varchar(255) DEFAULT NULL COMMENT '比较值\r\n\r\nbetween类型传值例子 [10,15] 必须是两位,且数字不能重复\r\n判断数据是否处于一个离散的取值范围内,例如输入[1,2,3,4],取值范围是1、2、3、4四个值,如果比较值类型为float(double),两个float(double)型数值相差在0.000001范围内即为相等', + `create_by` varchar(64) DEFAULT NULL COMMENT '创建人', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_by` varchar(64) DEFAULT NULL COMMENT '更新人', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB DEFAULT CHARSET = utf8 COMMENT ='规则条件表'; @@ -1989,7 +2091,8 @@ CREATE TABLE `sys_config` BEGIN; INSERT INTO `sys_config` (`config_id`, `config_name`, `config_key`, `config_value`, `config_type`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1, '主框架页-默认皮肤样式名称', 'sys.index.skinName', 'skin-green', 'Y', 'admin', '2021-09-17 18:40:14', 'admin', +VALUES (1, '主框架页-默认皮肤样式名称', 'sys.index.skinName', 'skin-green', 'Y', 'admin', '2021-09-17 18:40:14', + 'admin', '2022-10-14 17:53:03', '蓝色 skin-blue、绿色 skin-green、紫色 skin-purple、红色 skin-red、黄色 skin-yellow'); INSERT INTO `sys_config` (`config_id`, `config_name`, `config_key`, `config_value`, `config_type`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) @@ -2001,7 +2104,8 @@ VALUES (3, '主框架页-侧边栏主题', 'sys.index.sideTheme', 'theme-dark', '2022-11-18 13:51:15', '深色主题theme-dark,浅色主题theme-light'); INSERT INTO `sys_config` (`config_id`, `config_name`, `config_key`, `config_value`, `config_type`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (4, '账号自助-是否开启用户注册功能', 'sys.account.registerUser', 'false', 'Y', 'admin', '2021-09-17 18:40:14', '', +VALUES (4, '账号自助-是否开启用户注册功能', 'sys.account.registerUser', 'false', 'Y', 'admin', '2021-09-17 18:40:14', + '', '2022-11-18 13:51:20', '是否开启注册用户功能(true开启,false关闭)'); COMMIT; @@ -2012,19 +2116,19 @@ DROP TABLE IF EXISTS `sys_dept`; CREATE TABLE `sys_dept` ( `dept_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '部门id', - `parent_id` bigint(20) DEFAULT '0' COMMENT '父部门id', - `ancestors` varchar(50) DEFAULT '' COMMENT '祖级列表', - `dept_name` varchar(30) DEFAULT '' COMMENT '部门名称', - `order_num` int(4) DEFAULT '0' COMMENT '显示顺序', - `leader` varchar(20) DEFAULT NULL COMMENT '负责人', - `phone` varchar(11) DEFAULT NULL COMMENT '联系电话', - `email` varchar(50) DEFAULT NULL COMMENT '邮箱', - `status` char(1) DEFAULT '0' COMMENT '部门状态(0正常 1停用)', - `del_flag` char(1) DEFAULT '0' COMMENT '删除标志(0代表存在 2代表删除)', - `create_by` varchar(64) DEFAULT '' COMMENT '创建者', - `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `update_by` varchar(64) DEFAULT '' COMMENT '更新者', - `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `parent_id` bigint(20) DEFAULT '0' COMMENT '父部门id', + `ancestors` varchar(50) DEFAULT '' COMMENT '祖级列表', + `dept_name` varchar(30) DEFAULT '' COMMENT '部门名称', + `order_num` int(4) DEFAULT '0' COMMENT '显示顺序', + `leader` varchar(20) DEFAULT NULL COMMENT '负责人', + `phone` varchar(11) DEFAULT NULL COMMENT '联系电话', + `email` varchar(50) DEFAULT NULL COMMENT '邮箱', + `status` char(1) DEFAULT '0' COMMENT '部门状态(0正常 1停用)', + `del_flag` char(1) DEFAULT '0' COMMENT '删除标志(0代表存在 2代表删除)', + `create_by` varchar(64) DEFAULT '' COMMENT '创建者', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_by` varchar(64) DEFAULT '' COMMENT '更新者', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`dept_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 110 @@ -2041,39 +2145,48 @@ VALUES (100, 0, '0', 'mqttsnet', 0, 'thinglinks', '15888888888', 'mqttsnet@163.c '2021-09-17 18:39:56', 'thinglinks', '2022-01-03 11:45:55'); INSERT INTO `sys_dept` (`dept_id`, `parent_id`, `ancestors`, `dept_name`, `order_num`, `leader`, `phone`, `email`, `status`, `del_flag`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (101, 100, '0,100', '深圳总公司', 1, 'mqtts', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2021-09-17 18:39:56', +VALUES (101, 100, '0,100', '深圳总公司', 1, 'mqtts', '15888888888', 'ry@qq.com', '0', '0', 'admin', + '2021-09-17 18:39:56', '', '2022-01-03 11:45:55'); INSERT INTO `sys_dept` (`dept_id`, `parent_id`, `ancestors`, `dept_name`, `order_num`, `leader`, `phone`, `email`, `status`, `del_flag`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (102, 100, '0,100', '长沙分公司', 2, 'mqtts', '15888888888', 'ry@qq.com', '0', '2', 'admin', '2021-09-17 18:39:56', +VALUES (102, 100, '0,100', '长沙分公司', 2, 'mqtts', '15888888888', 'ry@qq.com', '0', '2', 'admin', + '2021-09-17 18:39:56', '', '2022-01-03 11:45:55'); INSERT INTO `sys_dept` (`dept_id`, `parent_id`, `ancestors`, `dept_name`, `order_num`, `leader`, `phone`, `email`, `status`, `del_flag`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (103, 101, '0,100,101', '研发部门', 1, 'mqtts', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2021-09-17 18:39:56', +VALUES (103, 101, '0,100,101', '研发部门', 1, 'mqtts', '15888888888', 'ry@qq.com', '0', '0', 'admin', + '2021-09-17 18:39:56', '', '2022-01-03 11:45:55'); INSERT INTO `sys_dept` (`dept_id`, `parent_id`, `ancestors`, `dept_name`, `order_num`, `leader`, `phone`, `email`, `status`, `del_flag`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (104, 101, '0,100,101', '市场部门', 2, 'mqtts', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2021-09-17 18:39:57', +VALUES (104, 101, '0,100,101', '市场部门', 2, 'mqtts', '15888888888', 'ry@qq.com', '0', '0', 'admin', + '2021-09-17 18:39:57', '', '2022-01-03 11:45:55'); INSERT INTO `sys_dept` (`dept_id`, `parent_id`, `ancestors`, `dept_name`, `order_num`, `leader`, `phone`, `email`, `status`, `del_flag`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (105, 101, '0,100,101', '测试部门', 3, 'mqtts', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2021-09-17 18:39:57', +VALUES (105, 101, '0,100,101', '测试部门', 3, 'mqtts', '15888888888', 'ry@qq.com', '0', '0', 'admin', + '2021-09-17 18:39:57', '', '2022-01-03 11:45:55'); INSERT INTO `sys_dept` (`dept_id`, `parent_id`, `ancestors`, `dept_name`, `order_num`, `leader`, `phone`, `email`, `status`, `del_flag`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (106, 101, '0,100,101', '财务部门', 4, 'mqtts', '15888888888', 'ry@qq.com', '0', '2', 'admin', '2021-09-17 18:39:57', +VALUES (106, 101, '0,100,101', '财务部门', 4, 'mqtts', '15888888888', 'ry@qq.com', '0', '2', 'admin', + '2021-09-17 18:39:57', '', '2022-01-03 11:45:55'); INSERT INTO `sys_dept` (`dept_id`, `parent_id`, `ancestors`, `dept_name`, `order_num`, `leader`, `phone`, `email`, `status`, `del_flag`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (107, 101, '0,100,101', '运维部门', 5, 'mqtts', '15888888888', 'ry@qq.com', '0', '2', 'admin', '2021-09-17 18:39:57', +VALUES (107, 101, '0,100,101', '运维部门', 5, 'mqtts', '15888888888', 'ry@qq.com', '0', '2', 'admin', + '2021-09-17 18:39:57', '', '2022-01-03 11:45:55'); INSERT INTO `sys_dept` (`dept_id`, `parent_id`, `ancestors`, `dept_name`, `order_num`, `leader`, `phone`, `email`, `status`, `del_flag`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (108, 102, '0,100,102', '市场部门', 1, 'mqtts', '15888888888', 'ry@qq.com', '0', '2', 'admin', '2021-09-17 18:39:57', +VALUES (108, 102, '0,100,102', '市场部门', 1, 'mqtts', '15888888888', 'ry@qq.com', '0', '2', 'admin', + '2021-09-17 18:39:57', '', '2022-01-03 11:45:55'); INSERT INTO `sys_dept` (`dept_id`, `parent_id`, `ancestors`, `dept_name`, `order_num`, `leader`, `phone`, `email`, `status`, `del_flag`, `create_by`, `create_time`, `update_by`, `update_time`) -VALUES (109, 102, '0,100,102', '财务部门', 2, 'mqtts', '15888888888', 'ry@qq.com', '0', '2', 'admin', '2021-09-17 18:39:57', +VALUES (109, 102, '0,100,102', '财务部门', 2, 'mqtts', '15888888888', 'ry@qq.com', '0', '2', 'admin', + '2021-09-17 18:39:57', '', '2022-01-03 11:45:55'); COMMIT; @@ -2084,19 +2197,19 @@ DROP TABLE IF EXISTS `sys_dict_data`; CREATE TABLE `sys_dict_data` ( `dict_code` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '字典编码', - `dict_sort` int(4) DEFAULT '0' COMMENT '字典排序', - `dict_label` varchar(100) DEFAULT '' COMMENT '字典标签', - `dict_value` varchar(100) DEFAULT '' COMMENT '字典键值', - `dict_type` varchar(100) DEFAULT '' COMMENT '字典类型', - `css_class` varchar(100) DEFAULT NULL COMMENT '样式属性(其他样式扩展)', - `list_class` varchar(100) DEFAULT NULL COMMENT '表格回显样式', - `is_default` char(1) DEFAULT 'N' COMMENT '是否默认(Y是 N否)', - `status` char(1) DEFAULT '0' COMMENT '状态(0正常 1停用)', - `create_by` varchar(64) DEFAULT '' COMMENT '创建者', - `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `update_by` varchar(64) DEFAULT '' COMMENT '更新者', - `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - `remark` varchar(500) DEFAULT NULL COMMENT '备注', + `dict_sort` int(4) DEFAULT '0' COMMENT '字典排序', + `dict_label` varchar(100) DEFAULT '' COMMENT '字典标签', + `dict_value` varchar(100) DEFAULT '' COMMENT '字典键值', + `dict_type` varchar(100) DEFAULT '' COMMENT '字典类型', + `css_class` varchar(100) DEFAULT NULL COMMENT '样式属性(其他样式扩展)', + `list_class` varchar(100) DEFAULT NULL COMMENT '表格回显样式', + `is_default` char(1) DEFAULT 'N' COMMENT '是否默认(Y是 N否)', + `status` char(1) DEFAULT '0' COMMENT '状态(0正常 1停用)', + `create_by` varchar(64) DEFAULT '' COMMENT '创建者', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_by` varchar(64) DEFAULT '' COMMENT '更新者', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `remark` varchar(500) DEFAULT NULL COMMENT '备注', PRIMARY KEY (`dict_code`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 76 @@ -2250,7 +2363,8 @@ VALUES (28, 2, '失败', '1', 'sys_common_status', '', 'danger', 'N', '0', 'admi INSERT INTO `sys_dict_data` (`dict_code`, `dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (29, 0, '默认', 'default', 'link_device_auth_mode', NULL, 'default', 'N', '0', 'admin', '2021-10-21 17:56:52', '', +VALUES (29, 0, '默认', 'default', 'link_device_auth_mode', NULL, 'default', 'N', '0', 'admin', '2021-10-21 17:56:52', + '', '2021-09-17 18:40:13', '设备用户名+设备密码'); INSERT INTO `sys_dict_data` (`dict_code`, `dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `update_by`, @@ -2265,12 +2379,14 @@ VALUES (31, 0, '127.0.0.1:11883', '127.0.0.1:11883', 'link_device_connector', NU INSERT INTO `sys_dict_data` (`dict_code`, `dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (32, 0, '启用', 'ENABLE', 'link_device_status', NULL, 'success', 'N', '0', 'admin', '2021-10-22 16:28:13', 'admin', +VALUES (32, 0, '启用', 'ENABLE', 'link_device_status', NULL, 'success', 'N', '0', 'admin', '2021-10-22 16:28:13', + 'admin', '2021-09-17 18:40:13', '设备启用'); INSERT INTO `sys_dict_data` (`dict_code`, `dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (33, 1, '禁用', 'DISABLE', 'link_device_status', NULL, 'danger', 'N', '0', 'admin', '2021-10-22 16:28:31', 'admin', +VALUES (33, 1, '禁用', 'DISABLE', 'link_device_status', NULL, 'danger', 'N', '0', 'admin', '2021-10-22 16:28:31', + 'admin', '2021-09-17 18:40:13', '设备禁用'); INSERT INTO `sys_dict_data` (`dict_code`, `dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `update_by`, @@ -2320,12 +2436,14 @@ VALUES (42, 3, 'http', 'HTTP', 'link_device_protocol_type', NULL, 'default', 'N' INSERT INTO `sys_dict_data` (`dict_code`, `dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (43, 0, '普通设备', 'COMMON', 'link_device_device_type', NULL, 'default', 'N', '0', 'admin', '2021-10-22 16:57:26', +VALUES (43, 0, '普通设备', 'COMMON', 'link_device_device_type', NULL, 'default', 'N', '0', 'admin', + '2021-10-22 16:57:26', 'mqtts', '2021-09-17 18:40:13', '普通设备(无子设备也无父设备)'); INSERT INTO `sys_dict_data` (`dict_code`, `dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (44, 1, '网关设备', 'GATEWAY', 'link_device_device_type', NULL, 'default', 'N', '0', 'admin', '2021-10-22 16:57:44', +VALUES (44, 1, '网关设备', 'GATEWAY', 'link_device_device_type', NULL, 'default', 'N', '0', 'admin', + '2021-10-22 16:57:44', 'mqtts', '2021-09-17 18:40:13', '网关设备(可挂载子设备)'); INSERT INTO `sys_dict_data` (`dict_code`, `dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `update_by`, @@ -2365,7 +2483,8 @@ VALUES (52, 0, '必填', '1', 'link_product_isRequired', NULL, 'default', 'N', ' INSERT INTO `sys_dict_data` (`dict_code`, `dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (53, 0, '允许', 'allow', 'link_casbinRule_v3', NULL, 'success', 'N', '0', 'admin', '2022-06-16 18:03:46', 'admin', +VALUES (53, 0, '允许', 'allow', 'link_casbinRule_v3', NULL, 'success', 'N', '0', 'admin', '2022-06-16 18:03:46', + 'admin', '2021-09-17 18:40:13', NULL); INSERT INTO `sys_dict_data` (`dict_code`, `dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `update_by`, @@ -2380,12 +2499,14 @@ VALUES (57, 0, '发布', 'PUBLISH', 'link_casbinRule_v2', NULL, 'primary', 'N', INSERT INTO `sys_dict_data` (`dict_code`, `dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (58, 0, '订阅', 'SUBSCRIBE', 'link_casbinRule_v2', NULL, 'info', 'N', '0', 'admin', '2022-06-16 18:21:09', 'admin', +VALUES (58, 0, '订阅', 'SUBSCRIBE', 'link_casbinRule_v2', NULL, 'info', 'N', '0', 'admin', '2022-06-16 18:21:09', + 'admin', '2021-09-17 18:40:13', '订阅动作'); INSERT INTO `sys_dict_data` (`dict_code`, `dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (59, 0, '上线', 'ONLINE', 'link_device_action_type', NULL, 'success', 'N', '0', 'admin', '2022-06-17 17:45:24', '', +VALUES (59, 0, '上线', 'ONLINE', 'link_device_action_type', NULL, 'success', 'N', '0', 'admin', '2022-06-17 17:45:24', + '', '2021-09-17 18:40:13', NULL); INSERT INTO `sys_dict_data` (`dict_code`, `dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `update_by`, @@ -2455,7 +2576,8 @@ VALUES (72, 0, 'java', 'java', 'link_protocol_voice', NULL, 'default', 'N', '0', INSERT INTO `sys_dict_data` (`dict_code`, `dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (73, 3, '协议管理', 'PROTOCOL', 'sys_job_group', NULL, 'default', 'N', '0', 'admin', '2022-07-11 15:48:55', 'admin', +VALUES (73, 3, '协议管理', 'PROTOCOL', 'sys_job_group', NULL, 'default', 'N', '0', 'admin', '2022-07-11 15:48:55', + 'admin', '2021-09-17 18:40:13', '协议管理'); INSERT INTO `sys_dict_data` (`dict_code`, `dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `update_by`, @@ -2533,7 +2655,8 @@ INSERT INTO `sys_dict_type` (`dict_id`, `dict_name`, `dict_type`, `status`, `cre VALUES (12, '设备连接实例', 'link_device_connector', '0', 'admin', '2021-10-21 18:10:18', '', NULL, '设备连接实例'); INSERT INTO `sys_dict_type` (`dict_id`, `dict_name`, `dict_type`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (13, '设备状态', 'link_device_status', '0', 'admin', '2021-10-22 16:27:28', 'mqtts', '2021-10-25 15:48:58', '设备状态'); +VALUES (13, '设备状态', 'link_device_status', '0', 'admin', '2021-10-22 16:27:28', 'mqtts', '2021-10-25 15:48:58', + '设备状态'); INSERT INTO `sys_dict_type` (`dict_id`, `dict_name`, `dict_type`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) VALUES (14, '连接状态', 'link_device_connect_status', '0', 'admin', '2021-10-22 16:35:11', '', NULL, '设备连接状态\n'); @@ -2554,7 +2677,8 @@ VALUES (18, '集成应用类型', 'link_application_type', '0', 'thinglinks', '2 '2021-12-28 13:42:28', '集成应用'); INSERT INTO `sys_dict_type` (`dict_id`, `dict_name`, `dict_type`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (19, '产品设备类型', 'link_product_device_type', '0', 'admin', '2022-02-09 16:50:14', 'admin', '2022-02-09 17:53:25', +VALUES (19, '产品设备类型', 'link_product_device_type', '0', 'admin', '2022-02-09 16:50:14', 'admin', + '2022-02-09 17:53:25', '产品设备类型,支持英文大小写、数字、下划线和中划线'); INSERT INTO `sys_dict_type` (`dict_id`, `dict_name`, `dict_type`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) @@ -2565,7 +2689,8 @@ INSERT INTO `sys_dict_type` (`dict_id`, `dict_name`, `dict_type`, `status`, `cre VALUES (21, '是否必填', 'link_product_isRequired', '0', 'admin', '2022-03-25 15:39:40', '', NULL, NULL); INSERT INTO `sys_dict_type` (`dict_id`, `dict_name`, `dict_type`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (22, 'CAS策略类型', 'link_casbinRule_v3', '0', 'admin', '2022-06-16 18:02:31', '', NULL, 'CAS策略类型:允许||拒绝'); +VALUES (22, 'CAS策略类型', 'link_casbinRule_v3', '0', 'admin', '2022-06-16 18:02:31', '', NULL, + 'CAS策略类型:允许||拒绝'); INSERT INTO `sys_dict_type` (`dict_id`, `dict_name`, `dict_type`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) VALUES (23, 'CAS策略动作', 'link_casbinRule_v2', '0', 'admin', '2022-06-16 18:11:05', '', NULL, '认证动作'); @@ -2574,13 +2699,16 @@ INSERT INTO `sys_dict_type` (`dict_id`, `dict_name`, `dict_type`, `status`, `cre VALUES (24, '设备动作类型', 'link_device_action_type', '0', 'admin', '2022-06-17 17:43:34', '', NULL, NULL); INSERT INTO `sys_dict_type` (`dict_id`, `dict_name`, `dict_type`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (25, '设备影子状态', 'link_deviceInfo_shadow_enable', '0', 'admin', '2022-06-21 11:27:39', '', NULL, '是否支设备影子'); +VALUES (25, '设备影子状态', 'link_deviceInfo_shadow_enable', '0', 'admin', '2022-06-21 11:27:39', '', NULL, + '是否支设备影子'); INSERT INTO `sys_dict_type` (`dict_id`, `dict_name`, `dict_type`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (26, '业务数据状态', 'business_data_status', '0', 'admin', '2022-06-21 14:25:45', '', NULL, '业务数据状态标识(0启用 1停用)'); +VALUES (26, '业务数据状态', 'business_data_status', '0', 'admin', '2022-06-21 14:25:45', '', NULL, + '业务数据状态标识(0启用 1停用)'); INSERT INTO `sys_dict_type` (`dict_id`, `dict_name`, `dict_type`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (27, '指示数据类型', 'link_product_datatype', '0', 'admin', '2022-06-24 18:41:39', '', NULL, '产品模型指示数据类型'); +VALUES (27, '指示数据类型', 'link_product_datatype', '0', 'admin', '2022-06-24 18:41:39', '', NULL, + '产品模型指示数据类型'); INSERT INTO `sys_dict_type` (`dict_id`, `dict_name`, `dict_type`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) VALUES (28, '协议语言', 'link_protocol_voice', '0', 'admin', '2022-07-04 11:16:20', 'admin', '2022-07-04 17:09:29', @@ -2593,7 +2721,7 @@ COMMIT; DROP TABLE IF EXISTS `sys_job`; CREATE TABLE `sys_job` ( - `job_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '任务ID', + `job_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '任务ID', `job_name` varchar(64) NOT NULL DEFAULT '' COMMENT '任务名称', `job_group` varchar(64) NOT NULL DEFAULT 'DEFAULT' COMMENT '任务组名', `invoke_target` varchar(500) NOT NULL COMMENT '调用目标字符串', @@ -2618,7 +2746,8 @@ CREATE TABLE `sys_job` BEGIN; INSERT INTO `sys_job` (`job_id`, `job_name`, `job_group`, `invoke_target`, `cron_expression`, `misfire_policy`, `concurrent`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1, '系统默认(无参)', 'DEFAULT', 'ryTask.ryNoParams', '0/10 * * * * ?', '3', '1', '1', 'admin', '2021-09-17 18:40:15', +VALUES (1, '系统默认(无参)', 'DEFAULT', 'ryTask.ryNoParams', '0/10 * * * * ?', '3', '1', '1', 'admin', + '2021-09-17 18:40:15', 'mqtts', '2021-10-25 03:09:23', ''); INSERT INTO `sys_job` (`job_id`, `job_name`, `job_group`, `invoke_target`, `cron_expression`, `misfire_policy`, `concurrent`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) @@ -2626,11 +2755,13 @@ VALUES (2, '系统默认(有参)', 'DEFAULT', 'ryTask.ryParams(\'ry\')', '0/ '2021-09-17 18:40:15', '', '2022-11-23 13:54:34', ''); INSERT INTO `sys_job` (`job_id`, `job_name`, `job_group`, `invoke_target`, `cron_expression`, `misfire_policy`, `concurrent`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (3, '系统默认(多参)', 'DEFAULT', 'ryTask.ryMultipleParams(\'ry\', true, 2000L, 316.50D, 100)', '0/20 * * * * ?', '3', +VALUES (3, '系统默认(多参)', 'DEFAULT', 'ryTask.ryMultipleParams(\'ry\', true, 2000L, 316.50D, 100)', '0/20 * * * * ?', + '3', '1', '1', 'admin', '2021-09-17 18:40:15', '', '2022-11-18 13:54:40', ''); INSERT INTO `sys_job` (`job_id`, `job_name`, `job_group`, `invoke_target`, `cron_expression`, `misfire_policy`, `concurrent`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (4, '协议脚本缓存刷新定时任务', 'PROTOCOL', 'linkProtocolTask.protocolScriptCacheRefreshTask', '0/5 0 0/23 * * ?', '2', '1', +VALUES (4, '协议脚本缓存刷新定时任务', 'PROTOCOL', 'linkProtocolTask.protocolScriptCacheRefreshTask', + '0/5 0 0/23 * * ?', '2', '1', '1', 'admin', '2022-07-11 15:50:49', 'admin', '2022-07-29 14:35:06', ''); INSERT INTO `sys_job` (`job_id`, `job_name`, `job_group`, `invoke_target`, `cron_expression`, `misfire_policy`, `concurrent`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) @@ -2642,7 +2773,8 @@ VALUES (6, '测试2', 'RULE_TRIGGER', 'ruleConditionsTask.parsingRuleConditions2 'admin', '2022-07-19 15:21:48', 'admin', '2022-08-26 09:38:12', ''); INSERT INTO `sys_job` (`job_id`, `job_name`, `job_group`, `invoke_target`, `cron_expression`, `misfire_policy`, `concurrent`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (7, '刷新子设备数据模型', 'LINK_DEVICE', 'linkDeviceInfoTask.refreshDeviceInfoDataModel(\'\')', '0 0 0/12 * * ?', '1', +VALUES (7, '刷新子设备数据模型', 'LINK_DEVICE', 'linkDeviceInfoTask.refreshDeviceInfoDataModel(\'\')', '0 0 0/12 * * ?', + '1', '1', '1', 'admin', '2022-07-29 14:38:01', 'admin', '2022-07-29 16:09:15', ''); INSERT INTO `sys_job` (`job_id`, `job_name`, `job_group`, `invoke_target`, `cron_expression`, `misfire_policy`, `concurrent`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) @@ -2654,7 +2786,8 @@ VALUES (9, '测试4', 'RULE_TRIGGER', 'ryTask.ryParams(\'4\')', '0/2 * * * * ?', '2022-08-25 14:09:27', 'admin', '2022-08-25 14:15:49', ''); INSERT INTO `sys_job` (`job_id`, `job_name`, `job_group`, `invoke_target`, `cron_expression`, `misfire_policy`, `concurrent`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (10, '哈哈', 'RULE_TRIGGER', 'ruleConditionsTask.parsingRuleConditions(\'rule-001\')', '0/2 0/2 * * * ?', '1', '0', +VALUES (10, '哈哈', 'RULE_TRIGGER', 'ruleConditionsTask.parsingRuleConditions(\'rule-001\')', '0/2 0/2 * * * ?', '1', + '0', '0', 'admin', '2022-10-28 16:46:14', 'admin', '2022-11-04 18:22:57', ''); COMMIT; @@ -2664,7 +2797,7 @@ COMMIT; DROP TABLE IF EXISTS `sys_job_log`; CREATE TABLE `sys_job_log` ( - `job_log_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '任务日志ID', + `job_log_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '任务日志ID', `job_name` varchar(64) NOT NULL COMMENT '任务名称', `job_group` varchar(64) NOT NULL COMMENT '任务组名', `invoke_target` varchar(500) NOT NULL COMMENT '调用目标字符串', @@ -2691,11 +2824,11 @@ DROP TABLE IF EXISTS `sys_logininfor`; CREATE TABLE `sys_logininfor` ( `info_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '访问ID', - `user_name` varchar(50) DEFAULT '' COMMENT '用户账号', - `ipaddr` varchar(128) DEFAULT '' COMMENT '登录IP地址', - `status` char(1) DEFAULT '0' COMMENT '登录状态(0成功 1失败)', - `msg` varchar(255) DEFAULT '' COMMENT '提示信息', - `access_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '访问时间', + `user_name` varchar(50) DEFAULT '' COMMENT '用户账号', + `ipaddr` varchar(128) DEFAULT '' COMMENT '登录IP地址', + `status` char(1) DEFAULT '0' COMMENT '登录状态(0成功 1失败)', + `msg` varchar(255) DEFAULT '' COMMENT '提示信息', + `access_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '访问时间', PRIMARY KEY (`info_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 322 @@ -2714,15 +2847,15 @@ COMMIT; DROP TABLE IF EXISTS `sys_menu`; CREATE TABLE `sys_menu` ( - `menu_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '菜单ID', + `menu_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '菜单ID', `menu_name` varchar(50) NOT NULL COMMENT '菜单名称', - `parent_id` bigint(20) DEFAULT '0' COMMENT '父菜单ID', - `order_num` int(4) DEFAULT '0' COMMENT '显示顺序', + `parent_id` bigint(20) DEFAULT '0' COMMENT '父菜单ID', + `order_num` int(4) DEFAULT '0' COMMENT '显示顺序', `path` varchar(200) DEFAULT '' COMMENT '路由地址', `component` varchar(255) DEFAULT NULL COMMENT '组件路径', `query` varchar(255) DEFAULT NULL COMMENT '路由参数', - `is_frame` int(1) DEFAULT '1' COMMENT '是否为外链(0是 1否)', - `is_cache` int(1) DEFAULT '0' COMMENT '是否缓存(0缓存 1不缓存)', + `is_frame` int(1) DEFAULT '1' COMMENT '是否为外链(0是 1否)', + `is_cache` int(1) DEFAULT '0' COMMENT '是否缓存(0缓存 1不缓存)', `menu_type` char(1) DEFAULT '' COMMENT '菜单类型(M目录 C菜单 F按钮)', `visible` char(1) DEFAULT '0' COMMENT '菜单状态(0显示 1隐藏)', `status` char(1) DEFAULT '0' COMMENT '菜单状态(0正常 1停用)', @@ -2751,7 +2884,8 @@ VALUES (1, '系统管理', 0, 1, 'system', NULL, '', 1, 0, 'M', '0', '0', '', 's INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (2, '系统监控', 0, 2, 'monitor', NULL, '', 1, 0, 'M', '0', '0', '', 'monitor', 'admin', '2021-09-17 18:39:58', '', +VALUES (2, '系统监控', 0, 2, 'monitor', NULL, '', 1, 0, 'M', '0', '0', '', 'monitor', 'admin', '2021-09-17 18:39:58', + '', '2022-10-28 17:46:29', '系统监控目录'); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -2761,17 +2895,20 @@ VALUES (3, '系统工具', 0, 3, 'tool', NULL, '', 1, 0, 'M', '0', '0', '', 'too INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (4, 'ThingLinks官网', 0, 8, 'http://thinglinks.mqttsnet.com', NULL, '', 0, 0, 'M', '0', '1', '', 'guide', 'admin', +VALUES (4, 'ThingLinks官网', 0, 8, 'http://thinglinks.mqttsnet.com', NULL, '', 0, 0, 'M', '0', '1', '', 'guide', + 'admin', '2021-09-17 18:39:59', 'admin', '2022-10-28 17:46:29', 'mqtts官网地址'); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (100, '用户管理', 1, 1, 'user', 'system/user/index', '', 1, 0, 'C', '0', '0', 'system:user:list', 'user', 'admin', +VALUES (100, '用户管理', 1, 1, 'user', 'system/user/index', '', 1, 0, 'C', '0', '0', 'system:user:list', 'user', + 'admin', '2021-09-17 18:39:59', '', '2022-10-28 17:46:29', '用户管理菜单'); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (101, '角色管理', 1, 2, 'role', 'system/role/index', '', 1, 0, 'C', '0', '0', 'system:role:list', 'peoples', 'admin', +VALUES (101, '角色管理', 1, 2, 'role', 'system/role/index', '', 1, 0, 'C', '0', '0', 'system:role:list', 'peoples', + 'admin', '2021-09-17 18:39:59', '', '2022-10-28 17:46:29', '角色管理菜单'); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -2781,17 +2918,20 @@ VALUES (102, '菜单管理', 1, 3, 'menu', 'system/menu/index', '', 1, 0, 'C', ' INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (103, '部门管理', 1, 4, 'dept', 'system/dept/index', '', 1, 0, 'C', '0', '0', 'system:dept:list', 'tree', 'admin', +VALUES (103, '部门管理', 1, 4, 'dept', 'system/dept/index', '', 1, 0, 'C', '0', '0', 'system:dept:list', 'tree', + 'admin', '2021-09-17 18:39:59', '', '2022-10-28 17:46:29', '部门管理菜单'); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (104, '岗位管理', 1, 5, 'post', 'system/post/index', '', 1, 0, 'C', '0', '0', 'system:post:list', 'post', 'admin', +VALUES (104, '岗位管理', 1, 5, 'post', 'system/post/index', '', 1, 0, 'C', '0', '0', 'system:post:list', 'post', + 'admin', '2021-09-17 18:39:59', '', '2022-10-28 17:46:29', '岗位管理菜单'); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (105, '字典管理', 1, 6, 'dict', 'system/dict/index', '', 1, 0, 'C', '0', '0', 'system:dict:list', 'dict', 'admin', +VALUES (105, '字典管理', 1, 6, 'dict', 'system/dict/index', '', 1, 0, 'C', '0', '0', 'system:dict:list', 'dict', + 'admin', '2021-09-17 18:39:59', '', '2022-10-28 17:46:29', '字典管理菜单'); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -2801,7 +2941,8 @@ VALUES (106, '参数设置', 1, 7, 'config', 'system/config/index', '', 1, 0, 'C INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (107, '通知公告', 1, 8, 'notice', 'system/notice/index', '', 1, 0, 'C', '0', '0', 'system:notice:list', 'message', +VALUES (107, '通知公告', 1, 8, 'notice', 'system/notice/index', '', 1, 0, 'C', '0', '0', 'system:notice:list', + 'message', 'admin', '2021-09-17 18:39:59', '', '2022-10-28 17:46:29', '通知公告菜单'); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -2811,7 +2952,8 @@ VALUES (108, '日志管理', 1, 9, 'log', '', '', 1, 0, 'M', '0', '0', '', 'log' INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (109, '在线用户', 2, 1, 'online', 'monitor/online/index', '', 1, 0, 'C', '0', '0', 'monitor:online:list', 'online', +VALUES (109, '在线用户', 2, 1, 'online', 'monitor/online/index', '', 1, 0, 'C', '0', '0', 'monitor:online:list', + 'online', 'admin', '2021-09-17 18:39:59', '', '2022-10-28 17:46:29', '在线用户菜单'); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -2836,7 +2978,8 @@ VALUES (113, 'Admin控制台', 2, 5, 'http://localhost:19400/login', '', '', 0, INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (114, '表单构建', 3, 1, 'build', 'tool/build/index', '', 1, 0, 'C', '0', '0', 'tool:build:list', 'build', 'admin', +VALUES (114, '表单构建', 3, 1, 'build', 'tool/build/index', '', 1, 0, 'C', '0', '0', 'tool:build:list', 'build', + 'admin', '2021-09-17 18:39:59', '', '2022-10-28 17:46:29', '表单构建菜单'); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -2851,27 +2994,32 @@ VALUES (116, '系统接口', 3, 3, 'http://localhost:8080/swagger-ui/index.html' INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (500, '操作日志', 108, 1, 'operlog', 'system/operlog/index', '', 1, 0, 'C', '0', '0', 'system:operlog:list', 'form', +VALUES (500, '操作日志', 108, 1, 'operlog', 'system/operlog/index', '', 1, 0, 'C', '0', '0', 'system:operlog:list', + 'form', 'admin', '2021-09-17 18:40:00', '', '2022-10-28 17:46:29', '操作日志菜单'); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (501, '登录日志', 108, 2, 'logininfor', 'system/logininfor/index', '', 1, 0, 'C', '0', '0', 'system:logininfor:list', +VALUES (501, '登录日志', 108, 2, 'logininfor', 'system/logininfor/index', '', 1, 0, 'C', '0', '0', + 'system:logininfor:list', 'logininfor', 'admin', '2021-09-17 18:40:00', '', '2022-10-28 17:46:29', '登录日志菜单'); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1001, '用户查询', 100, 1, '', '', '', 1, 0, 'F', '0', '0', 'system:user:query', '#', 'admin', '2021-09-17 18:40:00', +VALUES (1001, '用户查询', 100, 1, '', '', '', 1, 0, 'F', '0', '0', 'system:user:query', '#', 'admin', + '2021-09-17 18:40:00', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1002, '用户新增', 100, 2, '', '', '', 1, 0, 'F', '0', '0', 'system:user:add', '#', 'admin', '2021-09-17 18:40:00', +VALUES (1002, '用户新增', 100, 2, '', '', '', 1, 0, 'F', '0', '0', 'system:user:add', '#', 'admin', + '2021-09-17 18:40:00', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1003, '用户修改', 100, 3, '', '', '', 1, 0, 'F', '0', '0', 'system:user:edit', '#', 'admin', '2021-09-17 18:40:00', +VALUES (1003, '用户修改', 100, 3, '', '', '', 1, 0, 'F', '0', '0', 'system:user:edit', '#', 'admin', + '2021-09-17 18:40:00', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -2896,17 +3044,20 @@ VALUES (1007, '重置密码', 100, 7, '', '', '', 1, 0, 'F', '0', '0', 'system:u INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1008, '角色查询', 101, 1, '', '', '', 1, 0, 'F', '0', '0', 'system:role:query', '#', 'admin', '2021-09-17 18:40:00', +VALUES (1008, '角色查询', 101, 1, '', '', '', 1, 0, 'F', '0', '0', 'system:role:query', '#', 'admin', + '2021-09-17 18:40:00', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1009, '角色新增', 101, 2, '', '', '', 1, 0, 'F', '0', '0', 'system:role:add', '#', 'admin', '2021-09-17 18:40:00', +VALUES (1009, '角色新增', 101, 2, '', '', '', 1, 0, 'F', '0', '0', 'system:role:add', '#', 'admin', + '2021-09-17 18:40:00', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1010, '角色修改', 101, 3, '', '', '', 1, 0, 'F', '0', '0', 'system:role:edit', '#', 'admin', '2021-09-17 18:40:01', +VALUES (1010, '角色修改', 101, 3, '', '', '', 1, 0, 'F', '0', '0', 'system:role:edit', '#', 'admin', + '2021-09-17 18:40:01', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -2921,17 +3072,20 @@ VALUES (1012, '角色导出', 101, 5, '', '', '', 1, 0, 'F', '0', '0', 'system:r INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1013, '菜单查询', 102, 1, '', '', '', 1, 0, 'F', '0', '0', 'system:menu:query', '#', 'admin', '2021-09-17 18:40:01', +VALUES (1013, '菜单查询', 102, 1, '', '', '', 1, 0, 'F', '0', '0', 'system:menu:query', '#', 'admin', + '2021-09-17 18:40:01', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1014, '菜单新增', 102, 2, '', '', '', 1, 0, 'F', '0', '0', 'system:menu:add', '#', 'admin', '2021-09-17 18:40:01', +VALUES (1014, '菜单新增', 102, 2, '', '', '', 1, 0, 'F', '0', '0', 'system:menu:add', '#', 'admin', + '2021-09-17 18:40:01', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1015, '菜单修改', 102, 3, '', '', '', 1, 0, 'F', '0', '0', 'system:menu:edit', '#', 'admin', '2021-09-17 18:40:01', +VALUES (1015, '菜单修改', 102, 3, '', '', '', 1, 0, 'F', '0', '0', 'system:menu:edit', '#', 'admin', + '2021-09-17 18:40:01', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -2941,17 +3095,20 @@ VALUES (1016, '菜单删除', 102, 4, '', '', '', 1, 0, 'F', '0', '0', 'system:m INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1017, '部门查询', 103, 1, '', '', '', 1, 0, 'F', '0', '0', 'system:dept:query', '#', 'admin', '2021-09-17 18:40:01', +VALUES (1017, '部门查询', 103, 1, '', '', '', 1, 0, 'F', '0', '0', 'system:dept:query', '#', 'admin', + '2021-09-17 18:40:01', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1018, '部门新增', 103, 2, '', '', '', 1, 0, 'F', '0', '0', 'system:dept:add', '#', 'admin', '2021-09-17 18:40:01', +VALUES (1018, '部门新增', 103, 2, '', '', '', 1, 0, 'F', '0', '0', 'system:dept:add', '#', 'admin', + '2021-09-17 18:40:01', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1019, '部门修改', 103, 3, '', '', '', 1, 0, 'F', '0', '0', 'system:dept:edit', '#', 'admin', '2021-09-17 18:40:01', +VALUES (1019, '部门修改', 103, 3, '', '', '', 1, 0, 'F', '0', '0', 'system:dept:edit', '#', 'admin', + '2021-09-17 18:40:01', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -2961,17 +3118,20 @@ VALUES (1020, '部门删除', 103, 4, '', '', '', 1, 0, 'F', '0', '0', 'system:d INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1021, '岗位查询', 104, 1, '', '', '', 1, 0, 'F', '0', '0', 'system:post:query', '#', 'admin', '2021-09-17 18:40:01', +VALUES (1021, '岗位查询', 104, 1, '', '', '', 1, 0, 'F', '0', '0', 'system:post:query', '#', 'admin', + '2021-09-17 18:40:01', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1022, '岗位新增', 104, 2, '', '', '', 1, 0, 'F', '0', '0', 'system:post:add', '#', 'admin', '2021-09-17 18:40:01', +VALUES (1022, '岗位新增', 104, 2, '', '', '', 1, 0, 'F', '0', '0', 'system:post:add', '#', 'admin', + '2021-09-17 18:40:01', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1023, '岗位修改', 104, 3, '', '', '', 1, 0, 'F', '0', '0', 'system:post:edit', '#', 'admin', '2021-09-17 18:40:01', +VALUES (1023, '岗位修改', 104, 3, '', '', '', 1, 0, 'F', '0', '0', 'system:post:edit', '#', 'admin', + '2021-09-17 18:40:01', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -2991,12 +3151,14 @@ VALUES (1026, '字典查询', 105, 1, '#', '', '', 1, 0, 'F', '0', '0', 'system: INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1027, '字典新增', 105, 2, '#', '', '', 1, 0, 'F', '0', '0', 'system:dict:add', '#', 'admin', '2021-09-17 18:40:02', +VALUES (1027, '字典新增', 105, 2, '#', '', '', 1, 0, 'F', '0', '0', 'system:dict:add', '#', 'admin', + '2021-09-17 18:40:02', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1028, '字典修改', 105, 3, '#', '', '', 1, 0, 'F', '0', '0', 'system:dict:edit', '#', 'admin', '2021-09-17 18:40:02', +VALUES (1028, '字典修改', 105, 3, '#', '', '', 1, 0, 'F', '0', '0', 'system:dict:edit', '#', 'admin', + '2021-09-17 18:40:02', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -3106,12 +3268,14 @@ VALUES (1049, '任务查询', 110, 1, '#', '', '', 1, 0, 'F', '0', '0', 'monitor INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1050, '任务新增', 110, 2, '#', '', '', 1, 0, 'F', '0', '0', 'monitor:job:add', '#', 'admin', '2021-09-17 18:40:03', +VALUES (1050, '任务新增', 110, 2, '#', '', '', 1, 0, 'F', '0', '0', 'monitor:job:add', '#', 'admin', + '2021-09-17 18:40:03', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1051, '任务修改', 110, 3, '#', '', '', 1, 0, 'F', '0', '0', 'monitor:job:edit', '#', 'admin', '2021-09-17 18:40:03', +VALUES (1051, '任务修改', 110, 3, '#', '', '', 1, 0, 'F', '0', '0', 'monitor:job:edit', '#', 'admin', + '2021-09-17 18:40:03', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -3131,32 +3295,38 @@ VALUES (1054, '任务导出', 110, 7, '#', '', '', 1, 0, 'F', '0', '0', 'monitor INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1055, '生成查询', 115, 1, '#', '', '', 1, 0, 'F', '0', '0', 'tool:gen:query', '#', 'admin', '2021-09-17 18:40:04', +VALUES (1055, '生成查询', 115, 1, '#', '', '', 1, 0, 'F', '0', '0', 'tool:gen:query', '#', 'admin', + '2021-09-17 18:40:04', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1056, '生成修改', 115, 2, '#', '', '', 1, 0, 'F', '0', '0', 'tool:gen:edit', '#', 'admin', '2021-09-17 18:40:04', +VALUES (1056, '生成修改', 115, 2, '#', '', '', 1, 0, 'F', '0', '0', 'tool:gen:edit', '#', 'admin', + '2021-09-17 18:40:04', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1057, '生成删除', 115, 3, '#', '', '', 1, 0, 'F', '0', '0', 'tool:gen:remove', '#', 'admin', '2021-09-17 18:40:04', +VALUES (1057, '生成删除', 115, 3, '#', '', '', 1, 0, 'F', '0', '0', 'tool:gen:remove', '#', 'admin', + '2021-09-17 18:40:04', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1058, '导入代码', 115, 2, '#', '', '', 1, 0, 'F', '0', '0', 'tool:gen:import', '#', 'admin', '2021-09-17 18:40:04', +VALUES (1058, '导入代码', 115, 2, '#', '', '', 1, 0, 'F', '0', '0', 'tool:gen:import', '#', 'admin', + '2021-09-17 18:40:04', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1059, '预览代码', 115, 4, '#', '', '', 1, 0, 'F', '0', '0', 'tool:gen:preview', '#', 'admin', '2021-09-17 18:40:04', +VALUES (1059, '预览代码', 115, 4, '#', '', '', 1, 0, 'F', '0', '0', 'tool:gen:preview', '#', 'admin', + '2021-09-17 18:40:04', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1060, '生成代码', 115, 5, '#', '', '', 1, 0, 'F', '0', '0', 'tool:gen:code', '#', 'admin', '2021-09-17 18:40:04', +VALUES (1060, '生成代码', 115, 5, '#', '', '', 1, 0, 'F', '0', '0', 'tool:gen:code', '#', 'admin', + '2021-09-17 18:40:04', '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -3166,7 +3336,8 @@ VALUES (1061, '设备集成', 0, 4, 'link', NULL, NULL, 1, 0, 'M', '0', '0', '', INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1062, '设备管理', 1061, 3, 'device', 'link/device/index', NULL, 1, 0, 'C', '0', '0', 'link:device:list', 'slider', +VALUES (1062, '设备管理', 1061, 3, 'device', 'link/device/index', NULL, 1, 0, 'C', '0', '0', 'link:device:list', + 'slider', 'admin', '2021-10-21 17:27:48', 'admin', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -3241,12 +3412,14 @@ VALUES (1076, '设备详情', 1062, 7, '', NULL, NULL, 1, 0, 'F', '0', '0', 'lin INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1077, '设备监控', 0, 6, 'tdengine', NULL, NULL, 1, 0, 'M', '0', '0', '', 'online', 'admin', '2022-05-05 14:06:11', +VALUES (1077, '设备监控', 0, 6, 'tdengine', NULL, NULL, 1, 0, 'M', '0', '0', '', 'online', 'admin', + '2022-05-05 14:06:11', 'admin', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1078, '设备影子', 1077, 1, 'tdengine', 'tdengine/shadow/index', NULL, 1, 0, 'C', '0', '0', 'tdengine:shadow:list', +VALUES (1078, '设备影子', 1077, 1, 'tdengine', 'tdengine/shadow/index', NULL, 1, 0, 'C', '0', '0', + 'tdengine:shadow:list', 'ContentUnion', 'admin', '2022-05-05 14:09:20', 'admin', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -3257,7 +3430,8 @@ INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path` `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) VALUES (1080, 'CAS规则管理', 1061, 6, 'casbinRule', 'link/casbinRule/index', NULL, 1, 0, 'C', '0', '0', - 'link:casbinRule:list', 'lock', 'admin', '2022-06-16 18:29:45', 'admin', '2022-10-28 17:46:29', 'CAS规则管理菜单'); + 'link:casbinRule:list', 'lock', 'admin', '2022-06-16 18:29:45', 'admin', '2022-10-28 17:46:29', + 'CAS规则管理菜单'); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) @@ -3316,7 +3490,8 @@ VALUES (1091, '设备Topic数据导出', 1086, 5, '#', '', NULL, 1, 0, 'F', '0', INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1092, '设备动作数据', 1076, 1, 'action', 'link/action/index', NULL, 1, 0, 'C', '0', '0', 'link:action:list', '#', +VALUES (1092, '设备动作数据', 1076, 1, 'action', 'link/action/index', NULL, 1, 0, 'C', '0', '0', 'link:action:list', + '#', 'admin', '2022-06-17 17:47:32', '', '2022-10-28 17:46:29', '设备动作数据菜单'); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -3347,7 +3522,8 @@ INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path` `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) VALUES (1098, '子设备管理', 1061, 4, 'deviceInfo', 'link/deviceInfo/index', NULL, 1, 0, 'C', '0', '0', - 'link:deviceInfo:list', 'cascader', 'admin', '2022-06-21 10:48:04', 'admin', '2022-10-28 17:46:29', '子设备管理菜单'); + 'link:deviceInfo:list', 'cascader', 'admin', '2022-06-21 10:48:04', 'admin', '2022-10-28 17:46:29', + '子设备管理菜单'); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) @@ -3447,7 +3623,8 @@ VALUES (1120, '产品模板导出', 1115, 5, '#', '', NULL, 1, 0, 'F', '0', '0', INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) -VALUES (1121, '设备调试', 0, 5, 'broker', NULL, NULL, 1, 0, 'M', '0', '0', NULL, 'bug', 'admin', '2022-07-08 19:12:34', '', +VALUES (1121, '设备调试', 0, 5, 'broker', NULL, NULL, 1, 0, 'M', '0', '0', NULL, 'bug', 'admin', '2022-07-08 19:12:34', + '', '2022-10-28 17:46:29', ''); INSERT INTO `sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `query`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`, @@ -3527,7 +3704,7 @@ COMMIT; DROP TABLE IF EXISTS `sys_notice`; CREATE TABLE `sys_notice` ( - `notice_id` int(4) NOT NULL AUTO_INCREMENT COMMENT '公告ID', + `notice_id` int(4) NOT NULL AUTO_INCREMENT COMMENT '公告ID', `notice_title` varchar(50) NOT NULL COMMENT '公告标题', `notice_type` char(1) NOT NULL COMMENT '公告类型(1通知 2公告)', `notice_content` longblob COMMENT '公告内容', @@ -3564,21 +3741,21 @@ DROP TABLE IF EXISTS `sys_oper_log`; CREATE TABLE `sys_oper_log` ( `oper_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '日志主键', - `title` varchar(50) DEFAULT '' COMMENT '模块标题', - `business_type` int(2) DEFAULT '0' COMMENT '业务类型(0其它 1新增 2修改 3删除)', - `method` varchar(100) DEFAULT '' COMMENT '方法名称', - `request_method` varchar(10) DEFAULT '' COMMENT '请求方式', - `operator_type` int(1) DEFAULT '0' COMMENT '操作类别(0其它 1后台用户 2手机端用户)', - `oper_name` varchar(50) DEFAULT '' COMMENT '操作人员', - `dept_name` varchar(50) DEFAULT '' COMMENT '部门名称', - `oper_url` varchar(255) DEFAULT '' COMMENT '请求URL', - `oper_ip` varchar(128) DEFAULT '' COMMENT '主机地址', - `oper_location` varchar(255) DEFAULT '' COMMENT '操作地点', - `oper_param` varchar(2000) DEFAULT '' COMMENT '请求参数', - `json_result` varchar(2000) DEFAULT '' COMMENT '返回参数', - `status` int(1) DEFAULT '0' COMMENT '操作状态(0正常 1异常)', - `error_msg` varchar(2000) DEFAULT '' COMMENT '错误消息', - `oper_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间', + `title` varchar(50) DEFAULT '' COMMENT '模块标题', + `business_type` int(2) DEFAULT '0' COMMENT '业务类型(0其它 1新增 2修改 3删除)', + `method` varchar(100) DEFAULT '' COMMENT '方法名称', + `request_method` varchar(10) DEFAULT '' COMMENT '请求方式', + `operator_type` int(1) DEFAULT '0' COMMENT '操作类别(0其它 1后台用户 2手机端用户)', + `oper_name` varchar(50) DEFAULT '' COMMENT '操作人员', + `dept_name` varchar(50) DEFAULT '' COMMENT '部门名称', + `oper_url` varchar(255) DEFAULT '' COMMENT '请求URL', + `oper_ip` varchar(128) DEFAULT '' COMMENT '主机地址', + `oper_location` varchar(255) DEFAULT '' COMMENT '操作地点', + `oper_param` varchar(2000) DEFAULT '' COMMENT '请求参数', + `json_result` varchar(2000) DEFAULT '' COMMENT '返回参数', + `status` int(1) DEFAULT '0' COMMENT '操作状态(0正常 1异常)', + `error_msg` varchar(2000) DEFAULT '' COMMENT '错误消息', + `oper_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间', PRIMARY KEY (`oper_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 178 @@ -3597,10 +3774,10 @@ COMMIT; DROP TABLE IF EXISTS `sys_post`; CREATE TABLE `sys_post` ( - `post_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '岗位ID', + `post_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '岗位ID', `post_code` varchar(64) NOT NULL COMMENT '岗位编码', `post_name` varchar(50) NOT NULL COMMENT '岗位名称', - `post_sort` int(4) NOT NULL COMMENT '显示顺序', + `post_sort` int(4) NOT NULL COMMENT '显示顺序', `status` char(1) NOT NULL COMMENT '状态(0正常 1停用)', `create_by` varchar(64) DEFAULT '' COMMENT '创建者', `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', @@ -3637,13 +3814,13 @@ COMMIT; DROP TABLE IF EXISTS `sys_role`; CREATE TABLE `sys_role` ( - `role_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '角色ID', + `role_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '角色ID', `role_name` varchar(30) NOT NULL COMMENT '角色名称', `role_key` varchar(100) NOT NULL COMMENT '角色权限字符串', - `role_sort` int(4) NOT NULL COMMENT '显示顺序', + `role_sort` int(4) NOT NULL COMMENT '显示顺序', `data_scope` char(1) DEFAULT '1' COMMENT '数据范围(1:全部数据权限 2:自定数据权限 3:本部门数据权限 4:本部门及以下数据权限)', - `menu_check_strictly` tinyint(1) DEFAULT '1' COMMENT '菜单树选择项是否关联显示', - `dept_check_strictly` tinyint(1) DEFAULT '1' COMMENT '部门树选择项是否关联显示', + `menu_check_strictly` tinyint(1) DEFAULT '1' COMMENT '菜单树选择项是否关联显示', + `dept_check_strictly` tinyint(1) DEFAULT '1' COMMENT '部门树选择项是否关联显示', `status` char(1) NOT NULL COMMENT '角色状态(0正常 1停用)', `del_flag` char(1) DEFAULT '0' COMMENT '删除标志(0代表存在 2代表删除)', `create_by` varchar(64) DEFAULT '' COMMENT '创建者', @@ -3962,8 +4139,8 @@ COMMIT; DROP TABLE IF EXISTS `sys_user`; CREATE TABLE `sys_user` ( - `user_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '用户ID', - `dept_id` bigint(20) DEFAULT NULL COMMENT '部门ID', + `user_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '用户ID', + `dept_id` bigint(20) DEFAULT NULL COMMENT '部门ID', `user_name` varchar(30) NOT NULL COMMENT '用户账号', `nick_name` varchar(30) NOT NULL COMMENT '用户昵称', `user_type` varchar(2) DEFAULT '00' COMMENT '用户类型(00系统用户)', @@ -4088,7 +4265,7 @@ COMMIT; DROP TABLE IF EXISTS `td_createStable_record`; CREATE TABLE `td_createStable_record` ( - `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', + `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', `table_name` varchar(255) NOT NULL COMMENT '表名', `sql_message` longtext COMMENT 'SQL报文', `execute_status` varchar(10) NOT NULL COMMENT '执行状态(成功 || 失败)', @@ -4099,14 +4276,107 @@ CREATE TABLE `td_createStable_record` `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', `remark` varchar(500) DEFAULT NULL COMMENT '备注', PRIMARY KEY (`id`), - KEY `table_name` (`table_name`) USING HASH COMMENT '超级表名' + KEY `table_name` (`table_name`) USING HASH COMMENT '超级表名' ) ENGINE = InnoDB DEFAULT CHARSET = utf8 COMMENT ='TDengine创建超级表记录'; -- ---------------------------- -- Records of td_createStable_record -- ---------------------------- + + +-- ---------------------------- +-- Table structure for ota_upgrades +-- ---------------------------- + +DROP TABLE IF EXISTS `ota_upgrades`; +CREATE TABLE `ota_upgrades` +( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', + `app_id` varchar(64) NOT NULL DEFAULT '' COMMENT '应用ID', + `package_name` varchar(100) NOT NULL DEFAULT '' COMMENT '包名称', + `package_type` smallint(1) NOT NULL DEFAULT '0' COMMENT '升级包类型(0:软件包、1:固件包)', + `product_identification` varchar(100) NOT NULL DEFAULT '' COMMENT '产品标识', + `version` varchar(255) NOT NULL DEFAULT '' COMMENT '升级包版本号', + `file_location` varchar(255) NOT NULL DEFAULT '' COMMENT '升级包的位置', + `status` smallint(1) NOT NULL DEFAULT '0' COMMENT '状态', + `description` varchar(255) DEFAULT '' COMMENT '升级包功能描述', + `custom_info` longtext COMMENT '自定义信息', + `remark` varchar(255) DEFAULT '' COMMENT '描述', + `created_by` bigint(20) DEFAULT NULL COMMENT '创建人', + `created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `updated_by` bigint(20) DEFAULT NULL COMMENT '更新人', + `updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + KEY `idx_app_id` (`app_id`) USING BTREE COMMENT '应用ID', + KEY `idx_product_identification` (`product_identification`) USING BTREE COMMENT '产品标识', + KEY `idx_version` (`version`) USING BTREE COMMENT '升级包版本号' +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='OTA升级包'; + +-- ---------------------------- +-- Records of ota_upgrades +-- ---------------------------- + +-- ---------------------------- +-- Table structure for ota_upgrade_tasks +-- ---------------------------- + +CREATE TABLE `ota_upgrade_tasks` +( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', + `upgrade_id` bigint(20) NOT NULL COMMENT '升级包ID,关联ota_upgrades表', + `task_name` varchar(100) NOT NULL DEFAULT '' COMMENT '任务名称', + `task_status` smallint(1) NOT NULL DEFAULT '0' COMMENT '任务状态(0:待发布、1:进行中、2:已完成、3:已取消)', + `scheduled_time` datetime DEFAULT NULL COMMENT '计划执行时间', + `description` varchar(255) DEFAULT '' COMMENT '任务描述', + `remark` varchar(255) DEFAULT '' COMMENT '描述', + `created_by` bigint(20) DEFAULT NULL COMMENT '创建人', + `created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `updated_by` bigint(20) DEFAULT NULL COMMENT '更新人', + `updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `created_org_id` bigint(20) DEFAULT NULL COMMENT '创建人组织', + PRIMARY KEY (`id`) USING BTREE, + KEY `idx_upgrade_id` (`upgrade_id`) USING BTREE COMMENT '升级包ID' +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='OTA升级任务表'; + +-- ---------------------------- +-- Records of ota_upgrade_tasks +-- ---------------------------- + + +-- ---------------------------- +-- Table structure for ota_upgrade_records +-- ---------------------------- + +CREATE TABLE `ota_upgrade_records` +( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', + `task_id` bigint(20) NOT NULL COMMENT '任务ID,关联ota_upgrade_tasks表', + `device_identification` varchar(100) NOT NULL DEFAULT '' COMMENT '设备标识', + `upgrade_status` smallint(1) NOT NULL DEFAULT '0' COMMENT '升级状态(0:待升级、1:升级中、2:升级成功、3:升级失败)', + `progress` smallint(3) NOT NULL DEFAULT '0' COMMENT '升级进度(百分比)', + `error_code` varchar(100) DEFAULT NULL COMMENT '错误代码', + `error_message` varchar(255) DEFAULT NULL COMMENT '错误信息', + `start_time` datetime DEFAULT NULL COMMENT '升级开始时间', + `end_time` datetime DEFAULT NULL COMMENT '升级结束时间', + `success_details` longtext COMMENT '升级成功详细信息', + `failure_details` longtext COMMENT '升级失败详细信息', + `log_details` longtext COMMENT '升级过程日志', + `remark` varchar(255) DEFAULT '' COMMENT '描述', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `idx_task_id_device_identification` (`task_id`,`device_identification`) USING BTREE, + KEY `idx_task_id` (`task_id`), + KEY `idx_device_identification` (`device_identification`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='OTA升级记录表'; + + +-- ---------------------------- +-- Records of ota_upgrade_records +-- ---------------------------- + + BEGIN; COMMIT; -SET FOREIGN_KEY_CHECKS = 1; +SET +FOREIGN_KEY_CHECKS = 1; diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml new file mode 100644 index 00000000..5ca41a61 --- /dev/null +++ b/docker/docker-compose.yml @@ -0,0 +1,224 @@ +version: '3.5' + +# 网络配置 +networks: + backend: + driver: bridge + +# 作者及社区信息 +x-metadata-config: &metadata-config + maintainer: "mqttsnet@163.com" + community: "mqttsnet" + copyright: "Copyright © 2023 mqttsnet" + +# 共享配置 +x-common-config: &common-config + environment: + - TZ=Asia/Shanghai + volumes: + - /data01/mqttsnet/thinglinks:/home/www/mqttsnet + - /etc/timezone:/etc/timezone + - /etc/localtime:/etc/localtime + restart: always + networks: + - backend + logging: + driver: json-file + options: + max-size: "10m" + max-file: "3" + +# 服务定义 +services: + thinglinks-base: + container_name: thinglinks-base-server + build: + context: ../thinglinks-base/thinglinks-base-server + dockerfile: Dockerfile + ports: + - "18764:18764" # 映射端口 + environment: + - SERVICE_PORT=18764 + healthcheck: + test: [ "CMD", "curl", "-f", "http://localhost:18764/actuator/health" ] + interval: 30s + timeout: 10s + retries: 5 + start_period: 60s + <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 + thinglinks-broker: + container_name: thinglinks-broker-server + build: + context: ../thinglinks-broker/thinglinks-broker-server + dockerfile: Dockerfile + ports: + - "18790:18790" + environment: + - SERVICE_PORT=18790 + healthcheck: + test: [ "CMD", "curl", "-f", "http://localhost:18790/actuator/health" ] + interval: 30s + timeout: 10s + retries: 5 + start_period: 60s + <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 + thinglinks-gateway: + container_name: thinglinks-gateway-server + build: + context: ../thinglinks-gateway/thinglinks-gateway-server + dockerfile: Dockerfile + ports: + - "18760:18760" + environment: + - SERVICE_PORT=18760 + healthcheck: + test: [ "CMD", "curl", "-f", "http://localhost:18760/actuator/health" ] + interval: 30s + timeout: 10s + retries: 5 + start_period: 60s + <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 + thinglinks-generator: + container_name: thinglinks-generator-server + build: + context: ../thinglinks-generator/thinglinks-generator-server + dockerfile: Dockerfile + ports: + - "18780:18780" + environment: + - SERVICE_PORT=18780 + healthcheck: + test: [ "CMD", "curl", "-f", "http://localhost:18780/actuator/health" ] + interval: 30s + timeout: 10s + retries: 5 + start_period: 60s + <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 + thinglinks-link: + container_name: thinglinks-link-server + build: + context: ../thinglinks-link/thinglinks-link-server + dockerfile: Dockerfile + ports: + - "18782:18782" + environment: + - SERVICE_PORT=18782 + healthcheck: + test: [ "CMD", "curl", "-f", "http://localhost:18782/actuator/health" ] + interval: 30s + timeout: 10s + retries: 5 + start_period: 60s + <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 + thinglinks-mqs: + container_name: thinglinks-mqs-server + build: + context: ../thinglinks-mqs/thinglinks-mqs-server + dockerfile: Dockerfile + ports: + - "18784:18784" + environment: + - SERVICE_PORT=18784 + healthcheck: + test: [ "CMD", "curl", "-f", "http://localhost:18784/actuator/health" ] + interval: 30s + timeout: 10s + retries: 5 + start_period: 60s + <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 + thinglinks-oauth: + container_name: thinglinks-oauth-server + build: + context: ../thinglinks-oauth/thinglinks-oauth-server + dockerfile: Dockerfile + ports: + - "18773:18773" + environment: + - SERVICE_PORT=18773 + healthcheck: + test: [ "CMD", "curl", "-f", "http://localhost:18773/actuator/health" ] + interval: 30s + timeout: 10s + retries: 5 + start_period: 60s + <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 + thinglinks-rule: + container_name: thinglinks-rule-server + build: + context: ../thinglinks-rule/thinglinks-rule-server + dockerfile: Dockerfile + ports: + - "18786:18786" + environment: + - SERVICE_PORT=18786 + healthcheck: + test: [ "CMD", "curl", "-f", "http://localhost:18786/actuator/health" ] + interval: 30s + timeout: 10s + retries: 5 + start_period: 60s + <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 + thinglinks-monitor: + container_name: thinglinks-monitor-server + build: + context: ../thinglinks-support/thinglinks-monitor-server + dockerfile: Dockerfile + ports: + - "18762:18762" + environment: + - SERVICE_PORT=18762 + healthcheck: + test: [ "CMD", "curl", "-f", "http://localhost:18762/actuator/health" ] + interval: 30s + timeout: 10s + retries: 5 + start_period: 60s + <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 + thinglinks-system: + container_name: thinglinks-system-server + build: + context: ../thinglinks-system/thinglinks-system-server + dockerfile: Dockerfile + ports: + - "18778:18778" + environment: + - SERVICE_PORT=18778 + healthcheck: + test: [ "CMD", "curl", "-f", "http://localhost:18778/actuator/health" ] + interval: 30s + timeout: 10s + retries: 5 + start_period: 60s + <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 + thinglinks-tds: + container_name: thinglinks-tds-server + build: + context: ../thinglinks-tds/thinglinks-tds-server + dockerfile: Dockerfile + ports: + - "18788:18788" + environment: + - SERVICE_PORT=18788 + healthcheck: + test: [ "CMD", "curl", "-f", "http://localhost:18788/actuator/health" ] + interval: 30s + timeout: 10s + retries: 5 + start_period: 60s + <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 + thinglinks-view: + container_name: thinglinks-view-server + build: + context: ../thinglinks-view/thinglinks-view-server + dockerfile: Dockerfile + ports: + - "18792:18792" + environment: + - SERVICE_PORT=18792 + healthcheck: + test: [ "CMD", "curl", "-f", "http://localhost:18792/actuator/health" ] + interval: 30s + timeout: 10s + retries: 5 + start_period: 60s + <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 \ No newline at end of file diff --git a/thinglinks-auth/Dockerfile b/thinglinks-auth/Dockerfile index ea670b7a..bbdcafd6 100644 --- a/thinglinks-auth/Dockerfile +++ b/thinglinks-auth/Dockerfile @@ -1,11 +1,25 @@ +# 使用 Java 运行环境 FROM openjdk:8-jre -MAINTAINER mqttsnet mqttsnet@163.com -RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ - && echo "Asia/Shanghai" > /etc/timezone +# 维护者信息 +LABEL maintainer="mqttsnet mqttsnet@163.com" -ARG JAR_FILE -COPY ${JAR_FILE} /app.jar +# 设置时区 +ENV TZ=Asia/Shanghai +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone -ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-Ddruid.mysql.usePingMethod=false", "-jar", "/app.jar"] -CMD ["--spring.profiles.active=docker"] +# 创建工作目录 +WORKDIR /home/www/mqttsnet/thinglinks-broker + +# 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 +COPY target/thinglinks-auth-server.jar /app.jar + +# 暴露服务端口 +EXPOSE 19200 + +# 添加健康检查,确保应用健康状态 +HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ + CMD curl -f http://localhost:19200/actuator/health || exit 1 + +# 启动 Java 应用 +ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-gateway/Dockerfile b/thinglinks-gateway/Dockerfile index ea670b7a..bbdcafd6 100644 --- a/thinglinks-gateway/Dockerfile +++ b/thinglinks-gateway/Dockerfile @@ -1,11 +1,25 @@ +# 使用 Java 运行环境 FROM openjdk:8-jre -MAINTAINER mqttsnet mqttsnet@163.com -RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ - && echo "Asia/Shanghai" > /etc/timezone +# 维护者信息 +LABEL maintainer="mqttsnet mqttsnet@163.com" -ARG JAR_FILE -COPY ${JAR_FILE} /app.jar +# 设置时区 +ENV TZ=Asia/Shanghai +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone -ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-Ddruid.mysql.usePingMethod=false", "-jar", "/app.jar"] -CMD ["--spring.profiles.active=docker"] +# 创建工作目录 +WORKDIR /home/www/mqttsnet/thinglinks-broker + +# 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 +COPY target/thinglinks-auth-server.jar /app.jar + +# 暴露服务端口 +EXPOSE 19200 + +# 添加健康检查,确保应用健康状态 +HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ + CMD curl -f http://localhost:19200/actuator/health || exit 1 + +# 启动 Java 应用 +ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-broker/Dockerfile b/thinglinks-modules/thinglinks-modules-broker/Dockerfile index ea670b7a..bbdcafd6 100644 --- a/thinglinks-modules/thinglinks-modules-broker/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-broker/Dockerfile @@ -1,11 +1,25 @@ +# 使用 Java 运行环境 FROM openjdk:8-jre -MAINTAINER mqttsnet mqttsnet@163.com -RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ - && echo "Asia/Shanghai" > /etc/timezone +# 维护者信息 +LABEL maintainer="mqttsnet mqttsnet@163.com" -ARG JAR_FILE -COPY ${JAR_FILE} /app.jar +# 设置时区 +ENV TZ=Asia/Shanghai +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone -ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-Ddruid.mysql.usePingMethod=false", "-jar", "/app.jar"] -CMD ["--spring.profiles.active=docker"] +# 创建工作目录 +WORKDIR /home/www/mqttsnet/thinglinks-broker + +# 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 +COPY target/thinglinks-auth-server.jar /app.jar + +# 暴露服务端口 +EXPOSE 19200 + +# 添加健康检查,确保应用健康状态 +HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ + CMD curl -f http://localhost:19200/actuator/health || exit 1 + +# 启动 Java 应用 +ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-broker/pom.xml b/thinglinks-modules/thinglinks-modules-broker/pom.xml index 0f3a1055..709d9571 100644 --- a/thinglinks-modules/thinglinks-modules-broker/pom.xml +++ b/thinglinks-modules/thinglinks-modules-broker/pom.xml @@ -67,20 +67,6 @@ ${thinglinks.version} - - - io.github.quickmsg - smqttx-spring-boot-starter - 2.0.9 - - - - com.h2database - h2 - 1.4.197 - - - com.mqttsnet diff --git a/thinglinks-modules/thinglinks-modules-file/Dockerfile b/thinglinks-modules/thinglinks-modules-file/Dockerfile index fa503cda..bbdcafd6 100644 --- a/thinglinks-modules/thinglinks-modules-file/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-file/Dockerfile @@ -1,11 +1,25 @@ +# 使用 Java 运行环境 FROM openjdk:8-jre -MAINTAINER mqttsnet mqttsnet@163.com -RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ - && echo "Asia/Shanghai" > /etc/timezone +# 维护者信息 +LABEL maintainer="mqttsnet mqttsnet@163.com" -ARG JAR_FILE -COPY ${JAR_FILE} /app.jar +# 设置时区 +ENV TZ=Asia/Shanghai +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone -ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] -CMD ["--spring.profiles.active=docker"] +# 创建工作目录 +WORKDIR /home/www/mqttsnet/thinglinks-broker + +# 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 +COPY target/thinglinks-auth-server.jar /app.jar + +# 暴露服务端口 +EXPOSE 19200 + +# 添加健康检查,确保应用健康状态 +HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ + CMD curl -f http://localhost:19200/actuator/health || exit 1 + +# 启动 Java 应用 +ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-gen/Dockerfile b/thinglinks-modules/thinglinks-modules-gen/Dockerfile index ea670b7a..bbdcafd6 100644 --- a/thinglinks-modules/thinglinks-modules-gen/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-gen/Dockerfile @@ -1,11 +1,25 @@ +# 使用 Java 运行环境 FROM openjdk:8-jre -MAINTAINER mqttsnet mqttsnet@163.com -RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ - && echo "Asia/Shanghai" > /etc/timezone +# 维护者信息 +LABEL maintainer="mqttsnet mqttsnet@163.com" -ARG JAR_FILE -COPY ${JAR_FILE} /app.jar +# 设置时区 +ENV TZ=Asia/Shanghai +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone -ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-Ddruid.mysql.usePingMethod=false", "-jar", "/app.jar"] -CMD ["--spring.profiles.active=docker"] +# 创建工作目录 +WORKDIR /home/www/mqttsnet/thinglinks-broker + +# 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 +COPY target/thinglinks-auth-server.jar /app.jar + +# 暴露服务端口 +EXPOSE 19200 + +# 添加健康检查,确保应用健康状态 +HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ + CMD curl -f http://localhost:19200/actuator/health || exit 1 + +# 启动 Java 应用 +ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-job/Dockerfile b/thinglinks-modules/thinglinks-modules-job/Dockerfile index ea670b7a..bbdcafd6 100644 --- a/thinglinks-modules/thinglinks-modules-job/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-job/Dockerfile @@ -1,11 +1,25 @@ +# 使用 Java 运行环境 FROM openjdk:8-jre -MAINTAINER mqttsnet mqttsnet@163.com -RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ - && echo "Asia/Shanghai" > /etc/timezone +# 维护者信息 +LABEL maintainer="mqttsnet mqttsnet@163.com" -ARG JAR_FILE -COPY ${JAR_FILE} /app.jar +# 设置时区 +ENV TZ=Asia/Shanghai +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone -ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-Ddruid.mysql.usePingMethod=false", "-jar", "/app.jar"] -CMD ["--spring.profiles.active=docker"] +# 创建工作目录 +WORKDIR /home/www/mqttsnet/thinglinks-broker + +# 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 +COPY target/thinglinks-auth-server.jar /app.jar + +# 暴露服务端口 +EXPOSE 19200 + +# 添加健康检查,确保应用健康状态 +HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ + CMD curl -f http://localhost:19200/actuator/health || exit 1 + +# 启动 Java 应用 +ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-link/Dockerfile b/thinglinks-modules/thinglinks-modules-link/Dockerfile index ea670b7a..bbdcafd6 100644 --- a/thinglinks-modules/thinglinks-modules-link/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-link/Dockerfile @@ -1,11 +1,25 @@ +# 使用 Java 运行环境 FROM openjdk:8-jre -MAINTAINER mqttsnet mqttsnet@163.com -RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ - && echo "Asia/Shanghai" > /etc/timezone +# 维护者信息 +LABEL maintainer="mqttsnet mqttsnet@163.com" -ARG JAR_FILE -COPY ${JAR_FILE} /app.jar +# 设置时区 +ENV TZ=Asia/Shanghai +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone -ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-Ddruid.mysql.usePingMethod=false", "-jar", "/app.jar"] -CMD ["--spring.profiles.active=docker"] +# 创建工作目录 +WORKDIR /home/www/mqttsnet/thinglinks-broker + +# 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 +COPY target/thinglinks-auth-server.jar /app.jar + +# 暴露服务端口 +EXPOSE 19200 + +# 添加健康检查,确保应用健康状态 +HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ + CMD curl -f http://localhost:19200/actuator/health || exit 1 + +# 启动 Java 应用 +ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-protocolAnalysis/Dockerfile b/thinglinks-modules/thinglinks-modules-protocolAnalysis/Dockerfile new file mode 100644 index 00000000..bbdcafd6 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-protocolAnalysis/Dockerfile @@ -0,0 +1,25 @@ +# 使用 Java 运行环境 +FROM openjdk:8-jre + +# 维护者信息 +LABEL maintainer="mqttsnet mqttsnet@163.com" + +# 设置时区 +ENV TZ=Asia/Shanghai +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone + +# 创建工作目录 +WORKDIR /home/www/mqttsnet/thinglinks-broker + +# 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 +COPY target/thinglinks-auth-server.jar /app.jar + +# 暴露服务端口 +EXPOSE 19200 + +# 添加健康检查,确保应用健康状态 +HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ + CMD curl -f http://localhost:19200/actuator/health || exit 1 + +# 启动 Java 应用 +ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-rule/Dockerfile b/thinglinks-modules/thinglinks-modules-rule/Dockerfile index ea670b7a..bbdcafd6 100644 --- a/thinglinks-modules/thinglinks-modules-rule/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-rule/Dockerfile @@ -1,11 +1,25 @@ +# 使用 Java 运行环境 FROM openjdk:8-jre -MAINTAINER mqttsnet mqttsnet@163.com -RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ - && echo "Asia/Shanghai" > /etc/timezone +# 维护者信息 +LABEL maintainer="mqttsnet mqttsnet@163.com" -ARG JAR_FILE -COPY ${JAR_FILE} /app.jar +# 设置时区 +ENV TZ=Asia/Shanghai +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone -ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-Ddruid.mysql.usePingMethod=false", "-jar", "/app.jar"] -CMD ["--spring.profiles.active=docker"] +# 创建工作目录 +WORKDIR /home/www/mqttsnet/thinglinks-broker + +# 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 +COPY target/thinglinks-auth-server.jar /app.jar + +# 暴露服务端口 +EXPOSE 19200 + +# 添加健康检查,确保应用健康状态 +HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ + CMD curl -f http://localhost:19200/actuator/health || exit 1 + +# 启动 Java 应用 +ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-system/Dockerfile b/thinglinks-modules/thinglinks-modules-system/Dockerfile index ea670b7a..bbdcafd6 100644 --- a/thinglinks-modules/thinglinks-modules-system/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-system/Dockerfile @@ -1,11 +1,25 @@ +# 使用 Java 运行环境 FROM openjdk:8-jre -MAINTAINER mqttsnet mqttsnet@163.com -RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ - && echo "Asia/Shanghai" > /etc/timezone +# 维护者信息 +LABEL maintainer="mqttsnet mqttsnet@163.com" -ARG JAR_FILE -COPY ${JAR_FILE} /app.jar +# 设置时区 +ENV TZ=Asia/Shanghai +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone -ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-Ddruid.mysql.usePingMethod=false", "-jar", "/app.jar"] -CMD ["--spring.profiles.active=docker"] +# 创建工作目录 +WORKDIR /home/www/mqttsnet/thinglinks-broker + +# 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 +COPY target/thinglinks-auth-server.jar /app.jar + +# 暴露服务端口 +EXPOSE 19200 + +# 添加健康检查,确保应用健康状态 +HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ + CMD curl -f http://localhost:19200/actuator/health || exit 1 + +# 启动 Java 应用 +ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-tdengine/Dockerfile b/thinglinks-modules/thinglinks-modules-tdengine/Dockerfile index ea670b7a..bbdcafd6 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-tdengine/Dockerfile @@ -1,11 +1,25 @@ +# 使用 Java 运行环境 FROM openjdk:8-jre -MAINTAINER mqttsnet mqttsnet@163.com -RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ - && echo "Asia/Shanghai" > /etc/timezone +# 维护者信息 +LABEL maintainer="mqttsnet mqttsnet@163.com" -ARG JAR_FILE -COPY ${JAR_FILE} /app.jar +# 设置时区 +ENV TZ=Asia/Shanghai +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone -ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-Ddruid.mysql.usePingMethod=false", "-jar", "/app.jar"] -CMD ["--spring.profiles.active=docker"] +# 创建工作目录 +WORKDIR /home/www/mqttsnet/thinglinks-broker + +# 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 +COPY target/thinglinks-auth-server.jar /app.jar + +# 暴露服务端口 +EXPOSE 19200 + +# 添加健康检查,确保应用健康状态 +HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ + CMD curl -f http://localhost:19200/actuator/health || exit 1 + +# 启动 Java 应用 +ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-visual/thinglinks-visual-monitor/Dockerfile b/thinglinks-visual/thinglinks-visual-monitor/Dockerfile index fa503cda..bbdcafd6 100644 --- a/thinglinks-visual/thinglinks-visual-monitor/Dockerfile +++ b/thinglinks-visual/thinglinks-visual-monitor/Dockerfile @@ -1,11 +1,25 @@ +# 使用 Java 运行环境 FROM openjdk:8-jre -MAINTAINER mqttsnet mqttsnet@163.com -RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ - && echo "Asia/Shanghai" > /etc/timezone +# 维护者信息 +LABEL maintainer="mqttsnet mqttsnet@163.com" -ARG JAR_FILE -COPY ${JAR_FILE} /app.jar +# 设置时区 +ENV TZ=Asia/Shanghai +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone -ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] -CMD ["--spring.profiles.active=docker"] +# 创建工作目录 +WORKDIR /home/www/mqttsnet/thinglinks-broker + +# 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 +COPY target/thinglinks-auth-server.jar /app.jar + +# 暴露服务端口 +EXPOSE 19200 + +# 添加健康检查,确保应用健康状态 +HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ + CMD curl -f http://localhost:19200/actuator/health || exit 1 + +# 启动 Java 应用 +ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] From 0123d0e6000cf70cabe3a1b920e161a505782099 Mon Sep 17 00:00:00 2001 From: xiaonan <13733918655@163.com> Date: Thu, 25 Jan 2024 10:16:17 +0800 Subject: [PATCH 03/35] =?UTF-8?q?=E6=96=B0=E5=A2=9EBifromq=20api?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DEFAULT_GROUP/application.yml | 13 +- doc/nacos-config/DEFAULT_GROUP/rocketmq.yml | 25 ++++ .../thinglinks-modules-broker.yml | 141 +----------------- .../DEFAULT_GROUP/thinglinks-modules-link.yml | 7 - .../DEFAULT_GROUP/thinglinks-modules-rule.yml | 6 - .../thinglinks-modules-tdengine.yml | 7 - .../thinglinks/broker/api/BifroMQApi.java | 136 +++++++++++++++++ .../broker/api/RemoteMqttBrokerOpenApi.java | 49 ++++++ .../broker/api/RemotePublishActorService.java | 47 ------ .../api/domain/PublishMessageRequest.java | 53 +++++++ .../api/factory/BifroMQApiFallback.java | 123 +++++++++++++++ .../RemoteMqttBrokerOpenApiFallback.java | 57 +++++++ .../RemotePublishActorFallbackFactory.java | 59 -------- .../common/core/constant/Constants.java | 10 +- .../kafka/config/KafkaConsumerConfig.java | 12 +- .../kafka/config/KafkaProviderConfig.java | 16 +- .../thinglinks-common-rocketmq/pom.xml | 2 +- .../thinglinks-modules-broker/pom.xml | 6 - .../broker/ThingLinksBrokerApplication.java | 12 +- .../link/ThingLinksLinkApplication.java | 3 - .../ThingLinksBeanDefinitionRegistrar.java | 49 ------ .../device/impl/DeviceDatasServiceImpl.java | 10 +- .../device/impl/DeviceInfoServiceImpl.java | 6 +- .../device/impl/DeviceServiceImpl.java | 6 +- .../src/main/resources/bootstrap.yml | 2 + .../ThingLinksBeanDefinitionRegistrar.java | 49 ------ .../ThingLinksTdengineApplication.java | 1 - .../src/main/resources/bootstrap.yml | 2 + 28 files changed, 491 insertions(+), 418 deletions(-) create mode 100644 doc/nacos-config/DEFAULT_GROUP/rocketmq.yml create mode 100644 thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/BifroMQApi.java create mode 100644 thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/RemoteMqttBrokerOpenApi.java delete mode 100644 thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/RemotePublishActorService.java create mode 100644 thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/PublishMessageRequest.java create mode 100644 thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/BifroMQApiFallback.java create mode 100644 thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/RemoteMqttBrokerOpenApiFallback.java delete mode 100644 thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/RemotePublishActorFallbackFactory.java delete mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/ThingLinksBeanDefinitionRegistrar.java delete mode 100644 thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/ThingLinksBeanDefinitionRegistrar.java diff --git a/doc/nacos-config/DEFAULT_GROUP/application.yml b/doc/nacos-config/DEFAULT_GROUP/application.yml index 421b2c5e..95b9f851 100755 --- a/doc/nacos-config/DEFAULT_GROUP/application.yml +++ b/doc/nacos-config/DEFAULT_GROUP/application.yml @@ -15,7 +15,7 @@ ribbon: # feign 配置 feign: - hystrix: + hystrix: enabled: true sentinel: enabled: true @@ -36,9 +36,9 @@ feign: # 暴露监控端点 management: - metrics: - export: - influx: + metrics: + export: + influx: enabled: false endpoints: web: @@ -56,7 +56,4 @@ threadBus: #缓冲队列大小 queue-capacity: 1000 #线程池名前缀 - thread-name-prefix: thinglinksAsync- -#消息队列转发true kafka | false rocketmq,默认为kakfa 自行选择 -mqs: - selector-kafka: true \ No newline at end of file + thread-name-prefix: thinglinksAsync- \ No newline at end of file diff --git a/doc/nacos-config/DEFAULT_GROUP/rocketmq.yml b/doc/nacos-config/DEFAULT_GROUP/rocketmq.yml new file mode 100644 index 00000000..2621a962 --- /dev/null +++ b/doc/nacos-config/DEFAULT_GROUP/rocketmq.yml @@ -0,0 +1,25 @@ +rocketmq: + consumer: + group: thinglinks + accessKey: + secretKey: + # 一次拉取消息最大值,注意是拉取消息的最大值而非消费最大值 + pull-batch-size: 10 + name-server: 127.0.0.1:19876 + producer: + # 发送同一类消息的设置为同一个group,保证唯一 + group: thinglinks + accessKey: + secretKey: + # 发送消息超时时间,默认3000 + sendMessageTimeout: 10000 + # 发送消息失败重试次数,默认2 + retryTimesWhenSendFailed: 2 + # 异步消息重试此处,默认2 + retryTimesWhenSendAsyncFailed: 2 + # 消息最大长度,默认1024 * 1024 * 4(默认4M) + maxMessageSize: 4096 + # 压缩消息阈值,默认4k(1024 * 4) + compressMessageBodyThreshold: 4096 + # 是否在内部发送失败时重试另一个broker,默认false + retryNextServer: false diff --git a/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-broker.yml b/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-broker.yml index 859aa5aa..195f59c1 100755 --- a/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-broker.yml +++ b/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-broker.yml @@ -2,137 +2,10 @@ server: port: 19306 -#smqtt配置文件V2.0 -smqtt: - logLevel: INFO # 系统日志 - tcp: # tcp配置 - port: 11883 # mqtt端口号 - notKickSecond: 30 # KICK互踢模式生效, 单位秒, 指定时间内客户端不互踢, 避免客户端自动连接持续互踢 - wiretap: false # 二进制日志 前提是 smqtt.logLevel = DEBUG - bossThreadSize: 1 # boss线程 默认=1 - workThreadSize: 9 # work线程 默认=cpu核心数+1 - businessThreadSize: 8 # 业务线程数 默认=cpu核心数 - businessQueueSize: 100000 #业务队列 默认=100000 - messageMaxSize: 4194304 # 接收消息的最大限制 默认4194304(4M) - lowWaterMark: 4000000 # 不建议配置 默认 32768 - highWaterMark: 80000000 # 不建议配置 默认 65536 - # globalReadWriteSize: 10000000,100000000 全局读写大小限制 - # channelReadWriteSize: 10000000,100000000 单个channel读写大小限制 - options: # netty option设置 - SO_BACKLOG: 2000 - childOptions: #netty child option设置 - SO_REUSEADDR: true - ssl: # ssl配置 - enable: false # 开关 - key: classpath:ssl/server.key # 指定ssl文件 默认系统生成 - crt: classpath:ssl/server.crt # 指定ssl文件 默认系统生成 - ca: classpath:ssl/server.ca # ca证书 双向加密配置 - acl: - aclPolicy: JDBC # NONE or FILE or JDBC - filePath: # FILE时配置filePath - jdbcAclConfig: - driver: com.mysql.jdbc.Driver - url: ${spring.datasource.dynamic.datasource.master.url} - username: ${spring.datasource.dynamic.datasource.master.username} - password: ${spring.datasource.dynamic.datasource.master.password} - http: # http相关配置 端口固定60000 - enable: true # 开关 - accessLog: false # http访问日志 - ssl: # ssl配置 - enable: false - admin: # Broker后台管理配置 - enable: true # 开关 - username: thinglinks # 访问用户名 - password: thinglinks # 访问密码 - auth: - http: #设备鉴权模式(请求方式固定 POST body 格式为: {"clientIdentifier":"","username":"","password":""} 返回状态码 200 即可 如果检验失败返回400) - host: 127.0.0.1 #网关服务器IP - port: 19100 #网关服务端口 - path: /link/device/clientAuthentication - params: {"deviceStatus":"ENABLE","protocolType":"MQTT"} - ws: # websocket配置 - enable: true # 开关 - port: 18999 # 端口 - path: /mqtt # ws 的访问path mqtt.js请设置此选项 - cluster: # 集群配置 - #本地IP,多网卡时候指定 - localAddress: 127.0.0.1 - #集群IP集合 - addresses: ["127.0.0.1"] - #集群持久化目录,默认启动目录 - #workDirectory: /soft/dir - meter: - meterType: PROMETHEUS # INFLUXDB , PROMETHEUS - rules: - - ruleName: ROCKET_MQ - chain: - - ruleType: PREDICATE - script: $.event.equals("ping") - # - ruleType: ROCKET_MQ - # script: "{'event':'ping','clientId':clientId,'messageId':messageId,'time':time}" - - ruleType: KAFKA - script: "{'event':'ping','clientId':clientId,'messageId':messageId,'time':time}" - - ruleName: ROCKET_MQ - chain: - - ruleType: PREDICATE - script: $.event.equals("connect") - # - ruleType: ROCKET_MQ - # script: "{'event':'connect','clientId':clientId,'auth':auth,'clientAddress':clientAddress,'keepalive':keepalive,'nodeIp':nodeIp,'version':version,'time':time,'will':will}" - - ruleType: KAFKA - script: "{'event':'connect','clientId':clientId,'auth':auth,'clientAddress':clientAddress,'keepalive':keepalive,'nodeIp':nodeIp,'version':version,'time':time,'will':will}" - - ruleName: ROCKET_MQ - chain: - - ruleType: PREDICATE - script: $.event.equals("publish") - # - ruleType: ROCKET_MQ - # script: "{'event':'publish','topic':topic,'body':body,'qos':qos,'clientId':clientId,'messageId':messageId,'time':time}" - - ruleType: KAFKA - script: "{'event':'publish','topic':topic,'body':body,'qos':qos,'clientId':clientId,'messageId':messageId,'time':time}" - - ruleName: ROCKET_MQ - chain: - - ruleType: PREDICATE - script: $.event.equals("disconnect") - # - ruleType: ROCKET_MQ - # script: "{'event':'disconnect','clientId':clientId,'time':time}" - - ruleType: KAFKA - script: "{'event':'disconnect','clientId':clientId,'time':time}" - - ruleName: ROCKET_MQ - chain: - - ruleType: PREDICATE - script: $.event.equals("clone") - # - ruleType: ROCKET_MQ - # script: "{'event':'disconnect','clientId':clientId,'time':time}" - - ruleType: KAFKA - script: "{'event':'disconnect','clientId':clientId,'time':time}" - - ruleName: ROCKET_MQ - chain: - - ruleType: PREDICATE - script: $.event.equals("subscribe") - # - ruleType: ROCKET_MQ - # script: "{'event':'subscribe','clientId':clientId,'subscribeTopics':subscribeTopics,'time':time}" - - ruleType: KAFKA - script: "{'event':'subscribe','clientId':clientId,'subscribeTopics':subscribeTopics,'time':time}" - - ruleName: ROCKET_MQ - chain: - - ruleType: PREDICATE - script: $.event.equals("unsubscribe") - # - ruleType: ROCKET_MQ - # script: "{'event':'unsubscribe','clientId':clientId,'topics':topics,'time':time}" - - ruleType: KAFKA - script: "{'event':'unsubscribe','clientId':clientId,'topics':topics,'time':time}" - sources: # 配置数据源sources - # - source: ROCKET_MQ # rocketmq配置 - # sourceName: rocket_mq - # sourceAttributes: - # topic: thinglinks-link-mqttMsg - # tags: thinglinks - # namesrvAddr: 127.0.0.1:9876 - # instanceName: broker-a - # producerGroup: thinglinks-broker - - source: KAFKA # kafka配置 - sourceName: kafka - sourceAttributes: - topic: thinglinks-link-mqttMsg - bootstrap-servers: 127.0.0.1:9092 - key-serializer: org.apache.kafka.common.serialization.StringSerializer - value-serializer: org.apache.kafka.common.serialization.StringSerializer \ No newline at end of file +thinglinks: + #feign 通用三方API服务 + feign: + #bifromq 服务API + bifromq: + #api-service的HTTP端口 + bifromq-api-server: http://127.0.0.1:8091 \ No newline at end of file diff --git a/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-link.yml b/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-link.yml index 5c2abe88..abccaa25 100755 --- a/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-link.yml +++ b/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-link.yml @@ -2,13 +2,6 @@ server: port: 19305 -# rocketmq地址 -rocketmq: - name-server: 127.0.0.1:19876 - # 默认的消息组 - producer: - group: thinglinks-link - # mybatis配置 mybatis: # 搜索指定包别名 diff --git a/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-rule.yml b/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-rule.yml index 1e2d0704..0b5eb36d 100755 --- a/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-rule.yml +++ b/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-rule.yml @@ -2,12 +2,6 @@ server: port: 19308 -# rocketmq地址 -rocketmq: - name-server: 127.0.0.1:19876 - # 默认的消息组 - producer: - group: thinglinks-rule # mybatis配置 mybatis: diff --git a/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-tdengine.yml b/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-tdengine.yml index f6c9acbf..6f1c49a9 100755 --- a/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-tdengine.yml +++ b/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-tdengine.yml @@ -47,13 +47,6 @@ spring: mybatis: mapper-locations: classpath:mapper/*.xml -# rocketmq地址 -rocketmq: - name-server: 127.0.0.1:19876 - # 默认的消息组 - producer: - group: thinglinks-tdengine - # seata配置 seata: # 默认关闭,如需启用spring.datasource.dynami.seata需要同时开启 diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/BifroMQApi.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/BifroMQApi.java new file mode 100644 index 00000000..a1baf6eb --- /dev/null +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/BifroMQApi.java @@ -0,0 +1,136 @@ +package com.mqttsnet.thinglinks.broker.api; + +import com.mqttsnet.thinglinks.common.core.constant.Constants; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +/** + * ----------------------------------------------------------------------------- + * File Name: BifroMQApi.java + * ----------------------------------------------------------------------------- + * Description: + * BifroMQ Api + * ----------------------------------------------------------------------------- + * + * @author ShiHuan Sun + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + *

+ * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2023-10-31 12:20 + */ +@FeignClient(name = "BifroMQApi", url = "${" + Constants.PROJECT_PREFIX + ".feign.bifromq.bifromq-api-server:http://127.0.0.1:8091}", path = "/") +public interface BifroMQApi { + + /** + * Publish a message to a given topic. + * + * @param reqId Optional caller provided request id. + * @param tenantId The tenant id. + * @param topic The message topic. + * @param clientType The client type. + * @param pubQos QoS of the message to be distributed. + * @param retain The message should be retained. + * @param clientMeta Metadata header about the kicker client. + * @param payload Message payload. + * @return Response indicating success or failure. + */ + @PostMapping(path = "/pub", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE}) + ResponseEntity publishMessage( + @RequestHeader(name = "req_id", required = false) Long reqId, + @RequestHeader(name = "tenant_id") String tenantId, + @RequestHeader(name = "topic") String topic, + @RequestHeader(name = "client_type") String clientType, + @RequestHeader(name = "pub_qos") String pubQos, + @RequestHeader(name = "retain", required = false) String retain, + @RequestHeader(name = "client_meta_*", required = false) String clientMeta, + @RequestBody String payload + ); + + /** + * Manually expires the inbox based on the provided parameters. + * + * @param reqId Optional caller provided request id. + * @param tenantId The tenant id. + * @param expirySeconds The inbox's expiry time. + * @return ResponseEntity indicating the result of the operation. + */ + @DeleteMapping("/expireinbox") + ResponseEntity expireInbox( + @RequestHeader(name = "req_id", required = false) Long reqId, + @RequestHeader("tenant_id") String tenantId, + @RequestHeader("expiry_seconds") String expirySeconds + ); + + /** + * Disconnects a MQTT client connection based on the provided parameters. + * + * @param reqId Optional caller provided request id. + * @param tenantId The tenant id. + * @param userId The user id of the MQTT client connection to be disconnected. + * @param clientId The client id of the MQTT client connection to be disconnected. + * @param clientType The client type. + * @param clientMeta Metadata header about the kicker client, must start with client_meta_. + * @return ResponseEntity indicating the result of the operation. + */ + @DeleteMapping("/kill") + ResponseEntity killClientConnection( + @RequestHeader(name = "req_id", required = false) Long reqId, + @RequestHeader("tenant_id") String tenantId, + @RequestHeader("user_id") String userId, + @RequestHeader("client_id") String clientId, + @RequestHeader("client_type") String clientType, + @RequestHeader(name = "client_meta_*", required = false) String clientMeta // Note: This logic needs further implementation + ); + + /** + * Adds a topic subscription to an inbox. + * + * @param reqId Optional caller provided request id. + * @param tenantId The tenant id. + * @param topicFilter The topic filter to add. + * @param subQos The QoS of the subscription. + * @param inboxId The inbox for receiving subscribed messages. + * @param delivererKey Deliverer key for subBroker. + * @param subBrokerId The ID of the subbroker hosting the inbox. + * @return ResponseEntity indicating the result of the operation. + */ + @PutMapping("/sub") + ResponseEntity addTopicSubscription( + @RequestHeader(name = "req_id", required = false) Long reqId, + @RequestHeader("tenant_id") String tenantId, + @RequestHeader("topic_filter") String topicFilter, + @RequestHeader("sub_qos") String subQos, + @RequestHeader("inbox_id") String inboxId, + @RequestHeader(name = "deliverer_key", required = false) String delivererKey, + @RequestHeader("subbroker_id") Integer subBrokerId + ); + + /** + * Removes a topic subscription from an inbox. + * + * @param reqId Optional caller provided request id. + * @param tenantId The tenant id. + * @param topicFilter The topic filter to remove. + * @param inboxId The inbox for receiving subscribed messages. + * @param delivererKey Deliverer key for subBroker. + * @param subBrokerId The ID of the subbroker hosting the inbox. + * @return ResponseEntity indicating the result of the operation. + */ + @DeleteMapping("/unsub") + ResponseEntity removeTopicSubscription( + @RequestHeader(name = "req_id", required = false) Long reqId, + @RequestHeader("tenant_id") String tenantId, + @RequestHeader("topic_filter") String topicFilter, + @RequestHeader("inbox_id") String inboxId, + @RequestHeader(name = "deliverer_key", required = false) String delivererKey, + @RequestHeader("subbroker_id") Integer subBrokerId + ); + +} diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/RemoteMqttBrokerOpenApi.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/RemoteMqttBrokerOpenApi.java new file mode 100644 index 00000000..7cf05e10 --- /dev/null +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/RemoteMqttBrokerOpenApi.java @@ -0,0 +1,49 @@ +package com.mqttsnet.thinglinks.broker.api; + +import com.mqttsnet.thinglinks.broker.api.domain.PublishMessageRequest; +import com.mqttsnet.thinglinks.broker.api.factory.RemoteMqttBrokerOpenApiFallback; +import com.mqttsnet.thinglinks.common.core.constant.ServiceNameConstants; +import com.mqttsnet.thinglinks.common.core.domain.R; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; + +import java.util.List; + +/** + * @Description: MqttBroker-开放接口API + * @Author: ShiHuan SUN + * @E-mail: 13733918655@163.com + * @Website: http://thinglinks.mqttsnet.com + * @CreateDate: 2022/1/14$ 16:46$ + * @UpdateUser: ShiHuan SUN + * @UpdateDate: 2024/1/14$ 16:46$ + * @UpdateRemark: 调整入参格式 + * @Version: V2.0 + */ +@FeignClient(contextId = "remoteMqttBrokerOpenApi", value = ServiceNameConstants.THINGLINKS_BROKER, fallbackFactory = RemoteMqttBrokerOpenApiFallback.class) +public interface RemoteMqttBrokerOpenApi { + + + /** + * MQTT推送消息接口 + * + * @param publishMessageRequest 推送消息请求参数 + * @return {@link R} 结果 + */ + @ApiOperation(value = "MQTT推送消息", notes = "根据提供的主题、服务质量等级、保留标志和消息内容推送MQTT消息") + @PostMapping("/sendMessage") + R sendMessage(@ApiParam(value = "推送消息请求参数", required = true) @RequestBody PublishMessageRequest publishMessageRequest); + + /** + * 关闭客户端连接 + * + * @param clientIdentifiers 客户端标识集合 + * @return {@link R} 结果 + */ + @ApiOperation(value = "关闭连接", notes = "关闭指定客户端的连接") + @PostMapping("/close/connection") + R closeConnection(@RequestBody @ApiParam(value = "客户端标识符列表") List clientIdentifiers); +} diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/RemotePublishActorService.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/RemotePublishActorService.java deleted file mode 100644 index a5477e25..00000000 --- a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/RemotePublishActorService.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.mqttsnet.thinglinks.broker.api; - -import com.mqttsnet.thinglinks.broker.api.factory.RemotePublishActorFallbackFactory; -import com.mqttsnet.thinglinks.common.core.constant.ServiceNameConstants; -import com.mqttsnet.thinglinks.common.core.domain.R; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; - -import java.util.List; -import java.util.Map; - -/** - * @Description: Broker推送设备消息 - * @Author: ShiHuan SUN - * @E-mail: 13733918655@163.com - * @Website: http://thinglinks.mqttsnet.com - * @CreateDate: 2022/1/14$ 16:46$ - * @UpdateUser: ShiHuan SUN - * @UpdateDate: 2022/1/14$ 16:46$ - * @UpdateRemark: 修改内容 - * @Version: V1.0 - */ -@FeignClient(contextId = "remotePublishActorService", value = ServiceNameConstants.THINGLINKS_BROKER, fallbackFactory = RemotePublishActorFallbackFactory.class) -public interface RemotePublishActorService { - - /** - * 通知ThingLins MQTT Broker推送消息 - * @param params - * topic topic String 是 - * qos 服务等级 Integer 是 - * retain 保留消息 Boolean 是 - * message 消息 String 是 - * @return - */ - @PostMapping("/publish/sendMessage") - public R sendMessage(@RequestBody Map params); - - - /** - * 通知ThingLins MQTT Broker断开链接 - * @param clientIdentifiers 客户端ID - * @return - */ - @PostMapping("/close/connection") - public R closeConnection(@RequestBody List clientIdentifiers); -} diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/PublishMessageRequest.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/PublishMessageRequest.java new file mode 100644 index 00000000..989f8609 --- /dev/null +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/PublishMessageRequest.java @@ -0,0 +1,53 @@ +package com.mqttsnet.thinglinks.broker.api.domain; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @program: thinglinks + * @description: MQTT 发送消息VO + * @packagename: com.mqttsnet.thinglinks.broker.api.domain + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2024-01-20 19:11 + **/ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "PublishMessageRequestVO", description = "MQTT 发送消息VO") +public class PublishMessageRequest implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "可选的调用者提供的请求ID", example = "1234567890") + private Long reqId; + + @ApiModelProperty(value = "租户ID", required = true, example = "tenant12345") + private String tenantId; + + @ApiModelProperty(value = "消息主题", required = true, example = "exampleTopic") + private String topic; + + @ApiModelProperty(value = "QoS of the message to be distributed", required = true) + private String pubQos; + + @ApiModelProperty(value = "客户端类型", required = true, example = "web") + private String clientType; + + @ApiModelProperty(value = "消息是否应保留", example = "true") + private String retain; + + @ApiModelProperty(value = "关于kicker客户端的元数据头,必须以client_meta_开头", example = "client_meta_exampleKey") + private String clientMeta; + + @ApiModelProperty(value = "payload", required = true) + private String payload; +} diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/BifroMQApiFallback.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/BifroMQApiFallback.java new file mode 100644 index 00000000..285abee8 --- /dev/null +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/BifroMQApiFallback.java @@ -0,0 +1,123 @@ +package com.mqttsnet.thinglinks.broker.api.factory; + +import com.mqttsnet.thinglinks.broker.api.BifroMQApi; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.openfeign.FallbackFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; + +/** + * ----------------------------------------------------------------------------- + * File Name: BifroMQApiFallback.java + * ----------------------------------------------------------------------------- + * Description: + * BifroMQApi API熔断 + * ----------------------------------------------------------------------------- + * + * @author ShiHuan Sun + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + *

+ * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2023-10-31 12:31 + */ +@Slf4j +@Component +public class BifroMQApiFallback implements FallbackFactory { + + @Override + public BifroMQApi create(Throwable throwable) { + log.error("Broker推送设备消息服务调用失败:{}", throwable.getMessage()); + + return new BifroMQApi() { + + /** + * Publish a message to a given topic. + * + * @param reqId Optional caller provided request id. + * @param tenantId The tenant id. + * @param topic The message topic. + * @param clientType The client type. + * @param pubQos QoS of the message to be distributed. + * @param retain The message should be retained. + * @param clientMeta Metadata header about the kicker client. + * @param payload Message payload. + * @return Response indicating success or failure. + */ + @Override + public ResponseEntity publishMessage(Long reqId, String tenantId, String topic, String clientType, String pubQos, String retain, String clientMeta, String payload) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + /** + * Manually expires the inbox based on the provided parameters. + * + * @param reqId Optional caller provided request id. + * @param tenantId The tenant id. + * @param expirySeconds The inbox's expiry time. + * @return ResponseEntity indicating the result of the operation. + */ + @Override + public ResponseEntity expireInbox(Long reqId, String tenantId, String expirySeconds) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + /** + * Disconnects a MQTT client connection based on the provided parameters. + * + * @param reqId Optional caller provided request id. + * @param tenantId The tenant id. + * @param userId The user id of the MQTT client connection to be disconnected. + * @param clientId The client id of the MQTT client connection to be disconnected. + * @param clientType The client type. + * @param clientMeta Metadata header about the kicker client, must start with client_meta_. + * @return ResponseEntity indicating the result of the operation. + */ + @Override + public ResponseEntity killClientConnection(Long reqId, String tenantId, String userId, String clientId, String clientType, String clientMeta) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + + /** + * Adds a topic subscription to an inbox. + * + * @param reqId Optional caller provided request id. + * @param tenantId The tenant id. + * @param topicFilter The topic filter to add. + * @param subQos The QoS of the subscription. + * @param inboxId The inbox for receiving subscribed messages. + * @param delivererKey Deliverer key for subBroker. + * @param subBrokerId The ID of the subbroker hosting the inbox. + * @return ResponseEntity indicating the result of the operation. + */ + @Override + public ResponseEntity addTopicSubscription(Long reqId, String tenantId, String topicFilter, String subQos, String inboxId, String delivererKey, Integer subBrokerId) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + /** + * Removes a topic subscription from an inbox. + * + * @param reqId Optional caller provided request id. + * @param tenantId The tenant id. + * @param topicFilter The topic filter to remove. + * @param inboxId The inbox for receiving subscribed messages. + * @param delivererKey Deliverer key for subBroker. + * @param subBrokerId The ID of the subbroker hosting the inbox. + * @return ResponseEntity indicating the result of the operation. + */ + @Override + public ResponseEntity removeTopicSubscription(Long reqId, String tenantId, String topicFilter, String inboxId, String delivererKey, Integer subBrokerId) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + }; + } + + +} diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/RemoteMqttBrokerOpenApiFallback.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/RemoteMqttBrokerOpenApiFallback.java new file mode 100644 index 00000000..06bf9264 --- /dev/null +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/RemoteMqttBrokerOpenApiFallback.java @@ -0,0 +1,57 @@ +package com.mqttsnet.thinglinks.broker.api.factory; + +import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; +import com.mqttsnet.thinglinks.broker.api.domain.PublishMessageRequest; +import com.mqttsnet.thinglinks.common.core.domain.R; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.openfeign.FallbackFactory; +import org.springframework.stereotype.Component; + +import java.util.List; + +/** + * @Description: MqttBroker-开放接口API 熔断 + * @Author: ShiHuan SUN + * @E-mail: 13733918655@163.com + * @Website: http://thinglinks.mqttsnet.com + * @CreateDate: 2022/1/14$ 16:49$ + * @UpdateUser: ShiHuan SUN + * @UpdateDate: 2023/1/14$ 16:49$ + * @UpdateRemark: 修改内容 + * @Version: V2.0 + */ +@Component +public class RemoteMqttBrokerOpenApiFallback implements FallbackFactory { + private static final Logger log = LoggerFactory.getLogger(RemoteMqttBrokerOpenApiFallback.class); + + @Override + public RemoteMqttBrokerOpenApi create(Throwable throwable) { + log.error("Broker推送设备消息服务调用失败:{}", throwable.getMessage()); + return new RemoteMqttBrokerOpenApi() { + + + /** + * MQTT推送消息接口 + * + * @param publishMessageRequest 推送消息请求参数 + * @return {@link R} 结果 + */ + @Override + public R sendMessage(PublishMessageRequest publishMessageRequest) { + return R.fail("remoteMqttBrokerOpenApi.sendMessage() Service call failure e:{}", throwable.getMessage()); + } + + /** + * 关闭客户端连接 + * + * @param clientIdentifiers 客户端标识集合 + * @return {@link R} 结果 + */ + @Override + public R closeConnection(List clientIdentifiers) { + return R.fail("remoteMqttBrokerOpenApi.closeConnection() Service call failure e:{}", throwable.getMessage()); + } + }; + } +} diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/RemotePublishActorFallbackFactory.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/RemotePublishActorFallbackFactory.java deleted file mode 100644 index 0ccb2ab3..00000000 --- a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/RemotePublishActorFallbackFactory.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.mqttsnet.thinglinks.broker.api.factory; - -import com.mqttsnet.thinglinks.broker.api.RemotePublishActorService; -import com.mqttsnet.thinglinks.common.core.domain.R; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.cloud.openfeign.FallbackFactory; -import org.springframework.stereotype.Component; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; - -import java.util.List; -import java.util.Map; - -/** - * @Description: Broker推送设备消息降级处理 - * @Author: ShiHuan SUN - * @E-mail: 13733918655@163.com - * @Website: http://thinglinks.mqttsnet.com - * @CreateDate: 2022/1/14$ 16:49$ - * @UpdateUser: ShiHuan SUN - * @UpdateDate: 2022/1/14$ 16:49$ - * @UpdateRemark: 修改内容 - * @Version: V1.0 - */ -@Component -public class RemotePublishActorFallbackFactory implements FallbackFactory { - private static final Logger log = LoggerFactory.getLogger(RemotePublishActorFallbackFactory.class); - - @Override - public RemotePublishActorService create(Throwable throwable) { - log.error("Broker推送设备消息服务调用失败:{}", throwable.getMessage()); - return new RemotePublishActorService() { - - - /** - * 通知ThingLins MQTT Broker推送消息 - * - * @param params - * @return - */ - @Override - public R sendMessage(Map params) { - return R.fail("通知ThingLins MQTT Broker推送消息失败:" + throwable.getMessage()); - } - - /** - * 通知ThingLins MQTT Broker断开链接 - * @param clientIdentifiers 客户端ID - * @return - */ - @Override - public R closeConnection(@RequestBody List clientIdentifiers){ - return R.fail("通知ThingLins MQTT Broker推送消息失败:" + throwable.getMessage()); - } - - }; - } -} diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/Constants.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/Constants.java index a27ace2b..d36cb588 100644 --- a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/Constants.java +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/Constants.java @@ -2,11 +2,15 @@ /** * 通用常量信息 - * + * * @author thinglinks */ -public class Constants -{ +public class Constants { + + /** + * 项目前缀 + */ + public static final String PROJECT_PREFIX = "thinglinks"; /** * UTF-8 字符集 */ diff --git a/thinglinks-common/thinglinks-common-kafka/src/main/java/com/mqttsnet/thinglinks/common/kafka/config/KafkaConsumerConfig.java b/thinglinks-common/thinglinks-common-kafka/src/main/java/com/mqttsnet/thinglinks/common/kafka/config/KafkaConsumerConfig.java index 94d4b3be..75f80a52 100644 --- a/thinglinks-common/thinglinks-common-kafka/src/main/java/com/mqttsnet/thinglinks/common/kafka/config/KafkaConsumerConfig.java +++ b/thinglinks-common/thinglinks-common-kafka/src/main/java/com/mqttsnet/thinglinks/common/kafka/config/KafkaConsumerConfig.java @@ -84,13 +84,7 @@ public Map consumerConfigs() { @Bean public ConsumerFactory consumerFactory() { -/* //配置消费者的 Json 反序列化的可信赖包,反序列化实体类需要 - try(JsonDeserializer deserializer = new JsonDeserializer<>()) { - - deserializer.trustedPackages("*"); - return new DefaultKafkaConsumerFactory<>(consumerConfigs(), new JsonDeserializer<>(), deserializer); - }*/ - + //配置消费者的 Json 反序列化的可信赖包,反序列化实体类需要 try (StringDeserializer stringDeserializer = new StringDeserializer()) { return new DefaultKafkaConsumerFactory<>(consumerConfigs(), new StringDeserializer(), stringDeserializer); } @@ -106,10 +100,10 @@ public KafkaListenerContainerFactory producerConfigs() { //反序列化,和生产者的序列化方式对应 props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); - //为生产者分配一个唯一的事务 ID - props.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, UUID.randomUUID().toString()); - return props; } diff --git a/thinglinks-common/thinglinks-common-rocketmq/pom.xml b/thinglinks-common/thinglinks-common-rocketmq/pom.xml index ac17f4ae..be5df8bf 100644 --- a/thinglinks-common/thinglinks-common-rocketmq/pom.xml +++ b/thinglinks-common/thinglinks-common-rocketmq/pom.xml @@ -21,7 +21,7 @@ org.apache.rocketmq rocketmq-spring-boot-starter - 2.2.1 + 2.2.3 diff --git a/thinglinks-modules/thinglinks-modules-broker/pom.xml b/thinglinks-modules/thinglinks-modules-broker/pom.xml index 709d9571..cb072aeb 100644 --- a/thinglinks-modules/thinglinks-modules-broker/pom.xml +++ b/thinglinks-modules/thinglinks-modules-broker/pom.xml @@ -33,12 +33,6 @@ spring-boot-starter-actuator - - - mysql - mysql-connector-java - - com.mqttsnet diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/ThingLinksBrokerApplication.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/ThingLinksBrokerApplication.java index 058e7411..a9ae0cf3 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/ThingLinksBrokerApplication.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/ThingLinksBrokerApplication.java @@ -2,29 +2,25 @@ import com.mqttsnet.thinglinks.common.security.annotation.EnableRyFeignClients; import com.mqttsnet.thinglinks.common.swagger.annotation.EnableCustomSwagger2; -import io.github.quickmsg.starter.config.EnableMqttServer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.CrossOrigin; /** * Broker - * + * * @author thinglinks */ -@EnableMqttServer @EnableCustomSwagger2 @EnableRyFeignClients //实现跨域注解 //origin="*"代表所有域名都可访问 //maxAge飞行前响应的缓存持续时间的最大年龄,简单来说就是Cookie的有效期 单位为秒 //若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失 -@CrossOrigin(origins = "*",maxAge = 3600) +@CrossOrigin(origins = "*", maxAge = 3600) @SpringBootApplication(scanBasePackages = {"com.mqttsnet.thinglinks"}) -public class ThingLinksBrokerApplication -{ - public static void main(String[] args) - { +public class ThingLinksBrokerApplication { + public static void main(String[] args) { SpringApplication.run(ThingLinksBrokerApplication.class, args); System.out.println("(♥◠‿◠)ノ゙ Broker模块启动成功 ლ(´ڡ`ლ)゙ "); } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/ThingLinksLinkApplication.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/ThingLinksLinkApplication.java index dcc432bc..a1653902 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/ThingLinksLinkApplication.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/ThingLinksLinkApplication.java @@ -3,10 +3,8 @@ import com.mqttsnet.thinglinks.common.security.annotation.EnableCustomConfig; import com.mqttsnet.thinglinks.common.security.annotation.EnableRyFeignClients; import com.mqttsnet.thinglinks.common.swagger.annotation.EnableCustomSwagger2; -import com.mqttsnet.thinglinks.link.common.config.ThingLinksBeanDefinitionRegistrar; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Import; import org.springframework.web.bind.annotation.CrossOrigin; /** @@ -23,7 +21,6 @@ //若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失 @CrossOrigin(origins = "*", maxAge = 3600) @SpringBootApplication(scanBasePackages = {"com.mqttsnet.thinglinks"}) -@Import(ThingLinksBeanDefinitionRegistrar.class) public class ThingLinksLinkApplication { public static void main(String[] args) throws Exception { diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/ThingLinksBeanDefinitionRegistrar.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/ThingLinksBeanDefinitionRegistrar.java deleted file mode 100644 index c422bcfa..00000000 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/ThingLinksBeanDefinitionRegistrar.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.mqttsnet.thinglinks.link.common.config; - -import com.mqttsnet.thinglinks.common.core.mqs.SelectorConfig; -import com.mqttsnet.thinglinks.link.common.consumer.kafka.DeviceActionMessageKafkaConsumer; -import com.mqttsnet.thinglinks.link.common.consumer.rocketmq.DeviceActionMessageRocketmqConsumer; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; -import org.springframework.core.env.Environment; -import org.springframework.core.type.AnnotationMetadata; - -@Configuration -class ThingLinksConfiguration { - - @Bean - public ThingLinksBeanDefinitionRegistrar thingLinksBeanDefinitionRegistrar(Environment environment) { - return new ThingLinksBeanDefinitionRegistrar(environment); - } -} - -public class ThingLinksBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { - - private final Environment environment; - - public ThingLinksBeanDefinitionRegistrar(Environment environment) { - this.environment = environment; - } - - @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { - Class beanClass = getConsumerClass(); - String beanName = beanClass.getSimpleName(); - registerBeanDefinition(registry, beanClass, beanName); - } - - private Class getConsumerClass() { - boolean selectorKafka = Boolean.parseBoolean(environment.getProperty(SelectorConfig.selectorKafkaKey, "false")); - return selectorKafka ? DeviceActionMessageKafkaConsumer.class : - DeviceActionMessageRocketmqConsumer.class; - } - - private void registerBeanDefinition(BeanDefinitionRegistry registry, Class beanClass, String beanName) { - AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(beanClass).getBeanDefinition(); - registry.registerBeanDefinition(beanName, beanDefinition); - } -} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceDatasServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceDatasServiceImpl.java index 30a19bbf..64203356 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceDatasServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceDatasServiceImpl.java @@ -6,7 +6,7 @@ import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.JsonPath; -import com.mqttsnet.thinglinks.broker.api.RemotePublishActorService; +import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.common.core.constant.Constants; import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.common.core.dynamicCompilation.ClassInjector; @@ -90,7 +90,7 @@ public class DeviceDatasServiceImpl implements DeviceDatasService { @Autowired private DeviceInfoService deviceInfoService; @Resource - private RemotePublishActorService remotePublishActorService; + private RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi; /** * 数据库名称 */ @@ -190,7 +190,7 @@ public void insertBaseDatas(JSONObject thinglinksMessage) throws Exception { param.put("qos", Integer.valueOf(qos)); param.put("retain", false); param.put("message", payload); - remotePublishActorService.sendMessage(param); + remoteMqttBrokerOpenApi.sendMessage(param); } else if (topic.startsWith("/v1/devices/") && topic.endsWith("/topo/delete")) { final String deviceIdentification = SubStringUtil.subStr(topic, 12, -12); final String payload = this.processingTopoDeleteTopic(deviceIdentification, body); @@ -199,7 +199,7 @@ public void insertBaseDatas(JSONObject thinglinksMessage) throws Exception { param.put("qos", Integer.valueOf(qos)); param.put("retain", false); param.put("message", payload); - remotePublishActorService.sendMessage(param); + remoteMqttBrokerOpenApi.sendMessage(param); } else if (topic.startsWith("/v1/devices/") && topic.endsWith("/topo/update")) { final String deviceIdentification = SubStringUtil.subStr(topic, 12, -12); final String payload = this.processingTopoUpdateTopic(deviceIdentification, body); @@ -208,7 +208,7 @@ public void insertBaseDatas(JSONObject thinglinksMessage) throws Exception { param.put("qos", Integer.valueOf(qos)); param.put("retain", false); param.put("message", payload); - remotePublishActorService.sendMessage(param); + remoteMqttBrokerOpenApi.sendMessage(param); } else if (topic.startsWith("/v1/devices/") && topic.endsWith("/datas")) { final String deviceIdentification = SubStringUtil.subStr(topic, 12, -6); this.processingDatasTopic(deviceIdentification, body); diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java index 865a692f..32638eaf 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java @@ -1,7 +1,7 @@ package com.mqttsnet.thinglinks.link.service.device.impl; import com.alibaba.fastjson.JSON; -import com.mqttsnet.thinglinks.broker.api.RemotePublishActorService; +import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.common.core.constant.Constants; import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatus; @@ -67,7 +67,7 @@ public class DeviceInfoServiceImpl implements DeviceInfoService { private RemoteTdEngineService remoteTdEngineService; @Resource - private RemotePublishActorService remotePublishActorService; + private RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi; @Value("${spring.datasource.dynamic.datasource.master.dbName:thinglinks}") private String dataBaseName; @@ -239,7 +239,7 @@ public int deleteDeviceInfoByIds(Long[] ids) { param.put("qos", 2); param.put("retain", false); param.put("message", JSON.toJSONString(responseMaps)); - remotePublishActorService.sendMessage(param); + remoteMqttBrokerOpenApi.sendMessage(param); } responseMaps.clear(); }); diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java index f0f6b07c..d86eb92a 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java @@ -1,6 +1,6 @@ package com.mqttsnet.thinglinks.link.service.device.impl; -import com.mqttsnet.thinglinks.broker.api.RemotePublishActorService; +import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.common.core.constant.Constants; import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatus; @@ -73,7 +73,7 @@ public class DeviceServiceImpl implements DeviceService { @Autowired private RedisService redisService; @Resource - private RemotePublishActorService remotePublishActorService; + private RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi; @Autowired private DeviceTopicService deviceTopicService; @Autowired @@ -386,7 +386,7 @@ public Boolean disconnect(Long[] ids) { return false; } final List clientIdentifiers = deviceList.stream().map(Device::getClientId).collect(Collectors.toList()); - final R r = remotePublishActorService.closeConnection(clientIdentifiers); + final R r = remoteMqttBrokerOpenApi.closeConnection(clientIdentifiers); log.info("主动断开设备ID: {} 连接 , Broker 处理结果: {}", clientIdentifiers, r.toString()); return r.getCode() == ResultEnum.SUCCESS.getCode(); } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/resources/bootstrap.yml b/thinglinks-modules/thinglinks-modules-link/src/main/resources/bootstrap.yml index 2e53b3d1..296ecf20 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/resources/bootstrap.yml +++ b/thinglinks-modules/thinglinks-modules-link/src/main/resources/bootstrap.yml @@ -35,5 +35,7 @@ spring: refresh: true - dataId: kafka.yml refresh: false + - dataId: rocketmq.yml + refresh: false username: @nacos.username@ password: @nacos.password@ diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/ThingLinksBeanDefinitionRegistrar.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/ThingLinksBeanDefinitionRegistrar.java deleted file mode 100644 index 2208579a..00000000 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/ThingLinksBeanDefinitionRegistrar.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.mqttsnet.thinglinks.tdengine; - -import com.mqttsnet.thinglinks.common.core.mqs.SelectorConfig; -import com.mqttsnet.thinglinks.tdengine.common.consumer.kafka.ProductCreateSuperTableMessageKafkaConsumer; -import com.mqttsnet.thinglinks.tdengine.common.consumer.rocketmq.ProductCreateSuperTableMessageRocketmqConsumer; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; -import org.springframework.core.env.Environment; -import org.springframework.core.type.AnnotationMetadata; - -@Configuration -class ThingLinksConfiguration { - - @Bean - public ThingLinksBeanDefinitionRegistrar thingLinksBeanDefinitionRegistrar(Environment environment) { - return new ThingLinksBeanDefinitionRegistrar(environment); - } -} - -public class ThingLinksBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { - - private final Environment environment; - - public ThingLinksBeanDefinitionRegistrar(Environment environment) { - this.environment = environment; - } - - @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { - Class beanClass = getConsumerClass(); - String beanName = beanClass.getSimpleName(); - registerBeanDefinition(registry, beanClass, beanName); - } - - private Class getConsumerClass() { - boolean selectorKafka = Boolean.parseBoolean(environment.getProperty(SelectorConfig.selectorKafkaKey, "false")); - return selectorKafka ? ProductCreateSuperTableMessageKafkaConsumer.class : - ProductCreateSuperTableMessageRocketmqConsumer.class; - } - - private void registerBeanDefinition(BeanDefinitionRegistry registry, Class beanClass, String beanName) { - AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(beanClass).getBeanDefinition(); - registry.registerBeanDefinition(beanName, beanDefinition); - } -} diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/ThingLinksTdengineApplication.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/ThingLinksTdengineApplication.java index 8ea22252..9ae780ca 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/ThingLinksTdengineApplication.java +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/ThingLinksTdengineApplication.java @@ -18,7 +18,6 @@ //若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失 @CrossOrigin(origins = "*",maxAge = 3600) @SpringBootApplication(scanBasePackages = {"com.mqttsnet.thinglinks"}) -@Import(ThingLinksBeanDefinitionRegistrar.class) public class ThingLinksTdengineApplication { public static void main(String[] args) { diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/bootstrap.yml b/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/bootstrap.yml index bb8ee98c..bc66a993 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/bootstrap.yml +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/bootstrap.yml @@ -33,5 +33,7 @@ spring: refresh: false - dataId: kafka.yml refresh: false + - dataId: rocketmq.yml + refresh: false username: @nacos.username@ password: @nacos.password@ \ No newline at end of file From d2248e3aa82468988cb63f4a96e306b255a95d23 Mon Sep 17 00:00:00 2001 From: xiaonan <13733918655@163.com> Date: Thu, 25 Jan 2024 17:11:54 +0800 Subject: [PATCH 04/35] fix dockerfile --- docker/docker-compose.yml | 192 +++++++++------- thinglinks-auth/Dockerfile | 4 +- thinglinks-gateway/Dockerfile | 8 +- .../thinglinks-modules-broker/Dockerfile | 8 +- .../thinglinks-modules-file/Dockerfile | 8 +- .../thinglinks-modules-gen/Dockerfile | 8 +- .../thinglinks-modules-job/Dockerfile | 8 +- .../thinglinks-modules-link/Dockerfile | 8 +- .../thinglinks-modules-link/pom.xml | 211 +++++++++--------- .../src/main/resources/bootstrap.yml | 2 - .../Dockerfile | 8 +- .../thinglinks-modules-rule/Dockerfile | 8 +- .../thinglinks-modules-system/Dockerfile | 8 +- .../thinglinks-modules-tdengine/Dockerfile | 8 +- .../thinglinks-modules-tdengine/pom.xml | 7 - .../src/main/resources/bootstrap.yml | 2 - .../thinglinks-visual-monitor/Dockerfile | 8 +- 17 files changed, 255 insertions(+), 251 deletions(-) diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 5ca41a61..3215020e 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -11,8 +11,18 @@ x-metadata-config: &metadata-config community: "mqttsnet" copyright: "Copyright © 2023 mqttsnet" -# 共享配置 -x-common-config: &common-config +# 共享环境配置 +x-env-config: &env-config + TZ: Asia/Shanghai + SPRING_PROFILES_ACTIVE: test + NACOS_IP: 127.0.0.1 + NACOS_PORT: 18848 + NACOS_NAMESPACE: c0858b2e-960e-47b9-9b2d-17294dda787c + NACOS_USERNAME: thinglinks-test + NACOS_PASSWORD: 12345678 + +# 共享卷和网络配置 +x-shared-config: &shared-config environment: - TZ=Asia/Shanghai volumes: @@ -30,195 +40,207 @@ x-common-config: &common-config # 服务定义 services: - thinglinks-base: - container_name: thinglinks-base-server + thinglinks-auth: + container_name: thinglinks-auth build: - context: ../thinglinks-base/thinglinks-base-server + context: ../thinglinks-auth dockerfile: Dockerfile ports: - - "18764:18764" # 映射端口 + - "19200:19200" # 映射端口 environment: - - SERVICE_PORT=18764 + <<: *env-config + SERVICE_PORT: 19200 healthcheck: - test: [ "CMD", "curl", "-f", "http://localhost:18764/actuator/health" ] + test: [ "CMD", "curl", "-f", "http://localhost:19200/actuator/health" ] interval: 30s timeout: 10s retries: 5 start_period: 60s - <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 - thinglinks-broker: - container_name: thinglinks-broker-server + <<: *shared-config # 只引用 shared-config,因为 metadata-config 不应用于服务定义 + thinglinks-gateway: + container_name: thinglinks-gateway build: - context: ../thinglinks-broker/thinglinks-broker-server + context: ../thinglinks-gateway dockerfile: Dockerfile ports: - - "18790:18790" + - "19100:19100" environment: - - SERVICE_PORT=18790 + <<: *env-config + SERVICE_PORT: 19100 healthcheck: - test: [ "CMD", "curl", "-f", "http://localhost:18790/actuator/health" ] + test: [ "CMD", "curl", "-f", "http://localhost:19100/actuator/health" ] interval: 30s timeout: 10s retries: 5 start_period: 60s - <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 - thinglinks-gateway: - container_name: thinglinks-gateway-server + <<: *shared-config # 只引用 shared-config,因为 metadata-config 不应用于服务定义 + thinglinks-broker: + container_name: thinglinks-modules-broker build: - context: ../thinglinks-gateway/thinglinks-gateway-server + context: ../thinglinks-modules/thinglinks-modules-broker dockerfile: Dockerfile ports: - - "18760:18760" + - "19306:19306" environment: - - SERVICE_PORT=18760 + <<: *env-config + SERVICE_PORT: 19306 healthcheck: - test: [ "CMD", "curl", "-f", "http://localhost:18760/actuator/health" ] + test: [ "CMD", "curl", "-f", "http://localhost:19306/actuator/health" ] interval: 30s timeout: 10s retries: 5 start_period: 60s - <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 - thinglinks-generator: - container_name: thinglinks-generator-server + <<: *shared-config # 只引用 shared-config,因为 metadata-config 不应用于服务定义 + thinglinks-file: + container_name: thinglinks-modules-file build: - context: ../thinglinks-generator/thinglinks-generator-server + context: ../thinglinks-modules/thinglinks-modules-file dockerfile: Dockerfile ports: - - "18780:18780" + - "19300:19300" environment: - - SERVICE_PORT=18780 + <<: *env-config + SERVICE_PORT: 19300 healthcheck: - test: [ "CMD", "curl", "-f", "http://localhost:18780/actuator/health" ] + test: [ "CMD", "curl", "-f", "http://localhost:19300/actuator/health" ] interval: 30s timeout: 10s retries: 5 start_period: 60s - <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 - thinglinks-link: - container_name: thinglinks-link-server + <<: *shared-config # 只引用 shared-config,因为 metadata-config 不应用于服务定义 + thinglinks-gen: + container_name: thinglinks-modules-gen build: - context: ../thinglinks-link/thinglinks-link-server + context: ../thinglinks-modules/thinglinks-modules-gen dockerfile: Dockerfile ports: - - "18782:18782" + - "19301:19301" environment: - - SERVICE_PORT=18782 + <<: *env-config + SERVICE_PORT: 19301 healthcheck: - test: [ "CMD", "curl", "-f", "http://localhost:18782/actuator/health" ] + test: [ "CMD", "curl", "-f", "http://localhost:19301/actuator/health" ] interval: 30s timeout: 10s retries: 5 start_period: 60s - <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 - thinglinks-mqs: - container_name: thinglinks-mqs-server + <<: *shared-config # 只引用 shared-config,因为 metadata-config 不应用于服务定义 + thinglinks-job: + container_name: thinglinks-modules-job build: - context: ../thinglinks-mqs/thinglinks-mqs-server + context: ../thinglinks-modules/thinglinks-modules-job dockerfile: Dockerfile ports: - - "18784:18784" + - "19302:19302" environment: - - SERVICE_PORT=18784 + <<: *env-config + SERVICE_PORT: 19302 healthcheck: - test: [ "CMD", "curl", "-f", "http://localhost:18784/actuator/health" ] + test: [ "CMD", "curl", "-f", "http://localhost:19302/actuator/health" ] interval: 30s timeout: 10s retries: 5 start_period: 60s - <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 - thinglinks-oauth: - container_name: thinglinks-oauth-server + <<: *shared-config # 只引用 shared-config,因为 metadata-config 不应用于服务定义 + thinglinks-link: + container_name: thinglinks-modules-link build: - context: ../thinglinks-oauth/thinglinks-oauth-server + context: ../thinglinks-modules/thinglinks-modules-link dockerfile: Dockerfile ports: - - "18773:18773" + - "19305:19305" environment: - - SERVICE_PORT=18773 + <<: *env-config + SERVICE_PORT: 19305 healthcheck: - test: [ "CMD", "curl", "-f", "http://localhost:18773/actuator/health" ] + test: [ "CMD", "curl", "-f", "http://localhost:19305/actuator/health" ] interval: 30s timeout: 10s retries: 5 start_period: 60s - <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 - thinglinks-rule: - container_name: thinglinks-rule-server + <<: *shared-config # 只引用 shared-config,因为 metadata-config 不应用于服务定义 + thinglinks-protocolAnalysis: + container_name: thinglinks-modules-protocolAnalysis build: - context: ../thinglinks-rule/thinglinks-rule-server + context: ../thinglinks-modules/thinglinks-modules-protocolAnalysis dockerfile: Dockerfile ports: - - "18786:18786" + - "19307:19307" environment: - - SERVICE_PORT=18786 + <<: *env-config + SERVICE_PORT: 19307 healthcheck: - test: [ "CMD", "curl", "-f", "http://localhost:18786/actuator/health" ] + test: [ "CMD", "curl", "-f", "http://localhost:19307/actuator/health" ] interval: 30s timeout: 10s retries: 5 start_period: 60s - <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 - thinglinks-monitor: - container_name: thinglinks-monitor-server + <<: *shared-config # 只引用 shared-config,因为 metadata-config 不应用于服务定义 + thinglinks-rule: + container_name: thinglinks-modules-rule build: - context: ../thinglinks-support/thinglinks-monitor-server + context: ../thinglinks-modules/thinglinks-modules-rule dockerfile: Dockerfile ports: - - "18762:18762" + - "19308:19308" environment: - - SERVICE_PORT=18762 + <<: *env-config + SERVICE_PORT: 19308 healthcheck: - test: [ "CMD", "curl", "-f", "http://localhost:18762/actuator/health" ] + test: [ "CMD", "curl", "-f", "http://localhost:19308/actuator/health" ] interval: 30s timeout: 10s retries: 5 start_period: 60s - <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 + <<: *shared-config # 只引用 shared-config,因为 metadata-config 不应用于服务定义 thinglinks-system: - container_name: thinglinks-system-server + container_name: thinglinks-modules-system build: - context: ../thinglinks-system/thinglinks-system-server + context: ../thinglinks-modules/thinglinks-modules-system dockerfile: Dockerfile ports: - - "18778:18778" + - "19303:19303" environment: - - SERVICE_PORT=18778 + <<: *env-config + SERVICE_PORT: 19303 healthcheck: - test: [ "CMD", "curl", "-f", "http://localhost:18778/actuator/health" ] + test: [ "CMD", "curl", "-f", "http://localhost:19303/actuator/health" ] interval: 30s timeout: 10s retries: 5 start_period: 60s - <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 - thinglinks-tds: - container_name: thinglinks-tds-server + <<: *shared-config # 只引用 shared-config,因为 metadata-config 不应用于服务定义 + thinglinks-tdengine: + container_name: thinglinks-modules-tdengine build: - context: ../thinglinks-tds/thinglinks-tds-server + context: ../thinglinks-modules/thinglinks-modules-tdengine dockerfile: Dockerfile ports: - - "18788:18788" + - "19304:19304" environment: - - SERVICE_PORT=18788 + <<: *env-config + SERVICE_PORT: 19304 healthcheck: - test: [ "CMD", "curl", "-f", "http://localhost:18788/actuator/health" ] + test: [ "CMD", "curl", "-f", "http://localhost:19304/actuator/health" ] interval: 30s timeout: 10s retries: 5 start_period: 60s - <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 - thinglinks-view: - container_name: thinglinks-view-server + <<: *shared-config # 只引用 shared-config,因为 metadata-config 不应用于服务定义 + thinglinks-monitor: + container_name: thinglinks-visual-monitor build: - context: ../thinglinks-view/thinglinks-view-server + context: ../thinglinks-visual/thinglinks-visual-monitor dockerfile: Dockerfile ports: - - "18792:18792" + - "19400:19400" environment: - - SERVICE_PORT=18792 + <<: *env-config + SERVICE_PORT: 19400 healthcheck: - test: [ "CMD", "curl", "-f", "http://localhost:18792/actuator/health" ] + test: [ "CMD", "curl", "-f", "http://localhost:19400/actuator/health" ] interval: 30s timeout: 10s retries: 5 start_period: 60s - <<: *common-config # 只引用 common-config,因为 metadata-config 不应用于服务定义 \ No newline at end of file + <<: *shared-config # 只引用 shared-config,因为 metadata-config 不应用于服务定义 \ No newline at end of file diff --git a/thinglinks-auth/Dockerfile b/thinglinks-auth/Dockerfile index bbdcafd6..aff2d01d 100644 --- a/thinglinks-auth/Dockerfile +++ b/thinglinks-auth/Dockerfile @@ -9,10 +9,10 @@ ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 创建工作目录 -WORKDIR /home/www/mqttsnet/thinglinks-broker +WORKDIR /home/www/mqttsnet/thinglinks-auth # 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 -COPY target/thinglinks-auth-server.jar /app.jar +COPY target/thinglinks-auth.jar /app.jar # 暴露服务端口 EXPOSE 19200 diff --git a/thinglinks-gateway/Dockerfile b/thinglinks-gateway/Dockerfile index bbdcafd6..e752c35f 100644 --- a/thinglinks-gateway/Dockerfile +++ b/thinglinks-gateway/Dockerfile @@ -9,17 +9,17 @@ ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 创建工作目录 -WORKDIR /home/www/mqttsnet/thinglinks-broker +WORKDIR /home/www/mqttsnet/thinglinks-gateway # 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 -COPY target/thinglinks-auth-server.jar /app.jar +COPY target/thinglinks-gateway.jar /app.jar # 暴露服务端口 -EXPOSE 19200 +EXPOSE 19100 # 添加健康检查,确保应用健康状态 HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ - CMD curl -f http://localhost:19200/actuator/health || exit 1 + CMD curl -f http://localhost:19100/actuator/health || exit 1 # 启动 Java 应用 ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-broker/Dockerfile b/thinglinks-modules/thinglinks-modules-broker/Dockerfile index bbdcafd6..a15756ed 100644 --- a/thinglinks-modules/thinglinks-modules-broker/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-broker/Dockerfile @@ -9,17 +9,17 @@ ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 创建工作目录 -WORKDIR /home/www/mqttsnet/thinglinks-broker +WORKDIR /home/www/mqttsnet/thinglinks-modules-broker # 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 -COPY target/thinglinks-auth-server.jar /app.jar +COPY target/thinglinks-modules-broker.jar /app.jar # 暴露服务端口 -EXPOSE 19200 +EXPOSE 19306 # 添加健康检查,确保应用健康状态 HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ - CMD curl -f http://localhost:19200/actuator/health || exit 1 + CMD curl -f http://localhost:19306/actuator/health || exit 1 # 启动 Java 应用 ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-file/Dockerfile b/thinglinks-modules/thinglinks-modules-file/Dockerfile index bbdcafd6..bc8b52d6 100644 --- a/thinglinks-modules/thinglinks-modules-file/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-file/Dockerfile @@ -9,17 +9,17 @@ ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 创建工作目录 -WORKDIR /home/www/mqttsnet/thinglinks-broker +WORKDIR /home/www/mqttsnet/thinglinks-modules-file # 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 -COPY target/thinglinks-auth-server.jar /app.jar +COPY target/thinglinks-modules-file.jar /app.jar # 暴露服务端口 -EXPOSE 19200 +EXPOSE 19300 # 添加健康检查,确保应用健康状态 HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ - CMD curl -f http://localhost:19200/actuator/health || exit 1 + CMD curl -f http://localhost:19300/actuator/health || exit 1 # 启动 Java 应用 ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-gen/Dockerfile b/thinglinks-modules/thinglinks-modules-gen/Dockerfile index bbdcafd6..9cfd022a 100644 --- a/thinglinks-modules/thinglinks-modules-gen/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-gen/Dockerfile @@ -9,17 +9,17 @@ ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 创建工作目录 -WORKDIR /home/www/mqttsnet/thinglinks-broker +WORKDIR /home/www/mqttsnet/thinglinks-modules-gen # 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 -COPY target/thinglinks-auth-server.jar /app.jar +COPY target/thinglinks-modules-gen.jar /app.jar # 暴露服务端口 -EXPOSE 19200 +EXPOSE 19301 # 添加健康检查,确保应用健康状态 HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ - CMD curl -f http://localhost:19200/actuator/health || exit 1 + CMD curl -f http://localhost:19301/actuator/health || exit 1 # 启动 Java 应用 ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-job/Dockerfile b/thinglinks-modules/thinglinks-modules-job/Dockerfile index bbdcafd6..929d5563 100644 --- a/thinglinks-modules/thinglinks-modules-job/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-job/Dockerfile @@ -9,17 +9,17 @@ ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 创建工作目录 -WORKDIR /home/www/mqttsnet/thinglinks-broker +WORKDIR /home/www/mqttsnet/thinglinks-modules-job # 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 -COPY target/thinglinks-auth-server.jar /app.jar +COPY target/thinglinks-modules-job.jar /app.jar # 暴露服务端口 -EXPOSE 19200 +EXPOSE 19302 # 添加健康检查,确保应用健康状态 HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ - CMD curl -f http://localhost:19200/actuator/health || exit 1 + CMD curl -f http://localhost:19302/actuator/health || exit 1 # 启动 Java 应用 ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-link/Dockerfile b/thinglinks-modules/thinglinks-modules-link/Dockerfile index bbdcafd6..c146a54c 100644 --- a/thinglinks-modules/thinglinks-modules-link/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-link/Dockerfile @@ -9,17 +9,17 @@ ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 创建工作目录 -WORKDIR /home/www/mqttsnet/thinglinks-broker +WORKDIR /home/www/mqttsnet/thinglinks-modules-link # 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 -COPY target/thinglinks-auth-server.jar /app.jar +COPY target/thinglinks-modules-link.jar /app.jar # 暴露服务端口 -EXPOSE 19200 +EXPOSE 19305 # 添加健康检查,确保应用健康状态 HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ - CMD curl -f http://localhost:19200/actuator/health || exit 1 + CMD curl -f http://localhost:19305/actuator/health || exit 1 # 启动 Java 应用 ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-link/pom.xml b/thinglinks-modules/thinglinks-modules-link/pom.xml index 37064b9a..d98de5f8 100644 --- a/thinglinks-modules/thinglinks-modules-link/pom.xml +++ b/thinglinks-modules/thinglinks-modules-link/pom.xml @@ -80,13 +80,6 @@ ${thinglinks.version} - - - com.mqttsnet - thinglinks-common-kafka - ${thinglinks.version} - - com.mqttsnet @@ -156,110 +149,110 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/resources/bootstrap.yml b/thinglinks-modules/thinglinks-modules-link/src/main/resources/bootstrap.yml index 296ecf20..6be2c6c2 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/resources/bootstrap.yml +++ b/thinglinks-modules/thinglinks-modules-link/src/main/resources/bootstrap.yml @@ -33,8 +33,6 @@ spring: refresh: false - dataId: database.yml refresh: true - - dataId: kafka.yml - refresh: false - dataId: rocketmq.yml refresh: false username: @nacos.username@ diff --git a/thinglinks-modules/thinglinks-modules-protocolAnalysis/Dockerfile b/thinglinks-modules/thinglinks-modules-protocolAnalysis/Dockerfile index bbdcafd6..3dd28467 100644 --- a/thinglinks-modules/thinglinks-modules-protocolAnalysis/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-protocolAnalysis/Dockerfile @@ -9,17 +9,17 @@ ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 创建工作目录 -WORKDIR /home/www/mqttsnet/thinglinks-broker +WORKDIR /home/www/mqttsnet/thinglinks-modules-protocolAnalysis # 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 -COPY target/thinglinks-auth-server.jar /app.jar +COPY target/thinglinks-modules-protocolAnalysis.jar /app.jar # 暴露服务端口 -EXPOSE 19200 +EXPOSE 19307 # 添加健康检查,确保应用健康状态 HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ - CMD curl -f http://localhost:19200/actuator/health || exit 1 + CMD curl -f http://localhost:19307/actuator/health || exit 1 # 启动 Java 应用 ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-rule/Dockerfile b/thinglinks-modules/thinglinks-modules-rule/Dockerfile index bbdcafd6..b127d225 100644 --- a/thinglinks-modules/thinglinks-modules-rule/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-rule/Dockerfile @@ -9,17 +9,17 @@ ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 创建工作目录 -WORKDIR /home/www/mqttsnet/thinglinks-broker +WORKDIR /home/www/mqttsnet/thinglinks-modules-rule # 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 -COPY target/thinglinks-auth-server.jar /app.jar +COPY target/thinglinks-modules-rule.jar /app.jar # 暴露服务端口 -EXPOSE 19200 +EXPOSE 19308 # 添加健康检查,确保应用健康状态 HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ - CMD curl -f http://localhost:19200/actuator/health || exit 1 + CMD curl -f http://localhost:19308/actuator/health || exit 1 # 启动 Java 应用 ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-system/Dockerfile b/thinglinks-modules/thinglinks-modules-system/Dockerfile index bbdcafd6..cdcc35ae 100644 --- a/thinglinks-modules/thinglinks-modules-system/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-system/Dockerfile @@ -9,17 +9,17 @@ ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 创建工作目录 -WORKDIR /home/www/mqttsnet/thinglinks-broker +WORKDIR /home/www/mqttsnet/thinglinks-modules-system # 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 -COPY target/thinglinks-auth-server.jar /app.jar +COPY target/thinglinks-modules-system.jar /app.jar # 暴露服务端口 -EXPOSE 19200 +EXPOSE 19303 # 添加健康检查,确保应用健康状态 HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ - CMD curl -f http://localhost:19200/actuator/health || exit 1 + CMD curl -f http://localhost:19303/actuator/health || exit 1 # 启动 Java 应用 ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-tdengine/Dockerfile b/thinglinks-modules/thinglinks-modules-tdengine/Dockerfile index bbdcafd6..4d6a6f95 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/Dockerfile +++ b/thinglinks-modules/thinglinks-modules-tdengine/Dockerfile @@ -9,17 +9,17 @@ ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 创建工作目录 -WORKDIR /home/www/mqttsnet/thinglinks-broker +WORKDIR /home/www/mqttsnet/thinglinks-modules-tdengine # 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 -COPY target/thinglinks-auth-server.jar /app.jar +COPY target/thinglinks-modules-tdengine.jar /app.jar # 暴露服务端口 -EXPOSE 19200 +EXPOSE 19304 # 添加健康检查,确保应用健康状态 HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ - CMD curl -f http://localhost:19200/actuator/health || exit 1 + CMD curl -f http://localhost:19304/actuator/health || exit 1 # 启动 Java 应用 ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/thinglinks-modules/thinglinks-modules-tdengine/pom.xml b/thinglinks-modules/thinglinks-modules-tdengine/pom.xml index 6ec1687b..2c871a90 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/pom.xml +++ b/thinglinks-modules/thinglinks-modules-tdengine/pom.xml @@ -86,13 +86,6 @@ ${thinglinks.version} - - - com.mqttsnet - thinglinks-common-kafka - ${thinglinks.version} - - com.mqttsnet diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/bootstrap.yml b/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/bootstrap.yml index bc66a993..d375112f 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/bootstrap.yml +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/bootstrap.yml @@ -31,8 +31,6 @@ spring: refresh: true - dataId: redis.yml refresh: false - - dataId: kafka.yml - refresh: false - dataId: rocketmq.yml refresh: false username: @nacos.username@ diff --git a/thinglinks-visual/thinglinks-visual-monitor/Dockerfile b/thinglinks-visual/thinglinks-visual-monitor/Dockerfile index bbdcafd6..23bdce89 100644 --- a/thinglinks-visual/thinglinks-visual-monitor/Dockerfile +++ b/thinglinks-visual/thinglinks-visual-monitor/Dockerfile @@ -9,17 +9,17 @@ ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 创建工作目录 -WORKDIR /home/www/mqttsnet/thinglinks-broker +WORKDIR /home/www/mqttsnet/thinglinks-visual-monitor # 从构建上下文(Dockerfile 所在目录的相对路径)复制 JAR 文件 -COPY target/thinglinks-auth-server.jar /app.jar +COPY target/thinglinks-visual-monitor.jar /app.jar # 暴露服务端口 -EXPOSE 19200 +EXPOSE 19400 # 添加健康检查,确保应用健康状态 HEALTHCHECK --interval=30s --timeout=30s --retries=3 \ - CMD curl -f http://localhost:19200/actuator/health || exit 1 + CMD curl -f http://localhost:19400/actuator/health || exit 1 # 启动 Java 应用 ENTRYPOINT ["java", "-Xmx512m", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] From 61f3d40b24686b075d7b9b910227c325005f304e Mon Sep 17 00:00:00 2001 From: xiaonan <13733918655@163.com> Date: Thu, 25 Jan 2024 17:16:13 +0800 Subject: [PATCH 05/35] =?UTF-8?q?Revert=20"fix=EF=BC=9A=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E4=BB=A3=E7=90=86=E5=9C=B0=E5=9D=80"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit a408ac66c12cddb1013bc05532386d4b7f4d3943. --- .../.env_20221121185243.development | 11 -- .../.env_20231012170233.development | 12 -- .../.env_20231012170414.development | 12 -- .../.env_20231012173152.development | 12 -- .../vue.config_20231012165327.js | 126 ------------------ .../vue.config_20231012170036.js | 125 ----------------- .../vue.config_20231012170400.js | 125 ----------------- .../vue.config_20231012170401.js | 125 ----------------- .../vue.config_20231012170409.js | 125 ----------------- thinglinks-ui/.env.development | 3 +- thinglinks-ui/vue.config.js | 7 +- 11 files changed, 5 insertions(+), 678 deletions(-) delete mode 100644 .history/thinglinks-ui/.env_20221121185243.development delete mode 100644 .history/thinglinks-ui/.env_20231012170233.development delete mode 100644 .history/thinglinks-ui/.env_20231012170414.development delete mode 100644 .history/thinglinks-ui/.env_20231012173152.development delete mode 100644 .history/thinglinks-ui/vue.config_20231012165327.js delete mode 100644 .history/thinglinks-ui/vue.config_20231012170036.js delete mode 100644 .history/thinglinks-ui/vue.config_20231012170400.js delete mode 100644 .history/thinglinks-ui/vue.config_20231012170401.js delete mode 100644 .history/thinglinks-ui/vue.config_20231012170409.js diff --git a/.history/thinglinks-ui/.env_20221121185243.development b/.history/thinglinks-ui/.env_20221121185243.development deleted file mode 100644 index ab110dcc..00000000 --- a/.history/thinglinks-ui/.env_20221121185243.development +++ /dev/null @@ -1,11 +0,0 @@ -# 页面标题 -VUE_APP_TITLE = ThingLinks物联网一体化平台 - -# 开发环境配置 -ENV = 'development' - -# ThingLinks物联网一体化平台/开发环境 -VUE_APP_BASE_API = '/dev-api' - -# 路由懒加载 -VUE_CLI_BABEL_TRANSPILE_MODULES = true diff --git a/.history/thinglinks-ui/.env_20231012170233.development b/.history/thinglinks-ui/.env_20231012170233.development deleted file mode 100644 index dff48828..00000000 --- a/.history/thinglinks-ui/.env_20231012170233.development +++ /dev/null @@ -1,12 +0,0 @@ -# 页面标题 -VUE_APP_TITLE = ThingLinks物联网一体化平台 - -# 开发环境配置 -ENV = 'development' - -# ThingLinks物联网一体化平台/开发环境 -#VUE_APP_BASE_API = '/dev-api' -VUE_APP_BASE_API = '/prod-api' - -# 路由懒加载 -VUE_CLI_BABEL_TRANSPILE_MODULES = true diff --git a/.history/thinglinks-ui/.env_20231012170414.development b/.history/thinglinks-ui/.env_20231012170414.development deleted file mode 100644 index 20456fbf..00000000 --- a/.history/thinglinks-ui/.env_20231012170414.development +++ /dev/null @@ -1,12 +0,0 @@ -# 页面标题 -VUE_APP_TITLE = ThingLinks物联网一体化平台 - -# 开发环境配置 -ENV = 'development' - -# ThingLinks物联网一体化平台/开发环境 -#VUE_APP_BASE_API = '/dev-api' -VUE_APP_BASE_API = '/' - -# 路由懒加载 -VUE_CLI_BABEL_TRANSPILE_MODULES = true diff --git a/.history/thinglinks-ui/.env_20231012173152.development b/.history/thinglinks-ui/.env_20231012173152.development deleted file mode 100644 index 20456fbf..00000000 --- a/.history/thinglinks-ui/.env_20231012173152.development +++ /dev/null @@ -1,12 +0,0 @@ -# 页面标题 -VUE_APP_TITLE = ThingLinks物联网一体化平台 - -# 开发环境配置 -ENV = 'development' - -# ThingLinks物联网一体化平台/开发环境 -#VUE_APP_BASE_API = '/dev-api' -VUE_APP_BASE_API = '/' - -# 路由懒加载 -VUE_CLI_BABEL_TRANSPILE_MODULES = true diff --git a/.history/thinglinks-ui/vue.config_20231012165327.js b/.history/thinglinks-ui/vue.config_20231012165327.js deleted file mode 100644 index b29d553c..00000000 --- a/.history/thinglinks-ui/vue.config_20231012165327.js +++ /dev/null @@ -1,126 +0,0 @@ -'use strict' -const path = require('path') - -function resolve(dir) { - return path.join(__dirname, dir) -} - -const name = process.env.VUE_APP_TITLE || 'ThingLinks物联网一体化平台' // 网页标题 - -const port = process.env.port || process.env.npm_config_port || 3000 // 端口 - -// vue.config.js 配置说明 -//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions -// 这里只列一部分,具体配置参考文档 -module.exports = { - // 部署生产环境和开发环境下的URL。 - // 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上 - // 例如 https://thinglinks.mqttsnet.com/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://thinglinks.mqttsnet.com/admin/,则设置 baseUrl 为 /admin/。 - publicPath: process.env.NODE_ENV === "production" ? "/" : "/", - // 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist) - outputDir: 'dist', - // 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下) - assetsDir: 'static', - // 是否开启eslint保存检测,有效值:ture | false | 'error' - lintOnSave: process.env.NODE_ENV === 'development', - // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。 - productionSourceMap: false, - // webpack-dev-server 相关配置 - devServer: { - host: '127.0.0.1', - port: port, - open: true, - proxy: { - // detail: https://cli.vuejs.org/config/#devserver-proxy - [process.env.VUE_APP_BASE_API]: { - target: `http://localhost:19100`, - // target: `http://124.223.113.139:19100`, - changeOrigin: true, - pathRewrite: { - ['^' + process.env.VUE_APP_BASE_API]: '' - } - }, - [process.env.VUE_APP_BASE_SOCKETIP]: { - target: `ws://localhost:19100`, - // target: `ws://frp1.xiaonannet.com:6901`, - changeOrigin: true, - pathRewrite: { - ['^' + process.env.VUE_APP_BASE_SOCKETIP]: '' - } - } - }, - disableHostCheck: true - }, - configureWebpack: { - name: name, - resolve: { - alias: { - '@': resolve('src') - } - } - }, - chainWebpack(config) { - config.plugins.delete('preload') // TODO: need test - config.plugins.delete('prefetch') // TODO: need test - - // set svg-sprite-loader - config.module - .rule('svg') - .exclude.add(resolve('src/assets/icons')) - .end() - config.module - .rule('icons') - .test(/\.svg$/) - .include.add(resolve('src/assets/icons')) - .end() - .use('svg-sprite-loader') - .loader('svg-sprite-loader') - .options({ - symbolId: 'icon-[name]' - }) - .end() - - config - .when(process.env.NODE_ENV !== 'development', - config => { - config - .plugin('ScriptExtHtmlWebpackPlugin') - .after('html') - .use('script-ext-html-webpack-plugin', [{ - // `runtime` must same as runtimeChunk name. default is `runtime` - inline: /runtime\..*\.js$/ - }]) - .end() - config - .optimization.splitChunks({ - chunks: 'all', - cacheGroups: { - libs: { - name: 'chunk-libs', - test: /[\\/]node_modules[\\/]/, - priority: 10, - chunks: 'initial' // only package third parties that are initially dependent - }, - elementUI: { - name: 'chunk-elementUI', // split elementUI into a single package - priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app - test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm - }, - commons: { - name: 'chunk-commons', - test: resolve('src/components'), // can customize your rules - minChunks: 3, // minimum common number - priority: 5, - reuseExistingChunk: true - } - } - }) - config.optimization.runtimeChunk('single'), - { - from: path.resolve(__dirname, './public/robots.txt'), //防爬虫文件 - to: './', //到根目录下 - } - } - ) - } -} diff --git a/.history/thinglinks-ui/vue.config_20231012170036.js b/.history/thinglinks-ui/vue.config_20231012170036.js deleted file mode 100644 index 29f4f75b..00000000 --- a/.history/thinglinks-ui/vue.config_20231012170036.js +++ /dev/null @@ -1,125 +0,0 @@ -'use strict' -const path = require('path') - -function resolve(dir) { - return path.join(__dirname, dir) -} - -const name = process.env.VUE_APP_TITLE || 'ThingLinks物联网一体化平台' // 网页标题 - -const port = process.env.port || process.env.npm_config_port || 3000 // 端口 - -// vue.config.js 配置说明 -//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions -// 这里只列一部分,具体配置参考文档 -module.exports = { - // 部署生产环境和开发环境下的URL。 - // 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上 - // 例如 https://thinglinks.mqttsnet.com/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://thinglinks.mqttsnet.com/admin/,则设置 baseUrl 为 /admin/。 - publicPath: process.env.NODE_ENV === "production" ? "/" : "/", - // 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist) - outputDir: 'dist', - // 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下) - assetsDir: 'static', - // 是否开启eslint保存检测,有效值:ture | false | 'error' - lintOnSave: process.env.NODE_ENV === 'development', - // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。 - productionSourceMap: false, - // webpack-dev-server 相关配置 - devServer: { - host: '127.0.0.1', - port: port, - open: true, - proxy: { - // detail: https://cli.vuejs.org/config/#devserver-proxy - [process.env.VUE_APP_BASE_API]: { - // target: `http://localhost:19100`, - target: `http://thinglinks.mqttsnet.com`, - changeOrigin: true, - pathRewrite: { - ['^' + process.env.VUE_APP_BASE_API]: '' - } - }, - [process.env.VUE_APP_BASE_SOCKETIP]: { - target: `ws://localhost:19100`, - // target: `ws://frp1.xiaonannet.com:6901`, - changeOrigin: true, - pathRewrite: { - ['^' + process.env.VUE_APP_BASE_SOCKETIP]: '' - } - } - }, - disableHostCheck: true - }, - configureWebpack: { - name: name, - resolve: { - alias: { - '@': resolve('src') - } - } - }, - chainWebpack(config) { - config.plugins.delete('preload') // TODO: need test - config.plugins.delete('prefetch') // TODO: need test - - // set svg-sprite-loader - config.module - .rule('svg') - .exclude.add(resolve('src/assets/icons')) - .end() - config.module - .rule('icons') - .test(/\.svg$/) - .include.add(resolve('src/assets/icons')) - .end() - .use('svg-sprite-loader') - .loader('svg-sprite-loader') - .options({ - symbolId: 'icon-[name]' - }) - .end() - - config - .when(process.env.NODE_ENV !== 'development', - config => { - config - .plugin('ScriptExtHtmlWebpackPlugin') - .after('html') - .use('script-ext-html-webpack-plugin', [{ - // `runtime` must same as runtimeChunk name. default is `runtime` - inline: /runtime\..*\.js$/ - }]) - .end() - config - .optimization.splitChunks({ - chunks: 'all', - cacheGroups: { - libs: { - name: 'chunk-libs', - test: /[\\/]node_modules[\\/]/, - priority: 10, - chunks: 'initial' // only package third parties that are initially dependent - }, - elementUI: { - name: 'chunk-elementUI', // split elementUI into a single package - priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app - test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm - }, - commons: { - name: 'chunk-commons', - test: resolve('src/components'), // can customize your rules - minChunks: 3, // minimum common number - priority: 5, - reuseExistingChunk: true - } - } - }) - config.optimization.runtimeChunk('single'), { - from: path.resolve(__dirname, './public/robots.txt'), //防爬虫文件 - to: './', //到根目录下 - } - } - ) - } -} diff --git a/.history/thinglinks-ui/vue.config_20231012170400.js b/.history/thinglinks-ui/vue.config_20231012170400.js deleted file mode 100644 index 29f4f75b..00000000 --- a/.history/thinglinks-ui/vue.config_20231012170400.js +++ /dev/null @@ -1,125 +0,0 @@ -'use strict' -const path = require('path') - -function resolve(dir) { - return path.join(__dirname, dir) -} - -const name = process.env.VUE_APP_TITLE || 'ThingLinks物联网一体化平台' // 网页标题 - -const port = process.env.port || process.env.npm_config_port || 3000 // 端口 - -// vue.config.js 配置说明 -//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions -// 这里只列一部分,具体配置参考文档 -module.exports = { - // 部署生产环境和开发环境下的URL。 - // 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上 - // 例如 https://thinglinks.mqttsnet.com/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://thinglinks.mqttsnet.com/admin/,则设置 baseUrl 为 /admin/。 - publicPath: process.env.NODE_ENV === "production" ? "/" : "/", - // 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist) - outputDir: 'dist', - // 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下) - assetsDir: 'static', - // 是否开启eslint保存检测,有效值:ture | false | 'error' - lintOnSave: process.env.NODE_ENV === 'development', - // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。 - productionSourceMap: false, - // webpack-dev-server 相关配置 - devServer: { - host: '127.0.0.1', - port: port, - open: true, - proxy: { - // detail: https://cli.vuejs.org/config/#devserver-proxy - [process.env.VUE_APP_BASE_API]: { - // target: `http://localhost:19100`, - target: `http://thinglinks.mqttsnet.com`, - changeOrigin: true, - pathRewrite: { - ['^' + process.env.VUE_APP_BASE_API]: '' - } - }, - [process.env.VUE_APP_BASE_SOCKETIP]: { - target: `ws://localhost:19100`, - // target: `ws://frp1.xiaonannet.com:6901`, - changeOrigin: true, - pathRewrite: { - ['^' + process.env.VUE_APP_BASE_SOCKETIP]: '' - } - } - }, - disableHostCheck: true - }, - configureWebpack: { - name: name, - resolve: { - alias: { - '@': resolve('src') - } - } - }, - chainWebpack(config) { - config.plugins.delete('preload') // TODO: need test - config.plugins.delete('prefetch') // TODO: need test - - // set svg-sprite-loader - config.module - .rule('svg') - .exclude.add(resolve('src/assets/icons')) - .end() - config.module - .rule('icons') - .test(/\.svg$/) - .include.add(resolve('src/assets/icons')) - .end() - .use('svg-sprite-loader') - .loader('svg-sprite-loader') - .options({ - symbolId: 'icon-[name]' - }) - .end() - - config - .when(process.env.NODE_ENV !== 'development', - config => { - config - .plugin('ScriptExtHtmlWebpackPlugin') - .after('html') - .use('script-ext-html-webpack-plugin', [{ - // `runtime` must same as runtimeChunk name. default is `runtime` - inline: /runtime\..*\.js$/ - }]) - .end() - config - .optimization.splitChunks({ - chunks: 'all', - cacheGroups: { - libs: { - name: 'chunk-libs', - test: /[\\/]node_modules[\\/]/, - priority: 10, - chunks: 'initial' // only package third parties that are initially dependent - }, - elementUI: { - name: 'chunk-elementUI', // split elementUI into a single package - priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app - test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm - }, - commons: { - name: 'chunk-commons', - test: resolve('src/components'), // can customize your rules - minChunks: 3, // minimum common number - priority: 5, - reuseExistingChunk: true - } - } - }) - config.optimization.runtimeChunk('single'), { - from: path.resolve(__dirname, './public/robots.txt'), //防爬虫文件 - to: './', //到根目录下 - } - } - ) - } -} diff --git a/.history/thinglinks-ui/vue.config_20231012170401.js b/.history/thinglinks-ui/vue.config_20231012170401.js deleted file mode 100644 index 29f4f75b..00000000 --- a/.history/thinglinks-ui/vue.config_20231012170401.js +++ /dev/null @@ -1,125 +0,0 @@ -'use strict' -const path = require('path') - -function resolve(dir) { - return path.join(__dirname, dir) -} - -const name = process.env.VUE_APP_TITLE || 'ThingLinks物联网一体化平台' // 网页标题 - -const port = process.env.port || process.env.npm_config_port || 3000 // 端口 - -// vue.config.js 配置说明 -//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions -// 这里只列一部分,具体配置参考文档 -module.exports = { - // 部署生产环境和开发环境下的URL。 - // 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上 - // 例如 https://thinglinks.mqttsnet.com/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://thinglinks.mqttsnet.com/admin/,则设置 baseUrl 为 /admin/。 - publicPath: process.env.NODE_ENV === "production" ? "/" : "/", - // 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist) - outputDir: 'dist', - // 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下) - assetsDir: 'static', - // 是否开启eslint保存检测,有效值:ture | false | 'error' - lintOnSave: process.env.NODE_ENV === 'development', - // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。 - productionSourceMap: false, - // webpack-dev-server 相关配置 - devServer: { - host: '127.0.0.1', - port: port, - open: true, - proxy: { - // detail: https://cli.vuejs.org/config/#devserver-proxy - [process.env.VUE_APP_BASE_API]: { - // target: `http://localhost:19100`, - target: `http://thinglinks.mqttsnet.com`, - changeOrigin: true, - pathRewrite: { - ['^' + process.env.VUE_APP_BASE_API]: '' - } - }, - [process.env.VUE_APP_BASE_SOCKETIP]: { - target: `ws://localhost:19100`, - // target: `ws://frp1.xiaonannet.com:6901`, - changeOrigin: true, - pathRewrite: { - ['^' + process.env.VUE_APP_BASE_SOCKETIP]: '' - } - } - }, - disableHostCheck: true - }, - configureWebpack: { - name: name, - resolve: { - alias: { - '@': resolve('src') - } - } - }, - chainWebpack(config) { - config.plugins.delete('preload') // TODO: need test - config.plugins.delete('prefetch') // TODO: need test - - // set svg-sprite-loader - config.module - .rule('svg') - .exclude.add(resolve('src/assets/icons')) - .end() - config.module - .rule('icons') - .test(/\.svg$/) - .include.add(resolve('src/assets/icons')) - .end() - .use('svg-sprite-loader') - .loader('svg-sprite-loader') - .options({ - symbolId: 'icon-[name]' - }) - .end() - - config - .when(process.env.NODE_ENV !== 'development', - config => { - config - .plugin('ScriptExtHtmlWebpackPlugin') - .after('html') - .use('script-ext-html-webpack-plugin', [{ - // `runtime` must same as runtimeChunk name. default is `runtime` - inline: /runtime\..*\.js$/ - }]) - .end() - config - .optimization.splitChunks({ - chunks: 'all', - cacheGroups: { - libs: { - name: 'chunk-libs', - test: /[\\/]node_modules[\\/]/, - priority: 10, - chunks: 'initial' // only package third parties that are initially dependent - }, - elementUI: { - name: 'chunk-elementUI', // split elementUI into a single package - priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app - test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm - }, - commons: { - name: 'chunk-commons', - test: resolve('src/components'), // can customize your rules - minChunks: 3, // minimum common number - priority: 5, - reuseExistingChunk: true - } - } - }) - config.optimization.runtimeChunk('single'), { - from: path.resolve(__dirname, './public/robots.txt'), //防爬虫文件 - to: './', //到根目录下 - } - } - ) - } -} diff --git a/.history/thinglinks-ui/vue.config_20231012170409.js b/.history/thinglinks-ui/vue.config_20231012170409.js deleted file mode 100644 index 9b3e03f2..00000000 --- a/.history/thinglinks-ui/vue.config_20231012170409.js +++ /dev/null @@ -1,125 +0,0 @@ -'use strict' -const path = require('path') - -function resolve(dir) { - return path.join(__dirname, dir) -} - -const name = process.env.VUE_APP_TITLE || 'ThingLinks物联网一体化平台' // 网页标题 - -const port = process.env.port || process.env.npm_config_port || 3000 // 端口 - -// vue.config.js 配置说明 -//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions -// 这里只列一部分,具体配置参考文档 -module.exports = { - // 部署生产环境和开发环境下的URL。 - // 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上 - // 例如 https://thinglinks.mqttsnet.com/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://thinglinks.mqttsnet.com/admin/,则设置 baseUrl 为 /admin/。 - publicPath: process.env.NODE_ENV === "production" ? "/" : "/", - // 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist) - outputDir: 'dist', - // 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下) - assetsDir: 'static', - // 是否开启eslint保存检测,有效值:ture | false | 'error' - lintOnSave: process.env.NODE_ENV === 'development', - // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。 - productionSourceMap: false, - // webpack-dev-server 相关配置 - devServer: { - host: '127.0.0.1', - port: port, - open: true, - proxy: { - // detail: https://cli.vuejs.org/config/#devserver-proxy - [process.env.VUE_APP_BASE_API]: { - // target: `http://localhost:19100`, - target: `http://thinglinks.mqttsnet.com/prod-api`, - changeOrigin: true, - pathRewrite: { - ['^' + process.env.VUE_APP_BASE_API]: '' - } - }, - [process.env.VUE_APP_BASE_SOCKETIP]: { - target: `ws://localhost:19100`, - // target: `ws://frp1.xiaonannet.com:6901`, - changeOrigin: true, - pathRewrite: { - ['^' + process.env.VUE_APP_BASE_SOCKETIP]: '' - } - } - }, - disableHostCheck: true - }, - configureWebpack: { - name: name, - resolve: { - alias: { - '@': resolve('src') - } - } - }, - chainWebpack(config) { - config.plugins.delete('preload') // TODO: need test - config.plugins.delete('prefetch') // TODO: need test - - // set svg-sprite-loader - config.module - .rule('svg') - .exclude.add(resolve('src/assets/icons')) - .end() - config.module - .rule('icons') - .test(/\.svg$/) - .include.add(resolve('src/assets/icons')) - .end() - .use('svg-sprite-loader') - .loader('svg-sprite-loader') - .options({ - symbolId: 'icon-[name]' - }) - .end() - - config - .when(process.env.NODE_ENV !== 'development', - config => { - config - .plugin('ScriptExtHtmlWebpackPlugin') - .after('html') - .use('script-ext-html-webpack-plugin', [{ - // `runtime` must same as runtimeChunk name. default is `runtime` - inline: /runtime\..*\.js$/ - }]) - .end() - config - .optimization.splitChunks({ - chunks: 'all', - cacheGroups: { - libs: { - name: 'chunk-libs', - test: /[\\/]node_modules[\\/]/, - priority: 10, - chunks: 'initial' // only package third parties that are initially dependent - }, - elementUI: { - name: 'chunk-elementUI', // split elementUI into a single package - priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app - test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm - }, - commons: { - name: 'chunk-commons', - test: resolve('src/components'), // can customize your rules - minChunks: 3, // minimum common number - priority: 5, - reuseExistingChunk: true - } - } - }) - config.optimization.runtimeChunk('single'), { - from: path.resolve(__dirname, './public/robots.txt'), //防爬虫文件 - to: './', //到根目录下 - } - } - ) - } -} diff --git a/thinglinks-ui/.env.development b/thinglinks-ui/.env.development index 20456fbf..ab110dcc 100644 --- a/thinglinks-ui/.env.development +++ b/thinglinks-ui/.env.development @@ -5,8 +5,7 @@ VUE_APP_TITLE = ThingLinks物联网一体化平台 ENV = 'development' # ThingLinks物联网一体化平台/开发环境 -#VUE_APP_BASE_API = '/dev-api' -VUE_APP_BASE_API = '/' +VUE_APP_BASE_API = '/dev-api' # 路由懒加载 VUE_CLI_BABEL_TRANSPILE_MODULES = true diff --git a/thinglinks-ui/vue.config.js b/thinglinks-ui/vue.config.js index 9b3e03f2..b29d553c 100644 --- a/thinglinks-ui/vue.config.js +++ b/thinglinks-ui/vue.config.js @@ -33,8 +33,8 @@ module.exports = { proxy: { // detail: https://cli.vuejs.org/config/#devserver-proxy [process.env.VUE_APP_BASE_API]: { - // target: `http://localhost:19100`, - target: `http://thinglinks.mqttsnet.com/prod-api`, + target: `http://localhost:19100`, + // target: `http://124.223.113.139:19100`, changeOrigin: true, pathRewrite: { ['^' + process.env.VUE_APP_BASE_API]: '' @@ -115,7 +115,8 @@ module.exports = { } } }) - config.optimization.runtimeChunk('single'), { + config.optimization.runtimeChunk('single'), + { from: path.resolve(__dirname, './public/robots.txt'), //防爬虫文件 to: './', //到根目录下 } From 83f0f6c72695adf8a455cb9030e8b0873c67a5bd Mon Sep 17 00:00:00 2001 From: xiaonan <13733918655@163.com> Date: Sun, 4 Feb 2024 10:57:06 +0800 Subject: [PATCH 06/35] fix --- doc/nacos-config/DEFAULT_GROUP/rocketmq.yml | 1 + .../broker/api/RemoteMqttBrokerOpenApi.java | 2 +- .../broker/api/domain/entity/MqttEvent.java | 30 +++ .../api/domain/enumeration/MqttEventEnum.java | 115 ++++++++++ .../{ => model}/PublishMessageRequest.java | 6 +- .../RemoteMqttBrokerOpenApiFallback.java | 2 +- .../src/main/resources/bootstrap.yml | 2 - .../common/core/mqs/SelectorConfig.java | 24 -- .../thinglinks-common-kafka/pom.xml | 9 +- .../src/main/resources/bootstrap.yml | 4 +- .../thinglinks-modules-broker/pom.xml | 215 +++++++++--------- .../broker/Actors/CloseConnectionActor.java | 46 ---- .../broker/Actors/PublishActor.java | 49 ---- .../controller/MqttBrokerOpenController.java | 75 ++++++ .../broker/service/MqttBrokerService.java | 36 +++ .../service/impl/MqttBrokerServiceImpl.java | 88 +++++++ .../thinglinks-modules-link/pom.xml | 15 +- .../common}/config/KafkaConsumerConfig.java | 6 +- .../common}/config/KafkaProviderConfig.java | 21 +- .../DeviceActionMessageKafkaConsumer.java | 8 - .../DeviceActionMessageRocketmqConsumer.java | 4 +- .../controller/kafka/KafkaController.java | 7 +- .../device/impl/DeviceDatasServiceImpl.java | 6 +- .../device/impl/DeviceInfoServiceImpl.java | 2 +- .../product/impl/ProductServiceImpl.java | 16 +- .../src/main/resources/bootstrap.yml | 2 + .../thinglinks-modules-rule/pom.xml | 7 - .../ThingLinksBeanDefinitionRegistrar.java | 49 ---- .../rule/ThingLinksRuleApplication.java | 2 - .../RuleTriggerMessageKafkaConsumer.java | 56 ----- .../impl/RuleDeviceLinkageServiceImpl.java | 17 +- ...tCreateSuperTableMessageKafkaConsumer.java | 70 ------ 32 files changed, 493 insertions(+), 499 deletions(-) create mode 100644 thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/entity/MqttEvent.java create mode 100644 thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/enumeration/MqttEventEnum.java rename thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/{ => model}/PublishMessageRequest.java (93%) delete mode 100644 thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/SelectorConfig.java delete mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/Actors/CloseConnectionActor.java delete mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/Actors/PublishActor.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/controller/MqttBrokerOpenController.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/service/MqttBrokerService.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/service/impl/MqttBrokerServiceImpl.java rename {thinglinks-common/thinglinks-common-kafka/src/main/java/com/mqttsnet/thinglinks/common/kafka => thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common}/config/KafkaConsumerConfig.java (97%) rename {thinglinks-common/thinglinks-common-kafka/src/main/java/com/mqttsnet/thinglinks/common/kafka => thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common}/config/KafkaProviderConfig.java (85%) delete mode 100644 thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/ThingLinksBeanDefinitionRegistrar.java delete mode 100644 thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/common/consumer/kafka/RuleTriggerMessageKafkaConsumer.java delete mode 100644 thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/consumer/kafka/ProductCreateSuperTableMessageKafkaConsumer.java diff --git a/doc/nacos-config/DEFAULT_GROUP/rocketmq.yml b/doc/nacos-config/DEFAULT_GROUP/rocketmq.yml index 2621a962..89e4231d 100644 --- a/doc/nacos-config/DEFAULT_GROUP/rocketmq.yml +++ b/doc/nacos-config/DEFAULT_GROUP/rocketmq.yml @@ -1,6 +1,7 @@ rocketmq: consumer: group: thinglinks + # ACL 开启时填写(未开启为空即可) accessKey: secretKey: # 一次拉取消息最大值,注意是拉取消息的最大值而非消费最大值 diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/RemoteMqttBrokerOpenApi.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/RemoteMqttBrokerOpenApi.java index 7cf05e10..881a406e 100644 --- a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/RemoteMqttBrokerOpenApi.java +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/RemoteMqttBrokerOpenApi.java @@ -1,6 +1,6 @@ package com.mqttsnet.thinglinks.broker.api; -import com.mqttsnet.thinglinks.broker.api.domain.PublishMessageRequest; +import com.mqttsnet.thinglinks.broker.api.domain.model.PublishMessageRequest; import com.mqttsnet.thinglinks.broker.api.factory.RemoteMqttBrokerOpenApiFallback; import com.mqttsnet.thinglinks.common.core.constant.ServiceNameConstants; import com.mqttsnet.thinglinks.common.core.domain.R; diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/entity/MqttEvent.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/entity/MqttEvent.java new file mode 100644 index 00000000..cfb719cd --- /dev/null +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/entity/MqttEvent.java @@ -0,0 +1,30 @@ +package com.mqttsnet.thinglinks.broker.api.domain.entity; + + +import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; + +/** + * @program: thinglinks + * @description: MQTT事件类 + * @packagename: com.mqttsnet.thinglinks.broker.api.domain.entity + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 00:10 + **/ +public class MqttEvent { + private final MqttEventEnum eventEnum; + private final String message; + + public MqttEvent(MqttEventEnum eventEnum, String message) { + this.eventEnum = eventEnum; + this.message = message; + } + + public MqttEventEnum getEventEnum() { + return eventEnum; + } + + public String getMessage() { + return message; + } +} diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/enumeration/MqttEventEnum.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/enumeration/MqttEventEnum.java new file mode 100644 index 00000000..17674a8a --- /dev/null +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/enumeration/MqttEventEnum.java @@ -0,0 +1,115 @@ +package com.mqttsnet.thinglinks.broker.api.domain.enumeration; + + +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.apache.commons.lang3.StringUtils; + +import java.util.Optional; +import java.util.stream.Stream; + +/** + * @program: thinglinks + * @description: MQTT事件枚举 + * @packagename: com.mqttsnet.thinglinks.broker.api.domain.enumeration + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2022-12-16 19:42 + **/ +@Getter +@AllArgsConstructor +@NoArgsConstructor +@ApiModel(value = "MqttEventEnum", description = "MQTT事件枚举") +public enum MqttEventEnum { + + /** + * Event type for publish. + */ + PUBLISH("PUBLISH"), + + /** + * Event type for write. + */ + WRITE("WRITE"), + + /** + * Event type for cluster. + */ + CLUSTER("CLUSTER"), + + /** + * Event type for connect. + */ + CONNECT("CONNECT"), + + /** + * Event type for close. + */ + CLOSE("CLOSE"), + + /** + * Event type for subscribe. + */ + SUBSCRIBE("SUBSCRIBE"), + + /** + * Event type for unsubscribe. + */ + UNSUBSCRIBE("UNSUBSCRIBE"), + + /** + * Event type for bridge. + */ + BRIDGE("BRIDGE"), + + /** + * Event type for disconnect. + */ + DISCONNECT("DISCONNECT"), + + /** + * Event type for ping. + */ + PING("PING"), + + /** + * Event type for publish acknowledgment. + */ + PUBLISH_ACK("PUBLISH_ACK"), + + /** + * Event type for retry. + */ + RETRY("RETRY"), + + /** + * Event type for heart timeout. + */ + HEART_TIMEOUT("HEART_TIMEOUT"), + + /** + * Event type for system. + */ + SYSTEM("SYSTEM"), + + ; + + private String name; + + /** + * Retrieves the corresponding MqttEventEnum for a given name. + * + * @param name the name of the MQTT event. + * @return an Optional of MqttEventEnum. + */ + public static Optional getMqttEventEnum(String name) { + if (StringUtils.isEmpty(name)) { + return Optional.empty(); + } + return Stream.of(MqttEventEnum.values()) + .filter(event -> event.getName().equalsIgnoreCase(name)) + .findFirst(); + } +} diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/PublishMessageRequest.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/model/PublishMessageRequest.java similarity index 93% rename from thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/PublishMessageRequest.java rename to thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/model/PublishMessageRequest.java index 989f8609..7d19aad8 100644 --- a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/PublishMessageRequest.java +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/model/PublishMessageRequest.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.broker.api.domain; +package com.mqttsnet.thinglinks.broker.api.domain.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -30,13 +30,13 @@ public class PublishMessageRequest implements Serializable { @ApiModelProperty(value = "可选的调用者提供的请求ID", example = "1234567890") private Long reqId; - @ApiModelProperty(value = "租户ID", required = true, example = "tenant12345") + @ApiModelProperty(value = "租户ID", required = true, example = "thinglinks") private String tenantId; @ApiModelProperty(value = "消息主题", required = true, example = "exampleTopic") private String topic; - @ApiModelProperty(value = "QoS of the message to be distributed", required = true) + @ApiModelProperty(value = "QoS of the message to be distributed", required = true, example = "1") private String pubQos; @ApiModelProperty(value = "客户端类型", required = true, example = "web") diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/RemoteMqttBrokerOpenApiFallback.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/RemoteMqttBrokerOpenApiFallback.java index 06bf9264..c1f2b7c9 100644 --- a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/RemoteMqttBrokerOpenApiFallback.java +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/RemoteMqttBrokerOpenApiFallback.java @@ -1,7 +1,7 @@ package com.mqttsnet.thinglinks.broker.api.factory; import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; -import com.mqttsnet.thinglinks.broker.api.domain.PublishMessageRequest; +import com.mqttsnet.thinglinks.broker.api.domain.model.PublishMessageRequest; import com.mqttsnet.thinglinks.common.core.domain.R; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/thinglinks-auth/src/main/resources/bootstrap.yml b/thinglinks-auth/src/main/resources/bootstrap.yml index 95bb9ead..10dadc37 100644 --- a/thinglinks-auth/src/main/resources/bootstrap.yml +++ b/thinglinks-auth/src/main/resources/bootstrap.yml @@ -33,7 +33,5 @@ spring: refresh: false - dataId: database.yml refresh: true - - dataId: rocketmq.yml - refresh: false username: @nacos.username@ password: @nacos.password@ diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/SelectorConfig.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/SelectorConfig.java deleted file mode 100644 index a4a580bd..00000000 --- a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/SelectorConfig.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.mqttsnet.thinglinks.common.core.mqs; - -import lombok.Data; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -@Component -@Data -public class SelectorConfig { - - /* - * 用于动态加载kafka rockermq bean的环境变量 - * */ - public static String selectorKafkaKey = "mqs.selector-kafka"; - - /* - * true 默认值,kafka - * false reockermq - * - * */ - @Value("${mqs.selector-kafka}") - private boolean selectorKafka; - -} diff --git a/thinglinks-common/thinglinks-common-kafka/pom.xml b/thinglinks-common/thinglinks-common-kafka/pom.xml index 38408b95..239a4d80 100644 --- a/thinglinks-common/thinglinks-common-kafka/pom.xml +++ b/thinglinks-common/thinglinks-common-kafka/pom.xml @@ -20,14 +20,7 @@ org.springframework.kafka spring-kafka - 2.8.0 - - - - - org.apache.kafka - kafka-clients - 3.0.0 + 3.1.1 diff --git a/thinglinks-gateway/src/main/resources/bootstrap.yml b/thinglinks-gateway/src/main/resources/bootstrap.yml index a68fcee1..5e202c77 100644 --- a/thinglinks-gateway/src/main/resources/bootstrap.yml +++ b/thinglinks-gateway/src/main/resources/bootstrap.yml @@ -33,13 +33,11 @@ spring: refresh: false - dataId: database.yml refresh: true - - dataId: rocketmq.yml - refresh: false username: @nacos.username@ password: @nacos.password@ sentinel: # 取消控制台懒加载 - eager: true + eager: false transport: # 控制台地址 dashboard: @sentinel.dashboard@ diff --git a/thinglinks-modules/thinglinks-modules-broker/pom.xml b/thinglinks-modules/thinglinks-modules-broker/pom.xml index cb072aeb..6dac3ed0 100644 --- a/thinglinks-modules/thinglinks-modules-broker/pom.xml +++ b/thinglinks-modules/thinglinks-modules-broker/pom.xml @@ -73,6 +73,11 @@ org.springframework.boot spring-boot-starter-websocket + + com.mqttsnet + thinglinks-api-broker + ${thinglinks.version} + @@ -108,110 +113,110 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/Actors/CloseConnectionActor.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/Actors/CloseConnectionActor.java deleted file mode 100644 index 0ecb87ec..00000000 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/Actors/CloseConnectionActor.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.mqttsnet.thinglinks.broker.Actors; - -import cn.hutool.http.HttpRequest; -import com.alibaba.fastjson.JSONObject; -import com.mqttsnet.thinglinks.common.core.domain.R; -import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.List; -import java.util.Map; - -/** - * @Description: Broker推送设备消息 - * @Author: ShiHuan Sun - * @E-mail: 13733918655@163.com - * @CreateDate: 2021/10/25$ 17:46$ - * @UpdateUser: ShiHuan Sun - * @UpdateDate: 2021/10/25$ 17:46$ - * @UpdateRemark: 修改内容 - * @Version: 1.0 - */ -@Slf4j -@RestController -@RequestMapping("/close") -public class CloseConnectionActor { - - /** - * 关闭连接 - * @param clientIdentifiers - * @return - */ - @PostMapping("/connection") - public R closeConnection(@RequestBody List clientIdentifiers) { - log.info("MQTT Broker 关闭连接 {}", clientIdentifiers.toString()); - JSONObject param = new JSONObject(); - param.put("ids", clientIdentifiers); - String result = HttpRequest.post("http://127.0.0.1:60000/smqtt/close/connection") - .header("Content-Type", "application/json;charset=UTF-8") - .body(param.toString()) - .execute().body(); - return R.ok(); - } -} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/Actors/PublishActor.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/Actors/PublishActor.java deleted file mode 100644 index 94789a20..00000000 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/Actors/PublishActor.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.mqttsnet.thinglinks.broker.Actors; - -import cn.hutool.http.HttpRequest; -import com.alibaba.fastjson.JSONObject; -import com.mqttsnet.thinglinks.common.core.domain.R; -import com.mqttsnet.thinglinks.common.core.web.domain.AjaxResult; -import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.Map; - -/** - * @Description: Broker推送设备消息 - * @Author: ShiHuan Sun - * @E-mail: 13733918655@163.com - * @CreateDate: 2021/10/25$ 17:46$ - * @UpdateUser: ShiHuan Sun - * @UpdateDate: 2021/10/25$ 17:46$ - * @UpdateRemark: 修改内容 - * @Version: 1.0 - */ -@Slf4j -@RestController -@RequestMapping("/publish") -public class PublishActor{ - - /** - * MQTT推送消息接口 - * @param params - * @return - */ - @PostMapping("/sendMessage") - public R sendMessage(@RequestBody Map params) { - log.info("MQTT Broker publish {}", params.toString()); - JSONObject param = new JSONObject(); - param.put("topic", params.get("topic")); - param.put("qos", Integer.valueOf(params.get("qos").toString())); - param.put("retain", Boolean.valueOf(params.get("retain").toString())); - param.put("message", String.valueOf(params.get("message"))); - String result = HttpRequest.post("http://127.0.0.1:60000/smqtt/publish") - .header("Content-Type", "application/json;charset=UTF-8") - .body(param.toString()) - .execute().body(); - return R.ok(); - } -} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/controller/MqttBrokerOpenController.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/controller/MqttBrokerOpenController.java new file mode 100644 index 00000000..fc23f856 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/controller/MqttBrokerOpenController.java @@ -0,0 +1,75 @@ +package com.mqttsnet.thinglinks.broker.controller; + +import cn.hutool.http.HttpRequest; +import com.alibaba.fastjson.JSONObject; +import com.mqttsnet.thinglinks.broker.api.domain.model.PublishMessageRequest; +import com.mqttsnet.thinglinks.broker.service.MqttBrokerService; +import com.mqttsnet.thinglinks.common.core.domain.R; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * MqttBroker相关开放接口(anyTenant) + * + * @author mqttsnet + * @date 2023-05-22 + * @create [2021-06-30] [mqttsnet] + */ +@Slf4j +@Validated +@RestController +@RequiredArgsConstructor +@RequestMapping("/mqttBrokerOpen") +@Api(value = "MqttBrokerOpenController", tags = "开放接口-MQTTBroker") +public class MqttBrokerOpenController { + + @Autowired + private MqttBrokerService mqttBrokerService; + + /** + * MQTT推送消息接口 + * + * @param publishMessageRequest 推送消息请求参数 + * @return {@link R} 结果 + */ + @ApiOperation(value = "MQTT推送消息", notes = "根据提供的主题、服务质量等级、保留标志和消息内容推送MQTT消息") + @PostMapping("/sendMessage") + public R sendMessage(@ApiParam(value = "推送消息请求参数", required = true) + @RequestBody PublishMessageRequest publishMessageRequest) { + log.info("MQTT Broker publish {}", publishMessageRequest.toString()); + return R.ok(mqttBrokerService.publishMessage(publishMessageRequest)); + } + + + /** + * 关闭客户端连接 + * TODO 暂时不可用 + * + * @param clientIdentifiers 客户端标识集合 + * @return {@link R} 结果 + */ + @ApiOperation(value = "关闭连接", notes = "关闭指定客户端的连接") + @PostMapping("/close/connection") + public R closeConnection(@RequestBody @ApiParam(value = "客户端标识符列表") List clientIdentifiers) { + log.info("MQTT Broker 关闭连接 {}", clientIdentifiers.toString()); + JSONObject param = new JSONObject(); + param.put("ids", clientIdentifiers); + String result = HttpRequest.post("http://127.0.0.1:60000/smqtt/close/connection") + .header("Content-Type", "application/json;charset=UTF-8") + .body(param.toString()) + .execute().body(); + return R.ok(result); + } + +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/service/MqttBrokerService.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/service/MqttBrokerService.java new file mode 100644 index 00000000..1f15eae9 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/service/MqttBrokerService.java @@ -0,0 +1,36 @@ +package com.mqttsnet.thinglinks.broker.service; + +import com.mqttsnet.thinglinks.broker.api.domain.model.PublishMessageRequest; +import com.mqttsnet.thinglinks.common.core.exception.base.BaseException; + +/** + * ----------------------------------------------------------------------------- + * File Name: MqttBrokerService.java + * ----------------------------------------------------------------------------- + * Description: + * MqttBroker API + * ----------------------------------------------------------------------------- + * + * @author ShiHuan Sun + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + *

+ * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2023-10-31 19:43 + */ +public interface MqttBrokerService { + + + /** + * Publishes a message to a specified topic and returns the content if successful. + * + * @param publishMessageRequest Object containing the required parameters for publishing. + * @return The content of the published message. + * @throws BaseException If the publishing fails. + */ + String publishMessage(PublishMessageRequest publishMessageRequest); +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/service/impl/MqttBrokerServiceImpl.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/service/impl/MqttBrokerServiceImpl.java new file mode 100644 index 00000000..391b6442 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/service/impl/MqttBrokerServiceImpl.java @@ -0,0 +1,88 @@ +package com.mqttsnet.thinglinks.broker.service.impl; + +import com.mqttsnet.thinglinks.broker.api.BifroMQApi; +import com.mqttsnet.thinglinks.broker.api.domain.model.PublishMessageRequest; +import com.mqttsnet.thinglinks.broker.service.MqttBrokerService; +import com.mqttsnet.thinglinks.common.core.exception.base.BaseException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; + +/** + * ----------------------------------------------------------------------------- + * File Name: MqttBrokerServiceImpl.java + * ----------------------------------------------------------------------------- + * Description: + * MqttBroker API 实现类 + * ----------------------------------------------------------------------------- + * + * @author ShiHuan Sun + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + *

+ * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2023-10-31 19:44 + */ +@Slf4j +@RequiredArgsConstructor +@Service +public class MqttBrokerServiceImpl implements MqttBrokerService { + private final BifroMQApi bifroMQApi; + + + /** + * Publishes a message to a specified topic and returns the content if successful. + * + * @param publishMessageRequest Object containing the required parameters for publishing. + * @return The content of the published message. + * @throws BaseException If the publishing fails. + */ + @Override + public String publishMessage(PublishMessageRequest publishMessageRequest) throws BaseException { + log.info("Preparing to publish message with topic: {}", publishMessageRequest.getTopic()); + try { + ResponseEntity response = callPublishApi(publishMessageRequest); + + if (response.getStatusCode().is2xxSuccessful()) { + log.info("Successfully published message with topic: {}", publishMessageRequest.getTopic()); + return publishMessageRequest.getPayload(); // Return the message content that was published + } else { + log.error("Failed to publish message with topic: {}. Response Status: {}", + publishMessageRequest.getTopic(), response.getStatusCode()); + throw new BaseException("Failed to publish message with topic: " + publishMessageRequest.getTopic()); + } + } catch (HttpClientErrorException e) { + log.error("HTTP error occurred while publishing message: {}", e.getMessage()); + throw new BaseException("Error during message publishing: " + e.getResponseBodyAsString()); + } catch (Exception e) { + log.error("Unexpected error occurred while publishing message: {}", e.getMessage()); + throw new BaseException("Unexpected error during message publishing: " + e.getMessage()); + } + } + + + /** + * Makes the actual API call to publish a message. + * + * @param publishMessageRequest Object containing the required parameters for publishing. + * @return R Response indicating success or failure from the BifroMQApi. + */ + private ResponseEntity callPublishApi(PublishMessageRequest publishMessageRequest) { + return bifroMQApi.publishMessage( + publishMessageRequest.getReqId(), + publishMessageRequest.getTenantId(), + publishMessageRequest.getTopic(), + publishMessageRequest.getClientType(), + publishMessageRequest.getPubQos(), + publishMessageRequest.getRetain(), + publishMessageRequest.getClientMeta(), + publishMessageRequest.getPayload() + ); + } +} diff --git a/thinglinks-modules/thinglinks-modules-link/pom.xml b/thinglinks-modules/thinglinks-modules-link/pom.xml index d98de5f8..71f7f6bd 100644 --- a/thinglinks-modules/thinglinks-modules-link/pom.xml +++ b/thinglinks-modules/thinglinks-modules-link/pom.xml @@ -80,24 +80,17 @@ ${thinglinks.version} - + com.mqttsnet - thinglinks-api-link + thinglinks-common-kafka ${thinglinks.version} - - - - + com.mqttsnet - thinglinks-common-kafka + thinglinks-api-link ${thinglinks.version} diff --git a/thinglinks-common/thinglinks-common-kafka/src/main/java/com/mqttsnet/thinglinks/common/kafka/config/KafkaConsumerConfig.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/KafkaConsumerConfig.java similarity index 97% rename from thinglinks-common/thinglinks-common-kafka/src/main/java/com/mqttsnet/thinglinks/common/kafka/config/KafkaConsumerConfig.java rename to thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/KafkaConsumerConfig.java index 75f80a52..d4df6df5 100644 --- a/thinglinks-common/thinglinks-common-kafka/src/main/java/com/mqttsnet/thinglinks/common/kafka/config/KafkaConsumerConfig.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/KafkaConsumerConfig.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.common.kafka.config; +package com.mqttsnet.thinglinks.link.common.config; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.StringDeserializer; @@ -17,9 +17,9 @@ import java.util.Map; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: KafkaConsumerConfig - * @packagename: com.mqttsnet.thinglinks.config.kafka + * @packagename: com.mqttsnet.thinglinks.common.kafka.config * @author: ShiHuan Sun * @e-mainl: 13733918655@163.com * @date: 2023-06-18 11:29 diff --git a/thinglinks-common/thinglinks-common-kafka/src/main/java/com/mqttsnet/thinglinks/common/kafka/config/KafkaProviderConfig.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/KafkaProviderConfig.java similarity index 85% rename from thinglinks-common/thinglinks-common-kafka/src/main/java/com/mqttsnet/thinglinks/common/kafka/config/KafkaProviderConfig.java rename to thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/KafkaProviderConfig.java index f07be428..92fe8016 100644 --- a/thinglinks-common/thinglinks-common-kafka/src/main/java/com/mqttsnet/thinglinks/common/kafka/config/KafkaProviderConfig.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/KafkaProviderConfig.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.common.kafka.config; +package com.mqttsnet.thinglinks.link.common.config; import org.apache.kafka.clients.producer.ProducerConfig; import org.springframework.beans.factory.annotation.Value; @@ -14,9 +14,9 @@ import java.util.Map; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: KafkaProviderConfig - * @packagename: com.mqttsnet.thinglinks.config.kafka + * @packagename: com.mqttsnet.thinglinks.common.kafka.config * @author: ShiHuan Sun * @e-mainl: 13733918655@163.com * @date: 2023-06-18 11:28 @@ -24,17 +24,18 @@ @Configuration public class KafkaProviderConfig { - @Value("${spring.kafka.thingLinksPro.producer.bootstrap-servers}") + + @Value("${spring.kafka.thingLinks.producer.bootstrap-servers}") private String bootstrapServers; - @Value("${spring.kafka.thingLinksPro.producer.transaction-id-prefix}") + @Value("${spring.kafka.thingLinks.producer.transaction-id-prefix}") private String transactionIdPrefix; - @Value("${spring.kafka.thingLinksPro.producer.acks}") + @Value("${spring.kafka.thingLinks.producer.acks}") private String acks; - @Value("${spring.kafka.thingLinksPro.producer.retries}") + @Value("${spring.kafka.thingLinks.producer.retries}") private String retries; - @Value("${spring.kafka.thingLinksPro.producer.batch-size}") + @Value("${spring.kafka.thingLinks.producer.batch-size}") private String batchSize; - @Value("${spring.kafka.thingLinksPro.producer.buffer-memory}") + @Value("${spring.kafka.thingLinks.producer.buffer-memory}") private String bufferMemory; @Bean @@ -82,7 +83,7 @@ public KafkaTransactionManager kafkaTransactionManager(ProducerF } @Bean - public KafkaTemplate thingLinksProKafkaTemplate() { + public KafkaTemplate thingLinksKafkaTemplate() { return new KafkaTemplate<>(producerFactory()); } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/kafka/DeviceActionMessageKafkaConsumer.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/kafka/DeviceActionMessageKafkaConsumer.java index e88b5ac6..6e573661 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/kafka/DeviceActionMessageKafkaConsumer.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/kafka/DeviceActionMessageKafkaConsumer.java @@ -3,23 +3,15 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.mqttsnet.thinglinks.common.core.enums.MqttEvent; -import com.mqttsnet.thinglinks.common.rocketmq.constant.ConsumerGroupConstant; import com.mqttsnet.thinglinks.common.kafka.constant.ConsumerTopicConstant; import com.mqttsnet.thinglinks.link.service.device.DeviceActionService; import com.mqttsnet.thinglinks.link.service.device.DeviceDatasService; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.rocketmq.spring.annotation.MessageModel; -import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; -import org.apache.rocketmq.spring.core.RocketMQListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Component; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.Map; import java.util.Objects; /** diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/rocketmq/DeviceActionMessageRocketmqConsumer.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/rocketmq/DeviceActionMessageRocketmqConsumer.java index a1d1f515..7c2afd17 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/rocketmq/DeviceActionMessageRocketmqConsumer.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/rocketmq/DeviceActionMessageRocketmqConsumer.java @@ -39,8 +39,8 @@ public class DeviceActionMessageRocketmqConsumer implements RocketMQListener { @Async("linkAsync") @Override public void onMessage(Object message) { - if (null == message){ - log.warn("message cannot be empty {}",message); + if (null == message) { + log.warn("message cannot be empty {}", message); return; } log.info("ThingLinks物联网平台数据消费-->Received message={}", message); diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/kafka/KafkaController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/kafka/KafkaController.java index 6bc76417..3715d1d6 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/kafka/KafkaController.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/kafka/KafkaController.java @@ -1,6 +1,5 @@ package com.mqttsnet.thinglinks.link.controller.kafka; -import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.core.KafkaTemplate; @@ -32,8 +31,8 @@ public class KafkaController { @Transactional @PostMapping("/send") - public String kafkaMessageSend(@RequestBody Map params){ - thingLinksProKafkaTemplate.send(new ProducerRecord<>(String.valueOf(params.get("topic")),String.valueOf(params.get("msg")))); - return "success-"+params.get("topic"); + public String kafkaMessageSend(@RequestBody Map params) { + thingLinksProKafkaTemplate.send(new ProducerRecord<>(String.valueOf(params.get("topic")), String.valueOf(params.get("msg")))); + return "success-" + params.get("topic"); } } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceDatasServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceDatasServiceImpl.java index 64203356..24ef248a 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceDatasServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceDatasServiceImpl.java @@ -190,7 +190,7 @@ public void insertBaseDatas(JSONObject thinglinksMessage) throws Exception { param.put("qos", Integer.valueOf(qos)); param.put("retain", false); param.put("message", payload); - remoteMqttBrokerOpenApi.sendMessage(param); +// remoteMqttBrokerOpenApi.sendMessage(param); } else if (topic.startsWith("/v1/devices/") && topic.endsWith("/topo/delete")) { final String deviceIdentification = SubStringUtil.subStr(topic, 12, -12); final String payload = this.processingTopoDeleteTopic(deviceIdentification, body); @@ -199,7 +199,7 @@ public void insertBaseDatas(JSONObject thinglinksMessage) throws Exception { param.put("qos", Integer.valueOf(qos)); param.put("retain", false); param.put("message", payload); - remoteMqttBrokerOpenApi.sendMessage(param); +// remoteMqttBrokerOpenApi.sendMessage(param); } else if (topic.startsWith("/v1/devices/") && topic.endsWith("/topo/update")) { final String deviceIdentification = SubStringUtil.subStr(topic, 12, -12); final String payload = this.processingTopoUpdateTopic(deviceIdentification, body); @@ -208,7 +208,7 @@ public void insertBaseDatas(JSONObject thinglinksMessage) throws Exception { param.put("qos", Integer.valueOf(qos)); param.put("retain", false); param.put("message", payload); - remoteMqttBrokerOpenApi.sendMessage(param); +// remoteMqttBrokerOpenApi.sendMessage(param); } else if (topic.startsWith("/v1/devices/") && topic.endsWith("/datas")) { final String deviceIdentification = SubStringUtil.subStr(topic, 12, -6); this.processingDatasTopic(deviceIdentification, body); diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java index 32638eaf..8e55a4a5 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java @@ -239,7 +239,7 @@ public int deleteDeviceInfoByIds(Long[] ids) { param.put("qos", 2); param.put("retain", false); param.put("message", JSON.toJSONString(responseMaps)); - remoteMqttBrokerOpenApi.sendMessage(param); +// remoteMqttBrokerOpenApi.sendMessage(param); } responseMaps.clear(); }); diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServiceImpl.java index 9b63714e..a22b21fa 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServiceImpl.java @@ -9,7 +9,6 @@ import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.common.core.enums.DataTypeEnum; import com.mqttsnet.thinglinks.common.core.enums.ResultEnum; -import com.mqttsnet.thinglinks.common.core.mqs.SelectorConfig; import com.mqttsnet.thinglinks.common.core.text.CharsetKit; import com.mqttsnet.thinglinks.common.core.text.UUID; import com.mqttsnet.thinglinks.common.core.utils.StringUtils; @@ -35,12 +34,10 @@ import com.mqttsnet.thinglinks.tdengine.api.domain.Fields; import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDto; import lombok.extern.slf4j.Slf4j; -import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.rocketmq.spring.core.RocketMQTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.kafka.core.KafkaTemplate; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; @@ -54,7 +51,6 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; -import java.util.stream.Collectors; /** * @Description: 产品模型业务层 @@ -88,12 +84,6 @@ public class ProductServiceImpl implements ProductService { @Autowired private RocketMQTemplate rocketMQTemplate; - @Autowired - private KafkaTemplate thingLinksProKafkaTemplate; - - @Autowired - private SelectorConfig selectorConfig; - /** * 数据库名称 */ @@ -675,11 +665,7 @@ public List createSuperTableDataModel(Long[] productIds, Boolean jsonObject.put("msg", JSON.toJSONString(superTableDto)); mqMessage.setMessage(jsonObject.toJSONString()); - if (selectorConfig.isSelectorKafka()) { - thingLinksProKafkaTemplate.send(new ProducerRecord<>(mqMessage.getTopic(), mqMessage.getMessage())); - } else { - rocketMQTemplate.convertAndSend(mqMessage.getTopic(), mqMessage.getMessage()); - } + rocketMQTemplate.convertAndSend(mqMessage.getTopic(), mqMessage.getMessage()); } } } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/resources/bootstrap.yml b/thinglinks-modules/thinglinks-modules-link/src/main/resources/bootstrap.yml index 6be2c6c2..dd7fcb63 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/resources/bootstrap.yml +++ b/thinglinks-modules/thinglinks-modules-link/src/main/resources/bootstrap.yml @@ -35,5 +35,7 @@ spring: refresh: true - dataId: rocketmq.yml refresh: false + - dataId: kafka.yml + refresh: false username: @nacos.username@ password: @nacos.password@ diff --git a/thinglinks-modules/thinglinks-modules-rule/pom.xml b/thinglinks-modules/thinglinks-modules-rule/pom.xml index 607de6dd..87083355 100644 --- a/thinglinks-modules/thinglinks-modules-rule/pom.xml +++ b/thinglinks-modules/thinglinks-modules-rule/pom.xml @@ -101,13 +101,6 @@ ${thinglinks.version} - - - com.mqttsnet - thinglinks-common-kafka - ${thinglinks.version} - - com.mqttsnet diff --git a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/ThingLinksBeanDefinitionRegistrar.java b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/ThingLinksBeanDefinitionRegistrar.java deleted file mode 100644 index c3f0cfbf..00000000 --- a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/ThingLinksBeanDefinitionRegistrar.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.mqttsnet.thinglinks.rule; - -import com.mqttsnet.thinglinks.common.core.mqs.SelectorConfig; -import com.mqttsnet.thinglinks.rule.common.consumer.kafka.RuleTriggerMessageKafkaConsumer; -import com.mqttsnet.thinglinks.rule.common.consumer.rocketmq.RuleTriggerMessageRocketmqConsumer; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; -import org.springframework.core.env.Environment; -import org.springframework.core.type.AnnotationMetadata; - -@Configuration -class ThingLinksConfiguration { - - @Bean - public ThingLinksBeanDefinitionRegistrar thingLinksBeanDefinitionRegistrar(Environment environment) { - return new ThingLinksBeanDefinitionRegistrar(environment); - } -} - -public class ThingLinksBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { - - private final Environment environment; - - public ThingLinksBeanDefinitionRegistrar(Environment environment) { - this.environment = environment; - } - - @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { - Class beanClass = getConsumerClass(); - String beanName = beanClass.getSimpleName(); - registerBeanDefinition(registry, beanClass, beanName); - } - - private Class getConsumerClass() { - boolean selectorKafka = Boolean.parseBoolean(environment.getProperty(SelectorConfig.selectorKafkaKey, "false")); - return selectorKafka ? RuleTriggerMessageKafkaConsumer.class : - RuleTriggerMessageRocketmqConsumer.class; - } - - private void registerBeanDefinition(BeanDefinitionRegistry registry, Class beanClass, String beanName) { - AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(beanClass).getBeanDefinition(); - registry.registerBeanDefinition(beanName, beanDefinition); - } -} diff --git a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/ThingLinksRuleApplication.java b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/ThingLinksRuleApplication.java index 467e200a..c25b53e2 100644 --- a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/ThingLinksRuleApplication.java +++ b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/ThingLinksRuleApplication.java @@ -5,7 +5,6 @@ import com.mqttsnet.thinglinks.common.swagger.annotation.EnableCustomSwagger2; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Import; import org.springframework.web.bind.annotation.CrossOrigin; /** @@ -22,7 +21,6 @@ //若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失 @CrossOrigin(origins = "*", maxAge = 3600) @SpringBootApplication(scanBasePackages = {"com.mqttsnet.thinglinks"}) -@Import(ThingLinksBeanDefinitionRegistrar.class) public class ThingLinksRuleApplication { public static void main(String[] args) { SpringApplication.run(ThingLinksRuleApplication.class, args); diff --git a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/common/consumer/kafka/RuleTriggerMessageKafkaConsumer.java b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/common/consumer/kafka/RuleTriggerMessageKafkaConsumer.java deleted file mode 100644 index 4df94ef2..00000000 --- a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/common/consumer/kafka/RuleTriggerMessageKafkaConsumer.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.mqttsnet.thinglinks.rule.common.consumer.kafka; - -import com.alibaba.fastjson.JSONObject; -import com.mqttsnet.thinglinks.common.kafka.constant.ConsumerTopicConstant; -import com.mqttsnet.thinglinks.rule.service.RuleDeviceLinkageService; -import lombok.extern.slf4j.Slf4j; -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.kafka.annotation.KafkaListener; -import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Component; - -/** - * @Description: 规则引擎-触发器规则消息消费(kafka模式) - * @Author: ShiHuan Sun - * @E-mail: 13733918655@163.com - * @Website: http://thinglinks.mqttsnet.com - * @CreateDate: 2022/10/28$ 16:11$ - * @UpdateUser: ShiHuan Sun - * @UpdateDate: 2022/10/28$ 16:11$ - * @UpdateRemark: 修改内容 - * @Version: 1.0 - */ -@Slf4j -//@Component -public class RuleTriggerMessageKafkaConsumer { - - @Autowired - private RuleDeviceLinkageService ruleDeviceLinkageService; - - @Async("ruleAsync") - @KafkaListener(topics = {ConsumerTopicConstant.THINGLINKS_RULE_TRIGGER}) - public void onMessage(ConsumerRecord record) { - if (null == record) { - log.warn("message cannot be empty {}", record); - return; - } - - log.info("规则引擎-触发器规则数据消费-->Received message={}", record); - - try { - - Object message = JSONObject.parse(String.valueOf(record.value())); - JSONObject json = JSONObject.parseObject(message.toString()); - Boolean flag = ruleDeviceLinkageService.checkRuleConditions(json.getString("msg")); - log.info("规则匹配结果:{}", flag); - //触发执行动作 - if(flag) { - ruleDeviceLinkageService.execAction(json.getString("msg")); - } - - } catch (Exception e) { - log.error("规则引擎-触发器规则数据消费-->消费失败,失败原因:{}", e.getMessage()); - } - } -} diff --git a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/service/impl/RuleDeviceLinkageServiceImpl.java b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/service/impl/RuleDeviceLinkageServiceImpl.java index bda53800..78cf36e0 100644 --- a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/service/impl/RuleDeviceLinkageServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/service/impl/RuleDeviceLinkageServiceImpl.java @@ -1,20 +1,16 @@ package com.mqttsnet.thinglinks.rule.service.impl; import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; import com.mqttsnet.thinglinks.common.core.constant.Constants; import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.common.core.enums.ConditionTypeEnum; import com.mqttsnet.thinglinks.common.core.enums.FieldTypeEnum; import com.mqttsnet.thinglinks.common.core.enums.OperatorEnum; import com.mqttsnet.thinglinks.common.core.enums.TriggeringEnum; -import com.mqttsnet.thinglinks.common.core.mqs.SelectorConfig; import com.mqttsnet.thinglinks.common.core.utils.CompareUtil; import com.mqttsnet.thinglinks.common.rocketmq.constant.ConsumerTopicConstant; import com.mqttsnet.thinglinks.common.rocketmq.domain.MQMessage; import com.mqttsnet.thinglinks.link.api.*; -import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; import com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductProperties; import com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductServices; @@ -29,10 +25,8 @@ import com.mqttsnet.thinglinks.tdengine.api.domain.TagsSelectDao; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; -import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.rocketmq.spring.core.RocketMQTemplate; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.kafka.core.KafkaTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.util.HtmlUtils; @@ -52,15 +46,10 @@ @Service public class RuleDeviceLinkageServiceImpl implements RuleDeviceLinkageService { - @Autowired - private KafkaTemplate thingLinksProKafkaTemplate; @Autowired private RocketMQTemplate rocketMQTemplate; - @Autowired - private SelectorConfig selectorConfig; - @Autowired private ActionCommandsService actionCommandsService; @@ -109,11 +98,7 @@ public void triggerDeviceLinkageByRuleIdentification(String ruleIdentification) log.info("topic:{}", mqMessage.getTopic()); log.info("message:{}", mqMessage.getMessage()); - if (selectorConfig.isSelectorKafka()) { - thingLinksProKafkaTemplate.send(new ProducerRecord<>(mqMessage.getTopic(), mqMessage.getMessage())); - } else { - rocketMQTemplate.convertAndSend(mqMessage.getTopic(), mqMessage.getMessage()); - } + rocketMQTemplate.convertAndSend(mqMessage.getTopic(), mqMessage.getMessage()); } /** diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/consumer/kafka/ProductCreateSuperTableMessageKafkaConsumer.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/consumer/kafka/ProductCreateSuperTableMessageKafkaConsumer.java deleted file mode 100644 index 0c202c2d..00000000 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/consumer/kafka/ProductCreateSuperTableMessageKafkaConsumer.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.mqttsnet.thinglinks.tdengine.common.consumer.kafka; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.JSONObject; -import com.mqttsnet.thinglinks.common.core.utils.StringUtils; -import com.mqttsnet.thinglinks.common.kafka.constant.ConsumerTopicConstant; -import com.mqttsnet.thinglinks.common.rocketmq.constant.ConsumerGroupConstant; -import com.mqttsnet.thinglinks.tdengine.service.ProductSuperTableCreateOrUpdateService; -import lombok.extern.slf4j.Slf4j; -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.rocketmq.spring.annotation.MessageModel; -import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; -import org.apache.rocketmq.spring.core.RocketMQListener; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.kafka.annotation.KafkaListener; -import org.springframework.stereotype.Component; - -/** - * @Description: TDengine超级表创键修改动作监听(kafka模式) - * @Author: ShiHuan Sun - * @E-mail: 13733918655@163.com - * @Website: http://thinglinks.mqttsnet.com - * @CreateDate: 2021/11/22$ 16:11$ - * @UpdateUser: ShiHuan Sun - * @UpdateDate: 2021/11/22$ 16:11$ - * @UpdateRemark: 修改内容 - * @Version: 1.0 - */ -@Slf4j -//@Component -public class ProductCreateSuperTableMessageKafkaConsumer { - - @Autowired - private ProductSuperTableCreateOrUpdateService productSuperTableCreateOrUpdateService; - - /** - * 超级表创建及修改处理 - * - * @param record - */ - @KafkaListener(topics = {ConsumerTopicConstant.PRODUCTSUPERTABLE_CREATEORUPDATE}) - public void onMessage(ConsumerRecord record) { - - try { - // 消息处理逻辑 - if (null == record) { - log.warn("message cannot be empty {}", record); - return; - } - - Object message = JSONObject.parse(String.valueOf(record.value())); - JSONObject stableMessage = JSONObject.parseObject(message.toString()); - log.info("TDengine消费{}超级表消息:{}", stableMessage.get("type"), stableMessage.get("msg")); - if ("create".equals(stableMessage.get("type"))) { - try { - productSuperTableCreateOrUpdateService.createProductSuperTable(String.valueOf(stableMessage.get("msg"))); - } catch (Exception e) { - log.error(e.getMessage()); - } - } else if ("update".equals(stableMessage.get("type"))) { - productSuperTableCreateOrUpdateService.updateProductSuperTable(String.valueOf(stableMessage.get("msg"))); - } - } catch (Exception e) { - // 记录具体错误信息和相关内容 - log.error(e.getMessage()); - } - - } -} From e7e1a45851a0832bf1bb0abdee4635778fcf2d2b Mon Sep 17 00:00:00 2001 From: xiaonan <13733918655@163.com> Date: Mon, 4 Mar 2024 16:55:36 +0800 Subject: [PATCH 07/35] =?UTF-8?q?=E8=A7=A3=E6=9E=90=E5=8D=8F=E8=AE=AE?= =?UTF-8?q?=E5=8D=87=E7=BA=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/sql/changeRecord/1.2.0.RELEASE.sql | 17 +- doc/sql/thinglinks.sql | 63 ++-- .../broker/api/RemoteMqttBrokerOpenApi.java | 6 +- .../PublishMessageRequestVO.java} | 4 +- .../RemoteMqttBrokerOpenApiFallback.java | 6 +- .../link/api/RemoteDeviceService.java | 143 +++++++- .../domain/cache/device/DeviceCacheVO.java | 41 +++ .../domain/cache/product/ProductCacheVO.java | 35 ++ .../cache/product/ProductModelCacheVO.java | 29 ++ .../link/api/domain/device/entity/Device.java | 54 ++- .../domain/device/entity/DeviceAction.java | 9 +- .../api/domain/device/entity/DeviceDatas.java | 8 +- .../domain/device/entity/DeviceLocation.java | 10 +- .../api/domain/device/entity/DeviceTopic.java | 8 +- .../enumeration/DeviceActionTypeEnum.java | 54 +++ .../domain/deviceInfo/entity/DeviceInfo.java | 10 +- .../api/domain/product/entity/Product.java | 10 +- .../product/entity/ProductCommands.java | 9 +- .../entity/ProductCommandsRequests.java | 8 +- .../entity/ProductCommandsResponse.java | 8 +- .../product/entity/ProductProperties.java | 9 +- .../product/entity/ProductServices.java | 11 +- .../product/entity/ProductTemplate.java | 11 +- .../link/api/domain/protocol/Protocol.java | 10 +- .../vo/param/CommandIssueRequestParam.java | 64 ++++ .../vo/param/DeviceCommandWrapperParam.java | 44 +++ .../vo/param/OpenAiChatRequestParam.java | 60 ++++ .../vo/param/OtaCommandRequestParam.java | 62 ++++ .../vo/param/OtaCommandResponseParam.java | 71 ++++ .../vo/param/TopoAddSubDeviceParam.java | 65 ++++ .../vo/param/TopoDeleteSubDeviceParam.java | 42 +++ .../vo/param/TopoDeviceDataReportParam.java | 78 +++++ .../domain/vo/param/TopoQueryDeviceParam.java | 37 ++ .../param/TopoUpdateSubDeviceStatusParam.java | 63 ++++ .../vo/result/DeviceCommandResultVO.java | 75 ++++ .../vo/result/OpenAiChatResponseResultVO.java | 128 +++++++ .../result/ProtocolDataMessageResultVO.java | 53 +++ .../vo/result/TopoAddDeviceResultVO.java | 79 +++++ .../result/TopoDeviceOperationResultVO.java | 58 ++++ .../vo/result/TopoQueryDeviceResultVO.java | 136 ++++++++ .../factory/RemoteDeviceFallbackFactory.java | 143 +++++++- .../api/domain/SuperTableDescribeVO.java | 56 +++ thinglinks-common/pom.xml | 1 + .../thinglinks-common-core/pom.xml | 2 +- .../common/core/constant/CacheConstants.java | 35 +- .../common/core/constant/Constants.java | 15 - .../core/enums/DeviceConnectStatus.java | 36 -- .../core/enums/DeviceConnectStatusEnum.java | 69 ++++ .../core/mqs/ConsumerGroupConstant.java | 19 + .../core/mqs/ConsumerTopicConstant.java | 102 ++++++ .../common/core/utils/AesUtils.java | 145 ++++++++ .../common/core/utils/SHA256Utils.java | 67 ++++ .../common/core/utils/Sm4Utils.java | 101 ++++++ .../common/core/utils/SnowflakeIdUtil.java | 143 ++++++++ .../common/core/utils/bean/BeanPlusUtil.java | 40 +++ .../kafka/constant/ConsumerTopicConstant.java | 82 ----- .../thinglinks-common-protocol/README.md | 4 + .../thinglinks-common-protocol/pom.xml | 24 ++ .../factory/ProtocolMessageAdapter.java | 76 ++++ .../protocol/model/EncryptionDetailsDTO.java | 69 ++++ .../model/ProtocolDataMessageDTO.java | 68 ++++ ...ProtocolMessageSignatureVerifierUtils.java | 285 +++++++++++++++ ...tocolRegexTopicVariableExtractorUtils.java | 47 +++ ...ot.autoconfigure.AutoConfiguration.imports | 1 + .../constant/ConsumerGroupConstant.java | 42 --- .../constant/ConsumerTopicConstant.java | 39 --- .../thinglinks-modules-broker/pom.xml | 21 ++ .../common/asyncthread/BrokerAsyncConfig.java | 94 +++++ .../broker/config/KafkaConsumerConfig.java | 109 ++++++ .../broker/config/KafkaProviderConfig.java | 90 +++++ .../controller/MqttBrokerOpenController.java | 10 +- .../broker/mqs/event/MqttCloseEvent.java | 31 ++ .../broker/mqs/event/MqttConnectEvent.java | 31 ++ .../broker/mqs/event/MqttDisconnectEvent.java | 31 ++ .../broker/mqs/event/MqttPingEvent.java | 31 ++ .../broker/mqs/event/MqttPublishEvent.java | 32 ++ .../broker/mqs/event/MqttSubscribeEvent.java | 31 ++ .../mqs/event/MqttUnsubscribeEvent.java | 32 ++ .../listener/MqttCloseEventListener.java | 81 +++++ .../listener/MqttConnectEventListener.java | 81 +++++ .../listener/MqttDisconnectEventListener.java | 81 +++++ .../event/listener/MqttPingEventListener.java | 32 ++ .../listener/MqttPublishEventListener.java | 58 ++++ .../listener/MqttSubscribeEventListener.java | 38 ++ .../MqttUnsubscribeEventListener.java | 38 ++ .../event/publisher/MqttEventPublisher.java | 59 ++++ .../handler/kafka/KafkaProducerService.java | 49 +++ .../handler/kafka/KafkaSendResultHandler.java | 34 ++ .../MqttMessageKafkaConsumerHandler.java | 131 +++++++ .../kafka/MyKafkaListenerErrorHandler.java | 38 ++ .../mqs/mqtt/handler/AddSubDeviceHandler.java | 118 +++++++ .../mqtt/handler/CommandResponseHandler.java | 78 +++++ .../mqs/mqtt/handler/DefaultHandler.java | 28 ++ .../mqtt/handler/DeleteSubDeviceHandler.java | 110 ++++++ .../mqs/mqtt/handler/DeviceDatasHandler.java | 326 ++++++++++++++++++ .../handler/OtaCommandResponseHandler.java | 88 +++++ .../mqs/mqtt/handler/QueryDeviceHandler.java | 116 +++++++ .../mqs/mqtt/handler/SecretKeyHandler.java | 86 +++++ .../broker/mqs/mqtt/handler/TopicHandler.java | 19 + .../mqtt/handler/UpdateSubDeviceHandler.java | 109 ++++++ .../mqtt/handler/event/MqttMessageEvent.java | 91 +++++ .../factory/AbstractMessageHandler.java | 85 +++++ .../handler/factory/TopicHandlerFactory.java | 106 ++++++ .../handler/listener/MqttMessageListener.java | 48 +++ .../mqtt/service/MqttEventActionService.java | 60 ++++ .../mqtt/service/MqttEventCommandService.java | 62 ++++ .../MqttEventOtaCommandResponseService.java | 75 ++++ .../broker/service/MqttBrokerService.java | 6 +- .../service/impl/MqttBrokerServiceImpl.java | 38 +- .../src/main/resources/bootstrap.yml | 2 + .../thinglinks-modules-link/pom.xml | 7 - .../common/asyncthread/LinkAsyncConfig.java | 4 +- .../link/common/cache/CacheSuperAbstract.java | 11 + .../common/cache/helper/CacheDataHelper.java | 112 ++++++ .../cache/service/DeviceCacheService.java | 133 +++++++ .../DeviceActionMessageKafkaConsumer.java | 21 +- .../DeviceActionMessageRocketmqConsumer.java | 1 + .../listener/RedisKeyExpirationListener.java | 5 +- .../controller/device/DeviceController.java | 186 +++++++++- .../device/impl/DeviceActionServiceImpl.java | 8 +- .../device/impl/DeviceDatasServiceImpl.java | 31 +- .../device/impl/DeviceInfoServiceImpl.java | 4 +- .../device/impl/DeviceServiceImpl.java | 13 +- .../product/impl/ProductServiceImpl.java | 13 +- .../protocol/impl/ProtocolServiceImpl.java | 7 +- .../thinglinks-modules-rule/pom.xml | 8 + .../RuleTriggerMessageRocketmqConsumer.java | 7 +- ...eateSuperTableMessageRocketmqConsumer.java | 14 +- 128 files changed, 6504 insertions(+), 394 deletions(-) rename thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/{model/PublishMessageRequest.java => vo/PublishMessageRequestVO.java} (93%) create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/device/DeviceCacheVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductCacheVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductModelCacheVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/enumeration/DeviceActionTypeEnum.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/CommandIssueRequestParam.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/DeviceCommandWrapperParam.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/OpenAiChatRequestParam.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/OtaCommandRequestParam.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/OtaCommandResponseParam.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoAddSubDeviceParam.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoDeleteSubDeviceParam.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoDeviceDataReportParam.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoQueryDeviceParam.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoUpdateSubDeviceStatusParam.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/DeviceCommandResultVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/OpenAiChatResponseResultVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/ProtocolDataMessageResultVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoAddDeviceResultVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoDeviceOperationResultVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoQueryDeviceResultVO.java create mode 100644 thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/SuperTableDescribeVO.java delete mode 100644 thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/enums/DeviceConnectStatus.java create mode 100644 thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/enums/DeviceConnectStatusEnum.java create mode 100644 thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/ConsumerGroupConstant.java create mode 100644 thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/ConsumerTopicConstant.java create mode 100644 thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/AesUtils.java create mode 100644 thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/SHA256Utils.java create mode 100644 thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/Sm4Utils.java create mode 100644 thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/SnowflakeIdUtil.java create mode 100755 thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/bean/BeanPlusUtil.java delete mode 100644 thinglinks-common/thinglinks-common-kafka/src/main/java/com/mqttsnet/thinglinks/common/kafka/constant/ConsumerTopicConstant.java create mode 100644 thinglinks-common/thinglinks-common-protocol/README.md create mode 100644 thinglinks-common/thinglinks-common-protocol/pom.xml create mode 100644 thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/factory/ProtocolMessageAdapter.java create mode 100644 thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/model/EncryptionDetailsDTO.java create mode 100644 thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/model/ProtocolDataMessageDTO.java create mode 100644 thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/utils/ProtocolMessageSignatureVerifierUtils.java create mode 100644 thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/utils/ProtocolRegexTopicVariableExtractorUtils.java create mode 100644 thinglinks-common/thinglinks-common-protocol/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports delete mode 100644 thinglinks-common/thinglinks-common-rocketmq/src/main/java/com/mqttsnet/thinglinks/common/rocketmq/constant/ConsumerGroupConstant.java delete mode 100644 thinglinks-common/thinglinks-common-rocketmq/src/main/java/com/mqttsnet/thinglinks/common/rocketmq/constant/ConsumerTopicConstant.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/common/asyncthread/BrokerAsyncConfig.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/config/KafkaConsumerConfig.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/config/KafkaProviderConfig.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttCloseEvent.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttConnectEvent.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttDisconnectEvent.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPingEvent.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPublishEvent.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttSubscribeEvent.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttUnsubscribeEvent.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttCloseEventListener.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttConnectEventListener.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttDisconnectEventListener.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPingEventListener.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPublishEventListener.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttSubscribeEventListener.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttUnsubscribeEventListener.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/publisher/MqttEventPublisher.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaProducerService.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaSendResultHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MqttMessageKafkaConsumerHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MyKafkaListenerErrorHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/AddSubDeviceHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/CommandResponseHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DefaultHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeleteSubDeviceHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeviceDatasHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/OtaCommandResponseHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/QueryDeviceHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/SecretKeyHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/TopicHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/UpdateSubDeviceHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/event/MqttMessageEvent.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/AbstractMessageHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/TopicHandlerFactory.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/listener/MqttMessageListener.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventActionService.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventCommandService.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventOtaCommandResponseService.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/CacheSuperAbstract.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/helper/CacheDataHelper.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java diff --git a/doc/sql/changeRecord/1.2.0.RELEASE.sql b/doc/sql/changeRecord/1.2.0.RELEASE.sql index 83f0b36d..ccdad5f8 100644 --- a/doc/sql/changeRecord/1.2.0.RELEASE.sql +++ b/doc/sql/changeRecord/1.2.0.RELEASE.sql @@ -1,3 +1,14 @@ +# 设备表新增字段 +ALTER TABLE thinglinks_test.device ADD encrypt_key varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '加密密钥'; +ALTER TABLE thinglinks_test.device ADD encrypt_vector varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '加密向量'; +ALTER TABLE thinglinks_test.device ADD sign_key varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '签名密钥'; +ALTER TABLE thinglinks_test.device ADD encrypt_method tinyint(4) DEFAULT 0 NOT NULL COMMENT '协议加密方式'; +ALTER TABLE thinglinks_test.device ADD sw_version varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '软件版本'; +ALTER TABLE thinglinks_test.device ADD fw_version varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '固件版本'; +ALTER TABLE thinglinks_test.device ADD device_sdk_version varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT 'v1' NOT NULL COMMENT 'sdk版本'; + + + CREATE TABLE `ota_upgrades` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', @@ -15,7 +26,6 @@ CREATE TABLE `ota_upgrades` `created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `updated_by` bigint(20) DEFAULT NULL COMMENT '更新人', `updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - `created_org_id` bigint(20) DEFAULT NULL COMMENT '创建人组织', PRIMARY KEY (`id`) USING BTREE, KEY `idx_app_id` (`app_id`) USING BTREE COMMENT '应用ID', KEY `idx_product_identification` (`product_identification`) USING BTREE COMMENT '产品标识', @@ -35,7 +45,6 @@ CREATE TABLE `ota_upgrade_tasks` `created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `updated_by` bigint(20) DEFAULT NULL COMMENT '更新人', `updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - `created_org_id` bigint(20) DEFAULT NULL COMMENT '创建人组织', PRIMARY KEY (`id`) USING BTREE, KEY `idx_upgrade_id` (`upgrade_id`) USING BTREE COMMENT '升级包ID' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='OTA升级任务表'; @@ -55,8 +64,10 @@ CREATE TABLE `ota_upgrade_records` `failure_details` longtext COMMENT '升级失败详细信息', `log_details` longtext COMMENT '升级过程日志', `remark` varchar(255) DEFAULT '' COMMENT '描述', + `created_by` bigint(20) DEFAULT NULL COMMENT '创建人', `created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '记录创建时间', - `created_org_id` bigint(20) DEFAULT NULL COMMENT '创建人组织', + `updated_by` bigint(20) DEFAULT NULL COMMENT '更新人', + `updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`) USING BTREE, UNIQUE KEY `idx_task_id_device_identification` (`task_id`,`device_identification`) USING BTREE, KEY `idx_task_id` (`task_id`), diff --git a/doc/sql/thinglinks.sql b/doc/sql/thinglinks.sql index 270d2165..6d838fee 100644 --- a/doc/sql/thinglinks.sql +++ b/doc/sql/thinglinks.sql @@ -450,36 +450,43 @@ COMMIT; -- Table structure for device -- ---------------------------- DROP TABLE IF EXISTS `device`; +-- thinglinks_test.device definition + CREATE TABLE `device` ( `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT 'id', - `client_id` varchar(255) NOT NULL COMMENT '客户端标识', - `user_name` varchar(255) NOT NULL COMMENT '用户名', - `password` varchar(255) NOT NULL COMMENT '密码', - `app_id` varchar(64) NOT NULL COMMENT '应用ID', - `auth_mode` varchar(255) DEFAULT NULL COMMENT '认证方式', - `device_identification` varchar(100) NOT NULL COMMENT '设备标识', - `device_name` varchar(255) NOT NULL COMMENT '设备名称', - `connector` varchar(255) DEFAULT NULL COMMENT '连接实例', - `device_description` varchar(255) DEFAULT NULL COMMENT '设备描述', - `device_status` varchar(255) NOT NULL COMMENT '设备状态: 启用 || 禁用', - `connect_status` varchar(255) DEFAULT NULL COMMENT '连接状态 : 在线:ONLINE || 离线:OFFLINE || 未连接:INIT', - `is_will` varchar(255) DEFAULT NULL COMMENT '是否遗言', - `device_tags` varchar(255) DEFAULT NULL COMMENT '设备标签', - `product_identification` varchar(255) NOT NULL COMMENT '产品标识', - `protocol_type` varchar(255) NOT NULL COMMENT '产品协议类型 :mqtt || coap || modbus || http', - `device_type` varchar(255) DEFAULT NULL COMMENT '设备类型', - `create_by` varchar(64) DEFAULT 'ununited' COMMENT '创建者', - `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `update_by` varchar(64) DEFAULT '' COMMENT '更新者', - `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - `remark` varchar(500) DEFAULT NULL COMMENT '备注', + `client_id` varchar(255) NOT NULL COMMENT '客户端标识', + `user_name` varchar(255) NOT NULL COMMENT '用户名', + `password` varchar(255) NOT NULL COMMENT '密码', + `app_id` varchar(64) NOT NULL COMMENT '应用ID', + `auth_mode` varchar(255) DEFAULT NULL COMMENT '认证方式', + `device_identification` varchar(100) NOT NULL COMMENT '设备标识', + `device_name` varchar(255) NOT NULL COMMENT '设备名称', + `connector` varchar(255) DEFAULT NULL COMMENT '连接实例', + `device_description` varchar(255) DEFAULT NULL COMMENT '设备描述', + `device_status` varchar(255) NOT NULL COMMENT '设备状态: 启用 || 禁用', + `connect_status` varchar(255) DEFAULT NULL COMMENT '连接状态 : 在线:ONLINE || 离线:OFFLINE || 未连接:INIT', + `is_will` varchar(255) DEFAULT NULL COMMENT '是否遗言', + `device_tags` varchar(255) DEFAULT NULL COMMENT '设备标签', + `product_identification` varchar(255) NOT NULL COMMENT '产品标识', + `protocol_type` varchar(255) NOT NULL COMMENT '产品协议类型 :mqtt || coap || modbus || http', + `device_type` varchar(255) DEFAULT NULL COMMENT '设备类型', + `create_by` varchar(64) DEFAULT 'ununited' COMMENT '创建者', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_by` varchar(64) DEFAULT '' COMMENT '更新者', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `remark` varchar(500) DEFAULT NULL COMMENT '备注', + `encrypt_key` varchar(255) CHARACTER SET utf8mb4 DEFAULT '' COMMENT '加密密钥', + `encrypt_vector` varchar(255) CHARACTER SET utf8mb4 DEFAULT '' COMMENT '加密向量', + `sign_key` varchar(255) CHARACTER SET utf8mb4 DEFAULT '' COMMENT '签名密钥', + `encrypt_method` tinyint(4) NOT NULL DEFAULT '0' COMMENT '协议加密方式', + `sw_version` varchar(255) CHARACTER SET utf8mb4 DEFAULT '' COMMENT '软件版本', + `fw_version` varchar(255) CHARACTER SET utf8mb4 DEFAULT '' COMMENT '固件版本', + `device_sdk_version` varchar(255) CHARACTER SET utf8mb4 NOT NULL DEFAULT 'v1' COMMENT 'sdk版本', PRIMARY KEY (`id`) USING BTREE, KEY `device_id` (`device_identification`) USING BTREE COMMENT '设备标识', KEY `client_id` (`client_id`) USING BTREE COMMENT '客户端标识' -) ENGINE = InnoDB - AUTO_INCREMENT = 67 - DEFAULT CHARSET = utf8 COMMENT ='边设备档案信息表'; +) ENGINE=InnoDB AUTO_INCREMENT=84 DEFAULT CHARSET=utf8 COMMENT='边设备档案信息表'; -- ---------------------------- -- Records of device @@ -4321,6 +4328,8 @@ CREATE TABLE `ota_upgrades` -- Table structure for ota_upgrade_tasks -- ---------------------------- +-- thinglinks_test.ota_upgrade_tasks definition + CREATE TABLE `ota_upgrade_tasks` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', @@ -4334,7 +4343,6 @@ CREATE TABLE `ota_upgrade_tasks` `created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `updated_by` bigint(20) DEFAULT NULL COMMENT '更新人', `updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - `created_org_id` bigint(20) DEFAULT NULL COMMENT '创建人组织', PRIMARY KEY (`id`) USING BTREE, KEY `idx_upgrade_id` (`upgrade_id`) USING BTREE COMMENT '升级包ID' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='OTA升级任务表'; @@ -4348,6 +4356,7 @@ CREATE TABLE `ota_upgrade_tasks` -- Table structure for ota_upgrade_records -- ---------------------------- + CREATE TABLE `ota_upgrade_records` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', @@ -4363,6 +4372,10 @@ CREATE TABLE `ota_upgrade_records` `failure_details` longtext COMMENT '升级失败详细信息', `log_details` longtext COMMENT '升级过程日志', `remark` varchar(255) DEFAULT '' COMMENT '描述', + `created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '记录创建时间', + `created_by` bigint(20) DEFAULT NULL COMMENT '创建人', + `updated_by` bigint(20) DEFAULT NULL COMMENT '更新人', + `updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`) USING BTREE, UNIQUE KEY `idx_task_id_device_identification` (`task_id`,`device_identification`) USING BTREE, KEY `idx_task_id` (`task_id`), diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/RemoteMqttBrokerOpenApi.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/RemoteMqttBrokerOpenApi.java index 881a406e..eaada038 100644 --- a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/RemoteMqttBrokerOpenApi.java +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/RemoteMqttBrokerOpenApi.java @@ -1,6 +1,6 @@ package com.mqttsnet.thinglinks.broker.api; -import com.mqttsnet.thinglinks.broker.api.domain.model.PublishMessageRequest; +import com.mqttsnet.thinglinks.broker.api.domain.vo.PublishMessageRequestVO; import com.mqttsnet.thinglinks.broker.api.factory.RemoteMqttBrokerOpenApiFallback; import com.mqttsnet.thinglinks.common.core.constant.ServiceNameConstants; import com.mqttsnet.thinglinks.common.core.domain.R; @@ -30,12 +30,12 @@ public interface RemoteMqttBrokerOpenApi { /** * MQTT推送消息接口 * - * @param publishMessageRequest 推送消息请求参数 + * @param publishMessageRequestVO 推送消息请求参数 * @return {@link R} 结果 */ @ApiOperation(value = "MQTT推送消息", notes = "根据提供的主题、服务质量等级、保留标志和消息内容推送MQTT消息") @PostMapping("/sendMessage") - R sendMessage(@ApiParam(value = "推送消息请求参数", required = true) @RequestBody PublishMessageRequest publishMessageRequest); + R sendMessage(@ApiParam(value = "推送消息请求参数", required = true) @RequestBody PublishMessageRequestVO publishMessageRequestVO); /** * 关闭客户端连接 diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/model/PublishMessageRequest.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/vo/PublishMessageRequestVO.java similarity index 93% rename from thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/model/PublishMessageRequest.java rename to thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/vo/PublishMessageRequestVO.java index 7d19aad8..2fd9a069 100644 --- a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/model/PublishMessageRequest.java +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/vo/PublishMessageRequestVO.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.broker.api.domain.model; +package com.mqttsnet.thinglinks.broker.api.domain.vo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -23,7 +23,7 @@ @EqualsAndHashCode @Builder @ApiModel(value = "PublishMessageRequestVO", description = "MQTT 发送消息VO") -public class PublishMessageRequest implements Serializable { +public class PublishMessageRequestVO implements Serializable { private static final long serialVersionUID = 1L; diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/RemoteMqttBrokerOpenApiFallback.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/RemoteMqttBrokerOpenApiFallback.java index c1f2b7c9..71ab86ae 100644 --- a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/RemoteMqttBrokerOpenApiFallback.java +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/factory/RemoteMqttBrokerOpenApiFallback.java @@ -1,7 +1,7 @@ package com.mqttsnet.thinglinks.broker.api.factory; import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; -import com.mqttsnet.thinglinks.broker.api.domain.model.PublishMessageRequest; +import com.mqttsnet.thinglinks.broker.api.domain.vo.PublishMessageRequestVO; import com.mqttsnet.thinglinks.common.core.domain.R; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,11 +34,11 @@ public RemoteMqttBrokerOpenApi create(Throwable throwable) { /** * MQTT推送消息接口 * - * @param publishMessageRequest 推送消息请求参数 + * @param publishMessageRequestVO 推送消息请求参数 * @return {@link R} 结果 */ @Override - public R sendMessage(PublishMessageRequest publishMessageRequest) { + public R sendMessage(PublishMessageRequestVO publishMessageRequestVO) { return R.fail("remoteMqttBrokerOpenApi.sendMessage() Service call failure e:{}", throwable.getMessage()); } diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceService.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceService.java index 7b911a93..00e2b08a 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceService.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceService.java @@ -3,10 +3,17 @@ import com.mqttsnet.thinglinks.common.core.constant.ServiceNameConstants; import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.*; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoQueryDeviceResultVO; import com.mqttsnet.thinglinks.link.api.factory.RemoteDeviceFallbackFactory; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.*; +import javax.validation.Valid; import java.util.List; import java.util.Map; @@ -55,10 +62,11 @@ public interface RemoteDeviceService { */ @GetMapping("/device/selectByProductIdentificationAndDeviceIdentification/{productIdentification}/{deviceIdentification}") public R selectByProductIdentificationAndDeviceIdentification(@PathVariable("productIdentification") String productIdentification, - @PathVariable("deviceIdentification") String deviceIdentification); + @PathVariable("deviceIdentification") String deviceIdentification); /** * 根据客户端标识获取设备信息 + * * @param clientId * @return */ @@ -67,6 +75,7 @@ public R selectByProductIdentificationAndDeviceIdentification(@PathVaria /** * 根据产品标识获取产品所有关联设备 + * * @param productIdentification * @return */ @@ -75,4 +84,136 @@ public R selectByProductIdentificationAndDeviceIdentification(@PathVaria @PostMapping("/device/selectDeviceByDeviceIdentificationList") public R selectDeviceByDeviceIdentificationList(@RequestBody List deviceIdentificationList); + + /** + * (MQTT)协议新增子设备档案 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 新增结果 + */ + @ApiOperation(value = "(MQTT)协议新增子设备档案", httpMethod = "POST", notes = "(MQTT)协议新增子设备档案") + @PostMapping("/saveSubDeviceByMqtt") + R saveSubDeviceByMqtt(@RequestBody TopoAddSubDeviceParam topoAddSubDeviceParam); + + + /** + * (HTTP)协议新增子设备档案 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 新增结果 + */ + @ApiOperation(value = "(HTTP)协议新增子设备档案", httpMethod = "POST", notes = "(HTTP)协议新增子设备档案") + @PostMapping("/saveSubDeviceByHttp") + public R saveSubDeviceByHttp(@RequestBody TopoAddSubDeviceParam topoAddSubDeviceParam); + + + /** + * MQTT协议修改子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 连接状态参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @ApiOperation(value = "(MQTT)协议修改子设备连接状态", httpMethod = "PUT", notes = "(MQTT)协议修改子设备连接状态") + @PutMapping("/updateSubDeviceConnectStatusByMqtt") + R updateSubDeviceConnectStatusByMqtt(@RequestBody @ApiParam(value = "连接状态参数") TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam); + + + /** + * HTTP协议修改子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 连接状态参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @ApiOperation(value = "(HTTP)协议修改子设备连接状态", httpMethod = "PUT", notes = "(HTTP)协议修改子设备连接状态") + @PutMapping("/updateSubDeviceConnectStatusByHttp") + R updateSubDeviceConnectStatusByHttp(@RequestBody @ApiParam(value = "连接状态参数") TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam); + + /** + * MQTT协议删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @ApiOperation(value = "(MQTT)协议删除子设备", httpMethod = "PUT", notes = "(MQTT)协议删除子设备") + @PutMapping("/deleteSubDeviceByMqtt") + R deleteSubDeviceByMqtt(@RequestBody @ApiParam(value = "删除参数") TopoDeleteSubDeviceParam topoDeleteSubDeviceParam); + + + /** + * HTTP协议删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @ApiOperation(value = "(HTTP)协议删除子设备", httpMethod = "PUT", notes = "(HTTP)协议删除子设备") + @PutMapping("/deleteSubDeviceByHttp") + R deleteSubDeviceByHttp(@RequestBody @ApiParam(value = "删除参数") TopoDeleteSubDeviceParam topoDeleteSubDeviceParam); + + + /** + * MQTT协议数据上报 + * + * @param topoDeviceDataReportParam 数据上报参数 + * @return {@link TopoDeviceOperationResultVO} 上报结果 + */ + @ApiOperation(value = "(MQTT)协议数据上报", httpMethod = "PUT", notes = "(MQTT)协议数据上报") + @PostMapping("/deviceDataReportByMqtt") + R deviceDataReportByMqtt(@RequestBody @ApiParam(value = "数据上报参数") TopoDeviceDataReportParam topoDeviceDataReportParam); + + /** + * HTTP协议数据上报 + * + * @param topoDeviceDataReportParam 数据上报参数 + * @return {@link TopoDeviceOperationResultVO} 上报结果 + */ + @ApiOperation(value = "(HTTP)协议数据上报", httpMethod = "PUT", notes = "(HTTP)协议数据上报") + @PostMapping("/deviceDataReportByHttp") + R deviceDataReportByHttp(@RequestBody @ApiParam(value = "数据上报参数") TopoDeviceDataReportParam topoDeviceDataReportParam); + + /** + * Queries device information using the MQTT protocol. + * + * @param topoQueryDeviceParam The device query parameters. + * @return {@link TopoQueryDeviceResultVO} The result of the device query. + */ + @ApiOperation(value = "Query Device Information via MQTT Protocol", httpMethod = "POST", notes = "Queries device information using the MQTT protocol") + @PostMapping("/queryDeviceByMqtt") + public R queryDeviceByMqtt(@RequestBody TopoQueryDeviceParam topoQueryDeviceParam); + + /** + * Queries device information using the HTTP protocol. + * + * @param topoQueryDeviceParam The device query parameters. + * @return {@link TopoQueryDeviceResultVO} The result of the device query. + */ + @ApiOperation(value = "Query Device Information via HTTP Protocol", httpMethod = "POST", notes = "Queries device information using the HTTP protocol") + @PostMapping("/queryDeviceByHttp") + public R queryDeviceByHttp(@RequestBody TopoQueryDeviceParam topoQueryDeviceParam); + + + /** + * Receives and saves a new OTA upgrade record from an MQTT message. This endpoint + * captures the command response parameters from the MQTT message body and persists them. + * + * @param otaCommandResponseParam The response parameters from an OTA command sent via MQTT. + * @return {@link R} A response entity containing the saved OTA upgrade record. + */ + @ApiOperation(value = "Save OTA Upgrade Record", httpMethod = "POST", notes = "Saves a new OTA upgrade record from MQTT message data.") + @PostMapping("/saveUpgradeRecordByMqtt") + public R saveUpgradeRecordByMqtt(@Valid @RequestBody OtaCommandResponseParam otaCommandResponseParam); + + + /** + * Receives and saves a new OTA upgrade record from an HTTP request. This endpoint + * captures the command response parameters from the request body and persists them. + * + * @param otaCommandResponseParam The response parameters from an OTA command sent via HTTP. + * @return {@link R} A response wrapper containing the saved OTA upgrade record. + */ + @ApiOperation(value = "Save OTA Upgrade Record via HTTP", httpMethod = "POST", notes = "Saves a new OTA upgrade record from HTTP request data.") + @PostMapping("/saveUpgradeRecordByHttp") + public R saveUpgradeRecordByHttp(@Valid @RequestBody OtaCommandResponseParam otaCommandResponseParam); + + + } diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/device/DeviceCacheVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/device/DeviceCacheVO.java new file mode 100644 index 00000000..f8c8c28d --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/device/DeviceCacheVO.java @@ -0,0 +1,41 @@ +package com.mqttsnet.thinglinks.link.api.domain.cache.device; + +import cn.hutool.core.map.MapUtil; +import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Map; + +/** + *

+ * 设备档案缓存VO + *

+ * + * @author mqttsnet + * @date 2023-03-14 19:39:59 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode(callSuper = false) +@Builder +@ApiModel(value = "DeviceCacheVO", description = "设备档案缓存VO") +public class DeviceCacheVO extends Device implements Serializable { + + private static final long serialVersionUID = 1L; + + private Map echoMap = MapUtil.newHashMap(); + /** + * 设备产品基础信息 + */ + @ApiModelProperty(value = "设备产品基础信息") + private ProductCacheVO productCacheVO; + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductCacheVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductCacheVO.java new file mode 100644 index 00000000..2c00f490 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductCacheVO.java @@ -0,0 +1,35 @@ +package com.mqttsnet.thinglinks.link.api.domain.cache.product; + +import cn.hutool.core.map.MapUtil; +import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; +import io.swagger.annotations.ApiModel; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Map; + +/** + *

+ * 产品模型缓存VO + *

+ * + * @author mqttsnet + * @date 2023-03-14 19:39:59 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode(callSuper = true) +@Builder +@ApiModel(value = "ProductCacheVO", description = "产品模型缓存VO") +public class ProductCacheVO extends Product implements Serializable { + + private static final long serialVersionUID = 1L; + + private Map echoMap = MapUtil.newHashMap(); + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductModelCacheVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductModelCacheVO.java new file mode 100644 index 00000000..940fe0cb --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductModelCacheVO.java @@ -0,0 +1,29 @@ +package com.mqttsnet.thinglinks.link.api.domain.cache.product; + +import com.mqttsnet.thinglinks.link.api.domain.product.model.ProductModel; +import io.swagger.annotations.ApiModel; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + *

+ * 产品模型缓存VO + *

+ * + * @author mqttsnet + * @date 2023-03-14 19:39:59 + */ + +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "ProductModelCacheVO", description = "产品模型缓存VO") +public class ProductModelCacheVO extends ProductModel implements Serializable { + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/Device.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/Device.java index c7f2d592..b567a462 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/Device.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/Device.java @@ -6,8 +6,9 @@ import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.time.LocalDateTime; -import lombok.Data; -import lombok.EqualsAndHashCode; + +import lombok.*; +import lombok.experimental.Accessors; /** @@ -29,6 +30,11 @@ @EqualsAndHashCode(callSuper = true) @ApiModel(value = "设备管理") @Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder public class Device extends BaseEntity implements Serializable{ /** * id @@ -150,6 +156,50 @@ public class Device extends BaseEntity implements Serializable{ @ApiModelProperty(value = "设备类型") private String deviceType; + /** + * 加密密钥 + */ + @Excel(name = "加密密钥") + @ApiModelProperty(value = "加密密钥") + private String encryptKey; + /** + * 加密向量 + */ + @Excel(name = "加密向量") + @ApiModelProperty(value = "加密向量") + private String encryptVector; + /** + * 签名密钥 + */ + @Excel(name = "签名密钥") + @ApiModelProperty(value = "签名密钥") + private String signKey; + /** + * 传输协议的加密方式:0-明文传输、1-SM4、2-AES + */ + @Excel(name = "传输协议的加密方式") + @ApiModelProperty(value = "传输协议的加密方式:0-明文传输、1-SM4、2-AES ") + private Integer encryptMethod; + + /** + * 软件版本 + */ + @Excel(name = "软件版本") + @ApiModelProperty(value = "软件版本") + private String swVersion; + /** + * 固件版本 + */ + @Excel(name = "固件版本") + @ApiModelProperty(value = "固件版本") + private String fwVersion; + /** + * sdk版本 + */ + @Excel(name = "sdk版本") + @ApiModelProperty(value = "sdk版本") + private String deviceSdkVersion; + private static final long serialVersionUID = 1L; } diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/DeviceAction.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/DeviceAction.java index e2259348..e4101219 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/DeviceAction.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/DeviceAction.java @@ -4,7 +4,9 @@ import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.time.LocalDateTime; -import lombok.Data; + +import lombok.*; +import lombok.experimental.Accessors; /** @@ -24,6 +26,11 @@ */ @ApiModel(value="设备动作数据") @Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder public class DeviceAction implements Serializable { /** * id diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/DeviceDatas.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/DeviceDatas.java index 821a88c1..d71f3d42 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/DeviceDatas.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/DeviceDatas.java @@ -2,7 +2,8 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import lombok.Data; +import lombok.*; +import lombok.experimental.Accessors; import java.io.Serializable; import java.time.LocalDateTime; @@ -25,6 +26,11 @@ */ @ApiModel(value="设备消息") @Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder public class DeviceDatas implements Serializable { /** * id diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/DeviceLocation.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/DeviceLocation.java index a5a29842..8eb45caf 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/DeviceLocation.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/DeviceLocation.java @@ -3,9 +3,8 @@ import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; +import lombok.*; +import lombok.experimental.Accessors; import java.io.Serializable; import java.math.BigDecimal; @@ -28,8 +27,11 @@ */ @ApiModel(value = "设备位置表") @Data -@AllArgsConstructor @NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder public class DeviceLocation implements Serializable { /** * 主键 diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/DeviceTopic.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/DeviceTopic.java index 487aa3d3..143eff06 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/DeviceTopic.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/DeviceTopic.java @@ -2,7 +2,8 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import lombok.Data; +import lombok.*; +import lombok.experimental.Accessors; import java.io.Serializable; import java.time.LocalDateTime; @@ -20,6 +21,11 @@ */ @ApiModel(value="设备Topic数据表") @Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder public class DeviceTopic implements Serializable { /** * id diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/enumeration/DeviceActionTypeEnum.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/enumeration/DeviceActionTypeEnum.java new file mode 100644 index 00000000..61f4da53 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/enumeration/DeviceActionTypeEnum.java @@ -0,0 +1,54 @@ +package com.mqttsnet.thinglinks.link.api.domain.device.enumeration; + +import io.swagger.annotations.ApiModel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +/** + *

+ * 设备动作类型 枚举 + *

+ * + * @author shihuan sun + * @date 2023-08-20 + */ +@Getter +@NoArgsConstructor +@ApiModel(value = "DeviceActionTypeEnum", description = "设备动作类型 枚举") +public enum DeviceActionTypeEnum { + + PUBLISH("PUBLISH", "Publishing data to a topic."), + WRITE("WRITE", "Writing data to a device or topic."), + + CLUSTER("CLUSTER", "Cluster-based actions or references to clusters."), + CONNECT("CONNECT", "Initiating a connection to a server."), + CLOSE("CLOSE", "Closing a connection to a server."), + + SUBSCRIBE("SUBSCRIBE", "Subscribing to a topic to receive messages."), + + UNSUBSCRIBE("UNSUBSCRIBE", "Unsubscribing from a topic to stop receiving messages."), + + BRIDGE("BRIDGE", "Bridging or connecting two different networks or brokers."), + DISCONNECT("DISCONNECT", "Terminating a connection gracefully."), + PING("PING", "Sending a ping request to maintain or check a connection."), + + PUBLISH_ACK("PUBLISH_ACK", "Acknowledging the receipt of a published message."), + + RETRY("RETRY", "Retrying a certain action or request after a failure."), + + HEART_TIMEOUT("HEART_TIMEOUT", "An event indicating a timeout due to lack of heartbeat or keep-alive signal."), + + SYSTEM("SYSTEM", "System level or internal events."), + + UNKNOWN("UNKNOWN", "Unknown action type."); + + private String action; + private String description; + + DeviceActionTypeEnum(String action, String description) { + this.action = action; + this.description = description; + } + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/deviceInfo/entity/DeviceInfo.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/deviceInfo/entity/DeviceInfo.java index 89d7da2c..340a2dff 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/deviceInfo/entity/DeviceInfo.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/deviceInfo/entity/DeviceInfo.java @@ -5,9 +5,8 @@ import com.mqttsnet.thinglinks.link.api.domain.deviceInfo.model.DeviceInfoParams; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; +import lombok.*; +import lombok.experimental.Accessors; import java.io.Serializable; import java.time.LocalDateTime; @@ -25,8 +24,11 @@ */ @ApiModel(value="子设备档案表") @Data -@AllArgsConstructor @NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder public class DeviceInfo implements Serializable { /** * 主键 diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/Product.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/Product.java index 16e9ca85..28f2a57b 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/Product.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/Product.java @@ -2,9 +2,8 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; +import lombok.*; +import lombok.experimental.Accessors; import java.io.Serializable; import java.time.LocalDateTime; @@ -23,8 +22,11 @@ */ @ApiModel(value = "产品模型") @Data -@AllArgsConstructor @NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder public class Product implements Serializable { /** * id diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductCommands.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductCommands.java index 6e99e5d5..70838488 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductCommands.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductCommands.java @@ -5,7 +5,9 @@ import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.time.LocalDateTime; -import lombok.Data; + +import lombok.*; +import lombok.experimental.Accessors; /** @@ -25,6 +27,11 @@ */ @ApiModel(value="产品模型设备服务命令表") @Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder public class ProductCommands extends BaseEntity implements Serializable { /** * 命令id diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductCommandsRequests.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductCommandsRequests.java index 3a5d41c6..b42b2b3d 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductCommandsRequests.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductCommandsRequests.java @@ -7,7 +7,8 @@ import java.io.Serializable; import java.time.LocalDateTime; -import lombok.Data; +import lombok.*; +import lombok.experimental.Accessors; /** * @Description: java类作用描述 @@ -26,6 +27,11 @@ */ @ApiModel(value = "产品模型设备下发服务命令属性表") @Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder public class ProductCommandsRequests extends BaseEntity implements Serializable { /** * id diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductCommandsResponse.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductCommandsResponse.java index af3ceb58..39556d19 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductCommandsResponse.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductCommandsResponse.java @@ -3,7 +3,8 @@ import com.mqttsnet.thinglinks.common.core.web.domain.BaseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import lombok.Data; +import lombok.*; +import lombok.experimental.Accessors; import java.io.Serializable; @@ -25,6 +26,11 @@ */ @ApiModel(value="产品模型设备响应服务命令属性表") @Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder public class ProductCommandsResponse extends BaseEntity implements Serializable { /** * id diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductProperties.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductProperties.java index eb3c012e..f079648a 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductProperties.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductProperties.java @@ -5,7 +5,9 @@ import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.time.LocalDateTime; -import lombok.Data; + +import lombok.*; +import lombok.experimental.Accessors; /** @@ -25,6 +27,11 @@ */ @ApiModel(value="产品模型服务属性表") @Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder public class ProductProperties extends BaseEntity implements Serializable { /** * 属性id diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductServices.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductServices.java index af7dcd2e..7002fbb5 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductServices.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductServices.java @@ -4,9 +4,9 @@ import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.time.LocalDateTime; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; + +import lombok.*; +import lombok.experimental.Accessors; /** * @program: thinglinks @@ -22,8 +22,11 @@ */ @ApiModel(value = "产品模型服务表") @Data -@AllArgsConstructor @NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder public class ProductServices implements Serializable { /** * 服务id diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductTemplate.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductTemplate.java index 29f8bda6..550d367e 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductTemplate.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductTemplate.java @@ -4,9 +4,9 @@ import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.time.LocalDateTime; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; + +import lombok.*; +import lombok.experimental.Accessors; /** * @program: thinglinks @@ -22,8 +22,11 @@ */ @ApiModel(value = "产品模板") @Data -@AllArgsConstructor @NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder public class ProductTemplate implements Serializable { /** * id diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/protocol/Protocol.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/protocol/Protocol.java index a74aba3e..457a3d4a 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/protocol/Protocol.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/protocol/Protocol.java @@ -2,9 +2,8 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; +import lombok.*; +import lombok.experimental.Accessors; import java.io.Serializable; import java.time.LocalDateTime; @@ -23,8 +22,11 @@ */ @ApiModel(value="协议信息表") @Data -@AllArgsConstructor @NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder public class Protocol implements Serializable { /** * id diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/CommandIssueRequestParam.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/CommandIssueRequestParam.java new file mode 100644 index 00000000..563ca6d3 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/CommandIssueRequestParam.java @@ -0,0 +1,64 @@ +package com.mqttsnet.thinglinks.link.api.domain.vo.param; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.Map; + +/** + * ----------------------------------------------------------------------------- + * 文件名称: CommandIssueRequestParam.java + * ----------------------------------------------------------------------------- + * 描述: + * Platform Command Issue Request Data Model + * ----------------------------------------------------------------------------- + * + * @author ShiHuan Sun + * @version 1.0 + * ----------------------------------------------------------------------------- + * 修改历史: + * 日期 作者 版本 描述 + * -------- -------- ------- -------------------- + *

+ * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2023-10-17 09:48 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Builder +@ApiModel(value = "CommandIssueRequestParam", description = "Device Command Request Data Structure") +public class CommandIssueRequestParam implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "Device unique identifier, ALL for all devices.", notes = "Device unique ID generated by the platform.") + @NotEmpty(message = "Device ID cannot be empty") + private String deviceIdentification; + + @ApiModelProperty(value = "Product unique identifier.", notes = "Product unique ID generated by the platform.") + @NotEmpty(message = "Product ID cannot be empty") + private String productIdentification; + + @ApiModelProperty(value = "Fixed value 'cloudReq', indicating the request issued by the platform.", notes = "Fixed value 'cloudReq', indicating the request issued by the platform.") + @NotEmpty(message = "Message type cannot be empty") + private String msgType; + + @ApiModelProperty(value = "Service code.", notes = "Service code.") + @NotEmpty(message = "Service code cannot be empty") + private String serviceCode; + + @ApiModelProperty(value = "Command code for the service.", notes = "Command code for the service.") + @NotEmpty(message = "Command cannot be empty") + private String cmd; + + @ApiModelProperty(value = "Parameters for the command.", notes = "Parameters for the command.") + @NotNull(message = "Parameters cannot be null") + private Map params; +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/DeviceCommandWrapperParam.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/DeviceCommandWrapperParam.java new file mode 100644 index 00000000..550d481b --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/DeviceCommandWrapperParam.java @@ -0,0 +1,44 @@ +package com.mqttsnet.thinglinks.link.api.domain.vo.param; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; + +import java.io.Serializable; +import java.util.List; + +/** + * ----------------------------------------------------------------------------- + * File Name: DeviceCommandWrapperParam.java + * ----------------------------------------------------------------------------- + * Description: + * Device Command Request Wrapper Data Structure + * ----------------------------------------------------------------------------- + * + * @author ShiHuan Sun + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + *

+ * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2023-11-11 14:55 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Builder +@ApiModel(value = "DeviceCommandWrapperParam", description = "Device Command Request Wrapper Data Structure") +public class DeviceCommandWrapperParam implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "List of serial command requests", notes = "List of serial command requests") + private List serial; + + @ApiModelProperty(value = "List of parallel command requests", notes = "List of parallel command requests") + private List parallel; +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/OpenAiChatRequestParam.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/OpenAiChatRequestParam.java new file mode 100644 index 00000000..28809008 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/OpenAiChatRequestParam.java @@ -0,0 +1,60 @@ +package com.mqttsnet.thinglinks.link.api.domain.vo.param; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.Size; +import java.io.Serializable; + +/** + * ----------------------------------------------------------------------------- + * File Name: OpenAiChatRequestParam + * ----------------------------------------------------------------------------- + * Description: + * OpenAiChatRequest + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2023/12/12 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2023/12/12 23:20 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "OpenAiChatRequest", description = "Request parameters for OpenAI Chat API") +public class OpenAiChatRequestParam implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "The unique session ID generated by OpenAI.", notes = "Specify the id to use for this callback.") + private String id; + + @ApiModelProperty(value = "The model to use for this chat (e.g., gpt-3.5-turbo)", notes = "Specifies the model to be used by the API.") + @NotEmpty(message = "Model is required") + private String model; + + @ApiModelProperty(value = "Content of the message to be processed", notes = "Message content to be sent to OpenAI Chat.") + @NotEmpty(message = "Content cannot be null") + @Size(min = 1, max = 1000, message = "Content must be between 1 and 1000 characters") + private String content; + + @ApiModelProperty(value = "API Key for OpenAI", notes = "The API Key for authentication with OpenAI services.") + private String apiKey; + + @ApiModelProperty(value = "API Host for OpenAI", notes = "The host URL for OpenAI services.") + private String apiHost; + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/OtaCommandRequestParam.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/OtaCommandRequestParam.java new file mode 100644 index 00000000..d7d33fbb --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/OtaCommandRequestParam.java @@ -0,0 +1,62 @@ +package com.mqttsnet.thinglinks.link.api.domain.vo.param; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * ----------------------------------------------------------------------------- + * File Name: OtaCommandResponseParam + * ----------------------------------------------------------------------------- + * Description: + * OTA 远程升级请求参数 + * 用于物联网平台向设备发送 OTA 升级指令 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/1/18 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/1/18 22:28 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ApiModel(value = "OtaCommandRequestParam", description = "Request Data Structure for OTA Command") +public class OtaCommandRequestParam implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "Unique identifier for the device", notes = "Unique identifier for the device, as generated by the platform.") + private String deviceIdentification; + + @ApiModelProperty(value = "Unique identifier for the product", notes = "Unique identifier for the product, as generated by the platform.") + private String productIdentification; + + @ApiModelProperty(value = "Unique identifier for the OTA task", notes = "Unique identifier for the OTA task, as assigned by the platform.") + private Long otaTaskId; + + @ApiModelProperty(value = "Type of OTA package", notes = "The type of OTA package, e.g., 0 for software, 1 for firmware.") + private Integer packageType; + + @ApiModelProperty(value = "Version of the OTA package", notes = "The version of the OTA package. Should not exceed 256 characters and may include letters, numbers, underscores (_), hyphens (-), and periods (.)") + private String version; + + @ApiModelProperty(value = "Location of the OTA package file", notes = "The file path or location where the OTA package is stored, accessible within 24 hours.") + private String fileLocation; + + @ApiModelProperty(value = "Description of the OTA package", notes = "A brief description of the OTA package's functionality.") + private String description; + + @ApiModelProperty(value = "Custom information for the OTA package", notes = "Additional custom information related to the OTA package, if any.") + private String customInfo; +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/OtaCommandResponseParam.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/OtaCommandResponseParam.java new file mode 100644 index 00000000..c84e1036 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/OtaCommandResponseParam.java @@ -0,0 +1,71 @@ +package com.mqttsnet.thinglinks.link.api.domain.vo.param; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * ----------------------------------------------------------------------------- + * File Name: OtaCommandResponseParam + * ----------------------------------------------------------------------------- + * Description: + * OTA 远程升级响应参数 + * 用于设备向物联网平台上报 OTA 升级结果 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/1/18 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/1/18 22:28 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ApiModel(value = "OtaCommandResponseParam", description = "Response Data Structure for OTA Command") +public class OtaCommandResponseParam implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "The unique identifier of the device.") + private String deviceIdentification; + + @ApiModelProperty(value = "The unique identifier of the OTA task.") + private Long otaTaskId; + + @ApiModelProperty(value = "The status of the OTA upgrade: 0 for pending, 1 for in progress, 2 for success, 3 for failure.") + private Integer upgradeStatus; + + @ApiModelProperty(value = "The progress of the OTA upgrade in percentage.") + private Integer progress; + + @ApiModelProperty(value = "The start time of the OTA upgrade as a timestamp.") + private Long startTime; + + @ApiModelProperty(value = "The end time of the OTA upgrade as a timestamp.") + private Long endTime; + + @ApiModelProperty(value = "The error code, if any, resulting from the OTA upgrade.") + private String errorCode; + + @ApiModelProperty(value = "The error message, if any, resulting from the OTA upgrade.") + private String errorMessage; + + @ApiModelProperty(value = "Details about the success of the OTA upgrade.") + private String successDetails; + + @ApiModelProperty(value = "Details about the failure of the OTA upgrade.") + private String failureDetails; + + @ApiModelProperty(value = "Logs detailing the OTA upgrade process.") + private String logDetails; +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoAddSubDeviceParam.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoAddSubDeviceParam.java new file mode 100644 index 00000000..3d18925a --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoAddSubDeviceParam.java @@ -0,0 +1,65 @@ +package com.mqttsnet.thinglinks.link.api.domain.vo.param; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.List; + +/** + * @Description: 网关设备添加子设备数据模型 + * @Author: ShiHuan SUN + * @E-mail: 13733918655@163.com + * @Website: http://thinglinks.mqttsnet.com + * @CreateDate: 2022/4/25$ 12:52$ + * @UpdateUser: ShiHuan SUN + * @UpdateDate: 2022/4/25$ 12:52$ + * @UpdateRemark: 修改内容 + * @Version: V1.0 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "TopoAddDeviceSaveVO", description = "网关设备添加子设备数据模型") +public class TopoAddSubDeviceParam implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "网关设备标识", notes = "网关设备自身的唯一标识") + @NotEmpty(message = "网关设备标识不能为空") + private String gatewayIdentification; + + @ApiModelProperty(value = "子设备信息集合", notes = "子设备信息集合") + @NotNull(message = "子设备信息集合不能为空") + private List deviceInfos; + + + @Data + @NoArgsConstructor + @AllArgsConstructor + @Builder + public static class DeviceInfos { + + @ApiModelProperty(value = "子设备ID", notes = "子设备自身的唯一标识") + private String nodeId; + + @ApiModelProperty(value = "子设备名称", notes = "子设备名称") + private String name; + + @ApiModelProperty(value = "子设备描述", notes = "子设备描述") + private String description; + + @ApiModelProperty(value = "子设备厂商ID", notes = "子设备厂商ID") + private String manufacturerId; + + @ApiModelProperty(value = "子设备型号", notes = "子设备型号") + private String model; + } +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoDeleteSubDeviceParam.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoDeleteSubDeviceParam.java new file mode 100644 index 00000000..7d242c2a --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoDeleteSubDeviceParam.java @@ -0,0 +1,42 @@ +package com.mqttsnet.thinglinks.link.api.domain.vo.param; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.List; + +/** + * @Description: 网关设备删除子设备数据模型 + * @Author: ShiHuan SUN + * @E-mail: 13733918655@163.com + * @Website: http://thinglinks.mqttsnet.com + * @CreateDate: 2022/4/25$ 12:52$ + * @UpdateUser: ShiHuan SUN + * @UpdateDate: 2022/4/25$ 12:52$ + * @UpdateRemark: 修改内容 + * @Version: V1.0 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "TopoDeleteDeviceParam", description = "网关设备删除子设备数据模型") +public class TopoDeleteSubDeviceParam implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "网关设备标识", notes = "网关设备自身的唯一标识") + @NotEmpty(message = "网关设备标识不能为空") + private String gatewayIdentification; + + @ApiModelProperty(value = "子设备标识集合", notes = "子设备标识集合") + @NotNull(message = "子设备标识集合不能为空") + private List deviceIds; +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoDeviceDataReportParam.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoDeviceDataReportParam.java new file mode 100644 index 00000000..f94fea2c --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoDeviceDataReportParam.java @@ -0,0 +1,78 @@ +package com.mqttsnet.thinglinks.link.api.domain.vo.param; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.List; + +/** + * @Description: 设备数据上报数据模型 + * @Author: ShiHuan SUN + * @E-mail: 13733918655@163.com + * @Website: http://thinglinks.mqttsnet.com + * @CreateDate: 2022/4/25$ 12:52$ + * @UpdateUser: ShiHuan SUN + * @UpdateDate: 2022/4/25$ 12:52$ + * @UpdateRemark: 修改内容 + * @Version: V1.0 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "TopoDeviceDataReportParam", description = "设备数据上报数据模型") +public class TopoDeviceDataReportParam implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "设备数据", notes = "设备数据") + @NotNull(message = "设备数据不能为空") + private List devices; + + @Data + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Accessors(chain = true) + @ApiModel(value = "DeviceS", description = "设备数据模型") + public static class DeviceS implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "设备唯一标识", notes = "平台生成的设备唯一标识") + @NotEmpty(message = "设备唯一标识不能为空") + private String deviceId; + + @ApiModelProperty(value = "服务列表", notes = "服务列表") + @NotNull(message = "服务列表不能为空") + private List services; + + @Data + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Accessors(chain = true) + @ApiModel(value = "Services", description = "服务数据模型") + public static class Services implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "服务编码", notes = "服务编码,对应平台产品服务编码") + @NotEmpty(message = "服务编码不能为空") + private String serviceCode; + + @ApiModelProperty(value = "服务数据", notes = "服务数据,不固定内容") + @NotNull(message = "服务数据不能为空") + private Object data; + + @ApiModelProperty(value = "事件时间", notes = "时间格式:13位毫秒时间戳。例如,1622552643000表示2021年6月1日17时24分3秒(UTC时间)。") + @NotEmpty(message = "事件时间不能为空") + private Long eventTime; + } + } +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoQueryDeviceParam.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoQueryDeviceParam.java new file mode 100644 index 00000000..06f0d3b1 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoQueryDeviceParam.java @@ -0,0 +1,37 @@ +package com.mqttsnet.thinglinks.link.api.domain.vo.param; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.List; + +/** + * @Description: 查询设备信息数据模型 + * @Author: ShiHuan SUN + * @E-mail: 13733918655@163.com + * @Website: http://thinglinks.mqttsnet.com + * @CreateDate: 2022/4/25$ 12:52$ + * @UpdateUser: ShiHuan SUN + * @UpdateDate: 2024/01/10$ 12:52$ + * @UpdateRemark: 修改内容 + * @Version: V1.0 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "TopoQueryDeviceParam", description = "查询设备信息数据模型") +public class TopoQueryDeviceParam implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "设备标识集合", notes = "设备标识集合") + @NotNull(message = "设备标识集合不能为空") + private List deviceIds; +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoUpdateSubDeviceStatusParam.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoUpdateSubDeviceStatusParam.java new file mode 100644 index 00000000..14aa0596 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoUpdateSubDeviceStatusParam.java @@ -0,0 +1,63 @@ +package com.mqttsnet.thinglinks.link.api.domain.vo.param; + +import com.mqttsnet.thinglinks.device.enumeration.DeviceConnectStatusEnum; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; +import java.util.List; + +/** + * @Description: 网关设备更新子设备状态数据模型 + * @Author: ShiHuan SUN + * @E-mail: 13733918655@163.com + * @Website: http://thinglinks.mqttsnet.com + * @CreateDate: 2022/4/25$ 12:52$ + * @UpdateUser: ShiHuan SUN + * @UpdateDate: 2022/4/25$ 12:52$ + * @UpdateRemark: 修改内容 + * @Version: V1.0 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "TopoUpdateSubDeviceStatusParam", description = "子设备状态更新数据模型") +public class TopoUpdateSubDeviceStatusParam implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "网关设备标识", notes = "网关设备自身的唯一标识") + @NotEmpty(message = "网关设备标识不能为空") + private String gatewayIdentification; + + @ApiModelProperty(value = "子设备状态列表", notes = "子设备状态列表,列表大小 1~100") + @NotNull(message = "子设备状态列表不能为空") + @Size(min = 1, max = 100, message = "子设备状态列表大小必须在1到100之间") + private List deviceStatuses; + + @Data + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Accessors(chain = true) + @ApiModel(value = "DeviceStatus", description = "子设备状态数据模型") + public static class DeviceStatus implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "子设备唯一标识", notes = "平台生成的子设备唯一标识") + @NotEmpty(message = "子设备唯一标识不能为空") + private String deviceId; + + @ApiModelProperty(value = "子设备状态", notes = "子设备状态:OFFLINE:设备离线;ONLINE:设备上线;") + @NotNull(message = "子设备状态不能为空") + private DeviceConnectStatusEnum status; + } +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/DeviceCommandResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/DeviceCommandResultVO.java new file mode 100644 index 00000000..f71163f9 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/DeviceCommandResultVO.java @@ -0,0 +1,75 @@ +package com.mqttsnet.thinglinks.link.api.domain.vo.result; + +import cn.hutool.core.map.MapUtil; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Map; + +/** + *

+ * 表单查询方法返回值VO + * 设备命令下发及响应表 + *

+ * + * @author mqttsnet + * @date 2023-10-20 17:27:25 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode(callSuper = false) +@Builder +@ApiModel(value = "DeviceCommandResultVO", description = "设备命令下发及响应表") +public class DeviceCommandResultVO implements Serializable { + + private static final long serialVersionUID = 1L; + + private Map echoMap = MapUtil.newHashMap(); + + @ApiModelProperty(value = "id") + private Long id; + + /** + * 设备标识 + */ + @ApiModelProperty(value = "设备标识") + private String deviceIdentification; + /** + * 命令标识 + */ + @ApiModelProperty(value = "命令标识") + private String commandIdentification; + /** + * 命令类型(0:命名下发、1:命令响应) + */ + @ApiModelProperty(value = "命令类型(0:命名下发、1:命令响应)") + private Integer commandType; + /** + * 状态 + */ + @ApiModelProperty(value = "状态") + private Integer status; + /** + * 内容 + */ + @ApiModelProperty(value = "内容") + private String content; + /** + * 备注 + */ + @ApiModelProperty(value = "备注") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/OpenAiChatResponseResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/OpenAiChatResponseResultVO.java new file mode 100644 index 00000000..b86a00d6 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/OpenAiChatResponseResultVO.java @@ -0,0 +1,128 @@ +package com.mqttsnet.thinglinks.link.api.domain.vo.result; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.List; + +/** + * ----------------------------------------------------------------------------- + * File Name: OpenAiChatRequestParam + * ----------------------------------------------------------------------------- + * Description: + * OpenAiChatRequest + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2023/12/12 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2023/12/12 23:20 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "OpenAiChatResponseResultVO", description = "Response data from OpenAI Chat API") +public class OpenAiChatResponseResultVO implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "Unique identifier for the response") + private String id; + + @ApiModelProperty(value = "Type of the object returned") + private String object; + + @ApiModelProperty(value = "Timestamp of creation") + private long created; + + @ApiModelProperty(value = "Model used for generating the response") + private String model; + + @ApiModelProperty(value = "List of choices provided by OpenAI") + private List choices; + + @ApiModelProperty(value = "Usage information of tokens") + private Usage usage; + + @ApiModelProperty(value = "Any warning returned by the API") + private String warning; + + @ApiModelProperty(value = "System fingerprint") + @JsonProperty("system_fingerprint") + private String systemFingerprint; + + @Data + @NoArgsConstructor + @AllArgsConstructor + @ToString + @EqualsAndHashCode + public static class Usage implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "Number of tokens used in the prompt") + @JsonProperty("prompt_tokens") + private long promptTokens; + + @ApiModelProperty(value = "Number of tokens used in the completion") + @JsonProperty("completion_tokens") + private long completionTokens; + + @ApiModelProperty(value = "Total number of tokens used") + @JsonProperty("total_tokens") + private long totalTokens; + } + + @Data + @NoArgsConstructor + @AllArgsConstructor + @ToString + @EqualsAndHashCode + public static class ChatChoice implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "Index of the choice") + private long index; + + @ApiModelProperty(value = "Message content in delta format (when stream is true)") + @JsonProperty("delta") + private Message delta; + + @ApiModelProperty(value = "Message content (when stream is false)") + @JsonProperty("message") + private Message message; + + @ApiModelProperty(value = "Reason for completion") + @JsonProperty("finish_reason") + private String finishReason; + + + @Data + @NoArgsConstructor + @AllArgsConstructor + @ToString + @EqualsAndHashCode + public static class Message implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "Content of the message") + private String content; + + @ApiModelProperty(value = "Role of the message sender (e.g., 'user', 'system')") + private String role; + } + } + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/ProtocolDataMessageResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/ProtocolDataMessageResultVO.java new file mode 100644 index 00000000..5b0afee6 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/ProtocolDataMessageResultVO.java @@ -0,0 +1,53 @@ +package com.mqttsnet.thinglinks.link.api.domain.vo.result; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 协议数据内容返回VO + * @packagename: com.mqttsnet.thinglinks.device.vo.result + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-22 15:44 + **/ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder +@ApiModel(value = "ProtocolDataMessageResultVO", description = "协议数据内容返回VO") +public class ProtocolDataMessageResultVO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "消息头部") + private Head head; + + @ApiModelProperty(value = "报文体") + private T dataBody; + + @ApiModelProperty(value = "数据签名") + private String dataSign; + + @ApiModel(description = "消息头部实体类") + @Data + @NoArgsConstructor + @AllArgsConstructor + @Builder + public static class Head { + @ApiModelProperty(value = "加密标志,0-不加密;1-SM4;2-AES", allowableValues = "0, 1, 2", example = "0") + private Integer cipherFlag; + + @ApiModelProperty(value = "消息ID(从1自增即可)", example = "3342") + private Long mid; + + @ApiModelProperty(value = "报文发送时间戳(毫秒)", example = "1624982406963") + private Long timeStamp; + } +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoAddDeviceResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoAddDeviceResultVO.java new file mode 100644 index 00000000..dd7289af --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoAddDeviceResultVO.java @@ -0,0 +1,79 @@ +package com.mqttsnet.thinglinks.link.api.domain.vo.result; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.List; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 协议添加网关子设备响应信息 + * @packagename: com.mqttsnet.thinglinks.device.vo.result + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-18 23:03 + **/ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder +@ApiModel(value = "TopoAddDeviceResultVO", description = "网关子设备响应信息") +public class TopoAddDeviceResultVO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "请求处理的结果码。'0'表示成功。非'0'表示失败。详见附录。", required = true) + private int statusCode; + + @ApiModelProperty(value = "响应状态描述。") + private String statusDesc; + + @ApiModelProperty(value = "添加子设备的结果信息。", required = true) + private List data; + + @Data + @NoArgsConstructor + @AllArgsConstructor + @Builder + public static class DataItem { + + @ApiModelProperty(value = "请求处理的结果码。'0'表示成功。非'0'表示失败。详见附录。", required = true) + private int statusCode; + + @ApiModelProperty(value = "响应状态描述。") + private String statusDesc; + + @ApiModelProperty(value = "设备详细信息") + private DeviceInfo deviceInfo; + + @Data + @NoArgsConstructor + @AllArgsConstructor + @Builder + public static class DeviceInfo { + + @ApiModelProperty(value = "设备名称", required = true) + private String name; + + @ApiModelProperty(value = "厂商ID", required = true) + private String manufacturerId; + + @ApiModelProperty(value = "设备描述") + private String description; + + @ApiModelProperty(value = "设备型号") + private String model; + + @ApiModelProperty(value = "平台生成的设备唯一标识", required = true) + private String deviceId; + + @ApiModelProperty(value = "设备自身的唯一标识", required = true) + private String nodeId; + } + } +} \ No newline at end of file diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoDeviceOperationResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoDeviceOperationResultVO.java new file mode 100644 index 00000000..80aa939b --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoDeviceOperationResultVO.java @@ -0,0 +1,58 @@ +package com.mqttsnet.thinglinks.link.api.domain.vo.result; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.List; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 设备操作结果数据模型 + * @packagename: com.mqttsnet.thinglinks.device.vo.result + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-22 14:17 + **/ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +@Accessors(chain = true) +@ApiModel(value = "TopoDeviceOperationResultVO", description = "设备操作结果数据ResultVO") +public class TopoDeviceOperationResultVO implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "请求处理的结果码", notes = "“0”表示成功。非“0”表示失败。详见附录。") + private Integer statusCode; + + @ApiModelProperty(value = "响应状态描述", notes = "响应状态描述", required = false) + private String statusDesc; + + @ApiModelProperty(value = "操作结果信息", notes = "操作结果信息") + private List data; + + @Data + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Accessors(chain = true) + @ApiModel(value = "OperationRsp", description = "操作结果结果数据模型") + public static class OperationRsp implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "设备ID", notes = "设备ID,平台生成的设备唯一标识") + private String deviceId; + + @ApiModelProperty(value = "请求处理的结果码", notes = "“0”表示成功。非“0”表示失败。详见附录。") + private Integer statusCode; + + @ApiModelProperty(value = "响应状态描述", notes = "响应状态描述", required = false) + private String statusDesc; + } +} \ No newline at end of file diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoQueryDeviceResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoQueryDeviceResultVO.java new file mode 100644 index 00000000..6adad129 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoQueryDeviceResultVO.java @@ -0,0 +1,136 @@ +package com.mqttsnet.thinglinks.link.api.domain.vo.result; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.List; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 协议查询设备档案信息响应信息 + * @packagename: com.mqttsnet.thinglinks.device.vo.result + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-18 23:03 + **/ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder +@ApiModel(value = "TopoQueryDeviceResultVO", description = "设备档案响应信息") +public class TopoQueryDeviceResultVO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "请求处理的结果码。'0'表示成功。非'0'表示失败。详见附录。", required = true) + private int statusCode; + + @ApiModelProperty(value = "响应状态描述。") + private String statusDesc; + + @ApiModelProperty(value = "查询设备的结果信息。", required = true) + private List data; + + @Data + @NoArgsConstructor + @AllArgsConstructor + @Builder + public static class DataItem { + + @ApiModelProperty(value = "请求处理的结果码。'0'表示成功。非'0'表示失败。详见附录。", required = true) + private int statusCode; + + @ApiModelProperty(value = "响应状态描述。") + private String statusDesc; + + @ApiModelProperty(value = "平台生成的设备唯一标识", required = true) + private String deviceId; + + @ApiModelProperty(value = "设备详细信息") + private DeviceInfo deviceInfo; + + @Data + @NoArgsConstructor + @AllArgsConstructor + @Builder + public static class DeviceInfo { + + /** + * 客户端标识 + */ + @ApiModelProperty(value = "客户端标识") + private String clientId; + + /** + * 设备名称 + */ + @ApiModelProperty(value = "设备名称") + private String deviceName; + /** + * 连接实例 + */ + @ApiModelProperty(value = "连接实例") + private String connector; + /** + * 设备描述 + */ + @ApiModelProperty(value = "设备描述") + private String description; + /** + * 设备状态:1启用ENABLE || 2禁用DISABLE||未激活NOTACTIVE 0 + */ + @ApiModelProperty(value = "设备状态:1启用ENABLE || 2禁用DISABLE||未激活NOTACTIVE 0") + private Integer deviceStatus; + /** + * 连接状态:在线:1ONLINE || 离线:2OFFLINE || 未连接:INIT 0 + */ + @ApiModelProperty(value = "连接状态:在线:1ONLINE || 离线:2OFFLINE || 未连接:INIT 0") + private Integer connectStatus; + /** + * 设备标签 + */ + @ApiModelProperty(value = "设备标签") + private String deviceTags; + /** + * 产品标识 + */ + @ApiModelProperty(value = "产品标识") + private String productIdentification; + /** + * 软件版本 + */ + @ApiModelProperty(value = "软件版本") + private String swVersion; + /** + * 固件版本 + */ + @ApiModelProperty(value = "固件版本") + private String fwVersion; + /** + * sdk版本 + */ + @ApiModelProperty(value = "sdk版本") + private String deviceSdkVersion; + /** + * 网关设备id + */ + @ApiModelProperty(value = "网关设备id") + private String gatewayId; + /** + * 设备类型:0普通设备 || 1网关设备 || 2子设备 + */ + @ApiModelProperty(value = "设备类型:0普通设备 || 1网关设备 || 2子设备 ") + private Integer nodeType; + /** + * 备注 + */ + @ApiModelProperty(value = "备注") + private String remark; + } + } +} \ No newline at end of file diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteDeviceFallbackFactory.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteDeviceFallbackFactory.java index 62d6ffb2..ead39d30 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteDeviceFallbackFactory.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteDeviceFallbackFactory.java @@ -3,6 +3,10 @@ import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.*; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoQueryDeviceResultVO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.openfeign.FallbackFactory; @@ -62,14 +66,149 @@ public R findOneByClientId(String clientId) { * @return */ @Override - public R selectAllByProductIdentification(String productIdentification){ + public R selectAllByProductIdentification(String productIdentification) { return R.fail("查询产品下的设备:" + throwable.getMessage()); } + @Override - public R selectDeviceByDeviceIdentificationList(List deviceIdentificationList){ + public R selectDeviceByDeviceIdentificationList(List deviceIdentificationList) { return R.fail("根据设备标识列表查询设备失败:" + throwable.getMessage()); } + + /** + * (MQTT)协议新增子设备档案 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 新增结果 + */ + @Override + public R saveSubDeviceByMqtt(TopoAddSubDeviceParam topoAddSubDeviceParam) { + return R.fail("新增子设备失败:" + throwable.getMessage()); + } + + /** + * (HTTP)协议新增子设备档案 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 新增结果 + */ + @Override + public R saveSubDeviceByHttp(TopoAddSubDeviceParam topoAddSubDeviceParam) { + return R.fail("新增子设备失败:" + throwable.getMessage()); + } + + /** + * MQTT协议修改子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 连接状态参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @Override + public R updateSubDeviceConnectStatusByMqtt(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { + return R.fail("修改子设备连接状态失败:" + throwable.getMessage()); + } + + /** + * HTTP协议修改子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 连接状态参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @Override + public R updateSubDeviceConnectStatusByHttp(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { + return R.fail("修改子设备连接状态失败:" + throwable.getMessage()); + } + + /** + * MQTT协议删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @Override + public R deleteSubDeviceByMqtt(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { + return R.fail("删除子设备失败:" + throwable.getMessage()); + } + + /** + * HTTP协议删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @Override + public R deleteSubDeviceByHttp(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { + return R.fail("删除子设备失败:" + throwable.getMessage()); + } + + /** + * MQTT协议数据上报 + * + * @param topoDeviceDataReportParam 数据上报参数 + * @return {@link TopoDeviceOperationResultVO} 上报结果 + */ + @Override + public R deviceDataReportByMqtt(TopoDeviceDataReportParam topoDeviceDataReportParam) { + return R.fail("数据上报失败:" + throwable.getMessage()); + } + + /** + * HTTP协议数据上报 + * + * @param topoDeviceDataReportParam 数据上报参数 + * @return {@link TopoDeviceOperationResultVO} 上报结果 + */ + @Override + public R deviceDataReportByHttp(TopoDeviceDataReportParam topoDeviceDataReportParam) { + return R.fail("数据上报失败:" + throwable.getMessage()); + } + + /** + * Queries device information using the MQTT protocol. + * + * @param topoQueryDeviceParam The device query parameters. + * @return {@link TopoQueryDeviceResultVO} The result of the device query. + */ + @Override + public R queryDeviceByMqtt(TopoQueryDeviceParam topoQueryDeviceParam) { + return R.fail("查询设备失败:" + throwable.getMessage()); + } + + /** + * Queries device information using the HTTP protocol. + * + * @param topoQueryDeviceParam The device query parameters. + * @return {@link TopoQueryDeviceResultVO} The result of the device query. + */ + @Override + public R queryDeviceByHttp(TopoQueryDeviceParam topoQueryDeviceParam) { + return R.fail("查询设备失败:" + throwable.getMessage()); + } + + /** + * Receives and saves a new OTA upgrade record from an MQTT message. This endpoint + * captures the command response parameters from the MQTT message body and persists them. + * + * @param otaCommandResponseParam The response parameters from an OTA command sent via MQTT. + * @return {@link R} A response entity containing the saved OTA upgrade record. + */ + @Override + public R saveUpgradeRecordByMqtt(OtaCommandResponseParam otaCommandResponseParam) { + return R.fail("保存升级记录失败:" + throwable.getMessage()); + } + + /** + * Receives and saves a new OTA upgrade record from an HTTP request. This endpoint + * captures the command response parameters from the request body and persists them. + * + * @param otaCommandResponseParam The response parameters from an OTA command sent via HTTP. + * @return {@link R} A response wrapper containing the saved OTA upgrade record. + */ + @Override + public R saveUpgradeRecordByHttp(OtaCommandResponseParam otaCommandResponseParam) { + return R.fail("保存升级记录失败:" + throwable.getMessage()); + } }; } } diff --git a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/SuperTableDescribeVO.java b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/SuperTableDescribeVO.java new file mode 100644 index 00000000..7a05343e --- /dev/null +++ b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/SuperTableDescribeVO.java @@ -0,0 +1,56 @@ +package com.mqttsnet.thinglinks.tdengine.api.domain; + +import cn.hutool.core.map.MapUtil; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Map; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 超级表结构VO + * @packagename: com.mqttsnet.thinglinks.tds.vo.result + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-09-17 21:12 + **/ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode(callSuper = false) +@Builder +@ApiModel(value = "SuperTableDescribeVO", description = "超级表结构VO") +public class SuperTableDescribeVO implements Serializable { + + private static final long serialVersionUID = 1L; + + private Map echoMap = MapUtil.newHashMap(); + + /** + * 标记 + */ + @ApiModelProperty(value = "标记") + private String note; + /** + * 字段名 + */ + @ApiModelProperty(value = "字段名") + private String field; + /** + * 字段长度 + */ + @ApiModelProperty(value = "字段长度") + private Integer length; + /** + * 字段类型 + */ + @ApiModelProperty(value = "字段类型") + private String type; + + +} diff --git a/thinglinks-common/pom.xml b/thinglinks-common/pom.xml index a3a6c0b8..8203b209 100644 --- a/thinglinks-common/pom.xml +++ b/thinglinks-common/pom.xml @@ -20,6 +20,7 @@ thinglinks-common-job thinglinks-common-kafka thinglinks-common-seata + thinglinks-common-protocol thinglinks-common diff --git a/thinglinks-common/thinglinks-common-core/pom.xml b/thinglinks-common/thinglinks-common-core/pom.xml index 21cda2c6..d92a38b4 100644 --- a/thinglinks-common/thinglinks-common-core/pom.xml +++ b/thinglinks-common/thinglinks-common-core/pom.xml @@ -118,7 +118,7 @@ cn.hutool hutool-all - 5.7.14 + 5.8.26 diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/CacheConstants.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/CacheConstants.java index 1452ef39..12673b8a 100644 --- a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/CacheConstants.java +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/CacheConstants.java @@ -2,19 +2,44 @@ /** * redis缓存的key 常量 - * + * * @author thinglinks */ -public class CacheConstants -{ +public class CacheConstants { /** * 权限缓存前缀 */ public final static String LOGIN_TOKEN_KEY = "login_tokens:"; + + /** + * 设备信息 cache key + * link-> device_record:deviceIdentification + */ + public static final String DEVICE_RECORD_KEY = "device_record:"; + + /** + * 全局产品信息 前缀 + * link-> def_product:productIdentification + */ + public static final String PRODUCT = "def_product"; + + /** + * 全局产品模型 前缀 + * link-> def_product_model:productIdentification + */ + public static final String PRODUCT_MODEL = "def_product_model"; + + /** + * 全局产品模型超级表 前缀 + * link-> def_product_model_super_table:productIdentification:serviceCode:deviceIdentification + */ + public static final String PRODUCT_MODEL_SUPER_TABLE = "def_product_model_super_table"; + /** - * 产品初始化数据模型缓存前缀 + * TDengine superTableFields cache key + * link-> tdengine_superTableFields:productIdentification:serviceCode:deviceIdentification */ - public final static String PRODUCT_INITIALIZEDATAMODEL = "product_initializeDataModel:"; + public static final String TDENGINE_SUPERTABLEFILELDS = "tdengine_superTableFields:"; } diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/Constants.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/Constants.java index d36cb588..d42c11d4 100644 --- a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/Constants.java +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/Constants.java @@ -141,24 +141,9 @@ public class Constants { */ public static final String APPLICATION_OCTET_STREAM = "application/octet-stream"; - /** - * 设备信息 cache key - */ - public static final String DEVICE_RECORD_KEY = "device_record:"; - /** * 重复提交 cache key */ public static final String RESUBMIT_URL_KEY = "resubmit_url:"; - /** - * TDengine superTableFields cache key - */ - public static final String TDENGINE_SUPERTABLEFILELDS = "TDengine_SuperTableFields:"; - - /** - * 设备数据上报协议脚本 cache key - */ - public static final String DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT = "device_data_reported_agreement_script:"; - } diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/enums/DeviceConnectStatus.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/enums/DeviceConnectStatus.java deleted file mode 100644 index e598e906..00000000 --- a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/enums/DeviceConnectStatus.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.mqttsnet.thinglinks.common.core.enums; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -/** - * @Description: 连接状态 - * @Author: ShiHuan Sun - * @E-mail: 13733918655@163.com - * @CreateDate: 2021/10/25$ 15:54$ - * @UpdateUser: ShiHuan Sun - * @UpdateDate: 2021/10/25$ 15:54$ - * @UpdateRemark: 修改内容 - * @Version: 1.0 - */ -@Getter -@AllArgsConstructor -public enum DeviceConnectStatus { - /** - * 初始化 - */ - INIT("INIT","INIT"), - - /** - * 在线 - */ - ONLINE("ONLINE","ONLINE"), - - /** - * 离线 - */ - OFFLINE("OFFLINE","OFFLINE"); - - private String key; - private String value; -} diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/enums/DeviceConnectStatusEnum.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/enums/DeviceConnectStatusEnum.java new file mode 100644 index 00000000..86544aa3 --- /dev/null +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/enums/DeviceConnectStatusEnum.java @@ -0,0 +1,69 @@ +package com.mqttsnet.thinglinks.common.core.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.Optional; +import java.util.stream.Stream; + +/** + * @Description: 连接状态 + * @Author: ShiHuan Sun + * @E-mail: 13733918655@163.com + * @CreateDate: 2021/10/25$ 15:54$ + * @UpdateUser: ShiHuan Sun + * @UpdateDate: 2021/10/25$ 15:54$ + * @UpdateRemark: 修改内容 + * @Version: 1.0 + */ +@Getter +@AllArgsConstructor +@NoArgsConstructor +public enum DeviceConnectStatusEnum { + /** + * 初始化 + */ + INIT("INIT", "INIT"), + + /** + * 在线 + */ + ONLINE("ONLINE", "ONLINE"), + + /** + * 离线 + */ + OFFLINE("OFFLINE", "OFFLINE"); + + private String key; + private String value; + + /** + * 根据key获取对应的枚举 + * + * @param key 设备连接的状态值 + * @return 返回对应的枚举,如果没找到则返回 Optional.empty() + */ + public static Optional fromValue(String key) { + return Stream.of(DeviceConnectStatusEnum.values()) + .filter(status -> status.getValue().equals(key)) + .findFirst(); + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/ConsumerGroupConstant.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/ConsumerGroupConstant.java new file mode 100644 index 00000000..4d2e1155 --- /dev/null +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/ConsumerGroupConstant.java @@ -0,0 +1,19 @@ +package com.mqttsnet.thinglinks.common.core.mqs; + +/** + * @Description: 消费者组常量(队列) + * @Author: ShiHuan SUN + * @E-mail: 13733918655@163.com + * @Website: http://thinglinks.mqttsnet.com + * @CreateDate: 2022/4/15$ 15:53$ + * @UpdateUser: ShiHuan SUN + * @UpdateDate: 2022/4/15$ 15:53$ + * @UpdateRemark: 修改内容 + * @Version: V1.0 + */ +public interface ConsumerGroupConstant { + /** + * default-consumer-group + */ + String THINGLINKS_GROUP = "thinglinks"; +} diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/ConsumerTopicConstant.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/ConsumerTopicConstant.java new file mode 100644 index 00000000..03907be1 --- /dev/null +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/ConsumerTopicConstant.java @@ -0,0 +1,102 @@ +package com.mqttsnet.thinglinks.common.core.mqs; + +/** + * @Description: 消费者主题常量(队列) + * @Author: ShiHuan SUN + * @E-mail: 13733918655@163.com + * @Website: http://thinglinks.mqttsnet.com + * @CreateDate: 2022/4/15$ 15:53$ + * @UpdateUser: ShiHuan SUN + * @UpdateDate: 2022/4/15$ 15:53$ + * @UpdateRemark: 修改内容 + * @Version: V1.0 + */ +public interface ConsumerTopicConstant { + + /** + * MQTT Broker 监听主题 + */ + interface Mqtt { + /** + * MQTT设备消息监听主题——》MQTT消息——》MQS + */ + String THINGLINKS_MQS_MQTT_MSG = "thinglinks-pro-mqs-mqttMsg"; + + /** + * 设备上线 + */ + String THINGLINKS_CLIENT_CONNECTED_TOPIC = "client.connected.topic"; + + /** + * 客户端设备离线 + */ + String THINGLINKS_CLIENT_DISCONNECTED_TOPIC = "client.disconnect.topic"; + + /** + * 服务端设备离线 + */ + String THINGLINKS_SERVER_CONNECTED_TOPIC = "server.disconnect.topic"; + + /** + * 设备离线 + */ + String THINGLINKS_DEVICE_KICKED_TOPIC = "device.kicked.topic"; + + /** + * 消息订阅 + */ + String THINGLINKS_SUBSCRIPTION_ACKED_TOPIC = "subscription.acked.topic"; + + /** + * 取消订阅 + */ + String THINGLINKS_UNSUBSCRIPTION_ACKED_TOPIC = "unsubscription.acked.topic"; + + /** + * 消息分发错误 + */ + String THINGLINKS_DISTRIBUTION_ERROR_TOPIC = "distribution.error.topic"; + + /** + * 消息分发 + */ + String THINGLINKS_DISTRIBUTION_COMPLETED_TOPIC = "distribution.completed.topic"; + + + /** + * PING 请求 + */ + String THINGLINKS_PING_REQ_TOPIC = "ping.req.topic"; + + } + + interface Link { + + /** + * 产品服务 + */ + String THINGLINKS_PRO_PRODUCT_SERVICE_MSG = "thinglinks-pro-product-service-msg"; + + /** + * 产品服务属性 + */ + String THINGLINKS_PRO_PRODUCT_PROPERTY_MSG = "thinglinks-pro-product-property-msg"; + } + + interface Rule { + + /** + * 规则引擎触发器规则动作监听主题 + */ + String THINGLINKS_RULE_TRIGGER = "thinglinks_rule_trigger"; + } + + interface Tdengine { + + /** + * TDengine超级表创键修改动作监听主题 + */ + String PRODUCTSUPERTABLE_CREATEORUPDATE = "productSuperTable-createOrUpdate"; + } + +} diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/AesUtils.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/AesUtils.java new file mode 100644 index 00000000..428c4075 --- /dev/null +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/AesUtils.java @@ -0,0 +1,145 @@ +package com.mqttsnet.thinglinks.common.core.utils; + +import org.apache.commons.codec.binary.Base64; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.spec.SecretKeySpec; +import java.security.SecureRandom; + +/** + * @Description: AES加密 + * @Author: ShiHuan Sun + * @CreateDate: 2021/9/8$ 14:49$ + * @UpdateUser: ShiHuan Sun + * @UpdateDate: 2021/9/8$ 14:49$ + * @UpdateRemark: 修改内容 + * @Version: 1.0 + */ +public class AesUtils { + public static void main(String[] args) throws Exception { + + String content = " {\n" + + " \"batID\": \"120434305152\",\n" + + " \"chgTime\": 293,\n" + + " \"detailsList\": [\n" + + " {\n" + + " \"elect\": 7.23,\n" + + " \"rateType\": 3,\n" + + " \"startTime\": \"2021-06-30 12:43:10\",\n" + + " \"stopTime\": \"2021-06-30 12:48:03\"\n" + + " }\n" + + " ],\n" + + " \"electAmount\": 1,\n" + + " \"equipNo\": \"1000280001000003\",\n" + + " \"flatElect\": 7.23,\n" + + " \"gunNo\": 0,\n" + + " \"orderSn\": \"100028000100000320210630124232\",\n" + + " \"peakElect\": 0,\n" + + " \"plateNo\": \"京888888\",\n" + + " \"rateModelID\": \"1\",\n" + + " \"sharpElect\": 0,\n" + + " \"startElect\": 41.1,\n" + + " \"startSoc\": 97,\n" + + " \"startTime\": \"2021-06-30 12:43:10\",\n" + + " \"stopElect\": 48.33,\n" + + " \"stopReason\": 53,\n" + + " \"stopSoc\": 100,\n" + + " \"stopTime\": \"2021-06-30 12:48:03\",\n" + + " \"swapSn\": \"100028000200000120210630120022\",\n" + + " \"valleyElect\": 0,\n" + + " \"vin\": \"LZ5RB7D37LB013286\"\n" + + " }"; + System.out.println("加密内容:" + content); + String key = "FA171555405706F73D7B973DB89F0B47"; + System.out.println("加密密钥和解密密钥:" + key); + String encrypt = aesEncrypt(content, key); + System.out.println("加密后:" +encrypt); + String decrypt = aesDecrypt(encrypt, key); + System.out.println("解密后:" + decrypt); + } + /** + * 编码 + * @param bstr + * @return String + */ + public static String Base64encode(byte[] bstr) { + return Base64.encodeBase64String(bstr); + } + + /** + * 解码 + * @param str + * @return string + */ + public static byte[] Base64decode(String str) { + return Base64.decodeBase64(str); + } + + /* + * AES加密 + * @param content 待加密的内容 + * @param encryptKey 加密密钥 + * @return 加密后的byte[] + * @throws Exception + */ + public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception { + KeyGenerator kgen = KeyGenerator.getInstance("AES"); + /*防止linux下 随机生成key*/ + SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); + random.setSeed(encryptKey.getBytes()); + kgen.init(128, random); + Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); + cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES")); + + return cipher.doFinal(content.getBytes("UTF-8")); + } + + /** + * AES加密为base 64 code + * @param content 待加密的内容 + * @param encryptKey 加密密钥 + * @return 加密后的base 64 code + * @throws Exception + */ + public static String aesEncrypt(String content, String encryptKey) throws Exception { + return Base64encode(aesEncryptToBytes(content, encryptKey)); + } + + /** + * AES解密 + * @param encryptBytes 待解密的byte[] + * @param decryptKey 解密密钥 + * @return 解密后的String + * @throws Exception + */ + public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) { + byte[] decryptBytes = new byte[0]; + try { + KeyGenerator kgen = KeyGenerator.getInstance("AES"); + /*防止linux下 随机生成key*/ + SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); + random.setSeed(decryptKey.getBytes()); + kgen.init(128, random); + Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); + cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES")); + decryptBytes = cipher.doFinal(encryptBytes); + return new String(decryptBytes,"UTF-8"); + } catch (Exception e) { + e.printStackTrace(); + } + return decryptKey; + + } + + /** + * 将base 64 code AES解密 + * @param encryptStr 待解密的base 64 code + * @param decryptKey 解密密钥 + * @return 解密后的string + * @throws Exception + */ + public static String aesDecrypt(String encryptStr, String decryptKey){ + return aesDecryptByBytes(Base64decode(encryptStr), decryptKey); + } +} diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/SHA256Utils.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/SHA256Utils.java new file mode 100644 index 00000000..0cb1eae9 --- /dev/null +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/SHA256Utils.java @@ -0,0 +1,67 @@ +package com.mqttsnet.thinglinks.common.core.utils; + +import org.springframework.stereotype.Component; + +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Random; + +@Component +public class SHA256Utils { + public static void main(String[] args) { + String appId="123"; + String appKey="123"; + String timestamp="1568383635245"; + String sha256String = getSHA256String(appId + appKey + timestamp); + System.out.println(sha256String); + } + + /** + * 用java原生的摘要实现SHA256加密 + * + * @param str 加密前的报文 + * @return + */ + public static String getSHA256String(String str) { + String encodeStr = ""; + try { + MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); + messageDigest.update(str.getBytes("UTF-8")); + encodeStr = byte2Hex(messageDigest.digest()); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return encodeStr; + } + + /** + * byte[]转为16进制 + * + * @param bytes + * @return + */ + private static String byte2Hex(byte[] bytes) { + StringBuffer stringBuffer = new StringBuffer(); + for (int i = 0; i < bytes.length; i++) { + String temp = Integer.toHexString(bytes[i] & 0xFF); + if (temp.length() == 1) { + stringBuffer.append("0"); + } + stringBuffer.append(temp); + } + return stringBuffer.toString(); + } + + //随机密码 : 6位数字 + public static String randompassword(){ + char[] chars = new char[6]; + Random rnd = new Random(); + for(int i=0;i < 6 ; i++){ + chars[i] = (char)('0'+rnd.nextInt(10)); + } + return new String(chars); + } +} diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/Sm4Utils.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/Sm4Utils.java new file mode 100644 index 00000000..b2108500 --- /dev/null +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/Sm4Utils.java @@ -0,0 +1,101 @@ +package com.mqttsnet.thinglinks.common.core.utils; + +import org.bouncycastle.crypto.engines.SM4Engine; +import org.bouncycastle.crypto.modes.CBCBlockCipher; +import org.bouncycastle.crypto.paddings.PKCS7Padding; +import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.util.encoders.Hex; + +import java.nio.charset.StandardCharsets; + +/** + * @Description: 国密SM4分组密码算法工具类(对称加密) + * @Author: ShiHuan Sun + * @CreateDate: 2021/8/25$ 15:27$ + * @UpdateUser: ShiHuan Sun + * @UpdateDate: 2021/8/25$ 15:27$ + * @UpdateRemark: 修改内容 + * @Version: 1.0 + */ +public class Sm4Utils { + /** + * 加密 + * + * @param key 密钥 + * @param iv 初始向量 + * @param data 明文 + * @return 密文 + */ + public static String encrypt(String key, String iv, String data) { + try { + // 创建SM4引擎 + SM4Engine sm4Engine = new SM4Engine(); + // 创建CBC模式的加密器 + CBCBlockCipher cbcBlockCipher = new CBCBlockCipher(sm4Engine); + // 创建填充加密器 + PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbcBlockCipher, new PKCS7Padding()); + // 创建密钥参数 + KeyParameter keyParameter = new KeyParameter(Hex.decode(key)); + // 创建带IV的参数 + ParametersWithIV parametersWithIV = new ParametersWithIV(keyParameter, Hex.decode(iv)); + // 初始化加密器 + cipher.init(true, parametersWithIV); + + byte[] encryptedData = new byte[cipher.getOutputSize(data.getBytes(StandardCharsets.UTF_8).length)]; + int length = cipher.processBytes(data.getBytes(StandardCharsets.UTF_8), 0, data.getBytes(StandardCharsets.UTF_8).length, encryptedData, 0); + cipher.doFinal(encryptedData, length); + + return Hex.toHexString(encryptedData); + } catch (Exception e) { + throw new RuntimeException("SM4加密失败", e); + } + } + + /** + * 解密 + * + * @param key 密钥 + * @param iv 初始向量 + * @param data 密文 + * @return 明文 + */ + public static String decrypt(String key, String iv, String data) { + try { + // 创建SM4引擎 + SM4Engine sm4Engine = new SM4Engine(); + // 创建CBC模式的解密器 + CBCBlockCipher cbcBlockCipher = new CBCBlockCipher(sm4Engine); + // 创建填充解密器 + PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbcBlockCipher, new PKCS7Padding()); + // 创建密钥参数 + KeyParameter keyParameter = new KeyParameter(Hex.decode(key)); + // 创建带IV的参数 + ParametersWithIV parametersWithIV = new ParametersWithIV(keyParameter, Hex.decode(iv)); + // 初始化解密器 + cipher.init(false, parametersWithIV); + + byte[] decryptedData = new byte[cipher.getOutputSize(Hex.decode(data).length)]; + int length = cipher.processBytes(Hex.decode(data), 0, Hex.decode(data).length, decryptedData, 0); + int finalLength = cipher.doFinal(decryptedData, length); + + return new String(decryptedData, 0, length + finalLength, StandardCharsets.UTF_8); + } catch (Exception e) { + throw new RuntimeException("SM4解密失败", e); + } + } + + public static void main(String[] args) { + String key = "0123456789abcdef0123456789abcdef"; + String iv = "0123456789abcdef0123456789abcdef"; + String data = "Hello, SM4!"; + + String encryptedData = Sm4Utils.encrypt(key, iv, data); + System.out.println("加密后的数据: " + encryptedData); + + String decryptedData = Sm4Utils.decrypt(key, iv, encryptedData); + System.out.println("解密后的数据: " + decryptedData); + } + +} diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/SnowflakeIdUtil.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/SnowflakeIdUtil.java new file mode 100644 index 00000000..7eb1c04e --- /dev/null +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/SnowflakeIdUtil.java @@ -0,0 +1,143 @@ +package com.mqttsnet.thinglinks.common.core.utils; + +import java.util.concurrent.ThreadLocalRandom; + +/** + * @program: thinglinks-util-pro + * @description: SnowflakeIdUtil 是一个基于雪花算法的唯一 ID 生成工具类。 雪花算法可以保证生成的 ID 全局唯一且趋势递增。 + * @packagename: com.mqttsnet.basic.utils + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-03 13:15 + **/ +public class SnowflakeIdUtil { + + private static final SnowflakeIdUtil INSTANCE = new SnowflakeIdUtil(); + + // 开始时间戳 (2022-01-01) + private static final long START_TIMESTAMP = 1672444800000L; + + // 工作器 ID 和数据中心 ID 的位数 + private static final int WORKER_ID_BITS = 5; + private static final int DATACENTER_ID_BITS = 5; + + // 序列号的位数 + private static final int SEQUENCE_BITS = 12; + + // 工作器 ID 和数据中心 ID 的最大值 + private static final int MAX_WORKER_ID = ~(-1 << WORKER_ID_BITS); + private static final int MAX_DATACENTER_ID = ~(-1 << DATACENTER_ID_BITS); + + // 工作器 ID、数据中心 ID 和序列号的位移 + private static final int WORKER_ID_SHIFT = SEQUENCE_BITS; + private static final int DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS; + private static final int TIMESTAMP_SHIFT = DATACENTER_ID_SHIFT + DATACENTER_ID_BITS; + + // 序列号的掩码 + private static final int SEQUENCE_MASK = ~(-1 << SEQUENCE_BITS); + + // 工作器 ID 和数据中心 ID + private final int workerId; + private final int datacenterId; + + // 序列号和上次生成 ID 的时间戳 + private int sequence = 0; + private long lastTimestamp = -1L; + + /** + * 创建一个新的 SnowflakeIdUtil 实例。 + */ + public SnowflakeIdUtil() { + this.workerId = generateWorkerId(); + this.datacenterId = generateDatacenterId(); + } + + + /** + * 生成一个新的唯一 ID,默认为 16 位。 + * + * @return 一个不重复的十进制字符串 + */ + public static String nextId() { + return INSTANCE.nextId(16); + } + + /** + * 生成一个新的唯一 ID。 + * + * @param numDigits 生成的 ID 的位数,最少为 16 位 + * @return 一个不重复的十进制字符串 + */ + public synchronized String nextId(int numDigits) { + if (numDigits < 16) { + throw new IllegalArgumentException("numDigits must be at least 16"); + } + + long id = nextLongId(); + String idString = String.format("%0" + numDigits + "d", id % (long) Math.pow(10, numDigits)); + return idString; + } + + /** + * 生成一个新的唯一长整型 ID。 + * + * @return 一个不重复的长整型值 + */ + public synchronized long nextLongId() { + long timestamp = System.currentTimeMillis(); + + if (timestamp < lastTimestamp) { + throw new RuntimeException("Clock moved backwards. Refusing to generate id."); + } + + if (timestamp == lastTimestamp) { + sequence = (sequence + 1) & SEQUENCE_MASK; + if (sequence == 0) { + timestamp = waitUntilNextMillis(lastTimestamp); + } + } else { + sequence = 0; + } + + lastTimestamp = timestamp; + + long id = ((timestamp - START_TIMESTAMP) << TIMESTAMP_SHIFT) + | (datacenterId << DATACENTER_ID_SHIFT) + | (workerId << WORKER_ID_SHIFT) + | sequence; + + return id; + } + + /** + * 等待直到下一个毫秒。 + * + * @param lastTimestamp 上次生成 ID 的时间戳 + * @return 当前时间戳 + */ + private long waitUntilNextMillis(long lastTimestamp) { + long timestamp = System.currentTimeMillis(); + while (timestamp <= lastTimestamp) { + timestamp = System.currentTimeMillis(); + } + return timestamp; + } + + /** + * 生成工作器 ID。 + * + * @return 一个介于 0 和最大工作器 ID 之间的整数 + */ + private int generateWorkerId() { + return ThreadLocalRandom.current().nextInt(MAX_WORKER_ID + 1); + } + + /** + * 生成数据中心 ID。 + * + * @return 一个介于 0 和最大数据中心 ID 之间的整数 + */ + private int generateDatacenterId() { + return ThreadLocalRandom.current().nextInt(MAX_DATACENTER_ID + 1); + } +} diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/bean/BeanPlusUtil.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/bean/BeanPlusUtil.java new file mode 100755 index 00000000..2800b0e4 --- /dev/null +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/bean/BeanPlusUtil.java @@ -0,0 +1,40 @@ +package com.mqttsnet.thinglinks.common.core.utils.bean; + +import cn.hutool.core.bean.BeanUtil; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * Bean增强类工具类 + * + *

+ * 把一个拥有对属性进行set和get方法的类,我们就可以称之为JavaBean。 + *

+ * + * @author mqttsnet + * @since 3.1.2 + */ +public class BeanPlusUtil extends BeanUtil { + + /** + * 转换 list + * + * @param sourceList 源集合 + * @param destinationClass 目标类型 + * @return 目标集合 + */ + public static List toBeanList(Collection sourceList, Class destinationClass) { + if (sourceList == null || sourceList.isEmpty() || destinationClass == null) { + return Collections.emptyList(); + } + return sourceList.parallelStream() + .filter(Objects::nonNull) + .map(source -> toBean(source, destinationClass)) + .collect(Collectors.toList()); + } + +} diff --git a/thinglinks-common/thinglinks-common-kafka/src/main/java/com/mqttsnet/thinglinks/common/kafka/constant/ConsumerTopicConstant.java b/thinglinks-common/thinglinks-common-kafka/src/main/java/com/mqttsnet/thinglinks/common/kafka/constant/ConsumerTopicConstant.java deleted file mode 100644 index 47923bf6..00000000 --- a/thinglinks-common/thinglinks-common-kafka/src/main/java/com/mqttsnet/thinglinks/common/kafka/constant/ConsumerTopicConstant.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.mqttsnet.thinglinks.common.kafka.constant; - -import lombok.Data; - -/** - * @Description: 消费者主题常量 - * @Author: ShiHuan SUN - * @E-mail: 13733918655@163.com - * @Website: http://thinglinks.mqttsnet.com - * @CreateDate: 2022/4/15$ 15:53$ - * @UpdateUser: ShiHuan SUN - * @UpdateDate: 2022/4/15$ 15:53$ - * @UpdateRemark: 修改内容 - * @Version: V1.0 - */ -@Data -public class ConsumerTopicConstant { - - /** - * SMQTT设备消息监听主题 - */ - public static final String THINGLINKS_LINK_MQTT_MSG = "thinglinks-link-mqttMsg"; - - /** - * TDengine超级表创键修改动作监听主题 - */ - public static final String PRODUCTSUPERTABLE_CREATEORUPDATE = "productSuperTable-createOrUpdate"; - - /** - * 系统指标数据采集动作监听主题 - */ - public static final String THINGLINKS_COLLECTION_SYSTEM = "thinglinks_collection_system"; - - /** - * 规则引擎触发器规则动作监听主题 - */ - public static final String THINGLINKS_RULE_TRIGGER = "thinglinks_rule_trigger"; - - /** - * 设备上线 - */ - public static final String THINGLINKS_CLIENT_CONNECTED_TOPIC = "client.connected.topic"; - - /** - * 客户端设备离线 - */ - public static final String THINGLINKS_CLIENT_DISCONNECTED_TOPIC = "client.disconnect.topic"; - - /** - * 服务端设备离线 - */ - public static final String THINGLINKS_SERVER_CONNECTED_TOPIC = "server.disconnect.topic"; - - /** - * 设备离线 - */ - public static final String THINGLINKS_DEVICE_KICKED_TOPIC = "device.kicked.topic"; - - /** - * 消息订阅 - */ - public static final String THINGLINKS_SUBSCRIPTION_ACKED_TOPIC = "subscription.acked.topic"; - - /** - * 取消订阅 - */ - public static final String THINGLINKS_UNSUBSCRIPTION_ACKED_TOPIC = "unsubscription.acked.topic"; - - /** - * 消息分发错误 - */ - public static final String THINGLINKS_DISTRIBUTION_ERROR_TOPIC = "distribution.error.topic"; - - /** - * 消息分发 - */ - public static final String THINGLINKS_DISTRIBUTION_COMPLETED_TOPIC = "distribution.completed.topic"; - - - - -} diff --git a/thinglinks-common/thinglinks-common-protocol/README.md b/thinglinks-common/thinglinks-common-protocol/README.md new file mode 100644 index 00000000..7d5cb942 --- /dev/null +++ b/thinglinks-common/thinglinks-common-protocol/README.md @@ -0,0 +1,4 @@ +# 说明 +本模块用于协议底层处理 + + diff --git a/thinglinks-common/thinglinks-common-protocol/pom.xml b/thinglinks-common/thinglinks-common-protocol/pom.xml new file mode 100644 index 00000000..26c2e327 --- /dev/null +++ b/thinglinks-common/thinglinks-common-protocol/pom.xml @@ -0,0 +1,24 @@ + + + + com.mqttsnet + thinglinks-common + ${thinglinks.version} + + + 4.0.0 + thinglinks-common-protocol + ${project.artifactId} + 协议解析核心服务模块 + + + + + com.mqttsnet + thinglinks-common-core + ${thinglinks.version} + + + \ No newline at end of file diff --git a/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/factory/ProtocolMessageAdapter.java b/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/factory/ProtocolMessageAdapter.java new file mode 100644 index 00000000..1a5ab6c9 --- /dev/null +++ b/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/factory/ProtocolMessageAdapter.java @@ -0,0 +1,76 @@ +package com.mqttsnet.basic.protocol.factory; + +import java.util.Map; + +import cn.hutool.core.bean.BeanUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.mqttsnet.basic.protocol.model.EncryptionDetailsDTO; +import com.mqttsnet.basic.protocol.model.ProtocolDataMessageDTO; +import com.mqttsnet.basic.protocol.utils.ProtocolMessageSignatureVerifierUtils; +import com.mqttsnet.basic.protocol.utils.ProtocolRegexTopicVariableExtractorUtils; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 协议信息适配器 + * @packagename: com.mqttsnet.thinglinks.mqtt.handler + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-30 15:08 + **/ +@Slf4j +@Component +public class ProtocolMessageAdapter { + + public boolean validateProtocolData(String body) { + return ProtocolMessageSignatureVerifierUtils.validateProtocolData(body); + } + + public Map extractVariables(String topic) { + return ProtocolRegexTopicVariableExtractorUtils.extractVariables(topic); + } + + public ProtocolDataMessageDTO parseProtocolDataMessage(String body) { + return BeanUtil.toBean(JSON.parseObject(body), ProtocolDataMessageDTO.class); + } + + public String decryptMessage(String body, EncryptionDetailsDTO encryptionDetailsDTO) throws Exception { + String signKey = encryptionDetailsDTO.getSignKey(); + String encryptKey = encryptionDetailsDTO.getEncryptKey(); + String encryptVector = encryptionDetailsDTO.getEncryptVector(); + return ProtocolMessageSignatureVerifierUtils.decryptMessage(body, signKey, encryptKey, encryptVector); + } + + public ProtocolDataMessageDTO buildResponse(ProtocolDataMessageDTO protocolDataMessageDTO, + String resultDataBody, EncryptionDetailsDTO encryptionDetailsDTO) throws Exception { + String signKey = encryptionDetailsDTO.getSignKey(); + String encryptKey = encryptionDetailsDTO.getEncryptKey(); + String encryptVector = encryptionDetailsDTO.getEncryptVector(); + //数据加密签名处理 + String dataBody = ProtocolMessageSignatureVerifierUtils.encryptMessage(resultDataBody, protocolDataMessageDTO.getHead().getCipherFlag(), signKey, encryptKey, + encryptVector); + //JSON字符串转换为对象 + protocolDataMessageDTO = JSON.parseObject(dataBody, new TypeReference() { + }); + + + return protocolDataMessageDTO; + } + + public ProtocolDataMessageDTO buildResponse(String resultDataBody, EncryptionDetailsDTO encryptionDetailsDTO) throws Exception { + String signKey = encryptionDetailsDTO.getSignKey(); + String encryptKey = encryptionDetailsDTO.getEncryptKey(); + String encryptVector = encryptionDetailsDTO.getEncryptVector(); + //数据加密签名处理 + String dataBody = ProtocolMessageSignatureVerifierUtils.encryptMessage(resultDataBody, encryptionDetailsDTO.getCipherFlag(), signKey, encryptKey, + encryptVector); + //JSON字符串转换为对象 + ProtocolDataMessageDTO protocolDataMessageDTO = JSON.parseObject(dataBody, new TypeReference() { + }); + + + return protocolDataMessageDTO; + } +} diff --git a/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/model/EncryptionDetailsDTO.java b/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/model/EncryptionDetailsDTO.java new file mode 100644 index 00000000..3dc3f685 --- /dev/null +++ b/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/model/EncryptionDetailsDTO.java @@ -0,0 +1,69 @@ +package com.mqttsnet.basic.protocol.model; + +import java.io.Serializable; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; +import lombok.experimental.Accessors; + +/** + * ----------------------------------------------------------------------------- + * File Name: EncryptionDetailsDto.java + * ----------------------------------------------------------------------------- + * Description: + * This class is used to encapsulate encryption and decryption details , for message processing, providing necessary information without + * ----------------------------------------------------------------------------- + * + * @author ShiHuan Sun + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + *

+ * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2023-11-12 01:48 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder +public class EncryptionDetailsDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + + /** + * The key used for signing the data. This is usually a secret key + * shared between the sender and the receiver to verify the integrity + * of the message. + */ + private String signKey; + + /** + * The key used for encrypting the data. This is typically a symmetric key + * used in encryption algorithms to ensure that the message contents are + * not readable by unauthorized parties. + */ + private String encryptKey; + + /** + * The initialization vector (IV) used for encryption algorithms that require it. + * The IV is a pseudo-random value and is used to ensure that the encryption + * result is different for the same plaintext and key. + */ + private String encryptVector; + + /** + * Indicates the encryption method used. Different values represent different + * encryption algorithms or no encryption. + * For example, 0 might represent no encryption, 1 might represent AES, etc. + */ + private Integer cipherFlag; +} diff --git a/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/model/ProtocolDataMessageDTO.java b/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/model/ProtocolDataMessageDTO.java new file mode 100644 index 00000000..23c4c2ac --- /dev/null +++ b/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/model/ProtocolDataMessageDTO.java @@ -0,0 +1,68 @@ +package com.mqttsnet.basic.protocol.model; + +import java.io.Serializable; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; +import lombok.experimental.Accessors; + +/** + * ----------------------------------------------------------------------------- + * File Name: ProtocolDataMessageDto.java + * ----------------------------------------------------------------------------- + * Description: + * ProtocolDataMessage + * ----------------------------------------------------------------------------- + * + * @author ShiHuan Sun + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + *

+ * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2023-11-12 01:50 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder +@ApiModel(value = "ProtocolDataMessageDto", description = "协议数据内容Dto") +public class ProtocolDataMessageDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "消息头部") + private Head head; + + @ApiModelProperty(value = "报文体") + private T dataBody; + + @ApiModelProperty(value = "数据签名") + private String dataSign; + + @ApiModel(description = "消息头部实体类") + @Data + @NoArgsConstructor + @AllArgsConstructor + @Builder + public static class Head { + @ApiModelProperty(value = "加密标志,0-不加密;1-SM4;2-AES", allowableValues = "0, 1, 2", example = "0") + private Integer cipherFlag; + + @ApiModelProperty(value = "消息ID(从1自增即可)", example = "3342") + private Long mid; + + @ApiModelProperty(value = "报文发送时间戳(毫秒)", example = "1624982406963") + private Long timeStamp; + } +} diff --git a/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/utils/ProtocolMessageSignatureVerifierUtils.java b/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/utils/ProtocolMessageSignatureVerifierUtils.java new file mode 100644 index 00000000..f0b729ec --- /dev/null +++ b/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/utils/ProtocolMessageSignatureVerifierUtils.java @@ -0,0 +1,285 @@ +package com.mqttsnet.basic.protocol.utils; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +import cn.hutool.core.text.CharSequenceUtil; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.mqttsnet.thinglinks.common.core.utils.AesUtils; +import com.mqttsnet.thinglinks.common.core.utils.Sm4Utils; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.codec.digest.DigestUtils; + +/** + * @program: thinglinks-util-pro + * @description: 协议消息处理Utils + * @packagename: com.mqttsnet.basic.utils + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-07 00:12 + **/ +@Slf4j +public class ProtocolMessageSignatureVerifierUtils { + private static final ObjectMapper objectMapper = new ObjectMapper(); + + /** + * 加密报文体 + * + * @param dataBody 报文体 + * @param cipherFlag 加密标识 0:不加密 1:SM4加密 2:AES加密 + * @param signKey 数据签名密钥 + * @param encryptKey 加密密钥 + * @param encryptVector 加密向量 + * @return 加密后的报文体 + * @throws IOException + */ + public static String encryptMessage(String dataBody, int cipherFlag, String signKey, String encryptKey, String encryptVector) throws Exception { + // 加密报文体 + String encryptedDataBody = encryptDataBody(dataBody, cipherFlag, encryptKey, encryptVector); + + // 计算数据签名 + long timeStamp = System.currentTimeMillis(); + String dataSign = calculateDataSign(dataBody, timeStamp, signKey); + + // 构建加密后的报文 + Map head = new HashMap<>(); + head.put("cipherFlag", cipherFlag); + head.put("timeStamp", timeStamp); + + Map encryptedMessage = new HashMap<>(); + encryptedMessage.put("head", head); + encryptedMessage.put("dataBody", objectMapper.readValue(encryptedDataBody, Object.class)); + encryptedMessage.put("dataSign", dataSign); + + // 转换为 JSON 字符串 + return objectMapper.writeValueAsString(encryptedMessage); + } + + /** + * 解密报文体 + * + * @param messageJson 加密后的报文 + * @param signKey 数据签名密钥 + * @param encryptKey 加密密钥 + * @param encryptVector 加密向量 + * @return 解密后的报文体 + * @throws IOException + */ + public static String decryptMessage(String messageJson, String signKey, String encryptKey, String encryptVector) throws Exception { + // 解析 JSON 报文 + Map message = objectMapper.readValue(messageJson, HashMap.class); + + // 获取报文头部信息 + Map head = (Map) message.get("head"); + int cipherFlag = (int) head.get("cipherFlag"); + long timeStamp = (long) head.get("timeStamp"); + + // 获取加密后的报文体和数据签名 + String encryptedDataBody = objectMapper.writeValueAsString(message.get("dataBody")); + String dataSign = (String) message.get("dataSign"); + + // 验证数据签名 + if (CharSequenceUtil.isNotBlank(dataSign) && !verifyDataSign(encryptedDataBody, timeStamp, signKey, dataSign)) { + throw new IllegalArgumentException("Invalid data sign"); + } + + // 解密报文体 + return decryptDataBody(encryptedDataBody, cipherFlag, encryptKey, encryptVector); + + } + + private static String encryptDataBody(String dataBody, int cipherFlag, String encryptKey, String encryptVector) throws Exception { + // 根据 cipherFlag 实现加密逻辑 + switch (cipherFlag) { + case 0: + return dataBody; + case 1: + // 使用 SM4 加密算法 + return sm4Encrypt(dataBody, encryptKey, encryptVector); + case 2: + // 使用 AES 加密算法 + return aesEncrypt(dataBody, encryptKey, encryptVector); + default: + // 不加密 + return dataBody; + } + } + + + private static String decryptDataBody(String encryptedDataBody, int cipherFlag, String encryptKey, String encryptVector) throws Exception { + // 根据 cipherFlag 实现解密逻辑 + switch (cipherFlag) { + case 0: + return encryptedDataBody; + case 1: + // 使用 SM4 解密算法 + return sm4Decrypt(encryptedDataBody, encryptKey, encryptVector); + case 2: + // 使用 AES 解密算法 + return aesDecrypt(encryptedDataBody, encryptKey, encryptVector); + default: + // 不解密 + return encryptedDataBody; + } + } + + /** + * 使用 SM4 加密算法加密数据 + * + * @param data 原始数据 + * @param encryptKey 加密密钥 + * @param encryptVector 加密向量 + * @return 加密后的数据 + */ + private static String sm4Encrypt(String data, String encryptKey, String encryptVector) throws Exception { + return Sm4Utils.encrypt(encryptKey, encryptVector, data); + } + + /** + * 使用 SM4 解密算法解密数据 + * + * @param encryptedData 加密后的数据 + * @param encryptKey 加密密钥 + * @param encryptVector 加密向量 + * @return 解密后的数据 + */ + private static String sm4Decrypt(String encryptedData, String encryptKey, String encryptVector) throws Exception { + return Sm4Utils.decrypt(encryptKey, encryptVector, encryptedData); + } + + /** + * 使用 AES 加密算法加密数据 + * + * @param data 原始数据 + * @param encryptKey 加密密钥 + * @param encryptVector 加密向量 + * @return 加密后的数据 + */ + private static String aesEncrypt(String data, String encryptKey, String encryptVector) throws Exception { + String encrypt = AesUtils.aesEncrypt(data, encryptKey); + log.info("AES,加密输出HEX = %s \n" + encrypt); + return encrypt; + } + + /** + * 使用 AES 解密算法解密数据 + * + * @param encryptedData 加密后的数据 + * @param encryptKey 加密密钥 + * @param encryptVector 加密向量 + * @return 解密后的数据 + */ + private static String aesDecrypt(String encryptedData, String encryptKey, String encryptVector) { + String decrypt = AesUtils.aesDecrypt(encryptedData, encryptKey); + log.info("AES,解密输出HEX = %s \n" + decrypt); + return decrypt; + } + + /** + * 计算数据签名 (SHA256) + * + * @param dataBody 报文体 + * @param timeStamp 时间戳 + * @param signKey 签名密钥 + * @return 数据签名 + */ + private static String calculateDataSign(String dataBody, long timeStamp, String signKey) { + // 使用 dataBody、timeStamp 和 signKey 计算签名 + return generateDataSign(dataBody, timeStamp, signKey); + } + + /** + * 生成数据签名 + * + * @param dataBody 报文体 + * @param timeStamp 时间戳 + * @param signKey 签名密钥 + * @return 数据签名 + */ + public static String generateDataSign(String dataBody, long timeStamp, String signKey) { + String dataToSign = dataBody + ":" + timeStamp + ":" + signKey; + return DigestUtils.md5Hex(dataToSign); + } + + /** + * 验证协议内容是否合法(系统默认数据格式) + * + * @param jsonString + * @return true:合法,false:不合法 + */ + public static boolean validateProtocolData(String jsonString) { + ObjectMapper objectMapper = new ObjectMapper(); + try { + JsonNode rootNode = objectMapper.readTree(jsonString); + + // 校验一级字段 + if (!validateJsonNode(rootNode, "head", JsonNode::isObject) || + !validateJsonNode(rootNode, "dataBody", JsonNode::isObject) || + !validateJsonNode(rootNode, "dataSign", JsonNode::isTextual)) { + return false; + } + + JsonNode headNode = rootNode.get("head"); + + // 校验二级字段和字段类型 + /*if (!validateJsonNode(headNode, "mid", JsonNode::isLong) || + !validateJsonNode(headNode, "cipherFlag", JsonNode::isInt) || + !validateJsonNode(headNode, "timeStamp", JsonNode::isLong)) { + return false; + }*/ + + // 校验必传字段 + if (headNode.get("mid").asLong() <= 0 || headNode.get("timeStamp").asLong() <= 0) { + return false; + } + + // 校验加密标志范围 + int cipherFlag = headNode.get("cipherFlag").asInt(); + if (cipherFlag < 0 || cipherFlag > 2) { + return false; + } + + } catch (IOException e) { + e.printStackTrace(); + return false; + } + + return true; + } + + private static boolean validateJsonNode(JsonNode node, String fieldName, Function validator) { + return node.has(fieldName) && validator.apply(node.get(fieldName)); + } + + + private static boolean verifyDataSign(String decryptedDataBody, long timeStamp, String signKey, String dataSign) { + // 使用 decryptedDataBody、timeStamp 和 signKey 计算签名 + String calculatedSign = calculateDataSign(decryptedDataBody, timeStamp, signKey); + + // 比较计算出的签名和报文中的签名 + return calculatedSign.equals(dataSign); + } + + public static void main(String[] args) { + String dataBody = "12233"; + int cipherFlag = 2; + String signKey = "yousignkey"; + String encryptKey = "yourncryptey"; + String encryptVector = "yourncryptvector"; + + try { + // 加密报文 + String encryptedMessage = encryptMessage(dataBody, cipherFlag, signKey, encryptKey, encryptVector); + System.out.println("Encrypted message: " + encryptedMessage); + + // 解密报文 + String decryptedDataBody = decryptMessage(encryptedMessage, signKey, encryptKey, encryptVector); + System.out.println("Decrypted data body: " + decryptedDataBody); + } catch (Exception e) { + System.err.println("Error processing message: " + e.getMessage()); + } + } +} diff --git a/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/utils/ProtocolRegexTopicVariableExtractorUtils.java b/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/utils/ProtocolRegexTopicVariableExtractorUtils.java new file mode 100644 index 00000000..1c2e4284 --- /dev/null +++ b/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/utils/ProtocolRegexTopicVariableExtractorUtils.java @@ -0,0 +1,47 @@ +package com.mqttsnet.basic.protocol.utils; + +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @program: thinglinks-util-pro + * @description: 协议Topic变量提取工具类 + * RegexVariableExtractor is a utility class that provides methods to extract + * specific variables (version and deviceId) from a given input string. + * @packagename: com.mqttsnet.basic.utils.protocol + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-07 14:10 + **/ +public class ProtocolRegexTopicVariableExtractorUtils { + + /** + * Extracts the version and deviceId variables from the given input string. + * + * @param input The input string to extract the variables from. + * @return A Map containing the extracted version and deviceId variables. + */ + public static Map extractVariables(String input) { + // Define the regex pattern to match the version and deviceId variables + String pattern = "/([^/]+)/devices/([^/]+)"; + + // Compile the regex pattern + Pattern compiledPattern = Pattern.compile(pattern); + // Match the input string against the compiled pattern + Matcher matcher = compiledPattern.matcher(input); + + // Create a map to store the extracted variables + Map variables = new HashMap<>(); + + // If the input string matches the pattern, extract the version and deviceId variables + if (matcher.find()) { + variables.put("version", matcher.group(1)); + variables.put("deviceId", matcher.group(2)); + } + + // Return the map containing the extracted variables + return variables; + } +} diff --git a/thinglinks-common/thinglinks-common-protocol/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/thinglinks-common/thinglinks-common-protocol/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..a311a045 --- /dev/null +++ b/thinglinks-common/thinglinks-common-protocol/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +com.mqttsnet.basic.protocol.factory.ProtocolMessageAdapter \ No newline at end of file diff --git a/thinglinks-common/thinglinks-common-rocketmq/src/main/java/com/mqttsnet/thinglinks/common/rocketmq/constant/ConsumerGroupConstant.java b/thinglinks-common/thinglinks-common-rocketmq/src/main/java/com/mqttsnet/thinglinks/common/rocketmq/constant/ConsumerGroupConstant.java deleted file mode 100644 index 653fbfee..00000000 --- a/thinglinks-common/thinglinks-common-rocketmq/src/main/java/com/mqttsnet/thinglinks/common/rocketmq/constant/ConsumerGroupConstant.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.mqttsnet.thinglinks.common.rocketmq.constant; - -/** - * @Description: 消费者组常量 - * @Author: ShiHuan SUN - * @E-mail: 13733918655@163.com - * @Website: http://thinglinks.mqttsnet.com - * @CreateDate: 2022/4/15$ 15:53$ - * @UpdateUser: ShiHuan SUN - * @UpdateDate: 2022/4/15$ 15:53$ - * @UpdateRemark: 修改内容 - * @Version: V1.0 - */ -public class ConsumerGroupConstant { - - /** - * broker-consumer-group - */ - public static final String THINGLINKS_BROKER_GROUP = "thinglinks-broker"; - - /** - * link-consumer-group - */ - public static final String THINGLINKS_LINK_GROUP = "thinglinks-link"; - - /** - * tdengine-consumer-group - */ - public static final String THINGLINKS_TDENGINE_GROUP = "thinglinks-tdengine"; - - /** - * job-consumer-group - */ - public static final String THINGLINKS_JOB_GROUP = "thinglinks-job"; - - /** - * rule-consumer-group - */ - public static final String THINGLINKS_RULE_GROUP = "thinglinks-rule"; - - -} diff --git a/thinglinks-common/thinglinks-common-rocketmq/src/main/java/com/mqttsnet/thinglinks/common/rocketmq/constant/ConsumerTopicConstant.java b/thinglinks-common/thinglinks-common-rocketmq/src/main/java/com/mqttsnet/thinglinks/common/rocketmq/constant/ConsumerTopicConstant.java deleted file mode 100644 index bef68340..00000000 --- a/thinglinks-common/thinglinks-common-rocketmq/src/main/java/com/mqttsnet/thinglinks/common/rocketmq/constant/ConsumerTopicConstant.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.mqttsnet.thinglinks.common.rocketmq.constant; - -import lombok.Data; - -/** - * @Description: 消费者主题常量 - * @Author: ShiHuan SUN - * @E-mail: 13733918655@163.com - * @Website: http://thinglinks.mqttsnet.com - * @CreateDate: 2022/4/15$ 15:53$ - * @UpdateUser: ShiHuan SUN - * @UpdateDate: 2022/4/15$ 15:53$ - * @UpdateRemark: 修改内容 - * @Version: V1.0 - */ -@Data -public class ConsumerTopicConstant { - - /** - * MQTT设备消息监听主题 - */ - public static final String THINGLINKS_LINK_MQTT_MSG = "thinglinks-link-mqttMsg"; - - /** - * TDengine超级表创键修改动作监听主题 - */ - public static final String PRODUCTSUPERTABLE_CREATEORUPDATE = "productSuperTable-createOrUpdate"; - - /** - * 系统指标数据采集动作监听主题 - */ - public static final String THINGLINKS_COLLECTION_SYSTEM = "thinglinks_collection_system"; - - /** - * 规则引擎触发器规则动作监听主题 - */ - public static final String THINGLINKS_RULE_TRIGGER = "thinglinks_rule_trigger"; - -} diff --git a/thinglinks-modules/thinglinks-modules-broker/pom.xml b/thinglinks-modules/thinglinks-modules-broker/pom.xml index 6dac3ed0..cb237e9f 100644 --- a/thinglinks-modules/thinglinks-modules-broker/pom.xml +++ b/thinglinks-modules/thinglinks-modules-broker/pom.xml @@ -61,6 +61,20 @@ ${thinglinks.version} + + + com.mqttsnet + thinglinks-common-kafka + ${thinglinks.version} + + + + + com.mqttsnet + thinglinks-common-protocol + ${thinglinks.version} + + com.mqttsnet @@ -79,6 +93,13 @@ ${thinglinks.version} + + com.mqttsnet + thinglinks-modules-link + ${thinglinks.version} + + + diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/common/asyncthread/BrokerAsyncConfig.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/common/asyncthread/BrokerAsyncConfig.java new file mode 100644 index 00000000..30a9848d --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/common/asyncthread/BrokerAsyncConfig.java @@ -0,0 +1,94 @@ +package com.mqttsnet.thinglinks.broker.common.asyncthread; + +import com.mqttsnet.thinglinks.common.core.asyncthread.SuRejectHandle; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.Executor; + +/** + * 异步@Async多线程配置 + * 使用原则:每一个业务场景使用独立的线程池,不要使用全局共享线程池 + * + * @author thinglinks + */ +@Configuration +@EnableAsync +public class BrokerAsyncConfig { + + /** + * 核心线程数(默认线程数) + */ + @Value("${threadBus.pool.core-pool-size}") + private int corePoolSize = Runtime.getRuntime().availableProcessors(); + /** + * 最大线程数 + */ + @Value("${threadBus.pool.max-pool-size}") + private int maxPoolSize = Runtime.getRuntime().availableProcessors(); + /** + * 允许线程空闲时间(单位:默认为秒) + */ + @Value("${threadBus.pool.keep-alive-time}") + private int keepAliveTime = 60; + /** + * 缓冲队列大小 + */ + @Value("${threadBus.pool.queue-capacity}") + private int queueCapacity = 200; + /** + * 线程池名前缀 + */ + @Value("${threadBus.pool.thread-name-prefix}") + private String threadNamePrefix = "thinglinksAsync-"; + + @Autowired + private SuRejectHandle rejectHandle; + + /** + * Broker服务全局共享异步线程池 + */ + @Bean("brokerAsync") + public Executor brokerAsync() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(corePoolSize);//核心线程数 + executor.setMaxPoolSize(maxPoolSize);//最大线程数 cpu核数/(1-0.8)//cup核数*2//cup核数+1 + //传参正值使用无界LinkedBlockingQueue + //其他传参使用不缓存SynchronousQueue + executor.setQueueCapacity(queueCapacity);//队列长度(超过队列长度无法存储,则开启最大线程数) + executor.setKeepAliveSeconds(keepAliveTime);//空闲线程最大存活时间 默认60s + executor.setThreadNamePrefix(threadNamePrefix + "brokerAsync-");//线程名前缀 + executor.setRejectedExecutionHandler(rejectHandle);// 自定义任务丢失处理策略 该策略输出由scheduling-1打印 + //设置线程池等待所有任务都完成再关闭 + executor.setWaitForTasksToCompleteOnShutdown(true); + executor.setAwaitTerminationSeconds(keepAliveTime); + executor.initialize(); + return executor; + } + + /** + * MQTT设备消息消费异步线程池配置 + */ + @Bean("brokerAsync-mqttMsg") + public Executor brokerAsyncMqttMsg() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(corePoolSize);//核心线程数 + executor.setMaxPoolSize(maxPoolSize);//最大线程数 cpu核数/(1-0.8)//cup核数*2//cup核数+1 + //传参正值使用无界LinkedBlockingQueue + //其他传参使用不缓存SynchronousQueue + executor.setQueueCapacity(queueCapacity);//队列长度(超过队列长度无法存储,则开启最大线程数) + executor.setKeepAliveSeconds(keepAliveTime);//空闲线程最大存活时间 默认60s + executor.setThreadNamePrefix(threadNamePrefix + "brokerAsync-mqttMsg");//线程名前缀 + executor.setRejectedExecutionHandler(rejectHandle);//自定义任务丢失处理策略 该策略输出由scheduling-1打印 + executor.setWaitForTasksToCompleteOnShutdown(true); + executor.setAwaitTerminationSeconds(keepAliveTime); + executor.initialize(); + return executor; + } + + +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/config/KafkaConsumerConfig.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/config/KafkaConsumerConfig.java new file mode 100644 index 00000000..14ffa5ab --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/config/KafkaConsumerConfig.java @@ -0,0 +1,109 @@ +package com.mqttsnet.thinglinks.broker.config; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.config.KafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; +import org.springframework.kafka.listener.ConcurrentMessageListenerContainer; +import org.springframework.kafka.listener.ContainerProperties; +import org.springframework.kafka.support.serializer.JsonDeserializer; + +import java.util.HashMap; +import java.util.Map; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: KafkaConsumerConfig + * @packagename: com.mqttsnet.thinglinks.config.kafka + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-06-18 11:29 + **/ +@Configuration +public class KafkaConsumerConfig { + + + @Value("${spring.kafka.thingLinks.consumer.bootstrap-servers}") + private String bootstrapServers; + @Value("${spring.kafka.thingLinks.consumer.group-id}") + private String groupId; + @Value("${spring.kafka.thingLinks.consumer.enable-auto-commit}") + private boolean enableAutoCommit; + @Value("${spring.kafka.thingLinks.properties.session.timeout.ms}") + private String sessionTimeout; + @Value("${spring.kafka.thingLinks.properties.max.poll.interval.ms}") + private String maxPollIntervalTime; + @Value("${spring.kafka.thingLinks.consumer.max-poll-records}") + private String maxPollRecords; + @Value("${spring.kafka.thingLinks.consumer.auto-offset-reset}") + private String autoOffsetReset; + @Value("${spring.kafka.thingLinks.listener.concurrency}") + private Integer concurrency; + @Value("${spring.kafka.thingLinks.listener.missing-topics-fatal}") + private boolean missingTopicsFatal; + @Value("${spring.kafka.thingLinks.listener.poll-timeout}") + private long pollTimeout; + + @Bean + public Map consumerConfigs() { + + Map propsMap = new HashMap<>(16); + propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); + propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, groupId); + //是否自动提交偏移量,默认值是true,为了避免出现重复数据和数据丢失,可以把它设置为false,然后手动提交偏移量 + propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, enableAutoCommit); + //自动提交的时间间隔,自动提交开启时生效 + propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "2000"); + //该属性指定了消费者在读取一个没有偏移量的分区或者偏移量无效的情况下该作何处理: + //earliest:当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,从头开始消费分区的记录 + //latest:当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,消费新产生的该分区下的数据(在消费者启动之后生成的记录) + //none:当各分区都存在已提交的offset时,从提交的offset开始消费;只要有一个分区不存在已提交的offset,则抛出异常 + propsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset); + //两次poll之间的最大间隔,默认值为5分钟。如果超过这个间隔会触发reBalance + propsMap.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, maxPollIntervalTime); + //这个参数定义了poll方法最多可以拉取多少条消息,默认值为500。如果在拉取消息的时候新消息不足500条,那有多少返回多少;如果超过500条,每次只返回500。 + //这个默认值在有些场景下太大,有些场景很难保证能够在5min内处理完500条消息, + //如果消费者无法在5分钟内处理完500条消息的话就会触发reBalance, + //然后这批消息会被分配到另一个消费者中,还是会处理不完,这样这批消息就永远也处理不完。 + //要避免出现上述问题,提前评估好处理一条消息最长需要多少时间,然后覆盖默认的max.poll.records参数 + //注:需要开启BatchListener批量监听才会生效,如果不开启BatchListener则不会出现reBalance情况 + propsMap.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, maxPollRecords); + //当broker多久没有收到consumer的心跳请求后就触发reBalance,默认值是10s + propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, sessionTimeout); + //序列化(建议使用Json,这种序列化方式可以无需额外配置传输实体类) + propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); + propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); + return propsMap; + } + + @Bean + public ConsumerFactory consumerFactory() { + + //配置消费者的 Json 反序列化的可信赖包,反序列化实体类需要 + try (StringDeserializer stringDeserializer = new StringDeserializer()) { + return new DefaultKafkaConsumerFactory<>(consumerConfigs(), new StringDeserializer(), stringDeserializer); + } + } + + @Bean + public KafkaListenerContainerFactory> kafkaListenerContainerFactory() { + + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory()); + //在侦听器容器中运行的线程数,一般设置为 机器数*分区数 + factory.setConcurrency(concurrency); + //消费监听接口监听的主题不存在时,默认会报错,所以设置为false忽略错误 + factory.setMissingTopicsFatal(missingTopicsFatal); + //自动提交关闭,需要设置手动消息确认 + factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE); + factory.getContainerProperties().setPollTimeout(pollTimeout); + //设置为批量监听,需要用List接收 + factory.setBatchListener(true); + return factory; + } +} \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/config/KafkaProviderConfig.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/config/KafkaProviderConfig.java new file mode 100644 index 00000000..5a2cca04 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/config/KafkaProviderConfig.java @@ -0,0 +1,90 @@ +package com.mqttsnet.thinglinks.broker.config; + +import org.apache.kafka.clients.producer.ProducerConfig; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.core.DefaultKafkaProducerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.core.ProducerFactory; +import org.springframework.kafka.support.serializer.JsonSerializer; +import org.springframework.kafka.transaction.KafkaTransactionManager; + +import java.util.HashMap; +import java.util.Map; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: KafkaProviderConfig + * @packagename: com.mqttsnet.thinglinks.config.kafka + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-06-18 11:28 + **/ +@Configuration +public class KafkaProviderConfig { + + + @Value("${spring.kafka.thingLinks.producer.bootstrap-servers}") + private String bootstrapServers; + @Value("${spring.kafka.thingLinks.producer.transaction-id-prefix}") + private String transactionIdPrefix; + @Value("${spring.kafka.thingLinks.producer.acks}") + private String acks; + @Value("${spring.kafka.thingLinks.producer.retries}") + private String retries; + @Value("${spring.kafka.thingLinks.producer.batch-size}") + private String batchSize; + @Value("${spring.kafka.thingLinks.producer.buffer-memory}") + private String bufferMemory; + + @Bean + public Map producerConfigs() { + + Map props = new HashMap<>(16); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); + //acks=0 : 生产者在成功写入消息之前不会等待任何来自服务器的响应。 + //acks=1 : 只要集群的首领节点收到消息,生产者就会收到一个来自服务器成功响应。 + //acks=all :只有当所有参与复制的节点全部收到消息时,生产者才会收到一个来自服务器的成功响应。 + //开启事务必须设为all + props.put(ProducerConfig.ACKS_CONFIG, acks); + //发生错误后,消息重发的次数,开启事务必须大于0 + props.put(ProducerConfig.RETRIES_CONFIG, retries); + //当多个消息发送到相同分区时,生产者会将消息打包到一起,以减少请求交互. 而不是一条条发送 + //批次的大小可以通过batch.size 参数设置.默认是16KB + //较小的批次大小有可能降低吞吐量(批次大小为0则完全禁用批处理)。 + //比如说,kafka里的消息5秒钟Batch才凑满了16KB,才能发送出去。那这些消息的延迟就是5秒钟 + //实测batchSize这个参数没有用 + props.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize); + //有的时刻消息比较少,过了很久,比如5min也没有凑够16KB,这样延时就很大,所以需要一个参数. 再设置一个时间,到了这个时间, + //即使数据没达到16KB,也将这个批次发送出去 + props.put(ProducerConfig.LINGER_MS_CONFIG, "5000"); + //生产者内存缓冲区的大小 + props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, bufferMemory); + //反序列化,和生产者的序列化方式对应 + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); + props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); + return props; + } + + @Bean + public ProducerFactory producerFactory() { + + DefaultKafkaProducerFactory factory = new DefaultKafkaProducerFactory<>(producerConfigs()); + //开启事务,会导致 LINGER_MS_CONFIG 配置失效 + factory.setTransactionIdPrefix(transactionIdPrefix); + return factory; + } + + @Bean + public KafkaTransactionManager kafkaTransactionManager(ProducerFactory producerFactory) { + + return new KafkaTransactionManager<>(producerFactory); + } + + @Bean + public KafkaTemplate thingLinksKafkaTemplate() { + + return new KafkaTemplate<>(producerFactory()); + } +} \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/controller/MqttBrokerOpenController.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/controller/MqttBrokerOpenController.java index fc23f856..64b5ad59 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/controller/MqttBrokerOpenController.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/controller/MqttBrokerOpenController.java @@ -2,7 +2,7 @@ import cn.hutool.http.HttpRequest; import com.alibaba.fastjson.JSONObject; -import com.mqttsnet.thinglinks.broker.api.domain.model.PublishMessageRequest; +import com.mqttsnet.thinglinks.broker.api.domain.vo.PublishMessageRequestVO; import com.mqttsnet.thinglinks.broker.service.MqttBrokerService; import com.mqttsnet.thinglinks.common.core.domain.R; import io.swagger.annotations.Api; @@ -40,15 +40,15 @@ public class MqttBrokerOpenController { /** * MQTT推送消息接口 * - * @param publishMessageRequest 推送消息请求参数 + * @param publishMessageRequestVO 推送消息请求参数 * @return {@link R} 结果 */ @ApiOperation(value = "MQTT推送消息", notes = "根据提供的主题、服务质量等级、保留标志和消息内容推送MQTT消息") @PostMapping("/sendMessage") public R sendMessage(@ApiParam(value = "推送消息请求参数", required = true) - @RequestBody PublishMessageRequest publishMessageRequest) { - log.info("MQTT Broker publish {}", publishMessageRequest.toString()); - return R.ok(mqttBrokerService.publishMessage(publishMessageRequest)); + @RequestBody PublishMessageRequestVO publishMessageRequestVO) { + log.info("MQTT Broker publish {}", publishMessageRequestVO.toString()); + return R.ok(mqttBrokerService.publishMessage(publishMessageRequestVO)); } diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttCloseEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttCloseEvent.java new file mode 100644 index 00000000..b50b4864 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttCloseEvent.java @@ -0,0 +1,31 @@ +package com.mqttsnet.thinglinks.broker.mqs.event; + +import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; +import org.springframework.context.ApplicationEvent; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: + * @packagename: com.mqttsnet.thinglinks.mqtt.event + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 01:52 + **/ +public class MqttCloseEvent extends ApplicationEvent { + private String message; + private MqttEventEnum eventType; + + public MqttCloseEvent(Object source, MqttEventEnum eventType, String message) { + super(source); + this.message = message; + this.eventType = eventType; + } + + public String getMessage() { + return message; + } + + public MqttEventEnum getEventType() { + return eventType; + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttConnectEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttConnectEvent.java new file mode 100644 index 00000000..090cdd45 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttConnectEvent.java @@ -0,0 +1,31 @@ +package com.mqttsnet.thinglinks.broker.mqs.event; + +import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; +import org.springframework.context.ApplicationEvent; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: + * @packagename: com.mqttsnet.thinglinks.mqtt.event + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 01:15 + **/ +public class MqttConnectEvent extends ApplicationEvent { + private String message; + private MqttEventEnum eventType; + + public MqttConnectEvent(Object source, MqttEventEnum eventType, String message) { + super(source); + this.message = message; + this.eventType = eventType; + } + + public String getMessage() { + return message; + } + + public MqttEventEnum getEventType() { + return eventType; + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttDisconnectEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttDisconnectEvent.java new file mode 100644 index 00000000..95c2aedf --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttDisconnectEvent.java @@ -0,0 +1,31 @@ +package com.mqttsnet.thinglinks.broker.mqs.event; + +import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; +import org.springframework.context.ApplicationEvent; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MqttDisconnectEvent + * @packagename: com.mqttsnet.thinglinks.mqtt.event + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 01:52 + **/ +public class MqttDisconnectEvent extends ApplicationEvent { + private String message; + private MqttEventEnum eventType; + + public MqttDisconnectEvent(Object source, MqttEventEnum eventType, String message) { + super(source); + this.message = message; + this.eventType = eventType; + } + + public String getMessage() { + return message; + } + + public MqttEventEnum getEventType() { + return eventType; + } +} \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPingEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPingEvent.java new file mode 100644 index 00000000..9fd98460 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPingEvent.java @@ -0,0 +1,31 @@ +package com.mqttsnet.thinglinks.broker.mqs.event; + +import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; +import org.springframework.context.ApplicationEvent; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MqttPingEvent + * @packagename: com.mqttsnet.thinglinks.mqtt.event + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 01:53 + **/ +public class MqttPingEvent extends ApplicationEvent { + private String message; + private MqttEventEnum eventType; + + public MqttPingEvent(Object source, MqttEventEnum eventType, String message) { + super(source); + this.message = message; + this.eventType = eventType; + } + + public String getMessage() { + return message; + } + + public MqttEventEnum getEventType() { + return eventType; + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPublishEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPublishEvent.java new file mode 100644 index 00000000..d64d908f --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPublishEvent.java @@ -0,0 +1,32 @@ +package com.mqttsnet.thinglinks.broker.mqs.event; + +import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; +import org.springframework.context.ApplicationEvent; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MqttPublishEvent + * @packagename: com.mqttsnet.thinglinks.mqtt.event + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 01:13 + **/ +public class MqttPublishEvent extends ApplicationEvent { + private String message; + private MqttEventEnum eventType; + + public MqttPublishEvent(Object source, MqttEventEnum eventType, String message) { + super(source); + this.message = message; + this.eventType = eventType; + } + + public String getMessage() { + return message; + } + + public MqttEventEnum getEventType() { + return eventType; + } +} + diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttSubscribeEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttSubscribeEvent.java new file mode 100644 index 00000000..82f2293a --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttSubscribeEvent.java @@ -0,0 +1,31 @@ +package com.mqttsnet.thinglinks.broker.mqs.event; + +import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; +import org.springframework.context.ApplicationEvent; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MqttSubscribeEvent + * @packagename: com.mqttsnet.thinglinks.mqtt.event + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 01:52 + **/ +public class MqttSubscribeEvent extends ApplicationEvent { + private String message; + private MqttEventEnum eventType; + + public MqttSubscribeEvent(Object source, MqttEventEnum eventType, String message) { + super(source); + this.message = message; + this.eventType = eventType; + } + + public String getMessage() { + return message; + } + + public MqttEventEnum getEventType() { + return eventType; + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttUnsubscribeEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttUnsubscribeEvent.java new file mode 100644 index 00000000..82987257 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttUnsubscribeEvent.java @@ -0,0 +1,32 @@ +package com.mqttsnet.thinglinks.broker.mqs.event; + +import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; +import org.springframework.context.ApplicationEvent; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MqttUnsubscribeEvent + * @packagename: com.mqttsnet.thinglinks.mqtt.event + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 01:53 + **/ +public class MqttUnsubscribeEvent extends ApplicationEvent { + private String message; + private MqttEventEnum eventType; + + public MqttUnsubscribeEvent(Object source, MqttEventEnum eventType, String message) { + super(source); + this.message = message; + this.eventType = eventType; + } + + public String getMessage() { + return message; + } + + public MqttEventEnum getEventType() { + return eventType; + } +} + diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttCloseEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttCloseEventListener.java new file mode 100644 index 00000000..057d4375 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttCloseEventListener.java @@ -0,0 +1,81 @@ +package com.mqttsnet.thinglinks.broker.mqs.event.listener; + +import com.google.gson.Gson; +import com.mqttsnet.thinglinks.broker.mqs.event.MqttCloseEvent; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventActionService; +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatusEnum; +import com.mqttsnet.thinglinks.common.core.enums.ResultEnum; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; +import com.mqttsnet.thinglinks.link.api.domain.device.enumeration.DeviceActionTypeEnum; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MQTT CLOSE事件监听器 + * @packagename: com.mqttsnet.thinglinks.mqtt.listener + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 00:42 + **/ +@Component +@Slf4j +public class MqttCloseEventListener { + + @Resource + private RemoteDeviceService remoteDeviceService; + + @Autowired + private MqttEventActionService mqttEventActionService; + + + /** + * 发布MQTT CLOSE事件 + * + * @param event 事件消息 + */ + @EventListener + @Async("brokerAsync-mqttMsg") + public void publishMqttCloseEvent(MqttCloseEvent event) { + log.info("Publishing MQTT CLOSE event: message={}", event.getMessage()); + Gson gson = new Gson(); + Map map = new HashMap<>(); + map = gson.fromJson(event.getMessage(), map.getClass()); + String clientId = String.valueOf(map.get("clientId")); + + // TODO 从缓存中获取设备信息 校验设备是否存在 + + // 构造设备对象并设置客户端ID和连接状态 + Device deviceToUpdate = new Device() + .setClientId(clientId) + .setConnectStatus(DeviceConnectStatusEnum.OFFLINE.getKey()); + + // 更新设备连接状态 + R updateDeviceConnectionStatus = remoteDeviceService.updateConnectStatusByClientId(deviceToUpdate); + + // 检查更新操作的结果 + if (ResultEnum.SUCCESS.getCode() != updateDeviceConnectionStatus.getCode()) { + log.error("Failed to update the device connection status to OFFLINE, clientId={}", clientId); + return; + } + + + String describable = Optional.ofNullable(DeviceConnectStatusEnum.OFFLINE.getKey()) + .flatMap(DeviceConnectStatusEnum::fromValue) + .map(DeviceConnectStatusEnum::getKey) + .map(desc -> "The device connection status is updated to " + desc) + .orElse("The device connection status is updated to OFFLINE"); + + mqttEventActionService.saveMqttEventAction(event.getMessage(), DeviceActionTypeEnum.CLOSE, describable); + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttConnectEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttConnectEventListener.java new file mode 100644 index 00000000..361047e2 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttConnectEventListener.java @@ -0,0 +1,81 @@ +package com.mqttsnet.thinglinks.broker.mqs.event.listener; + +import com.google.gson.Gson; +import com.mqttsnet.thinglinks.broker.mqs.event.MqttConnectEvent; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventActionService; +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatusEnum; +import com.mqttsnet.thinglinks.common.core.enums.ResultEnum; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; +import com.mqttsnet.thinglinks.link.api.domain.device.enumeration.DeviceActionTypeEnum; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MQTT CONNECT事件监听器 + * @packagename: com.mqttsnet.thinglinks.mqtt.listener + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 00:36 + **/ +@Component +@Slf4j +public class MqttConnectEventListener { + + @Resource + private RemoteDeviceService remoteDeviceService; + + @Autowired + private MqttEventActionService mqttEventActionService; + + + /** + * 发布MQTT CONNECT事件 + * + * @param event 事件消息 + */ + @EventListener + @Async("brokerAsync-mqttMsg") + public void publishMqttCloseEvent(MqttConnectEvent event) { + log.info("Publishing MQTT CONNECT event: message={}", event.getMessage()); + Gson gson = new Gson(); + Map map = new HashMap<>(); + map = gson.fromJson(event.getMessage(), map.getClass()); + String clientId = String.valueOf(map.get("clientId")); + + // TODO 从缓存中获取设备信息 校验设备是否存在 + + // 构造设备对象并设置客户端ID和连接状态 + Device deviceToUpdate = new Device() + .setClientId(clientId) + .setConnectStatus(DeviceConnectStatusEnum.ONLINE.getKey()); + + // 更新设备连接状态 + R updateDeviceConnectionStatus = remoteDeviceService.updateConnectStatusByClientId(deviceToUpdate); + + // 检查更新操作的结果 + if (ResultEnum.SUCCESS.getCode() != updateDeviceConnectionStatus.getCode()) { + log.error("Failed to update the device connection status to OFFLINE, clientId={}", clientId); + return; + } + + + String describable = Optional.ofNullable(DeviceConnectStatusEnum.ONLINE.getKey()) + .flatMap(DeviceConnectStatusEnum::fromValue) + .map(DeviceConnectStatusEnum::getKey) + .map(desc -> "The device connection status is updated to " + desc) + .orElse("The device connection status is updated to ONLINE"); + + mqttEventActionService.saveMqttEventAction(event.getMessage(), DeviceActionTypeEnum.CONNECT, describable); + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttDisconnectEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttDisconnectEventListener.java new file mode 100644 index 00000000..524e0ae4 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttDisconnectEventListener.java @@ -0,0 +1,81 @@ +package com.mqttsnet.thinglinks.broker.mqs.event.listener; + +import com.google.gson.Gson; +import com.mqttsnet.thinglinks.broker.mqs.event.MqttDisconnectEvent; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventActionService; +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatusEnum; +import com.mqttsnet.thinglinks.common.core.enums.ResultEnum; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; +import com.mqttsnet.thinglinks.link.api.domain.device.enumeration.DeviceActionTypeEnum; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MQTT DISCONNECT事件监听器 + * @packagename: com.mqttsnet.thinglinks.mqtt.listener + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 00:45 + **/ +@Component +@Slf4j +public class MqttDisconnectEventListener { + + @Resource + private RemoteDeviceService remoteDeviceService; + + @Autowired + private MqttEventActionService mqttEventActionService; + + + /** + * 发布MQTT DISCONNECT事件 + * + * @param event 事件消息 + */ + @EventListener + @Async("brokerAsync-mqttMsg") + public void publishMqttDisconnectEvent(MqttDisconnectEvent event) { + log.info("Publishing MQTT DISCONNECT event: message={}", event.getMessage()); + Gson gson = new Gson(); + Map map = new HashMap<>(); + map = gson.fromJson(event.getMessage(), map.getClass()); + String clientId = String.valueOf(map.get("clientId")); + + // TODO 从缓存中获取设备信息 校验设备是否存在 + + // 构造设备对象并设置客户端ID和连接状态 + Device deviceToUpdate = new Device() + .setClientId(clientId) + .setConnectStatus(DeviceConnectStatusEnum.OFFLINE.getKey()); + + // 更新设备连接状态 + R updateDeviceConnectionStatus = remoteDeviceService.updateConnectStatusByClientId(deviceToUpdate); + + // 检查更新操作的结果 + if (ResultEnum.SUCCESS.getCode() != updateDeviceConnectionStatus.getCode()) { + log.error("Failed to update the device connection status to OFFLINE, clientId={}", clientId); + return; + } + + + String describable = Optional.ofNullable(DeviceConnectStatusEnum.OFFLINE.getKey()) + .flatMap(DeviceConnectStatusEnum::fromValue) + .map(DeviceConnectStatusEnum::getKey) + .map(desc -> "The device connection status is updated to " + desc) + .orElse("The device connection status is updated to OFFLINE"); + + mqttEventActionService.saveMqttEventAction(event.getMessage(), DeviceActionTypeEnum.DISCONNECT, describable); + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPingEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPingEventListener.java new file mode 100644 index 00000000..d0598b4e --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPingEventListener.java @@ -0,0 +1,32 @@ +package com.mqttsnet.thinglinks.broker.mqs.event.listener; + +import com.mqttsnet.thinglinks.broker.mqs.event.MqttPingEvent; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MQTT PING事件监听器 + * @packagename: com.mqttsnet.thinglinks.mqtt.listener + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 00:48 + **/ +@Component +@Slf4j +public class MqttPingEventListener { + + /** + * 发布MQTT PING事件 + * + * @param event 事件消息 + */ + @EventListener + @Async("brokerAsync-mqttMsg") + public void publishMqttPingEvent(MqttPingEvent event) { + log.info("Publishing MQTT PING event: message={}", event.getMessage()); + // TODO: 处理MQTT PING事件 + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPublishEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPublishEventListener.java new file mode 100644 index 00000000..8862421c --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPublishEventListener.java @@ -0,0 +1,58 @@ +package com.mqttsnet.thinglinks.broker.mqs.event.listener; + +import cn.hutool.json.JSONUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.mqttsnet.thinglinks.broker.mqs.event.MqttPublishEvent; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.event.MqttMessageEvent; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MqttPublish事件监听器 + * @packagename: com.mqttsnet.thinglinks.consumer.mqtt.listener + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 00:12 + **/ +@Component +@Slf4j +public class MqttPublishEventListener { + + @Autowired + private ApplicationEventPublisher publisher; + + /** + * 处理MQTT PUBLISH事件 + * + * @param event 事件消息 + */ + @EventListener + @Async("brokerAsync-mqttMsg") + public void handleMqttPublishEvent(MqttPublishEvent event) { + log.info("Received MQTT PUBLISH event: message={}", event.getMessage()); + // 处理PUBLISH事件 + if (StringUtils.isEmpty(event.getMessage()) && JSONUtil.isTypeJSON(event.getMessage())) { + log.warn("The message is empty and ignored"); + return; + } + JSONObject mqttMessage = JSON.parseObject(event.getMessage()); + String topic = mqttMessage.getString("topic"); + String qos = mqttMessage.getString("qos"); + String body = mqttMessage.getString("body"); + String time = mqttMessage.getString("time"); + if (!JSONUtil.isTypeJSON(body)) { + log.error("Topic:{},The body is empty and ignored", topic); + return; + } + log.info("MqttPublishEventListener handleMqttPublishEvent mqttMessage topic:{}, qos:{}, body:{}, time:{}", topic, qos, body, time); + // 发布MQTT消息事件 + publisher.publishEvent(new MqttMessageEvent(this, topic, qos, body, time)); + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttSubscribeEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttSubscribeEventListener.java new file mode 100644 index 00000000..e2ec4041 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttSubscribeEventListener.java @@ -0,0 +1,38 @@ +package com.mqttsnet.thinglinks.broker.mqs.event.listener; + +import com.mqttsnet.thinglinks.broker.mqs.event.MqttSubscribeEvent; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventActionService; +import com.mqttsnet.thinglinks.link.api.domain.device.enumeration.DeviceActionTypeEnum; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MQTT SUBSCRIBE事件监听器 + * @packagename: com.mqttsnet.thinglinks.mqtt.listener + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 00:46 + **/ +@Component +@Slf4j +public class MqttSubscribeEventListener { + + @Autowired + private MqttEventActionService mqttEventActionService; + + /** + * 发布MQTT SUBSCRIBE事件 + * + * @param event 事件消息 + */ + @EventListener + @Async("brokerAsync-mqttMsg") + public void publishMqttSubscribeEvent(MqttSubscribeEvent event) { + log.info("Publishing MQTT SUBSCRIBE event: message={}", event.getMessage()); + mqttEventActionService.saveMqttEventAction(event.getMessage(), DeviceActionTypeEnum.SUBSCRIBE, DeviceActionTypeEnum.SUBSCRIBE.getDescription()); + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttUnsubscribeEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttUnsubscribeEventListener.java new file mode 100644 index 00000000..c264ffdb --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttUnsubscribeEventListener.java @@ -0,0 +1,38 @@ +package com.mqttsnet.thinglinks.broker.mqs.event.listener; + +import com.mqttsnet.thinglinks.broker.mqs.event.MqttUnsubscribeEvent; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventActionService; +import com.mqttsnet.thinglinks.link.api.domain.device.enumeration.DeviceActionTypeEnum; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MQTT UNSUBSCRIBE事件监听器 + * @packagename: com.mqttsnet.thinglinks.mqtt.listener + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 00:48 + **/ +@Component +@Slf4j +public class MqttUnsubscribeEventListener { + + @Autowired + private MqttEventActionService mqttEventActionService; + + /** + * 发布MQTT UNSUBSCRIBE事件 + * + * @param event 事件消息 + */ + @EventListener + @Async("brokerAsync-mqttMsg") + public void publishMqttUnsubscribeEvent(MqttUnsubscribeEvent event) { + log.info("Publishing MQTT UNSUBSCRIBE event: message={}", event.getMessage()); + mqttEventActionService.saveMqttEventAction(event.getMessage(), DeviceActionTypeEnum.UNSUBSCRIBE, DeviceActionTypeEnum.UNSUBSCRIBE.getDescription()); + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/publisher/MqttEventPublisher.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/publisher/MqttEventPublisher.java new file mode 100644 index 00000000..07167d16 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/publisher/MqttEventPublisher.java @@ -0,0 +1,59 @@ +package com.mqttsnet.thinglinks.broker.mqs.event.publisher; + +import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; +import com.mqttsnet.thinglinks.broker.mqs.event.*; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Component; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MQTT事件发布器 用于发布MQTT事件 TODO MqttEventEnum 事件枚举类 用于定义MQTT事件 预留 + * @packagename: com.mqttsnet.thinglinks.consumer.mqtt.publisher + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 00:07 + **/ +@Component +@Slf4j +public class MqttEventPublisher { + @Autowired + private ApplicationEventPublisher eventPublisher; + + public void publishMqttConnectEvent(MqttEventEnum eventEnum, String message) { + log.info("Publishing MQTT CONNECT event: message={}", message); + eventPublisher.publishEvent(new MqttConnectEvent(this, eventEnum, message)); + } + + public void publishMqttCloseEvent(MqttEventEnum eventEnum, String message) { + log.info("Publishing MQTT CLOSE event: message={}", message); + eventPublisher.publishEvent(new MqttCloseEvent(this, eventEnum, message)); + } + + public void publishMqttDisconnectEvent(MqttEventEnum eventEnum, String message) { + log.info("Publishing MQTT DISCONNECT event: message={}", message); + eventPublisher.publishEvent(new MqttDisconnectEvent(this, eventEnum, message)); + } + + public void publishMqttPublishEvent(MqttEventEnum eventEnum, String message) { + log.info("Publishing MQTT PUBLISH event: message={}", message); + eventPublisher.publishEvent(new MqttPublishEvent(this, eventEnum, message)); + } + + public void publishMqttSubscribeEvent(MqttEventEnum eventEnum, String message) { + log.info("Publishing MQTT SUBSCRIBE event: message={}", message); + eventPublisher.publishEvent(new MqttSubscribeEvent(this, eventEnum, message)); + } + + public void publishMqttUnsubscribeEvent(MqttEventEnum eventEnum, String message) { + log.info("Publishing MQTT UNSUBSCRIBE event: message={}", message); + eventPublisher.publishEvent(new MqttUnsubscribeEvent(this, eventEnum, message)); + } + + public void publishMqttPingEvent(MqttEventEnum eventEnum, String message) { + log.info("Publishing MQTT PING event: message={}", message); + eventPublisher.publishEvent(new MqttPingEvent(this, eventEnum, message)); + } + +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaProducerService.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaProducerService.java new file mode 100644 index 00000000..efb1fe4d --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaProducerService.java @@ -0,0 +1,49 @@ +package com.mqttsnet.thinglinks.broker.mqs.handler.kafka; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.support.SendResult; +import org.springframework.stereotype.Service; +import org.springframework.util.concurrent.ListenableFuture; +import org.springframework.util.concurrent.ListenableFutureCallback; + +/** + * @Description: kafka生产者 + * @Author: ShiHuan Sun + * @E-mail: 13733918655@163.com + * @CreateDate: 2023/01/06$ 16:02$ + * @UpdateUser: ShiHuan Sun + * @UpdateDate: 2023/01/06$ 16:02$ + * @UpdateRemark: 修改内容 + * @Version: 1.0 + */ +@Service +@Slf4j +public class KafkaProducerService { + + @Autowired + @Qualifier("thingLinksKafkaTemplate") + private KafkaTemplate thingLinksKafkaTemplate; + + + public void thingLinksKafkaTemplateSendMsg(String topic, String msg) { + log.info("thingLinksKafkaTemplate sendMsg ,topic:{},msg:{}", topic, msg); + + ListenableFuture> sendMsg = thingLinksKafkaTemplate.send(topic, msg); + //消息确认 + sendMsg.addCallback(new ListenableFutureCallback>() { + @Override + public void onFailure(Throwable throwable) { + log.error("send error,ex:{},topic:{},msg:{}", throwable, topic, msg); + } + + @Override + public void onSuccess(SendResult stringStringSendResult) { + log.info("send success,topic:{},msg:{}", topic, msg); + } + }); + log.info("kafka send end!"); + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaSendResultHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaSendResultHandler.java new file mode 100644 index 00000000..b0da2eeb --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaSendResultHandler.java @@ -0,0 +1,34 @@ +package com.mqttsnet.thinglinks.broker.mqs.handler.kafka; + +import lombok.extern.slf4j.Slf4j; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.clients.producer.RecordMetadata; +import org.springframework.kafka.support.ProducerListener; +import org.springframework.lang.Nullable; +import org.springframework.stereotype.Component; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: kafka消息发送回调 + * @packagename: com.mqttsnet.thinglinks.common.kafka.handler + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-06-18 11:39 + **/ +@Slf4j +@Component +public class KafkaSendResultHandler implements ProducerListener { + + + @Override + public void onSuccess(ProducerRecord producerRecord, RecordMetadata recordMetadata) { + + log.info("消息发送成功:{}", producerRecord.toString()); + } + + @Override + public void onError(ProducerRecord producerRecord, @Nullable RecordMetadata recordMetadata, Exception exception) { + + log.error("消息发送失败:{},{}", producerRecord.toString(), exception.getMessage()); + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MqttMessageKafkaConsumerHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MqttMessageKafkaConsumerHandler.java new file mode 100644 index 00000000..2e63b4fc --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MqttMessageKafkaConsumerHandler.java @@ -0,0 +1,131 @@ +package com.mqttsnet.thinglinks.broker.mqs.handler.kafka; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; +import com.mqttsnet.thinglinks.broker.mqs.event.publisher.MqttEventPublisher; +import com.mqttsnet.thinglinks.common.core.mqs.ConsumerTopicConstant; +import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.annotation.KafkaHandler; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.kafka.support.Acknowledgment; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Optional; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: Mqtt Message kafka监听消息 + * @packagename: com.mqttsnet.thinglinks.kafka + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-06-18 11:46 + **/ +@Slf4j +@Component +public class MqttMessageKafkaConsumerHandler { + + @Autowired + private MqttEventPublisher eventPublisher; + + @Autowired + private CacheDataHelper cacheDataHelper; + + /** + * 监听kafka消息(批量) + * + * @param records kafka的批量消息,用consumerRecord可以接收到更详细的信息,也可以用String message只接收消息 + * @param ack kafka的消息确认 + */ + @KafkaListener(topics = {ConsumerTopicConstant.Mqtt.THINGLINKS_MQS_MQTT_MSG, + ConsumerTopicConstant.Mqtt.THINGLINKS_CLIENT_CONNECTED_TOPIC, + ConsumerTopicConstant.Mqtt.THINGLINKS_CLIENT_DISCONNECTED_TOPIC, + ConsumerTopicConstant.Mqtt.THINGLINKS_SERVER_CONNECTED_TOPIC, + ConsumerTopicConstant.Mqtt.THINGLINKS_DEVICE_KICKED_TOPIC, + ConsumerTopicConstant.Mqtt.THINGLINKS_SUBSCRIPTION_ACKED_TOPIC, + ConsumerTopicConstant.Mqtt.THINGLINKS_UNSUBSCRIPTION_ACKED_TOPIC, + ConsumerTopicConstant.Mqtt.THINGLINKS_DISTRIBUTION_ERROR_TOPIC, + ConsumerTopicConstant.Mqtt.THINGLINKS_DISTRIBUTION_COMPLETED_TOPIC, + ConsumerTopicConstant.Mqtt.THINGLINKS_PING_REQ_TOPIC + }, errorHandler = "myKafkaListenerErrorHandler", containerFactory = "kafkaListenerContainerFactory") + @KafkaHandler + public void handleBatchMessages(List> records, Acknowledgment ack) { + try { + // 用于测试异常处理 + // int i = 1 / 0; + log.info("handleBatchMessages Listener, Thread ID:{}, records size:{}", Thread.currentThread().getId(), records.size()); + for (ConsumerRecord record : records) { + Optional kafkaMessage = Optional.ofNullable(record.value()); + if (!kafkaMessage.isPresent()) { + log.error("topic:{},报文体为空或数据格式有误已忽略" + record.topic()); + return; + } + String message = record.value().toString(); + String topic = record.topic(); + log.info("handleBatchMessages--> topic={} Received message={}", topic, message); + processMessage(message); + } + } finally { + // 手动确认 + ack.acknowledge(); + } + } + + /** + * 处理消息 + * + * @param message 消息记录 + */ + private void processMessage(String message) { + log.info("ThingLinks物联网平台数据消费-->Received message={}", message); + try { + JSONObject thinglinksMessage = JSON.parseObject(String.valueOf(message)); + String eventStr = Optional.ofNullable(thinglinksMessage.getString("event")) + .orElse(""); + Long tenantId = Optional.ofNullable(thinglinksMessage.getString("tenantId")) + .filter(StringUtils::isNotBlank) + .map(Long::valueOf) + .orElse(null); + if (StringUtils.isEmpty(eventStr) || tenantId == null) { + log.warn("event or tenantId cannot be empty {}", eventStr); + return; + } + Optional optionalEvent = MqttEventEnum.getMqttEventEnum(thinglinksMessage.get("event").toString()); + optionalEvent.ifPresent(event -> { + switch (event) { + case CONNECT: + eventPublisher.publishMqttConnectEvent(MqttEventEnum.CONNECT, thinglinksMessage.toJSONString()); + break; + case CLOSE: + eventPublisher.publishMqttCloseEvent(MqttEventEnum.CLOSE, thinglinksMessage.toJSONString()); + break; + case DISCONNECT: + eventPublisher.publishMqttDisconnectEvent(MqttEventEnum.DISCONNECT, thinglinksMessage.toJSONString()); + break; + case PUBLISH: + eventPublisher.publishMqttPublishEvent(MqttEventEnum.PUBLISH, thinglinksMessage.toJSONString()); + break; + case SUBSCRIBE: + eventPublisher.publishMqttSubscribeEvent(MqttEventEnum.SUBSCRIBE, thinglinksMessage.toJSONString()); + break; + case UNSUBSCRIBE: + eventPublisher.publishMqttUnsubscribeEvent(MqttEventEnum.UNSUBSCRIBE, thinglinksMessage.toJSONString()); + break; + case PING: + eventPublisher.publishMqttPingEvent(MqttEventEnum.PING, thinglinksMessage.toJSONString()); + break; + default: + break; + } + }); + } catch (Exception e) { + log.error("ThingLinks物联网平台数据消费-->消费失败,失败原因:{}", e.getMessage()); + } + } + +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MyKafkaListenerErrorHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MyKafkaListenerErrorHandler.java new file mode 100644 index 00000000..e11696ad --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MyKafkaListenerErrorHandler.java @@ -0,0 +1,38 @@ +package com.mqttsnet.thinglinks.broker.mqs.handler.kafka; + +import lombok.extern.slf4j.Slf4j; +import org.apache.kafka.clients.consumer.Consumer; +import org.springframework.kafka.listener.KafkaListenerErrorHandler; +import org.springframework.kafka.listener.ListenerExecutionFailedException; +import org.springframework.lang.NonNull; +import org.springframework.messaging.Message; +import org.springframework.stereotype.Component; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: kafkaListener异常处理 + * @packagename: com.mqttsnet.thinglinks.common.kafka.handler + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-06-18 11:44 + **/ +@Slf4j +@Component +public class MyKafkaListenerErrorHandler implements KafkaListenerErrorHandler { + + @Override + @NonNull + public Object handleError(@NonNull Message message, @NonNull ListenerExecutionFailedException exception) { + log.error("Error handling message: {}", message, exception); + return new Object(); + } + + @Override + @NonNull + public Object handleError(@NonNull Message message, @NonNull ListenerExecutionFailedException exception, Consumer consumer) { + log.error("Error handling message: {}", message, exception); + log.info("Consumer details: {}", consumer.groupMetadata()); + log.info("Listener topic: {}", consumer.listTopics()); + return KafkaListenerErrorHandler.super.handleError(message, exception, consumer); + } +} \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/AddSubDeviceHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/AddSubDeviceHandler.java new file mode 100644 index 00000000..5b8e5644 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/AddSubDeviceHandler.java @@ -0,0 +1,118 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.handler; + +import com.alibaba.fastjson.JSON; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.mqttsnet.basic.protocol.factory.ProtocolMessageAdapter; +import com.mqttsnet.basic.protocol.model.EncryptionDetailsDTO; +import com.mqttsnet.basic.protocol.model.ProtocolDataMessageDTO; +import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoAddSubDeviceParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; +import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.Map; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 处理ADD_SUB_DEVICE主题 + * @packagename: com.mqttsnet.thinglinks.mqtt.handler + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-05 22:59 + **/ +@Slf4j +@Service +public class AddSubDeviceHandler extends AbstractMessageHandler implements TopicHandler { + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + public AddSubDeviceHandler(CacheDataHelper cacheDataHelper, + RemoteDeviceService remoteDeviceService, + RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, + ProtocolMessageAdapter protocolMessageAdapter) { + super(cacheDataHelper, remoteDeviceService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + } + + /** + * @param topic the MQTT topic the message was received on. + * @param qos the quality of service level of the message. + * @param body the payload of the message. + */ + @Override + public void handle(String topic, String qos, String body) { + if (!protocolMessageAdapter.validateProtocolData(body)) { + log.warn("The protocol format is incorrect"); + return; + } + // 解析Topic + Map stringStringMap = protocolMessageAdapter.extractVariables(topic); + String version = stringStringMap.get("version"); + String deviceId = stringStringMap.get("deviceId"); + + DeviceCacheVO deviceCacheVO = getDeviceCacheVO(deviceId); + if (deviceCacheVO == null) { + log.warn("Device with ID {} not found.", deviceId); + return; + } + + try { + ProtocolDataMessageDTO protocolDataMessageDTO = protocolMessageAdapter.parseProtocolDataMessage(body); + // 构造 EncryptionDetails 对象 + EncryptionDetailsDTO encryptionDetailsDTO = EncryptionDetailsDTO.builder() + .signKey(deviceCacheVO.getSignKey()) + .encryptKey(deviceCacheVO.getEncryptKey()) + .encryptVector(deviceCacheVO.getEncryptVector()) + .build(); + String dataBody = protocolMessageAdapter.decryptMessage(body, encryptionDetailsDTO); + + // 解析body + TopoAddSubDeviceParam topoAddSubDeviceParam = JSON.toJavaObject(JSON.parseObject(dataBody), TopoAddSubDeviceParam.class); + topoAddSubDeviceParam.setGatewayIdentification(deviceId); + String resultDataBody = processingTopicMessage(topoAddSubDeviceParam); + + // 处理返回结果 + ProtocolDataMessageDTO handleResult = protocolMessageAdapter.buildResponse(protocolDataMessageDTO, resultDataBody, encryptionDetailsDTO); + + // 根据请求主题确定响应主题 + String responseTopic = "/topo/addResponse"; + // 生成响应主题字符串 + String responseTopicStr = generateResponseTopic(version, deviceId, responseTopic); + + // 序列化 handleResult 对象为 JSON 字符串 + String resultData = objectMapper.writeValueAsString(handleResult); + + // 推送消息到 MQTT 通知设备添加子设备成功&失败 + sendMessage(responseTopicStr, qos, resultData, String.valueOf(deviceCacheVO.getAppId())); + } catch (Exception e) { + log.error("Failed to decrypt the message", e); + } + } + + /** + * Processes the message received on the /topo/add Topic for adding a sub-device to a gateway device. + * + * @param topoAddSubDeviceParam The data for adding a sub-device. + * @return The JSON representation of the processing result. + * @throws Exception if there is an issue processing the message. + */ + @Override + protected String processingTopicMessage(Object topoAddSubDeviceParam) throws Exception { + if (!(topoAddSubDeviceParam instanceof TopoAddSubDeviceParam)) { + throw new IllegalArgumentException("Invalid parameter type for adding sub-device"); + } + + TopoAddSubDeviceParam addParam = (TopoAddSubDeviceParam) topoAddSubDeviceParam; + R mqttTopoAddDeviceResultVOR = remoteDeviceService.saveSubDeviceByMqtt(addParam); + + log.info("Processing /topo/add Topic result: {}", JSON.toJSONString(mqttTopoAddDeviceResultVOR)); + return JSON.toJSONString(mqttTopoAddDeviceResultVOR.getData()); + } + + +} \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/CommandResponseHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/CommandResponseHandler.java new file mode 100644 index 00000000..9be09dae --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/CommandResponseHandler.java @@ -0,0 +1,78 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.handler; + +import com.mqttsnet.basic.protocol.factory.ProtocolMessageAdapter; +import com.mqttsnet.basic.protocol.model.EncryptionDetailsDTO; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventCommandService; +import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; +import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Map; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 处理COMMAND_RESPONSE主题 + * @packagename: com.mqttsnet.thinglinks.mqtt.handler + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-05 23:00 + **/ +@Slf4j +@Service +public class CommandResponseHandler extends AbstractMessageHandler implements TopicHandler { + public CommandResponseHandler(CacheDataHelper cacheDataHelper, + DeviceOpenAnyTenantApi deviceOpenAnyTenantApi, + MqttBrokerOpenAnyTenantApi mqttBrokerOpenAnyTenantApi, + ProtocolMessageAdapter protocolMessageAdapter) { + super(cacheDataHelper, deviceOpenAnyTenantApi, mqttBrokerOpenAnyTenantApi, protocolMessageAdapter); + } + + @Autowired + private MqttEventCommandService mqttEventCommandService; + + /** + * Handles MQTT messages, decrypts them, and processes the command. + * + * @param topic The topic the message was published to. + * @param qos The Quality of Service level of the message. + * @param body The raw body of the MQTT message. + */ + @Override + public void handle(String topic, String qos, String body) { + if (!protocolMessageAdapter.validateProtocolData(body)) { + log.warn("The protocol format is incorrect"); + return; + } + + Map variables = protocolMessageAdapter.extractVariables(topic); + String deviceId = variables.get("deviceId"); + + DeviceCacheVO deviceCacheVO = getDeviceCacheVO(deviceId); + if (deviceCacheVO == null) { + log.warn("Device with ID {} not found.", deviceId); + return; + } + + try { + EncryptionDetailsDTO encryptionDetailsDTO = EncryptionDetailsDTO.builder() + .signKey(deviceCacheVO.getSignKey()) + .encryptKey(deviceCacheVO.getEncryptKey()) + .encryptVector(deviceCacheVO.getEncryptVector()) + .build(); + String decryptedBody = protocolMessageAdapter.decryptMessage(body, encryptionDetailsDTO); + mqttEventCommandService.processCommand(deviceCacheVO, decryptedBody); + } catch (Exception e) { + log.error("Failed to decrypt the message", e); + } + } + + + @Override + protected String processingTopicMessage(Object messageParam) throws Exception { + return null; + } + +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DefaultHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DefaultHandler.java new file mode 100644 index 00000000..5164ebca --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DefaultHandler.java @@ -0,0 +1,28 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.handler; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 其他默认Topic处理器 + * @packagename: com.mqttsnet.thinglinks.mqtt.handler + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-05 22:55 + **/ +@Service +@Slf4j +public class DefaultHandler implements TopicHandler { + + /** + * @param topic the MQTT topic the message was received on. + * @param qos the quality of service level of the message. + * @param body the payload of the message. + */ + @Override + public void handle(String topic, String qos, String body) { + // 处理默认情况的逻辑 + log.info("处理默认情况的逻辑,topic:{},qos:{},body:{}", topic, qos, body); + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeleteSubDeviceHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeleteSubDeviceHandler.java new file mode 100644 index 00000000..df94f290 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeleteSubDeviceHandler.java @@ -0,0 +1,110 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.handler; + +import com.alibaba.fastjson.JSON; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.mqttsnet.basic.protocol.factory.ProtocolMessageAdapter; +import com.mqttsnet.basic.protocol.model.EncryptionDetailsDTO; +import com.mqttsnet.basic.protocol.model.ProtocolDataMessageDTO; +import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoDeleteSubDeviceParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; +import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.Map; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 处理DELETE_SUB_DEVICE主题 + * @packagename: com.mqttsnet.thinglinks.mqtt.handler + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-05 22:59 + **/ +@Slf4j +@Service +public class DeleteSubDeviceHandler extends AbstractMessageHandler implements TopicHandler { + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + public DeleteSubDeviceHandler(CacheDataHelper cacheDataHelper, + RemoteDeviceService remoteDeviceService, + RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, + ProtocolMessageAdapter protocolMessageAdapter) { + super(cacheDataHelper, remoteDeviceService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + } + + /** + * @param topic the MQTT topic the message was received on. + * @param qos the quality of service level of the message. + * @param body the payload of the message. + */ + @Override + public void handle(String topic, String qos, String body) { + if (!protocolMessageAdapter.validateProtocolData(body)) { + log.warn("The protocol format is incorrect"); + return; + } + + // Extract variables from the topic + Map stringStringMap = protocolMessageAdapter.extractVariables(topic); + String version = stringStringMap.get("version"); + String deviceId = stringStringMap.get("deviceId"); + + DeviceCacheVO deviceCacheVO = getDeviceCacheVO(deviceId); + if (deviceCacheVO == null) { + return; + } + + try { + ProtocolDataMessageDTO protocolDataMessageDTO = protocolMessageAdapter.parseProtocolDataMessage(body); + // 构造 EncryptionDetails 对象 + EncryptionDetailsDTO encryptionDetailsDTO = EncryptionDetailsDTO.builder() + .signKey(deviceCacheVO.getSignKey()) + .encryptKey(deviceCacheVO.getEncryptKey()) + .encryptVector(deviceCacheVO.getEncryptVector()) + .build(); + String dataBody = protocolMessageAdapter.decryptMessage(body, encryptionDetailsDTO); + + // Parse body + TopoDeleteSubDeviceParam topoDeleteSubDeviceParam = JSON.toJavaObject(JSON.parseObject(dataBody), TopoDeleteSubDeviceParam.class); + topoDeleteSubDeviceParam.setGatewayIdentification(deviceId); + String resultDataBody = processingTopicMessage(topoDeleteSubDeviceParam); + + // Handle result + ProtocolDataMessageDTO handleResult = protocolMessageAdapter.buildResponse(protocolDataMessageDTO, resultDataBody, encryptionDetailsDTO); + + // Determine response topic based on request topic + String responseTopic = "/topo/deleteResponse"; + // Generate response topic string + String responseTopicStr = generateResponseTopic(version, deviceId, responseTopic); + + // 序列化 handleResult 对象为 JSON 字符串 + String resultData = objectMapper.writeValueAsString(handleResult); + + // Push message to MQTT to notify device of successful/failed sub-device deletion + sendMessage(responseTopicStr, qos, resultData, String.valueOf(deviceCacheVO.getAppId())); + } catch (Exception e) { + log.error("Failed to decrypt the message", e); + } + } + + /** + * Process /topo/delete Topic for gateway device to delete sub-device + * + * @param topoDeleteSubDeviceParam delete device data + * @return Processing result json + */ + @Override + protected String processingTopicMessage(Object topoDeleteSubDeviceParam) throws Exception { + R mqttTopoDeleteDeviceResultVOR = remoteDeviceService.deleteSubDeviceByMqtt((TopoDeleteSubDeviceParam) topoDeleteSubDeviceParam); + log.info("processingTopoDeleteTopic Processing result:{}", JSON.toJSONString(mqttTopoDeleteDeviceResultVOR)); + return JSON.toJSONString(mqttTopoDeleteDeviceResultVOR.getData()); + } +} + diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeviceDatasHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeviceDatasHandler.java new file mode 100644 index 00000000..f4739c01 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeviceDatasHandler.java @@ -0,0 +1,326 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.handler; + +import cn.hutool.core.collection.CollUtil; +import com.alibaba.fastjson.JSON; +import com.mqttsnet.basic.protocol.factory.ProtocolMessageAdapter; +import com.mqttsnet.basic.protocol.model.EncryptionDetailsDTO; +import com.mqttsnet.basic.protocol.model.ProtocolDataMessageDTO; +import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; +import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductModelCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoDeviceDataReportParam; +import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 处理DEVICE_DATA主题 + * @packagename: com.mqttsnet.thinglinks.mqtt.handler + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-05 23:00 + **/ +@Slf4j +@Service +public class DeviceDatasHandler extends AbstractMessageHandler implements TopicHandler { + + public DeviceDatasHandler(CacheDataHelper cacheDataHelper, + RemoteDeviceService remoteDeviceService, + RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, + ProtocolMessageAdapter protocolMessageAdapter) { + super(cacheDataHelper, remoteDeviceService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + } + + @Autowired + private TdsApi tdsApi; + + + /** + * @param topic the MQTT topic the message was received on. + * @param qos the quality of service level of the message. + * @param body the payload of the message. + */ + @Override + public void handle(String topic, String qos, String body) { + if (!protocolMessageAdapter.validateProtocolData(body)) { + log.warn("The protocol format is incorrect"); + return; + } + + // Extract variables from the topic + Map stringStringMap = protocolMessageAdapter.extractVariables(topic); + String version = stringStringMap.get("version"); + String deviceId = stringStringMap.get("deviceId"); + + DeviceCacheVO deviceCacheVO = getDeviceCacheVO(deviceId); + if (deviceCacheVO == null) { + return; + } + + try { + ProtocolDataMessageDTO protocolDataMessageDTO = protocolMessageAdapter.parseProtocolDataMessage(body); + // 构造 EncryptionDetails 对象 + EncryptionDetailsDTO encryptionDetailsDTO = EncryptionDetailsDTO.builder() + .signKey(deviceCacheVO.getSignKey()) + .encryptKey(deviceCacheVO.getEncryptKey()) + .encryptVector(deviceCacheVO.getEncryptVector()) + .build(); + String dataBody = protocolMessageAdapter.decryptMessage(body, encryptionDetailsDTO); + + + // Parse body + TopoDeviceDataReportParam deviceDataParam = new TopoDeviceDataReportParam(); + try { + deviceDataParam = JSON.toJavaObject(JSON.parseObject(dataBody), TopoDeviceDataReportParam.class); + } catch (Exception e) { + log.warn("The protocol format is incorrect"); + return; + } + String resultDataBody = processingTopicMessage(deviceDataParam); + + // Handle result + ProtocolDataMessageDTO handleResult = protocolMessageAdapter.buildResponse(protocolDataMessageDTO, resultDataBody, encryptionDetailsDTO); + String resultData = JSON.toJSONString(handleResult); + + // Determine response topic based on request topic + String responseTopic = "/dataResponse"; + // Generate response topic string + String responseTopicStr = generateResponseTopic(version, deviceId, responseTopic); + + // Push message to MQTT to notify device of successful/failed data report + sendMessage(responseTopicStr, qos, resultData, String.valueOf(deviceCacheVO.getAppId())); + } catch (Exception e) { + log.error("Failed to decrypt the message", e); + } + } + + /** + * Process /device/data Topic for device data reporting + * + * @param deviceDataParam device data + * @return Processing result json + */ + @Override + protected String processingTopicMessage(Object deviceDataParam) throws Exception { + log.info("processingDeviceDataTopic Processing result:{}", JSON.toJSONString(deviceDataParam)); + TopoDeviceDataReportParam dataReportParam = BeanPlusUtil.toBeanIgnoreError(deviceDataParam, TopoDeviceDataReportParam.class); + dataReportParam.getDevices().forEach(device -> { + log.info("processingDeviceDataTopic Processing result:{}", JSON.toJSONString(device)); + String deviceId = device.getDeviceId(); + DeviceCacheVO deviceCacheVO = getDeviceCacheVO(deviceId); + if (deviceCacheVO == null) { + log.warn("processingDeviceDataTopic Device not found:{}", deviceId); + return; + } + ProductModelCacheVO productModelCacheVO = getProductModelCacheVO(deviceCacheVO.getProductIdentification()); + if (productModelCacheVO == null) { + log.warn("processingDeviceDataTopic Product Model not found:{}", deviceCacheVO.getProductIdentification()); + return; + } + + Map> dataMap = new HashMap<>(); + + device.getServices().forEach(service -> { + String superTableName = TdsUtils.superTableName(ProductTypeEnum.valueOf(deviceCacheVO.getProductCacheVO().getProductType()).getDesc(), + deviceCacheVO.getProductIdentification(), + service.getServiceCode()); + + String subTableName = TdsUtils.subTableName(superTableName, deviceCacheVO.getDeviceIdentification()); + + List productModelSuperTableCacheVO = + getProductModelSuperTableCacheVO(Optional.ofNullable(deviceCacheVO.getProductIdentification()).orElse(""), + service.getServiceCode(), deviceCacheVO.getDeviceIdentification()); + + //如果是空,需要做设备的初始化动作,并缓存模型表结构 + if (CollUtil.isEmpty(productModelSuperTableCacheVO)) { + R> superTableDescribeVOListR = tdsApi.describeSuperOrSubTable(subTableName); + + List existingFields = Optional.ofNullable(superTableDescribeVOListR.getData()).orElse(Collections.emptyList()); + + if (existingFields.isEmpty()) { + log.info("设备初始化,设备标识:{},服务标识:{}", deviceCacheVO.getDeviceIdentification(), service.getServiceCode()); + TableDTO tableDTO = new TableDTO(); + tableDTO.setSuperTableName(superTableName); + tableDTO.setTableName(subTableName); + List tagsFieldValues = new ArrayList<>(); + Fields fields = new Fields(); + fields.setFieldName(TdsConstants.DEVICE_IDENTIFICATION); + fields.setFieldValue(deviceCacheVO.getDeviceIdentification()); + fields.setDataType(DataTypeEnum.BINARY); + tagsFieldValues.add(fields); + tableDTO.setTagsFieldValues(tagsFieldValues); + R subTable = tdsApi.createSubTable(tableDTO); + if (Boolean.TRUE.equals(subTable.getIsSuccess())) { + log.info("设备初始化,设备标识:{},服务标识:{},初始化成功", deviceCacheVO.getDeviceIdentification(), service.getServiceCode()); + // 查询新的表结构信息存redis + setProductModelSuperTableCacheVO(Optional.ofNullable(deviceCacheVO.getProductIdentification()).orElse(""), + service.getServiceCode(), deviceCacheVO.getDeviceIdentification(), tdsApi.describeSuperOrSubTable(superTableName).getData()); + + } else { + log.warn("设备初始化 ,设备标识:{},服务标识:{},初始化失败", deviceCacheVO.getDeviceIdentification(), service.getServiceCode()); + return; + } + } else { + setProductModelSuperTableCacheVO(Optional.ofNullable(deviceCacheVO.getProductIdentification()).orElse(""), + service.getServiceCode(), deviceCacheVO.getDeviceIdentification(), existingFields); + } + + } + + Long eventTime = Optional.ofNullable(service.getEventTime()) + .map(Object::toString) + .flatMap(s -> { + try { + return Optional.of(Long.parseLong(s)); + } catch (NumberFormatException e) { + return Optional.empty(); + } + }) + .orElse(System.currentTimeMillis()); + List schemaFieldsList = new ArrayList<>(); + List tagsFieldsList = new ArrayList<>(); + + Map data = StringUtils.jsonToMap(service.getData().toString()); + dataMap.put(service.getServiceCode(), data); + + productModelSuperTableCacheVO.forEach(superTableDescribeVO -> { + Fields fields = new Fields(); + fields.setFieldName(superTableDescribeVO.getField()); + DataTypeEnum dataTypeEnum = DataTypeEnum.valueOfByDataType(superTableDescribeVO.getType()); + fields.setDataType(dataTypeEnum); + fields.setSize(superTableDescribeVO.getLength()); + + // 根据字段名称获取data里的数据 + if (CollUtil.isNotEmpty(data) && data.containsKey(superTableDescribeVO.getField())) { + fields.setFieldValue(data.get(superTableDescribeVO.getField())); + } else if (TdsConstants.EVENT_TIME.equals(superTableDescribeVO.getField())) { + // 需要校验下是否为时间戳 + fields.setFieldValue(eventTime); + } else if (TdsConstants.TS.equals(superTableDescribeVO.getField())) { + // 需要校验下是否为时间戳 + fields.setFieldValue(DateUtils.millisecondStampL()); + } + + if (TdsConstants.TAG.equals(superTableDescribeVO.getNote())) { + if (!StringUtils.isEmpty(superTableDescribeVO.getField()) && TdsConstants.DEVICE_IDENTIFICATION.equals(superTableDescribeVO.getField())) { + fields.setFieldValue(deviceCacheVO.getDeviceIdentification()); + } + tagsFieldsList.add(fields); + } else { + schemaFieldsList.add(fields); + } + }); + + + //字段信息对象集合通过stream流过滤掉没有字段值的字段对象 + List schemaFieldsStream = schemaFieldsList.stream().filter(fields -> fields.getFieldValue() != null).collect(Collectors.toList()); + //字段信息对象集合通过stream流过滤掉没有字段值的字段对象 + List tagsFieldsStream = tagsFieldsList.stream().filter(fields -> fields.getFieldValue() != null).collect(Collectors.toList()); + //如果字段值只有第一个字段的时间戳,说明上报的数据没有符合该服务的属性,不做保存操作,跳过该循环,进入下个循环 + if (CollUtil.isEmpty(schemaFieldsStream)) { + return; + } + //设置插入所需参数 + TableDTO tableDTO = new TableDTO(); + tableDTO.setSuperTableName(superTableName); + tableDTO.setTableName(subTableName); + tableDTO.setSchemaFieldValues(schemaFieldsStream); + tableDTO.setTagsFieldValues(tagsFieldsStream); + + R insertedResult = tdsApi.insertTableData(tableDTO); + + if (Boolean.TRUE.equals(insertedResult.getIsSuccess())) { + log.info("insert table data success, tableName:{}", subTableName); + } else { + log.error("insert table data failed, tableName:{}", subTableName); + } + + }); + + ProductResultVO productResultVO = Optional.of(productModelCacheVO) + .map(item -> { + // 直接构建服务结果,如果productModelCacheVO为空,则会返回一个空列表 + List serviceResultVOs = buildServiceResults(dataMap, productModelCacheVO); + // 复制属性并设置服务结果 + ProductResultVO result = BeanPlusUtil.toBeanIgnoreError(productModelCacheVO, ProductResultVO.class); + result.setServices(serviceResultVOs); + return result; + }) + .orElseGet(() -> { + // 只有当deviceCacheVO为null或者没有找到ProductModelCacheVO时,才会返回一个新的ProductResultVO实例 + ProductResultVO emptyResult = new ProductResultVO(); + emptyResult.setServices(Collections.emptyList()); + return emptyResult; + }); + + log.info("productResultVO: {}", JSON.toJSONString(productResultVO)); + setDeviceDataCollectionPoolCacheVO(Optional.ofNullable(deviceCacheVO.getProductIdentification()).orElse(""), + deviceCacheVO.getDeviceIdentification(), productResultVO); + }); + + return JSON.toJSONString(""); + } + + private List buildServiceResults(Map> dataMap, ProductModelCacheVO productModelCacheVO) { + // Check if the productModelCacheVO is null or if getServices() returns null to avoid NullPointerException. + if (productModelCacheVO == null || productModelCacheVO.getServices() == null) { + return Collections.emptyList(); // Return an empty list if there are no services. + } + + // If dataMap is null, replace it with an empty map to avoid NullPointerException when calling get(). + Map> safeDataMap = (dataMap != null) ? dataMap : Collections.emptyMap(); + + return productModelCacheVO.getServices().stream() + .map(productServiceParamVO -> { + // Use the safeDataMap for getting the service data, handle potential null value from the map. + Map serviceData = safeDataMap.getOrDefault(productServiceParamVO.getServiceCode(), Collections.emptyMap()); + + // Build the property results, which also handles nulls inside the method. + List propertyResultVOs = buildPropertyResults(productServiceParamVO, serviceData); + + // Convert the service parameter object into a result object and set the properties. + ProductServiceResultVO serviceResultVO = BeanPlusUtil.toBeanIgnoreError(productServiceParamVO, ProductServiceResultVO.class); + serviceResultVO.setProperties(propertyResultVOs); // This will include the property results, even if empty. + + return serviceResultVO; + }) + .collect(Collectors.toList()); + } + + + private List buildPropertyResults(ProductServiceParamVO productServiceParamVO, Map dataList) { + // Check if the provided dataList is null and return an empty list if so + if (dataList == null) { + return Collections.emptyList(); + } + + // Now proceed as before, since we're sure dataList is not null + return productServiceParamVO.getProperties().stream() + .map(productPropertyParamVO -> { + String propertyCode = productPropertyParamVO.getPropertyCode(); + // Directly check if dataList contains the property code + if (dataList.containsKey(propertyCode)) { + ProductPropertyResultVO propertyResultVO = BeanPlusUtil.toBeanIgnoreError(productPropertyParamVO, ProductPropertyResultVO.class); + propertyResultVO.setPropertyValue(dataList.get(propertyCode)); + return propertyResultVO; + } else { + // If a property is not present, you might choose to skip it or return a default instance + // For example, you can return an instance with null for the property value, or you can simply return null to filter it out later + // This example will skip the missing properties + return null; + } + }) + .filter(Objects::nonNull) // Filter out any nulls if the property code was not present in dataList + .collect(Collectors.toList()); + } + + +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/OtaCommandResponseHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/OtaCommandResponseHandler.java new file mode 100644 index 00000000..67015df9 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/OtaCommandResponseHandler.java @@ -0,0 +1,88 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.handler; + +import com.mqttsnet.basic.protocol.factory.ProtocolMessageAdapter; +import com.mqttsnet.basic.protocol.model.EncryptionDetailsDTO; +import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventOtaCommandResponseService; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; +import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Map; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 处理OTA_COMMAND_RESPONSE主题 + * @packagename: com.mqttsnet.thinglinks.mqtt.handler + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2024-01-15 23:00 + **/ +@Slf4j +@Service +public class OtaCommandResponseHandler extends AbstractMessageHandler implements TopicHandler { + public OtaCommandResponseHandler(CacheDataHelper cacheDataHelper, + RemoteDeviceService remoteDeviceService, + RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, + ProtocolMessageAdapter protocolMessageAdapter) { + super(cacheDataHelper, remoteDeviceService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + } + + @Autowired + private MqttEventOtaCommandResponseService mqttEventOtaCommandResponseService; + + /** + * Handles MQTT messages, decrypts them, and processes the command. + * + * @param topic The topic the message was published to. + * @param qos The Quality of Service level of the message. + * @param body The raw body of the MQTT message. + */ + @Override + public void handle(String topic, String qos, String body) { + if (!protocolMessageAdapter.validateProtocolData(body)) { + log.warn("The protocol format is incorrect"); + return; + } + + Map variables = protocolMessageAdapter.extractVariables(topic); + String deviceId = variables.get("deviceId"); + + DeviceCacheVO deviceCacheVO = getDeviceCacheVO(deviceId); + if (deviceCacheVO == null) { + log.warn("Device with ID {} not found.", deviceId); + return; + } + + try { + EncryptionDetailsDTO encryptionDetailsDTO = EncryptionDetailsDTO.builder() + .signKey(deviceCacheVO.getSignKey()) + .encryptKey(deviceCacheVO.getEncryptKey()) + .encryptVector(deviceCacheVO.getEncryptVector()) + .build(); + String decryptedBody = protocolMessageAdapter.decryptMessage(body, encryptionDetailsDTO); + mqttEventOtaCommandResponseService.saveMqttEventOtaCommandResponse(deviceCacheVO, decryptedBody); + } catch (Exception e) { + log.error("Failed to decrypt the message", e); + } + } + + + /** + * Processes the message and returns the response body. + * + * @param messageParam The message body. + * @return The response body. + * @throws Exception If an error occurs while processing the message. + */ + @Override + protected String processingTopicMessage(Object messageParam) throws Exception { + + return null; + } + +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/QueryDeviceHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/QueryDeviceHandler.java new file mode 100644 index 00000000..a53f457b --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/QueryDeviceHandler.java @@ -0,0 +1,116 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.handler; + +import com.alibaba.fastjson.JSON; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.mqttsnet.basic.protocol.factory.ProtocolMessageAdapter; +import com.mqttsnet.basic.protocol.model.EncryptionDetailsDTO; +import com.mqttsnet.basic.protocol.model.ProtocolDataMessageDTO; +import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoQueryDeviceParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoQueryDeviceResultVO; +import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.Map; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 处理QUERY_DEVICE主题 + * @packagename: com.mqttsnet.thinglinks.mqtt.handler + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2024-01-10 11:59 + **/ +@Slf4j +@Service +public class QueryDeviceHandler extends AbstractMessageHandler implements TopicHandler { + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + public QueryDeviceHandler(CacheDataHelper cacheDataHelper, + RemoteDeviceService remoteDeviceService, + RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, + ProtocolMessageAdapter protocolMessageAdapter) { + super(cacheDataHelper, remoteDeviceService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + } + + /** + * @param topic the MQTT topic the message was received on. + * @param qos the quality of service level of the message. + * @param body the payload of the message. + */ + @Override + public void handle(String topic, String qos, String body) { + if (!protocolMessageAdapter.validateProtocolData(body)) { + log.warn("The protocol format is incorrect"); + return; + } + // 解析Topic + Map stringStringMap = protocolMessageAdapter.extractVariables(topic); + String version = stringStringMap.get("version"); + String deviceId = stringStringMap.get("deviceId"); + + DeviceCacheVO deviceCacheVO = getDeviceCacheVO(deviceId); + if (deviceCacheVO == null) { + return; + } + + try { + ProtocolDataMessageDTO protocolDataMessageDTO = protocolMessageAdapter.parseProtocolDataMessage(body); + // 构造 EncryptionDetails 对象 + EncryptionDetailsDTO encryptionDetailsDTO = EncryptionDetailsDTO.builder() + .signKey(deviceCacheVO.getSignKey()) + .encryptKey(deviceCacheVO.getEncryptKey()) + .encryptVector(deviceCacheVO.getEncryptVector()) + .build(); + String dataBody = protocolMessageAdapter.decryptMessage(body, encryptionDetailsDTO); + + // 解析body + TopoQueryDeviceParam topoQueryDeviceParam = JSON.toJavaObject(JSON.parseObject(dataBody), TopoQueryDeviceParam.class); + String resultDataBody = processingTopicMessage(topoQueryDeviceParam); + + // 处理返回结果 + ProtocolDataMessageDTO handleResult = protocolMessageAdapter.buildResponse(protocolDataMessageDTO, resultDataBody, encryptionDetailsDTO); + + // 根据请求主题确定响应主题 + String responseTopic = "/topo/queryResponse"; + // 生成响应主题字符串 + String responseTopicStr = generateResponseTopic(version, deviceId, responseTopic); + + // 序列化 handleResult 对象为 JSON 字符串 + String resultData = objectMapper.writeValueAsString(handleResult); + + // 推送消息到 MQTT 通知设备添加子设备成功&失败 + sendMessage(responseTopicStr, qos, resultData, String.valueOf(deviceCacheVO.getAppId())); + } catch (Exception e) { + log.error("Failed to decrypt the message", e); + } + } + + /** + * Processes the message received on the /topo/query Topic to query device information. + * + * @param topoQueryDeviceParam The device query parameters. + * @return The JSON representation of the query result. + * @throws Exception if there is an issue processing the message. + */ + @Override + protected String processingTopicMessage(Object topoQueryDeviceParam) throws Exception { + if (!(topoQueryDeviceParam instanceof TopoQueryDeviceParam)) { + throw new IllegalArgumentException("Invalid parameter type for device query"); + } + + TopoQueryDeviceParam queryParam = (TopoQueryDeviceParam) topoQueryDeviceParam; + R topoQueryDeviceResultVOR = remoteDeviceService.queryDeviceByMqtt(queryParam); + + log.info("Processing /topo/query result: {}", JSON.toJSONString(topoQueryDeviceResultVOR)); + return JSON.toJSONString(topoQueryDeviceResultVOR.getData()); + } + + +} \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/SecretKeyHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/SecretKeyHandler.java new file mode 100644 index 00000000..5408ad73 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/SecretKeyHandler.java @@ -0,0 +1,86 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.handler; + +import com.alibaba.fastjson.JSON; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.mqttsnet.basic.protocol.factory.ProtocolMessageAdapter; +import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; +import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.Map; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 处理SECRET_KEY主题 + * @packagename: com.mqttsnet.thinglinks.mqtt.handler + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-05 22:57 + **/ +@Slf4j +@Service +public class SecretKeyHandler extends AbstractMessageHandler implements TopicHandler { + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + public SecretKeyHandler(CacheDataHelper cacheDataHelper, + RemoteDeviceService remoteDeviceService, + RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, + ProtocolMessageAdapter protocolMessageAdapter) { + super(cacheDataHelper, remoteDeviceService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + } + + /** + * @param topic the MQTT topic the message was received on. + * @param qos the quality of service level of the message. + * @param body the payload of the message. + */ + @Override + public void handle(String topic, String qos, String body) { + // Extract variables from the topic + Map stringStringMap = protocolMessageAdapter.extractVariables(topic); + String version = stringStringMap.get("version"); + String deviceId = stringStringMap.get("deviceId"); + + DeviceCacheVO deviceCacheVO = getDeviceCacheVO(deviceId); + if (deviceCacheVO == null) { + return; + } + + try { + // Directly parse the body into SecretKeyParam class + /*SecretKeyParam secretKeyParam = JSON.toJavaObject(JSON.parseObject(body), SecretKeyParam.class); + secretKeyParam.setDeviceIdentification(deviceId); + String resultDataBody = processingTopicMessage(secretKeyParam);*/ + + // Determine response topic based on request topic + String responseTopic = "/secret/keyResponse"; + // Generate response topic string + String responseTopicStr = generateResponseTopic(version, deviceId, responseTopic); + + // Push message to MQTT to notify device of successful/failed secret key retrieval + sendMessage(responseTopicStr, qos, "", String.valueOf(deviceCacheVO.getAppId())); + } catch (Exception e) { + log.error("Failed to parse the message", e); + } + } + + /** + * Process /secret/key Topic for secret key retrieval + * + * @param secretKeyParam secret key data + * @return Processing result json + */ + @Override + protected String processingTopicMessage(Object secretKeyParam) throws Exception { + // Call the API to retrieve the secret key +// R mqttSecretKeyResultVOR = deviceOpenAnyTenantApi.getSecretKeyByMqtt((SecretKeyParam) secretKeyParam); + log.info("processingSecretKeyTopic Processing result:{}", JSON.toJSONString(secretKeyParam)); + return JSON.toJSONString(""); + } +} + diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/TopicHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/TopicHandler.java new file mode 100644 index 00000000..09c460f2 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/TopicHandler.java @@ -0,0 +1,19 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.handler; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: + * @packagename: com.mqttsnet.thinglinks.mqtt.handler + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-05 22:45 + **/ +public interface TopicHandler { + + /** + * @param topic the MQTT topic the message was received on. + * @param qos the quality of service level of the message. + * @param body the payload of the message. + */ + void handle(String topic, String qos, String body); +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/UpdateSubDeviceHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/UpdateSubDeviceHandler.java new file mode 100644 index 00000000..1dd8f0be --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/UpdateSubDeviceHandler.java @@ -0,0 +1,109 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.handler; + +import com.alibaba.fastjson.JSON; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.mqttsnet.basic.protocol.factory.ProtocolMessageAdapter; +import com.mqttsnet.basic.protocol.model.EncryptionDetailsDTO; +import com.mqttsnet.basic.protocol.model.ProtocolDataMessageDTO; +import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoUpdateSubDeviceStatusParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; +import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.Map; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 处理UPDATE_SUB_DEVICE主题 + * @packagename: com.mqttsnet.thinglinks.mqtt.handler + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-05 23:00 + **/ +@Slf4j +@Service +public class UpdateSubDeviceHandler extends AbstractMessageHandler implements TopicHandler { + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + public UpdateSubDeviceHandler(CacheDataHelper cacheDataHelper, + RemoteDeviceService remoteDeviceService, + RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, + ProtocolMessageAdapter protocolMessageAdapter) { + super(cacheDataHelper, remoteDeviceService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + } + + /** + * @param topic the MQTT topic the message was received on. + * @param qos the quality of service level of the message. + * @param body the payload of the message. + */ + @Override + public void handle(String topic, String qos, String body) { + if (!protocolMessageAdapter.validateProtocolData(body)) { + log.warn("The protocol format is incorrect"); + return; + } + + // Extract variables from the topic + Map stringStringMap = protocolMessageAdapter.extractVariables(topic); + String version = stringStringMap.get("version"); + String deviceId = stringStringMap.get("deviceId"); + + DeviceCacheVO deviceCacheVO = getDeviceCacheVO(deviceId); + if (deviceCacheVO == null) { + return; + } + + try { + ProtocolDataMessageDTO protocolDataMessageDTO = protocolMessageAdapter.parseProtocolDataMessage(body); + // 构造 EncryptionDetails 对象 + EncryptionDetailsDTO encryptionDetailsDTO = EncryptionDetailsDTO.builder() + .signKey(deviceCacheVO.getSignKey()) + .encryptKey(deviceCacheVO.getEncryptKey()) + .encryptVector(deviceCacheVO.getEncryptVector()) + .build(); + String dataBody = protocolMessageAdapter.decryptMessage(body, encryptionDetailsDTO); + + // Parse body + TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam = JSON.toJavaObject(JSON.parseObject(dataBody), TopoUpdateSubDeviceStatusParam.class); + topoUpdateSubDeviceStatusParam.setGatewayIdentification(deviceId); + String resultDataBody = processingTopicMessage(topoUpdateSubDeviceStatusParam); + + // Handle result + ProtocolDataMessageDTO handleResult = protocolMessageAdapter.buildResponse(protocolDataMessageDTO, resultDataBody, encryptionDetailsDTO); + + // Determine response topic based on request topic + String responseTopic = "/topo/updateResponse"; + // Generate response topic string + String responseTopicStr = generateResponseTopic(version, deviceId, responseTopic); + + // 序列化 handleResult 对象为 JSON 字符串 + String resultData = objectMapper.writeValueAsString(handleResult); + // Push message to MQTT to notify device of successful/failed sub-device update + sendMessage(responseTopicStr, qos, resultData, String.valueOf(deviceCacheVO.getAppId())); + } catch (Exception e) { + log.error("Failed to decrypt the message", e); + } + } + + /** + * Process /topo/update Topic for gateway device to update sub-device + * + * @param topoUpdateSubDeviceParam update device data + * @return Processing result json + */ + @Override + protected String processingTopicMessage(Object topoUpdateSubDeviceParam) throws Exception { + R topoDeviceOperationResultVOR = + remoteDeviceService.updateSubDeviceConnectStatusByMqtt((TopoUpdateSubDeviceStatusParam) topoUpdateSubDeviceParam); + log.info("processingTopoUpdateTopic Processing result:{}", JSON.toJSONString(topoDeviceOperationResultVOR)); + return JSON.toJSONString(topoDeviceOperationResultVOR.getData()); + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/event/MqttMessageEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/event/MqttMessageEvent.java new file mode 100644 index 00000000..77c5bba0 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/event/MqttMessageEvent.java @@ -0,0 +1,91 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.event; + +import org.springframework.context.ApplicationEvent; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MessageEvent + * @packagename: com.mqttsnet.thinglinks.mqtt.handle.event + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 14:42 + **/ +public class MqttMessageEvent extends ApplicationEvent { + private final String topic; + private final String qos; + private final String message; + private final String time; + + public MqttMessageEvent(Object source, String topic, String qos, String message, String time) { + super(source); + this.topic = topic; + this.qos = qos; + this.message = message; + this.time = time; + } + + public String getTopic() { + return topic; + } + + public String getQos() { + return qos; + } + + public String getMessage() { + return message; + } + + public String getTime() { + return time; + } + + + public class AddSubDeviceEvent extends MqttMessageEvent { + public AddSubDeviceEvent(Object source, String topic, String qos, String body, String time) { + super(source, topic, qos, body, time); + } + } + + public class AddSubDeviceResponseEvent extends MqttMessageEvent { + public AddSubDeviceResponseEvent(Object source, String topic, String qos, String body, String time) { + super(source, topic, qos, body, time); + } + } + + public class DeviceStatusEvent extends MqttMessageEvent { + public DeviceStatusEvent(Object source, String topic, String qos, String body, String time) { + super(source, topic, qos, body, time); + } + } + + public class DeviceStatusResponseEvent extends MqttMessageEvent { + public DeviceStatusResponseEvent(Object source, String topic, String qos, String body, String time) { + super(source, topic, qos, body, time); + } + } + + public class DeviceControlEvent extends MqttMessageEvent { + public DeviceControlEvent(Object source, String topic, String qos, String body, String time) { + super(source, topic, qos, body, time); + } + } + + public class DeviceControlResponseEvent extends MqttMessageEvent { + public DeviceControlResponseEvent(Object source, String topic, String qos, String body, String time) { + super(source, topic, qos, body, time); + } + } + + public class DeviceDataReportEvent extends MqttMessageEvent { + public DeviceDataReportEvent(Object source, String topic, String qos, String body, String time) { + super(source, topic, qos, body, time); + } + } + + public class DeviceDataReportResponseEvent extends MqttMessageEvent { + public DeviceDataReportResponseEvent(Object source, String topic, String qos, String body, String time) { + super(source, topic, qos, body, time); + } + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/AbstractMessageHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/AbstractMessageHandler.java new file mode 100644 index 00000000..51fab2bb --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/AbstractMessageHandler.java @@ -0,0 +1,85 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory; + + +import com.mqttsnet.basic.protocol.factory.ProtocolMessageAdapter; +import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; +import com.mqttsnet.thinglinks.broker.api.domain.vo.PublishMessageRequestVO; +import com.mqttsnet.thinglinks.common.core.utils.SnowflakeIdUtil; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductModelCacheVO; +import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; +import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDescribeVO; +import lombok.extern.slf4j.Slf4j; + +import java.util.List; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 通用逻辑处理器 + * @packagename: com.mqttsnet.thinglinks.mqtt.handler + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-30 15:07 + **/ +@Slf4j +public abstract class AbstractMessageHandler { + + protected final CacheDataHelper cacheDataHelper; + protected final RemoteDeviceService remoteDeviceService; + protected final RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi; + protected final ProtocolMessageAdapter protocolMessageAdapter; + + public AbstractMessageHandler(CacheDataHelper cacheDataHelper, + RemoteDeviceService remoteDeviceService, + RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, + ProtocolMessageAdapter protocolMessageAdapter) { + this.cacheDataHelper = cacheDataHelper; + this.remoteDeviceService = remoteDeviceService; + this.remoteMqttBrokerOpenApi = remoteMqttBrokerOpenApi; + this.protocolMessageAdapter = protocolMessageAdapter; + } + + protected DeviceCacheVO getDeviceCacheVO(String deviceIdentification) { + return cacheDataHelper.getDeviceCacheVO(deviceIdentification); + } + + protected ProductModelCacheVO getProductModelCacheVO(String productIdentification) { + return cacheDataHelper.getProductModelCacheVO(productIdentification); + } + + protected List getProductModelSuperTableCacheVO(String productIdentification, String serviceCode, String deviceIdentification) { + return cacheDataHelper.getProductModelSuperTableCacheVO(productIdentification, serviceCode, deviceIdentification); + } + + protected void setProductModelSuperTableCacheVO(String productIdentification, String serviceCode, String deviceIdentification, + List superTableDescribeOpt) { + cacheDataHelper.setProductModelSuperTableCacheVO(productIdentification, serviceCode, deviceIdentification, superTableDescribeOpt); + } + + protected void sendMessage(String topic, String qos, String message, String tenantId) { + PublishMessageRequestVO publishMessageRequestVO = new PublishMessageRequestVO(); + publishMessageRequestVO.setReqId(Long.valueOf(SnowflakeIdUtil.nextId())); + publishMessageRequestVO.setTenantId(tenantId); + publishMessageRequestVO.setTopic(topic); + publishMessageRequestVO.setPubQos(qos); + publishMessageRequestVO.setClientType("web"); + publishMessageRequestVO.setPayload(message); + publishMessageRequestVO.setRetain("false"); + remoteMqttBrokerOpenApi.sendMessage(publishMessageRequestVO); + } + + /** + * 生成响应主题字符串 + * + * @param version 版本号 + * @param deviceId 设备ID + * @param responseTopic 响应主题 + * @return 完整的响应主题字符串 + */ + protected String generateResponseTopic(String version, String deviceId, String responseTopic) { + return String.format("/%s/devices/%s%s", version, deviceId, responseTopic); + } + + protected abstract String processingTopicMessage(Object messageParam) throws Exception; +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/TopicHandlerFactory.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/TopicHandlerFactory.java new file mode 100644 index 00000000..a5fc13c4 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/TopicHandlerFactory.java @@ -0,0 +1,106 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory; + + +import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.*; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MQTT系统Topic 处理工厂类 + * @packagename: com.mqttsnet.thinglinks.handler.factory + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-05 22:00 + **/ +@Component +public class TopicHandlerFactory { + + private final DefaultHandler defaultHandler; + private final SecretKeyHandler secretKeyHandler; + private final AddSubDeviceHandler addSubDeviceHandler; + private final DeleteSubDeviceHandler deleteSubDeviceHandler; + private final UpdateSubDeviceHandler updateSubDeviceHandler; + private final QueryDeviceHandler queryDeviceHandler; + private final DeviceDatasHandler deviceDatasHandler; + private final CommandResponseHandler commandResponseHandler; + + private final OtaCommandResponseHandler otaCommandResponseHandler; + + // Define patterns as constants + private static final Pattern DEFAULT_PATTERN = Pattern.compile(""); + private static final Pattern SECRET_KEY_PATTERN = Pattern.compile("/([^/]+)/devices/([^/]+)/topo/secretKey"); + private static final Pattern ADD_SUB_DEVICE_PATTERN = Pattern.compile("/([^/]+)/devices/([^/]+)/topo/add"); + private static final Pattern DELETE_SUB_DEVICE_PATTERN = Pattern.compile("/([^/]+)/devices/([^/]+)/topo/delete"); + private static final Pattern UPDATE_SUB_DEVICE_PATTERN = Pattern.compile("/([^/]+)/devices/([^/]+)/topo/update"); + private static final Pattern QUERY_DEVICE_PATTERN = Pattern.compile("/([^/]+)/devices/([^/]+)/topo/query"); + private static final Pattern DEVICE_DATAS_PATTERN = Pattern.compile("/([^/]+)/devices/([^/]+)/datas"); + private static final Pattern COMMAND_RESPONSE_PATTERN = Pattern.compile("/([^/]+)/devices/([^/]+)/commandResponse"); + private static final Pattern OTA_COMMAND_RESPONSE_PATTERN = Pattern.compile("/([^/]+)/devices/([^/]+)/otaCommandResponse"); + + public TopicHandlerFactory(DefaultHandler defaultHandler, SecretKeyHandler secretKeyHandler, + AddSubDeviceHandler addSubDeviceHandler, DeleteSubDeviceHandler deleteSubDeviceHandler, + UpdateSubDeviceHandler updateSubDeviceHandler, QueryDeviceHandler queryDeviceHandler, DeviceDatasHandler deviceDatasHandler, + CommandResponseHandler commandResponseHandler, OtaCommandResponseHandler otaCommandResponseHandler) { + this.defaultHandler = defaultHandler; + this.secretKeyHandler = secretKeyHandler; + this.addSubDeviceHandler = addSubDeviceHandler; + this.deleteSubDeviceHandler = deleteSubDeviceHandler; + this.updateSubDeviceHandler = updateSubDeviceHandler; + this.queryDeviceHandler = queryDeviceHandler; + this.deviceDatasHandler = deviceDatasHandler; + this.commandResponseHandler = commandResponseHandler; + this.otaCommandResponseHandler = otaCommandResponseHandler; + } + + private static final class TopicHandlerEntry { + private final Pattern pattern; + private final TopicHandler handler; + + public TopicHandlerEntry(Pattern pattern, TopicHandler handler) { + this.pattern = pattern; + this.handler = handler; + } + + public Pattern getPattern() { + return pattern; + } + + public TopicHandler getHandler() { + return handler; + } + } + + private List topicHandlerEntries; + + // Use the @PostConstruct annotation to initialize the handler entries list after the dependencies are injected. + @PostConstruct + public void initTopicHandlerEntries() { + topicHandlerEntries = new ArrayList<>(); + topicHandlerEntries.add(new TopicHandlerEntry(DEFAULT_PATTERN, defaultHandler)); + topicHandlerEntries.add(new TopicHandlerEntry(SECRET_KEY_PATTERN, secretKeyHandler)); + topicHandlerEntries.add(new TopicHandlerEntry(ADD_SUB_DEVICE_PATTERN, addSubDeviceHandler)); + topicHandlerEntries.add(new TopicHandlerEntry(DELETE_SUB_DEVICE_PATTERN, deleteSubDeviceHandler)); + topicHandlerEntries.add(new TopicHandlerEntry(UPDATE_SUB_DEVICE_PATTERN, updateSubDeviceHandler)); + topicHandlerEntries.add(new TopicHandlerEntry(QUERY_DEVICE_PATTERN, queryDeviceHandler)); + topicHandlerEntries.add(new TopicHandlerEntry(DEVICE_DATAS_PATTERN, deviceDatasHandler)); + topicHandlerEntries.add(new TopicHandlerEntry(COMMAND_RESPONSE_PATTERN, commandResponseHandler)); + topicHandlerEntries.add(new TopicHandlerEntry(OTA_COMMAND_RESPONSE_PATTERN, otaCommandResponseHandler)); + } + + // This method searches for a matching handler based on the topic. + public TopicHandler findMatchingHandler(String topic) { + for (TopicHandlerEntry handlerEntry : topicHandlerEntries) { + Matcher matcher = handlerEntry.getPattern().matcher(topic); + if (matcher.matches()) { + return handlerEntry.getHandler(); + } + } + return defaultHandler; + } +} \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/listener/MqttMessageListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/listener/MqttMessageListener.java new file mode 100644 index 00000000..47a03a38 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/listener/MqttMessageListener.java @@ -0,0 +1,48 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.listener; + +import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.TopicHandler; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.event.MqttMessageEvent; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.TopicHandlerFactory; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: + * @packagename: com.mqttsnet.thinglinks.mqtt.handle.listener + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 14:43 + **/ +@Component +@Slf4j +public class MqttMessageListener { + + private final TopicHandlerFactory topicHandlerFactory; + + @Autowired + public MqttMessageListener(TopicHandlerFactory topicHandlerFactory) { + this.topicHandlerFactory = topicHandlerFactory; + } + + @EventListener + public void handleMessage(MqttMessageEvent event) { + // 校验并处理Topic + processTopic(event.getTopic(), event.getQos(), event.getMessage()); + } + + private void processTopic(String topic, String qos, String body) { + // Using the TopicHandlerFactory to find the matching handler + TopicHandler matchingHandler = topicHandlerFactory.findMatchingHandler(topic); + + if (matchingHandler != null) { + matchingHandler.handle(topic, qos, body); + } else { + // Handle the case when no topic matches + log.warn("No topic handler found for topic: {}", topic); + } + } +} \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventActionService.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventActionService.java new file mode 100644 index 00000000..00073186 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventActionService.java @@ -0,0 +1,60 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.service; + +import com.google.gson.Gson; +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.common.core.enums.ResultEnum; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceActionService; +import com.mqttsnet.thinglinks.link.api.domain.device.entity.DeviceAction; +import com.mqttsnet.thinglinks.link.api.domain.device.enumeration.DeviceActionTypeEnum; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.Map; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MqttEventActionHandler + * @packagename: com.mqttsnet.thinglinks.mqtt.handler + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-08-20 16:09 + **/ +@Slf4j +@Service +@RequiredArgsConstructor +public class MqttEventActionService { + + @Resource + private RemoteDeviceActionService remoteDeviceActionService; + + /** + * 保存MQTT事件动作 + * + * @param eventMessage 事件消息 + * @param actionType 动作类型 + * @param describable 描述 + */ + public void saveMqttEventAction(String eventMessage, DeviceActionTypeEnum actionType, String describable) { + Gson gson = new Gson(); + Map map = new HashMap<>(); + map = gson.fromJson(eventMessage, map.getClass()); + String clientId = String.valueOf(map.get("clientId")); + + // save device action + DeviceAction deviceAction = new DeviceAction() + .setDeviceIdentification(clientId) + .setActionType(actionType.getAction()) + .setStatus(ResultEnum.SUCCESS.getMessage()) + .setMessage(describable); + + R deviceActionR = remoteDeviceActionService.add(deviceAction); + if (ResultEnum.SUCCESS.getCode() != deviceActionR.getCode()) { + log.info("Save device action success: deviceAction={}", deviceActionR.getData()); + } else { + log.error("Save device action failed: deviceAction={}", deviceActionR.getData()); + } + } +} \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventCommandService.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventCommandService.java new file mode 100644 index 00000000..21e2a06d --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventCommandService.java @@ -0,0 +1,62 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.service; + +import com.alibaba.fastjson.JSON; +import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MqttEventCommandService + * @packagename: com.mqttsnet.thinglinks.mqtt.handler + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-11-12 16:09 + **/ +@Slf4j +@Service +@RequiredArgsConstructor +public class MqttEventCommandService { + + private final DeviceCommandApi deviceCommandApi; + + /** + * Processes the received message, converts it to a DeviceCommandSaveVO, and saves the command. + * + * @param deviceCacheVO The cached device information. + * @param dataBody The body of the MQTT message. + * @return A JSON string representing the saved device command. + */ + public String processCommand(DeviceCacheVO deviceCacheVO, String dataBody) { + DeviceCommandSaveVO saveVO = convertToSaveVO(deviceCacheVO, dataBody); + R response = deviceCommandApi.saveDeviceCommand(saveVO); + + if (Boolean.FALSE.equals(response.getIsSuccess())) { + log.error("Failed to process device command: {}", JSON.toJSONString(response)); + throw new IllegalStateException("Failed to save device command"); + } + + log.info("Device command processed and saved: {}", JSON.toJSONString(response.getData())); + return JSON.toJSONString(response.getData()); + } + + /** + * Converts the received message body to a DeviceCommandSaveVO object. + * + * @param deviceCacheVO The cached device information. + * @param dataBody The body of the MQTT message. + * @return The DeviceCommandSaveVO object. + */ + private DeviceCommandSaveVO convertToSaveVO(DeviceCacheVO deviceCacheVO, String dataBody) { + // Your conversion logic here + // For now, creating a new object with some default values + DeviceCommandSaveVO saveVO = new DeviceCommandSaveVO(); + saveVO.setDeviceIdentification(deviceCacheVO.getDeviceIdentification()); + saveVO.setCommandType(DeviceCommandTypeEnum.COMMAND_RESPONSE.getValue()); + saveVO.setStatus(DeviceCommandStatusEnum.SUCCESS.getValue()); + saveVO.setContent(dataBody); + saveVO.setRemark("Processed command response"); + return saveVO; + } +} \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventOtaCommandResponseService.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventOtaCommandResponseService.java new file mode 100644 index 00000000..052e8083 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventOtaCommandResponseService.java @@ -0,0 +1,75 @@ +package com.mqttsnet.thinglinks.broker.mqs.mqtt.service; + +import com.alibaba.fastjson.JSON; +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.OtaCommandResponseParam; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * ----------------------------------------------------------------------------- + * File Name: MqttEventOtaCommandResponseService + * ----------------------------------------------------------------------------- + * Description: + * OTA 远程升级 mqtt事件业务层 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/1/18 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/1/18 22:38 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class MqttEventOtaCommandResponseService { + + @Autowired + private RemoteDeviceService remoteDeviceService; + + + /** + * Saves the OTA command response from MQTT events. + * + * @param deviceCacheVO Device cache information for the device receiving the OTA command. + * @param dataBody The message body containing the OTA command response. + */ + public void saveMqttEventOtaCommandResponse(DeviceCacheVO deviceCacheVO, String dataBody) { + try { + // Convert the JSON data body to an OtaCommandResponseParam object + OtaCommandResponseParam otaCommandResponseParam = JSON.parseObject(dataBody, OtaCommandResponseParam.class); + + // Assuming a method that handles the actual saving of the response + saveOtaCommandResponse(otaCommandResponseParam); + + // Log the successfully saved command response + log.info("OTA command response successfully saved: {}", JSON.toJSONString(otaCommandResponseParam)); + + } catch (Exception e) { + // Log the error along with the stack trace for debugging + log.error("Failed to process OTA command response: {}", dataBody, e); + + // Re-throw the exception to maintain the flow (can be customized as needed) + throw new IllegalStateException("Failed to save OTA command response", e); + } + } + + // This is a placeholder for the actual saving logic + private void saveOtaCommandResponse(OtaCommandResponseParam responseParam) { + // Implementation for saving the response in your system + R otaCommandResponseParamR = remoteDeviceService.saveUpgradeRecordByMqtt(responseParam); + log.info("otaCommandResponseParamR:{}", JSON.toJSONString(otaCommandResponseParamR)); + } + + +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/service/MqttBrokerService.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/service/MqttBrokerService.java index 1f15eae9..edee825b 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/service/MqttBrokerService.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/service/MqttBrokerService.java @@ -1,6 +1,6 @@ package com.mqttsnet.thinglinks.broker.service; -import com.mqttsnet.thinglinks.broker.api.domain.model.PublishMessageRequest; +import com.mqttsnet.thinglinks.broker.api.domain.vo.PublishMessageRequestVO; import com.mqttsnet.thinglinks.common.core.exception.base.BaseException; /** @@ -28,9 +28,9 @@ public interface MqttBrokerService { /** * Publishes a message to a specified topic and returns the content if successful. * - * @param publishMessageRequest Object containing the required parameters for publishing. + * @param publishMessageRequestVO Object containing the required parameters for publishing. * @return The content of the published message. * @throws BaseException If the publishing fails. */ - String publishMessage(PublishMessageRequest publishMessageRequest); + String publishMessage(PublishMessageRequestVO publishMessageRequestVO); } diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/service/impl/MqttBrokerServiceImpl.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/service/impl/MqttBrokerServiceImpl.java index 391b6442..bc9d4f91 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/service/impl/MqttBrokerServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/service/impl/MqttBrokerServiceImpl.java @@ -1,7 +1,7 @@ package com.mqttsnet.thinglinks.broker.service.impl; import com.mqttsnet.thinglinks.broker.api.BifroMQApi; -import com.mqttsnet.thinglinks.broker.api.domain.model.PublishMessageRequest; +import com.mqttsnet.thinglinks.broker.api.domain.vo.PublishMessageRequestVO; import com.mqttsnet.thinglinks.broker.service.MqttBrokerService; import com.mqttsnet.thinglinks.common.core.exception.base.BaseException; import lombok.RequiredArgsConstructor; @@ -39,23 +39,23 @@ public class MqttBrokerServiceImpl implements MqttBrokerService { /** * Publishes a message to a specified topic and returns the content if successful. * - * @param publishMessageRequest Object containing the required parameters for publishing. + * @param publishMessageRequestVO Object containing the required parameters for publishing. * @return The content of the published message. * @throws BaseException If the publishing fails. */ @Override - public String publishMessage(PublishMessageRequest publishMessageRequest) throws BaseException { - log.info("Preparing to publish message with topic: {}", publishMessageRequest.getTopic()); + public String publishMessage(PublishMessageRequestVO publishMessageRequestVO) throws BaseException { + log.info("Preparing to publish message with topic: {}", publishMessageRequestVO.getTopic()); try { - ResponseEntity response = callPublishApi(publishMessageRequest); + ResponseEntity response = callPublishApi(publishMessageRequestVO); if (response.getStatusCode().is2xxSuccessful()) { - log.info("Successfully published message with topic: {}", publishMessageRequest.getTopic()); - return publishMessageRequest.getPayload(); // Return the message content that was published + log.info("Successfully published message with topic: {}", publishMessageRequestVO.getTopic()); + return publishMessageRequestVO.getPayload(); // Return the message content that was published } else { log.error("Failed to publish message with topic: {}. Response Status: {}", - publishMessageRequest.getTopic(), response.getStatusCode()); - throw new BaseException("Failed to publish message with topic: " + publishMessageRequest.getTopic()); + publishMessageRequestVO.getTopic(), response.getStatusCode()); + throw new BaseException("Failed to publish message with topic: " + publishMessageRequestVO.getTopic()); } } catch (HttpClientErrorException e) { log.error("HTTP error occurred while publishing message: {}", e.getMessage()); @@ -70,19 +70,19 @@ public String publishMessage(PublishMessageRequest publishMessageRequest) throws /** * Makes the actual API call to publish a message. * - * @param publishMessageRequest Object containing the required parameters for publishing. + * @param publishMessageRequestVO Object containing the required parameters for publishing. * @return R Response indicating success or failure from the BifroMQApi. */ - private ResponseEntity callPublishApi(PublishMessageRequest publishMessageRequest) { + private ResponseEntity callPublishApi(PublishMessageRequestVO publishMessageRequestVO) { return bifroMQApi.publishMessage( - publishMessageRequest.getReqId(), - publishMessageRequest.getTenantId(), - publishMessageRequest.getTopic(), - publishMessageRequest.getClientType(), - publishMessageRequest.getPubQos(), - publishMessageRequest.getRetain(), - publishMessageRequest.getClientMeta(), - publishMessageRequest.getPayload() + publishMessageRequestVO.getReqId(), + publishMessageRequestVO.getTenantId(), + publishMessageRequestVO.getTopic(), + publishMessageRequestVO.getClientType(), + publishMessageRequestVO.getPubQos(), + publishMessageRequestVO.getRetain(), + publishMessageRequestVO.getClientMeta(), + publishMessageRequestVO.getPayload() ); } } diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/resources/bootstrap.yml b/thinglinks-modules/thinglinks-modules-broker/src/main/resources/bootstrap.yml index 1c22968f..52a6e1d4 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/resources/bootstrap.yml +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/resources/bootstrap.yml @@ -33,5 +33,7 @@ spring: refresh: false - dataId: database.yml refresh: true + - dataId: kafka.yml + refresh: false username: @nacos.username@ password: @nacos.password@ \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-link/pom.xml b/thinglinks-modules/thinglinks-modules-link/pom.xml index 71f7f6bd..ade47d50 100644 --- a/thinglinks-modules/thinglinks-modules-link/pom.xml +++ b/thinglinks-modules/thinglinks-modules-link/pom.xml @@ -73,13 +73,6 @@ ${thinglinks.version} - - - com.mqttsnet - thinglinks-common-rocketmq - ${thinglinks.version} - - com.mqttsnet diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/asyncthread/LinkAsyncConfig.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/asyncthread/LinkAsyncConfig.java index b35d2638..1594caa1 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/asyncthread/LinkAsyncConfig.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/asyncthread/LinkAsyncConfig.java @@ -52,7 +52,7 @@ public class LinkAsyncConfig { * link服务全局共享异步线程池 */ @Bean("linkAsync") - public Executor tdengineAsync() { + public Executor linkAsync() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize);//核心线程数 executor.setMaxPoolSize(maxPoolSize);//最大线程数 cpu核数/(1-0.8)//cup核数*2//cup核数+1 @@ -73,7 +73,7 @@ public Executor tdengineAsync() { * MQTT设备消息消费异步线程池配置 */ @Bean("linkAsync-mqttMsg") - public Executor linkAsync() { + public Executor linkAsyncMqttMsg() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize);//核心线程数 executor.setMaxPoolSize(maxPoolSize);//最大线程数 cpu核数/(1-0.8)//cup核数*2//cup核数+1 diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/CacheSuperAbstract.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/CacheSuperAbstract.java new file mode 100644 index 00000000..4c37a80c --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/CacheSuperAbstract.java @@ -0,0 +1,11 @@ +package com.mqttsnet.thinglinks.link.common.cache; + +/** + * 缓存抽象类,提供共用方法 + */ +public abstract class CacheSuperAbstract { + + public static int PAGE_SIZE = 5000; + + +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/helper/CacheDataHelper.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/helper/CacheDataHelper.java new file mode 100644 index 00000000..1cafe62f --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/helper/CacheDataHelper.java @@ -0,0 +1,112 @@ +package com.mqttsnet.thinglinks.link.common.cache.helper; + +import com.mqttsnet.thinglinks.common.core.constant.CacheConstants; +import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; +import com.mqttsnet.thinglinks.common.redis.service.RedisService; +import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductModelCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; +import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDescribeVO; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +/** + * ----------------------------------------------------------------------------- + * 文件名称: CacheDataHelper.java + * ----------------------------------------------------------------------------- + * 描述: + * CacheDataHelper + * ----------------------------------------------------------------------------- + * + * @author ShiHuan Sun + * @version 1.0 + * ----------------------------------------------------------------------------- + * 修改历史: + * 日期 作者 版本 描述 + * -------- -------- ------- -------------------- + *

+ * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2023-10-12 22:26 + */ +@Component +@Slf4j +public class CacheDataHelper { + + private final RedisService redisService; + + public CacheDataHelper(RedisService redisService) { + this.redisService = redisService; + } + + public DeviceCacheVO getDeviceCacheVO(String deviceIdentification) { + if (deviceIdentification == null) { + log.warn("Device identification is null"); + return null; + } + Device deviceCacheObject = redisService.getCacheObject(CacheConstants.DEVICE_RECORD_KEY + deviceIdentification); + return BeanPlusUtil.toBeanIgnoreError(deviceCacheObject, DeviceCacheVO.class); + } + + public ProductModelCacheVO getProductModelCacheVO(String productIdentification) { + if (productIdentification == null) { + log.warn("Product identification is null"); + return null; + } + + ProductModelCacheVO objectCacheResult = redisService.getCacheObject(CacheConstants.DEVICE_RECORD_KEY + productIdentification); + return BeanPlusUtil.toBeanIgnoreError(objectCacheResult, ProductModelCacheVO.class); + } + + public List getProductModelSuperTableCacheVO(String productIdentification, String serviceCode, String deviceIdentification) { + // 构造缓存键 + String cacheKey = CacheConstants.PRODUCT_MODEL_SUPER_TABLE + productIdentification + ":" + serviceCode + ":" + deviceIdentification; + + // 尝试从缓存获取数据 + List cacheList; + try { + cacheList = redisService.getCacheList(cacheKey); + } catch (Exception e) { + log.error("Error fetching from cache for key: {}", cacheKey, e); + return Collections.emptyList(); + } + + // 检查缓存结果是否为空 + if (cacheList == null || cacheList.isEmpty()) { + log.warn("The product model super table is not in the cache for key: {}", cacheKey); + return Collections.emptyList(); + } + + // 尝试将缓存结果转换为预期类型的列表 + try { + // 这里假设所有缓存的对象都已经是SuperTableDescribeVO类型的实例 + // 为了安全起见,我们进行一次类型检查 + @SuppressWarnings("unchecked") + List result = (List) cacheList.stream() + .filter(SuperTableDescribeVO.class::isInstance) + .map(SuperTableDescribeVO.class::cast) + .collect(Collectors.toList()); + + if (result.isEmpty()) { + log.warn("The product model super table cache list is empty for key: {}", cacheKey); + } + return result; + } catch (ClassCastException e) { + log.error("Unexpected type in cached list for key: {}", cacheKey, e); + return Collections.emptyList(); + } + } + + + public void setProductModelSuperTableCacheVO(String productIdentification, String serviceCode, String deviceIdentification, + List superTableDescribeOpt) { + String cacheKey = CacheConstants.PRODUCT_MODEL_SUPER_TABLE + productIdentification + ":" + serviceCode + ":" + deviceIdentification; + redisService.delete(cacheKey); + redisService.setCacheObject(cacheKey, superTableDescribeOpt); + } + +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java new file mode 100644 index 00000000..1571484e --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java @@ -0,0 +1,133 @@ +package com.mqttsnet.thinglinks.link.common.cache.service; + +import cn.hutool.core.bean.BeanUtil; +import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; +import com.mqttsnet.thinglinks.common.redis.service.RedisService; +import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; +import com.mqttsnet.thinglinks.link.common.cache.CacheSuperAbstract; +import com.mqttsnet.thinglinks.link.service.device.DeviceService; +import com.mqttsnet.thinglinks.link.service.product.ProductService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +/** + * ----------------------------------------------------------------------------- + * File Name: DeviceCacheService.java + * ----------------------------------------------------------------------------- + * Description: + * Service layer for Device cache management. + * ----------------------------------------------------------------------------- + * + * @author ShiHuan Sun + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + *

+ * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2023-10-21 22:42 + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class DeviceCacheService extends CacheSuperAbstract { + private final RedisService redisService; + private final DeviceService deviceService; + private final ProductService productService; + + /** + * Refresh the cache with device data for a specific tenant. + * + * @param tenantId Identifier of the tenant whose device cache needs to be refreshed. + */ + public void refreshDeviceCacheForTenant(Long tenantId) { + int totalDataCount = deviceService.findDeviceTotal().intValue(); + int totalPages = (int) Math.ceil((double) totalDataCount / PAGE_SIZE); + + List deviceList = IntStream.range(0, totalPages) + .mapToObj(currentPage -> { + Page page = new Page<>(currentPage, PAGE_SIZE); + Page content = deviceService.page(page, null); + return Optional.ofNullable(content) + .map(Page::getRecords) + .orElse(Collections.emptyList()); + }) + .flatMap(Collection::stream) + .collect(Collectors.toList()); + + cacheDevicesForTenant(tenantId, deviceList); + } + + /** + * Cache a list of devices for a specific tenant. + * + * @param tenantId Identifier of the tenant. + * @param deviceList List of devices to be cached. + */ + public void cacheDevicesForTenant(Long tenantId, List deviceList) { + Optional.ofNullable(deviceList) + .orElse(Collections.emptyList()) + .stream() + .filter(Objects::nonNull) + .map(device -> transformToDeviceCacheVO(tenantId, device)) + .filter(Objects::nonNull) + .forEach(deviceCacheVO -> { + cacheDeviceBasedOnIdentification(deviceCacheVO); + cacheDeviceBasedOnClientId(deviceCacheVO); + }); + } + + /** + * Transforms a device object into a DeviceCacheVO object with associated product data. + * + * @param tenantId Identifier of the tenant. + * @param device Device object to be transformed. + * @return Transformed DeviceCacheVO object. + */ + private DeviceCacheVO transformToDeviceCacheVO(Long tenantId, Device device) { + DeviceCacheVO deviceCacheVO = BeanUtil.toBeanIgnoreError(device, DeviceCacheVO.class); + deviceCacheVO.setTenantId(tenantId); + + Optional.ofNullable(deviceCacheVO.getProductIdentification()) + .map(productService::selectProductByProductIdentificationList) + .ifPresent(product -> { + ProductCacheVO productCacheVO = BeanPlusUtil.toBeanIgnoreError(product, ProductCacheVO.class); + productCacheVO.setTenantId(tenantId); + deviceCacheVO.setProductCacheVO(productCacheVO); + }); + + return deviceCacheVO; + } + + /** + * Cache the DeviceCacheVO object based on its identification. + * + * @param deviceCacheVO DeviceCacheVO object to be cached. + */ + private void cacheDeviceBasedOnIdentification(DeviceCacheVO deviceCacheVO) { + CacheKey deviceIdentKey = DeviceCacheKeyBuilder.build(deviceCacheVO.getDeviceIdentification()); + cachePlusOps.del(deviceIdentKey); + cachePlusOps.set(deviceIdentKey, deviceCacheVO); + } + + /** + * Cache the DeviceCacheVO object based on its client ID. + * + * @param deviceCacheVO DeviceCacheVO object to be cached. + */ + private void cacheDeviceBasedOnClientId(DeviceCacheVO deviceCacheVO) { + CacheKey clientIdKey = DeviceCacheKeyBuilder.build(deviceCacheVO.getClientId()); + cachePlusOps.del(clientIdKey); + cachePlusOps.set(clientIdKey, deviceCacheVO); + } + +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/kafka/DeviceActionMessageKafkaConsumer.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/kafka/DeviceActionMessageKafkaConsumer.java index 6e573661..5b09dc6e 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/kafka/DeviceActionMessageKafkaConsumer.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/kafka/DeviceActionMessageKafkaConsumer.java @@ -3,7 +3,7 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.mqttsnet.thinglinks.common.core.enums.MqttEvent; -import com.mqttsnet.thinglinks.common.kafka.constant.ConsumerTopicConstant; +import com.mqttsnet.thinglinks.common.kafka.constant.ConsumerKafkaTopicConstant; import com.mqttsnet.thinglinks.link.service.device.DeviceActionService; import com.mqttsnet.thinglinks.link.service.device.DeviceDatasService; import lombok.extern.slf4j.Slf4j; @@ -27,6 +27,7 @@ */ @Slf4j //@Component +@Deprecated public class DeviceActionMessageKafkaConsumer { @Autowired private DeviceActionService deviceActionService; @@ -35,15 +36,15 @@ public class DeviceActionMessageKafkaConsumer { @Async("linkAsync") @KafkaListener(topics = { - ConsumerTopicConstant.THINGLINKS_LINK_MQTT_MSG, - ConsumerTopicConstant.THINGLINKS_CLIENT_CONNECTED_TOPIC, - ConsumerTopicConstant.THINGLINKS_CLIENT_DISCONNECTED_TOPIC, - ConsumerTopicConstant.THINGLINKS_SERVER_CONNECTED_TOPIC, - ConsumerTopicConstant.THINGLINKS_DEVICE_KICKED_TOPIC, - ConsumerTopicConstant.THINGLINKS_SUBSCRIPTION_ACKED_TOPIC, - ConsumerTopicConstant.THINGLINKS_UNSUBSCRIPTION_ACKED_TOPIC, - ConsumerTopicConstant.THINGLINKS_DISTRIBUTION_ERROR_TOPIC, - ConsumerTopicConstant.THINGLINKS_DISTRIBUTION_COMPLETED_TOPIC}) + ConsumerKafkaTopicConstant.THINGLINKS_LINK_MQTT_MSG, + ConsumerKafkaTopicConstant.THINGLINKS_CLIENT_CONNECTED_TOPIC, + ConsumerKafkaTopicConstant.THINGLINKS_CLIENT_DISCONNECTED_TOPIC, + ConsumerKafkaTopicConstant.THINGLINKS_SERVER_CONNECTED_TOPIC, + ConsumerKafkaTopicConstant.THINGLINKS_DEVICE_KICKED_TOPIC, + ConsumerKafkaTopicConstant.THINGLINKS_SUBSCRIPTION_ACKED_TOPIC, + ConsumerKafkaTopicConstant.THINGLINKS_UNSUBSCRIPTION_ACKED_TOPIC, + ConsumerKafkaTopicConstant.THINGLINKS_DISTRIBUTION_ERROR_TOPIC, + ConsumerKafkaTopicConstant.THINGLINKS_DISTRIBUTION_COMPLETED_TOPIC}) public void onMessage(ConsumerRecord record) { if (null == record) { log.warn("message cannot be empty {}", record); diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/rocketmq/DeviceActionMessageRocketmqConsumer.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/rocketmq/DeviceActionMessageRocketmqConsumer.java index 7c2afd17..0f0bfbb5 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/rocketmq/DeviceActionMessageRocketmqConsumer.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/rocketmq/DeviceActionMessageRocketmqConsumer.java @@ -29,6 +29,7 @@ */ @Slf4j //@Component +@Deprecated @RocketMQMessageListener(consumerGroup = ConsumerGroupConstant.THINGLINKS_BROKER_GROUP, topic = ConsumerTopicConstant.THINGLINKS_LINK_MQTT_MSG, messageModel = MessageModel.CLUSTERING) public class DeviceActionMessageRocketmqConsumer implements RocketMQListener { @Autowired diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/listener/RedisKeyExpirationListener.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/listener/RedisKeyExpirationListener.java index d6083f70..0653d283 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/listener/RedisKeyExpirationListener.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/listener/RedisKeyExpirationListener.java @@ -1,5 +1,6 @@ package com.mqttsnet.thinglinks.link.common.listener; +import com.mqttsnet.thinglinks.common.core.constant.CacheConstants; import com.mqttsnet.thinglinks.common.core.constant.Constants; import com.mqttsnet.thinglinks.common.core.text.UUID; import com.mqttsnet.thinglinks.common.redis.service.RedisService; @@ -50,9 +51,9 @@ public void onMessage(Message message, byte[] pattern) { resultLock = redisService.checkLock(expiredKey, uuid, 1000L); if (resultLock) { log.info("获取分布式锁成功-key:{},value:{}", expiredKey, uuid); - if (expiredKey.contains(Constants.DEVICE_RECORD_KEY)){ + if (expiredKey.contains(CacheConstants.DEVICE_RECORD_KEY)){ log.info("设备信息缓存失效{}",expiredKey); - deviceService.cacheInvalidation(expiredKey.replace(Constants.DEVICE_RECORD_KEY, "")); + deviceService.cacheInvalidation(expiredKey.replace(CacheConstants.DEVICE_RECORD_KEY, "")); } }else { log.info("获取分布式锁失败-key:{},value:{}", expiredKey, uuid); diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceController.java index 230f9b38..b6e0436d 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceController.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceController.java @@ -1,10 +1,8 @@ package com.mqttsnet.thinglinks.link.controller.device; -import cn.hutool.json.JSONConverter; -import com.alibaba.fastjson.JSON; import com.mqttsnet.thinglinks.common.core.annotation.NoRepeatSubmit; import com.mqttsnet.thinglinks.common.core.domain.R; -import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatus; +import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatusEnum; import com.mqttsnet.thinglinks.common.core.utils.StringUtils; import com.mqttsnet.thinglinks.common.core.utils.poi.ExcelUtil; import com.mqttsnet.thinglinks.common.core.web.controller.BaseController; @@ -16,17 +14,26 @@ import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; import com.mqttsnet.thinglinks.link.api.domain.device.model.DeviceParams; import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.OtaCommandResponseParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoAddSubDeviceParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoQueryDeviceParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoUpdateSubDeviceStatusParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoQueryDeviceResultVO; import com.mqttsnet.thinglinks.link.service.device.DeviceService; import com.mqttsnet.thinglinks.link.service.product.ProductService; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.validation.Valid; import java.io.IOException; import java.util.HashMap; import java.util.List; @@ -96,11 +103,11 @@ public AjaxResult listStatusCount(Device device) { Map countMap = new HashMap<>(); //统计设备在线数量 - countMap.put("onlineCount", !connectStatusCollect.isEmpty() && !CollectionUtils.isEmpty(connectStatusCollect.get(DeviceConnectStatus.ONLINE.getValue())) ? connectStatusCollect.get(DeviceConnectStatus.ONLINE.getValue()).size() : 0); + countMap.put("onlineCount", !connectStatusCollect.isEmpty() && !CollectionUtils.isEmpty(connectStatusCollect.get(DeviceConnectStatusEnum.ONLINE.getValue())) ? connectStatusCollect.get(DeviceConnectStatusEnum.ONLINE.getValue()).size() : 0); //统计设备离线数量 - countMap.put("offlineCount", !connectStatusCollect.isEmpty() && !CollectionUtils.isEmpty(connectStatusCollect.get(DeviceConnectStatus.OFFLINE.getValue())) ? connectStatusCollect.get(DeviceConnectStatus.OFFLINE.getValue()).size() : 0); + countMap.put("offlineCount", !connectStatusCollect.isEmpty() && !CollectionUtils.isEmpty(connectStatusCollect.get(DeviceConnectStatusEnum.OFFLINE.getValue())) ? connectStatusCollect.get(DeviceConnectStatusEnum.OFFLINE.getValue()).size() : 0); //统计设备初始化数量 - countMap.put("initCount", !connectStatusCollect.isEmpty() && !CollectionUtils.isEmpty(connectStatusCollect.get(DeviceConnectStatus.INIT.getValue())) ? connectStatusCollect.get(DeviceConnectStatus.INIT.getValue()).size() : 0); + countMap.put("initCount", !connectStatusCollect.isEmpty() && !CollectionUtils.isEmpty(connectStatusCollect.get(DeviceConnectStatusEnum.INIT.getValue())) ? connectStatusCollect.get(DeviceConnectStatusEnum.INIT.getValue()).size() : 0); return AjaxResult.success(countMap); } @@ -237,6 +244,7 @@ public AjaxResult disconnect(@PathVariable Long[] ids) { * @param params * @return */ + @Deprecated @PostMapping("/clientAuthentication") public ResponseEntity clientAuthentication(@RequestBody Map params) { final Object clientIdentifier = params.get("clientIdentifier"); @@ -307,4 +315,168 @@ public R> selectAllByProductIdentification(@PathVariable(value = "p public R selectDeviceByDeviceIdentificationList(@RequestBody List deviceIdentificationList) { return R.ok(deviceService.selectDeviceByDeviceIdentificationList(deviceIdentificationList)); } + + + /** + * (MQTT)协议新增子设备档案 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 新增结果 + */ + @ApiOperation(value = "(MQTT)协议新增子设备档案", httpMethod = "POST", notes = "(MQTT)协议新增子设备档案") + @PostMapping("/saveSubDeviceByMqtt") + public R saveSubDeviceByMqtt(@RequestBody TopoAddSubDeviceParam topoAddSubDeviceParam) { + return R.ok(deviceService.saveSubDeviceByMqtt(topoAddSubDeviceParam)); + } + + /** + * (HTTP)协议新增子设备档案 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 新增结果 + */ + @ApiOperation(value = "(HTTP)协议新增子设备档案", httpMethod = "POST", notes = "(HTTP)协议新增子设备档案") + @PostMapping("/saveSubDeviceByHttp") + public R saveSubDeviceByHttp(@RequestBody TopoAddSubDeviceParam topoAddSubDeviceParam) { + return R.ok(deviceService.saveSubDeviceByHttp(topoAddSubDeviceParam)); + } + + /** + * MQTT协议修改子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 连接状态参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @ApiOperation(value = "(MQTT)协议修改子设备连接状态", httpMethod = "PUT", notes = "(MQTT)协议修改子设备连接状态") + @PutMapping("/updateSubDeviceConnectStatusByMqtt") + public R updateSubDeviceConnectStatusByMqtt( + @RequestBody @ApiParam(value = "连接状态参数") TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { + TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceService.updateSubDeviceConnectStatusByMqtt(topoUpdateSubDeviceStatusParam); + return R.ok(topoDeviceOperationResultVO); + } + + /** + * HTTP协议修改子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 连接状态参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @ApiOperation(value = "(HTTP)协议修改子设备连接状态", httpMethod = "PUT", notes = "(HTTP)协议修改子设备连接状态") + @PutMapping("/updateSubDeviceConnectStatusByHttp") + public R updateSubDeviceConnectStatusByHttp( + @RequestBody @ApiParam(value = "连接状态参数") TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { + TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceService.updateSubDeviceConnectStatusByHttp(topoUpdateSubDeviceStatusParam); + return R.ok(topoDeviceOperationResultVO); + } + + /** + * MQTT协议删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @ApiOperation(value = "(MQTT)协议删除子设备", httpMethod = "PUT", notes = "(MQTT)协议删除子设备") + @PutMapping("/deleteSubDeviceByMqtt") + public R deleteSubDeviceByMqtt(@RequestBody @ApiParam(value = "删除参数") TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { + TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceService.deleteSubDeviceByMqtt(topoDeleteSubDeviceParam); + return R.ok(topoDeviceOperationResultVO); + } + + /** + * HTTP协议删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @ApiOperation(value = "(HTTP)协议删除子设备", httpMethod = "PUT", notes = "(HTTP)协议删除子设备") + @PutMapping("/deleteSubDeviceByHttp") + public R deleteSubDeviceByHttp(@RequestBody @ApiParam(value = "删除参数") TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { + TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceService.deleteSubDeviceByHttp(topoDeleteSubDeviceParam); + return R.ok(topoDeviceOperationResultVO); + } + + + /** + * MQTT协议数据上报 + * + * @param topoDeviceDataReportParam 数据上报参数 + * @return {@link TopoDeviceOperationResultVO} 上报结果 + */ + @ApiOperation(value = "(MQTT)协议数据上报", httpMethod = "POST", notes = "(MQTT)协议数据上报") + @PostMapping("/deviceDataReportByMqtt") + public R deviceDataReportByMqtt(@RequestBody @ApiParam(value = "数据上报参数") TopoDeviceDataReportParam topoDeviceDataReportParam) { + TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceService.deviceDataReportByMqtt(topoDeviceDataReportParam); + return R.ok(topoDeviceOperationResultVO); + } + + /** + * HTTP协议数据上报 + * + * @param topoDeviceDataReportParam 数据上报参数 + * @return {@link TopoDeviceOperationResultVO} 上报结果 + */ + @ApiOperation(value = "(HTTP)协议数据上报", httpMethod = "POST", notes = "(HTTP)协议数据上报") + @PostMapping("/deviceDataReportByHttp") + public R deviceDataReportByHttp(@RequestBody @ApiParam(value = "数据上报参数") TopoDeviceDataReportParam topoDeviceDataReportParam) { + TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceService.deviceDataReportByHttp(topoDeviceDataReportParam); + return R.ok(topoDeviceOperationResultVO); + } + + /** + * Queries device information using the HTTP protocol. + * + * @param topoQueryDeviceParam The device query parameters. + * @return {@link TopoQueryDeviceResultVO} The result of the device query. + */ + @ApiOperation(value = "Query Device Information via HTTP Protocol", httpMethod = "POST", notes = "Queries device information using the HTTP protocol") + @PostMapping("/queryDeviceByHttp") + public R queryDeviceByHttp(@RequestBody TopoQueryDeviceParam topoQueryDeviceParam) { + return R.ok(deviceService.queryDeviceByHttp(topoQueryDeviceParam)); + } + + /** + * Receives and saves a new OTA upgrade record from an MQTT message. This endpoint + * captures the command response parameters from the MQTT message body and persists them. + * + * @param otaCommandResponseParam The response parameters from an OTA command sent via MQTT. + * @return {@link R} A response entity containing the saved OTA upgrade record. + */ + @ApiOperation(value = "Save OTA Upgrade Record", httpMethod = "POST", notes = "Saves a new OTA upgrade record from MQTT message data.") + @PostMapping("/saveOtaUpgradeRecordByMqtt") + public R saveOtaUpgradeRecordByMqtt(@Valid @RequestBody OtaCommandResponseParam otaCommandResponseParam) { + try { + // Call the service method to save the record + OtaCommandResponseParam savedRecord = otaUpgradeRecordsService.saveOtaUpgradeRecordByMqtt(otaCommandResponseParam); + + // Return a successful response entity with the saved record + return R.ok(savedRecord); + } catch (Exception e) { + // Log the exception and return an error response entity + // Assuming R.fail() is a method to create a failure response + return R.fail("Error saving OTA upgrade record: " + e.getMessage()); + } + } + + /** + * Receives and saves a new OTA upgrade record from an HTTP request. This endpoint + * captures the command response parameters from the request body and persists them. + * + * @param otaCommandResponseParam The response parameters from an OTA command sent via HTTP. + * @return {@link R} A response wrapper containing the saved OTA upgrade record. + */ + @ApiOperation(value = "Save OTA Upgrade Record via HTTP", httpMethod = "POST", notes = "Saves a new OTA upgrade record from HTTP request data.") + @PostMapping("/saveUpgradeRecordByHttp") + public R saveUpgradeRecordByHttp(@Valid @RequestBody OtaCommandResponseParam otaCommandResponseParam) { + try { + // Call the service method to save the record + OtaCommandResponseParam savedRecord = otaUpgradeRecordsService.saveUpgradeRecordByHttp(otaCommandResponseParam); + + // Return a successful response wrapper with the saved record + return R.ok(savedRecord); + } catch (Exception e) { + // Log the exception and return a failure response wrapper + // Assuming R.fail() is a method to create a failure response + return R.fail("Error saving OTA upgrade record via HTTP: " + e.getMessage()); + } + } } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceActionServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceActionServiceImpl.java index 79970a7b..294b09de 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceActionServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceActionServiceImpl.java @@ -3,7 +3,7 @@ import com.alibaba.fastjson.JSONObject; import com.alibaba.nacos.shaded.com.google.gson.Gson; import com.mqttsnet.thinglinks.common.core.constant.Constants; -import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatus; +import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatusEnum; import com.mqttsnet.thinglinks.common.core.utils.DateUtils; import com.mqttsnet.thinglinks.common.redis.service.RedisService; import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; @@ -116,7 +116,7 @@ public void connectEvent(JSONObject thinglinksMessage) { Gson gson = new Gson(); Map map = new HashMap<>(); map = gson.fromJson(thinglinksMessage.toJSONString(), map.getClass()); - deviceService.updateConnectStatusByClientId(DeviceConnectStatus.ONLINE.getValue(), String.valueOf(map.get("clientId"))); + deviceService.updateConnectStatusByClientId(DeviceConnectStatusEnum.ONLINE.getValue(), String.valueOf(map.get("clientId"))); } /** @@ -129,7 +129,7 @@ public void closeEvent(JSONObject thinglinksMessage) { Gson gson = new Gson(); Map map = new HashMap<>(); map = gson.fromJson(thinglinksMessage.toJSONString(), map.getClass()); - deviceService.updateConnectStatusByClientId(DeviceConnectStatus.OFFLINE.getValue(), String.valueOf(map.get("clientId"))); + deviceService.updateConnectStatusByClientId(DeviceConnectStatusEnum.OFFLINE.getValue(), String.valueOf(map.get("clientId"))); } @@ -230,7 +230,7 @@ public void refreshDeviceCache(JSONObject thinglinksMessage) { Device device = deviceService.findOneByClientId(String.valueOf(map.get("clientId"))); if (null != device){ //缓存设备信息 - redisService.setCacheObject(Constants.DEVICE_RECORD_KEY+device.getClientId(),device,60L+ Long.parseLong(DateUtils.getRandom(1)), TimeUnit.SECONDS); + redisService.setCacheObject(CacheConstants.DEVICE_RECORD_KEY+device.getClientId(),device,60L+ Long.parseLong(DateUtils.getRandom(1)), TimeUnit.SECONDS); } } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceDatasServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceDatasServiceImpl.java index 24ef248a..235268fe 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceDatasServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceDatasServiceImpl.java @@ -7,13 +7,14 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.JsonPath; import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; +import com.mqttsnet.thinglinks.common.core.constant.CacheConstants; import com.mqttsnet.thinglinks.common.core.constant.Constants; import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.common.core.dynamicCompilation.ClassInjector; import com.mqttsnet.thinglinks.common.core.dynamicCompilation.DynamicClassLoader; import com.mqttsnet.thinglinks.common.core.dynamicCompilation.DynamicLoaderEngine; import com.mqttsnet.thinglinks.common.core.dynamicCompilation.bytecode.InjectionSystem; -import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatus; +import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatusEnum; import com.mqttsnet.thinglinks.common.core.enums.DeviceType; import com.mqttsnet.thinglinks.common.core.enums.ProtocolType; import com.mqttsnet.thinglinks.common.core.enums.ResultEnum; @@ -225,7 +226,7 @@ public void insertBaseDatas(JSONObject thinglinksMessage) throws Exception { * 处理/topo/add Topic边设备添加子设备 * * @param deviceIdentification 设备标识 - * @param body 数据 + * @param body 数据 */ @Override @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) @@ -261,7 +262,7 @@ public String processingTopoAddTopic(String deviceIdentification, String body) t deviceInfo.setDescription(deviceInfos.getDescription()); deviceInfo.setManufacturerId(deviceInfos.getManufacturerId()); deviceInfo.setModel(deviceInfos.getModel()); - deviceInfo.setConnectStatus(DeviceConnectStatus.INIT.getValue()); + deviceInfo.setConnectStatus(DeviceConnectStatusEnum.INIT.getValue()); deviceInfo.setShadowEnable(true); StringBuilder shadowTableNameBuilder = new StringBuilder(); // 新增设备管理成功后,创建TD普通表 @@ -321,7 +322,7 @@ public String processingTopoAddTopic(String deviceIdentification, String body) t * 处理/topo/delete Topic边设备删除子设备 * * @param deviceIdentification 设备标识 - * @param body 数据 + * @param body 数据 */ @Override @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) @@ -360,7 +361,7 @@ public String processingTopoDeleteTopic(String deviceIdentification, String body * 处理/topo/update Topic边设备更新子设备状态 * * @param deviceIdentification 设备标识 - * @param body 数据 + * @param body 数据 */ @Override @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) @@ -389,9 +390,9 @@ public String processingTopoUpdateTopic(String deviceIdentification, String body log.error("The side device reports data processing, but the device does not exist,DeviceIdentification:{},Body:{}", deviceIdentification, body); } if ("ONLINE".equals(status)) { - deviceInfo.setConnectStatus(DeviceConnectStatus.ONLINE.getValue()); + deviceInfo.setConnectStatus(DeviceConnectStatusEnum.ONLINE.getValue()); } else if ("OFFLINE".equals(status)) { - deviceInfo.setConnectStatus(DeviceConnectStatus.OFFLINE.getValue()); + deviceInfo.setConnectStatus(DeviceConnectStatusEnum.OFFLINE.getValue()); } final int updateByPrimaryKeySelectiveCount = deviceInfoService.updateByPrimaryKeySelective(deviceInfo); if (updateByPrimaryKeySelectiveCount > 0) { @@ -413,7 +414,7 @@ public String processingTopoUpdateTopic(String deviceIdentification, String body * 处理datas Topic数据上报 * * @param deviceIdentification 设备标识 - * @param body 数据 + * @param body 数据 */ @Override @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) @@ -426,12 +427,12 @@ public void processingDatasTopic(String deviceIdentification, String body) throw for (Map item : items) { final Object deviceId = item.get("deviceId"); Device device = null; - if (Boolean.TRUE.equals(redisService.hasKey(Constants.DEVICE_RECORD_KEY + deviceIdentification))) { - device = redisService.getCacheObject(Constants.DEVICE_RECORD_KEY + deviceIdentification); + if (Boolean.TRUE.equals(redisService.hasKey(CacheConstants.DEVICE_RECORD_KEY + deviceIdentification))) { + device = redisService.getCacheObject(CacheConstants.DEVICE_RECORD_KEY + deviceIdentification); } else { device = deviceService.findOneByDeviceIdentification(deviceIdentification); if (StringUtils.isNotNull(device)) { - redisService.setCacheObject(Constants.DEVICE_RECORD_KEY + deviceIdentification, device); + redisService.setCacheObject(CacheConstants.DEVICE_RECORD_KEY + deviceIdentification, device); } else { log.error("The side device reports data processing, but the device does not exist,DeviceIdentification:{},Body:{}", deviceIdentification, body); continue; @@ -471,7 +472,7 @@ public void processingDatasTopic(String deviceIdentification, String body) throw //子表命名规则 : 产品类型_产品标识_服务名称_设备标识(设备唯一标识) String tableName = superTableName + "_" + deviceId.toString(); //从redis根据超级表名称取出超级表表结构信息 - final Object cacheObject = redisService.getCacheObject(Constants.TDENGINE_SUPERTABLEFILELDS + superTableName); + final Object cacheObject = redisService.getCacheObject(CacheConstants.TDENGINE_SUPERTABLEFILELDS + superTableName); ObjectMapper objectMapper = new ObjectMapper(); SuperTableDto superTableDto = objectMapper.convertValue(cacheObject, SuperTableDto.class); //获取超级表的表结构信息 @@ -554,7 +555,7 @@ public void processingDatasTopic(String deviceIdentification, String body) throw * 处理/commandResponse Topic边设备返回给物联网平台的命令响应 * * @param deviceIdentification 设备标识 - * @param body 数据 + * @param body 数据 */ @Override @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) @@ -567,8 +568,8 @@ public void processingTopoCommandResponseTopic(String deviceIdentification, Stri * 根据设备找到所属产品 产品的服务及属性 转换出系统能识别的json 找到这个产品的协议内容即Java代码 */ public String convertToBody(String deviceIdentification, String body) { - if (Boolean.TRUE.equals(redisService.hasKey(Constants.DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + ProtocolType.MQTT.getValue() + deviceIdentification))) { - String protocolContent = redisService.get(Constants.DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + ProtocolType.MQTT.getValue() + deviceIdentification); + if (Boolean.TRUE.equals(redisService.hasKey(CacheConstants.DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + ProtocolType.MQTT.getValue() + deviceIdentification))) { + String protocolContent = redisService.get(CacheConstants.DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + ProtocolType.MQTT.getValue() + deviceIdentification); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); PrintWriter out = new PrintWriter(buffer, true); byte[] classBytes = DynamicLoaderEngine.compile(protocolContent, out, null);//传入要执行的代码 diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java index 8e55a4a5..fbf65740 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java @@ -4,7 +4,7 @@ import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.common.core.constant.Constants; import com.mqttsnet.thinglinks.common.core.domain.R; -import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatus; +import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatusEnum; import com.mqttsnet.thinglinks.common.core.enums.ResultEnum; import com.mqttsnet.thinglinks.common.core.text.UUID; import com.mqttsnet.thinglinks.common.core.utils.DateUtils; @@ -181,7 +181,7 @@ public int insertDeviceInfo(DeviceInfoParams deviceInfoParams) SysUser sysUser = loginUser.getSysUser(); deviceInfo.setCreateBy(sysUser.getUserName()); deviceInfo.setDeviceId(UUID.getUUID()); - deviceInfo.setConnectStatus(DeviceConnectStatus.INIT.getValue()); + deviceInfo.setConnectStatus(DeviceConnectStatusEnum.INIT.getValue()); deviceInfo.setShadowEnable(true); return deviceInfoMapper.insertDeviceInfo(deviceInfo); } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java index d86eb92a..8e0ce933 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java @@ -1,9 +1,10 @@ package com.mqttsnet.thinglinks.link.service.device.impl; import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; +import com.mqttsnet.thinglinks.common.core.constant.CacheConstants; import com.mqttsnet.thinglinks.common.core.constant.Constants; import com.mqttsnet.thinglinks.common.core.domain.R; -import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatus; +import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatusEnum; import com.mqttsnet.thinglinks.common.core.enums.DeviceTopicEnum; import com.mqttsnet.thinglinks.common.core.enums.DeviceType; import com.mqttsnet.thinglinks.common.core.enums.ResultEnum; @@ -224,7 +225,7 @@ public int insertDevice(DeviceParams deviceParams) throws Exception { if (StringUtils.isNotNull(oneByClientIdAndDeviceIdentification)) { throw new Exception("设备编号或者设备标识已存在"); } - device.setConnectStatus(DeviceConnectStatus.INIT.getValue()); + device.setConnectStatus(DeviceConnectStatusEnum.INIT.getValue()); device.setCreateBy(sysUser.getUserName()); final int insertDeviceCount = deviceMapper.insertOrUpdateSelective(device); if (insertDeviceCount > 0) { @@ -363,11 +364,11 @@ public Boolean cacheInvalidation(String clientId) { //设备信息缓存失效 删除缓存 更新数据库设备状态 if (StringUtils.isNotNull(oneByClientId)) { //删除缓存 - redisService.delete(Constants.DEVICE_RECORD_KEY + oneByClientId.getDeviceIdentification()); + redisService.delete(CacheConstants.DEVICE_RECORD_KEY + oneByClientId.getDeviceIdentification()); //更新数据库设备状态 Device device = new Device(); device.setId(oneByClientId.getId()); - device.setConnectStatus(DeviceConnectStatus.OFFLINE.getValue()); + device.setConnectStatus(DeviceConnectStatusEnum.OFFLINE.getValue()); deviceMapper.updateByPrimaryKeySelective(device); } return true; @@ -416,9 +417,9 @@ public Device clientAuthentication(String clientIdentifier, String username, Str final Device device = this.findOneByClientIdAndUserNameAndPasswordAndDeviceStatusAndProtocolType(clientIdentifier, username, password, deviceStatus, protocolType); if (Optional.ofNullable(device).isPresent()) { //缓存设备信息 - redisService.setCacheObject(Constants.DEVICE_RECORD_KEY + device.getDeviceIdentification(), device, 60L + Long.parseLong(DateUtils.getRandom(1)), TimeUnit.SECONDS); + redisService.setCacheObject(CacheConstants.DEVICE_RECORD_KEY + device.getDeviceIdentification(), device, 60L + Long.parseLong(DateUtils.getRandom(1)), TimeUnit.SECONDS); //更改设备在线状态为在线 - this.updateConnectStatusByClientId(DeviceConnectStatus.ONLINE.getValue(), clientIdentifier); + this.updateConnectStatusByClientId(DeviceConnectStatusEnum.ONLINE.getValue(), clientIdentifier); return device; } return null; diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServiceImpl.java index a22b21fa..ba4f3e3c 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServiceImpl.java @@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Lists; import com.jayway.jsonpath.JsonPath; +import com.mqttsnet.thinglinks.common.core.constant.CacheConstants; import com.mqttsnet.thinglinks.common.core.constant.Constants; import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.common.core.enums.DataTypeEnum; @@ -408,11 +409,11 @@ public AjaxResult createSuperTable(Product product, JSONArray services) throws E } log.info("Create SuperTable Result: {}", cstResult.getCode()); //将之前存在redis里的同样的名称的超级表的表结构信息删除 - if (redisService.hasKey(Constants.TDENGINE_SUPERTABLEFILELDS + superTableName)) { - redisService.deleteObject(Constants.TDENGINE_SUPERTABLEFILELDS + superTableName); + if (redisService.hasKey(CacheConstants.TDENGINE_SUPERTABLEFILELDS + superTableName)) { + redisService.deleteObject(CacheConstants.TDENGINE_SUPERTABLEFILELDS + superTableName); } //在redis里存入新的超级表对的表结构信息 - redisService.setCacheObject(Constants.TDENGINE_SUPERTABLEFILELDS + superTableName, superTableDto); + redisService.setCacheObject(CacheConstants.TDENGINE_SUPERTABLEFILELDS + superTableName, superTableDto); log.info("缓存超级表数据模型:{}", JSON.toJSONString(superTableDto)); } } catch (Exception e) { @@ -649,11 +650,11 @@ public List createSuperTableDataModel(Long[] productIds, Boolean //设置超级表标签字段列表 superTableDto.setTagsFields(tagsFields); //将之前存在redis里的同样的名称的超级表的表结构信息删除 - if (redisService.hasKey(Constants.TDENGINE_SUPERTABLEFILELDS + superTableName)) { - redisService.deleteObject(Constants.TDENGINE_SUPERTABLEFILELDS + superTableName); + if (redisService.hasKey(CacheConstants.TDENGINE_SUPERTABLEFILELDS + superTableName)) { + redisService.deleteObject(CacheConstants.TDENGINE_SUPERTABLEFILELDS + superTableName); } //在redis里存入新的超级表对的表结构信息 - redisService.setCacheObject(Constants.TDENGINE_SUPERTABLEFILELDS + superTableName, superTableDto); + redisService.setCacheObject(CacheConstants.TDENGINE_SUPERTABLEFILELDS + superTableName, superTableDto); log.info("缓存超级表数据模型:{}", JSON.toJSONString(superTableDto)); superTableDtoList.add(superTableDto); if (Boolean.TRUE.equals(InitializeOrNot)) { diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/protocol/impl/ProtocolServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/protocol/impl/ProtocolServiceImpl.java index d22d353b..ee3fd85a 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/protocol/impl/ProtocolServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/protocol/impl/ProtocolServiceImpl.java @@ -1,5 +1,6 @@ package com.mqttsnet.thinglinks.link.service.protocol.impl; +import com.mqttsnet.thinglinks.common.core.constant.CacheConstants; import com.mqttsnet.thinglinks.common.core.constant.Constants; import com.mqttsnet.thinglinks.common.core.exception.ServiceException; import com.mqttsnet.thinglinks.common.redis.service.RedisService; @@ -170,7 +171,7 @@ public int enable(Long[] ids) { List deviceList = deviceService.findAllByProductIdentification(protocol.getProductIdentification()); String content = StringEscapeUtils.unescapeHtml4(protocol.getContent()); for (Device device : deviceList) { - redisService.set(Constants.DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + device.getProtocolType() + device.getDeviceIdentification(), content); + redisService.set(CacheConstants.DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + device.getProtocolType() + device.getDeviceIdentification(), content); } protocolMapper.updateStatusById(Constants.ENABLE, protocol.getId()); } @@ -189,7 +190,7 @@ public int disable(Long[] ids) { for (Protocol protocol : protocolList) { List deviceList = deviceService.findAllByProductIdentification(protocol.getProductIdentification()); for (Device device : deviceList) { - redisService.delete(Constants.DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + protocol.getProtocolType() + device.getDeviceIdentification()); + redisService.delete(CacheConstants.DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + protocol.getProtocolType() + device.getDeviceIdentification()); } protocolMapper.updateStatusById(Constants.DISABLE, protocol.getId()); } @@ -217,7 +218,7 @@ public int protocolScriptCacheRefresh() { for (Protocol protocol : protocolList) { List deviceList = deviceService.findAllByProductIdentification(protocol.getProductIdentification()); for (Device device : deviceList) { - redisService.delete(Constants.DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + protocol.getProtocolType() + device.getDeviceIdentification()); + redisService.delete(CacheConstants.DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + protocol.getProtocolType() + device.getDeviceIdentification()); } protocolMapper.updateStatusById(Constants.DISABLE, protocol.getId()); } diff --git a/thinglinks-modules/thinglinks-modules-rule/pom.xml b/thinglinks-modules/thinglinks-modules-rule/pom.xml index 87083355..c5cab27d 100644 --- a/thinglinks-modules/thinglinks-modules-rule/pom.xml +++ b/thinglinks-modules/thinglinks-modules-rule/pom.xml @@ -45,6 +45,14 @@ mysql-connector-java + + + com.mqttsnet + thinglinks-common-core + ${thinglinks.version} + + + com.mqttsnet diff --git a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/common/consumer/rocketmq/RuleTriggerMessageRocketmqConsumer.java b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/common/consumer/rocketmq/RuleTriggerMessageRocketmqConsumer.java index 80aa4792..2be09743 100644 --- a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/common/consumer/rocketmq/RuleTriggerMessageRocketmqConsumer.java +++ b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/common/consumer/rocketmq/RuleTriggerMessageRocketmqConsumer.java @@ -1,8 +1,8 @@ package com.mqttsnet.thinglinks.rule.common.consumer.rocketmq; import com.alibaba.fastjson.JSONObject; -import com.mqttsnet.thinglinks.common.rocketmq.constant.ConsumerGroupConstant; -import com.mqttsnet.thinglinks.common.rocketmq.constant.ConsumerTopicConstant; +import com.mqttsnet.thinglinks.common.core.mqs.ConsumerGroupConstant; +import com.mqttsnet.thinglinks.common.core.mqs.ConsumerTopicConstant; import com.mqttsnet.thinglinks.rule.service.RuleDeviceLinkageService; import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.spring.annotation.MessageModel; @@ -10,7 +10,6 @@ import org.apache.rocketmq.spring.core.RocketMQListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Component; /** * @Description: 规则引擎-触发器规则消息消费(Rocketmq模式) @@ -25,7 +24,7 @@ */ @Slf4j //@Component -@RocketMQMessageListener(consumerGroup = ConsumerGroupConstant.THINGLINKS_RULE_GROUP, topic = ConsumerTopicConstant.THINGLINKS_RULE_TRIGGER, messageModel = MessageModel.CLUSTERING) +@RocketMQMessageListener(consumerGroup = ConsumerGroupConstant.THINGLINKS_GROUP, topic = ConsumerTopicConstant.Rule.THINGLINKS_RULE_TRIGGER, messageModel = MessageModel.CLUSTERING) public class RuleTriggerMessageRocketmqConsumer implements RocketMQListener { @Autowired diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/consumer/rocketmq/ProductCreateSuperTableMessageRocketmqConsumer.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/consumer/rocketmq/ProductCreateSuperTableMessageRocketmqConsumer.java index 97593ef2..26306011 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/consumer/rocketmq/ProductCreateSuperTableMessageRocketmqConsumer.java +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/consumer/rocketmq/ProductCreateSuperTableMessageRocketmqConsumer.java @@ -1,16 +1,15 @@ package com.mqttsnet.thinglinks.tdengine.common.consumer.rocketmq; import com.alibaba.fastjson.JSONObject; +import com.mqttsnet.thinglinks.common.core.mqs.ConsumerGroupConstant; +import com.mqttsnet.thinglinks.common.core.mqs.ConsumerTopicConstant; import com.mqttsnet.thinglinks.common.core.utils.StringUtils; -import com.mqttsnet.thinglinks.common.rocketmq.constant.ConsumerGroupConstant; -import com.mqttsnet.thinglinks.common.rocketmq.constant.ConsumerTopicConstant; import com.mqttsnet.thinglinks.tdengine.service.ProductSuperTableCreateOrUpdateService; import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.spring.annotation.MessageModel; import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; import org.apache.rocketmq.spring.core.RocketMQListener; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; /** * @Description: TDengine超级表创键修改动作监听(Rocketmq模式) @@ -25,7 +24,7 @@ */ @Slf4j //@Component -@RocketMQMessageListener(consumerGroup = ConsumerGroupConstant.THINGLINKS_LINK_GROUP, topic = ConsumerTopicConstant.PRODUCTSUPERTABLE_CREATEORUPDATE, messageModel = MessageModel.CLUSTERING) +@RocketMQMessageListener(consumerGroup = ConsumerGroupConstant.THINGLINKS_GROUP, topic = ConsumerTopicConstant.Tdengine.PRODUCTSUPERTABLE_CREATEORUPDATE, messageModel = MessageModel.CLUSTERING) public class ProductCreateSuperTableMessageRocketmqConsumer implements RocketMQListener { @Autowired @@ -33,6 +32,7 @@ public class ProductCreateSuperTableMessageRocketmqConsumer implements RocketMQL /** * 超级表创建及修改处理 + * * @param message */ @Override @@ -42,14 +42,14 @@ public void onMessage(Object message) { return; } JSONObject stableMessage = JSONObject.parseObject(String.valueOf(message)); - log.info("TDengine消费{}超级表消息:{}",stableMessage.get("type"),stableMessage.get("msg")); - if("create".equals(stableMessage.get("type"))){ + log.info("TDengine消费{}超级表消息:{}", stableMessage.get("type"), stableMessage.get("msg")); + if ("create".equals(stableMessage.get("type"))) { try { productSuperTableCreateOrUpdateService.createProductSuperTable(String.valueOf(stableMessage.get("msg"))); } catch (Exception e) { log.error(e.getMessage()); } - }else if("update".equals(stableMessage.get("type"))){ + } else if ("update".equals(stableMessage.get("type"))) { productSuperTableCreateOrUpdateService.updateProductSuperTable(String.valueOf(stableMessage.get("msg"))); } From 58c002f1004a990f62fcc8528b1c37ef278911b9 Mon Sep 17 00:00:00 2001 From: xiaonan <13733918655@163.com> Date: Tue, 5 Mar 2024 16:02:30 +0800 Subject: [PATCH 08/35] fix link error --- .../DEFAULT_GROUP/thinglinks-modules-link.yml | 2 +- .../DEFAULT_GROUP/thinglinks-modules-rule.yml | 2 +- .../domain/cache/device/DeviceCacheVO.java | 1 - .../domain/cache/product/ProductCacheVO.java | 1 - .../cache/product/ProductModelCacheVO.java | 3 +- .../param/TopoUpdateSubDeviceStatusParam.java | 2 +- .../common/core/constant/CacheConstants.java | 7 + .../core/mqs/ConsumerGroupConstant.java | 2 +- .../thinglinks-modules-link/pom.xml | 7 - .../cache/service/DeviceCacheService.java | 266 +++++++++--------- .../common/config/KafkaConsumerConfig.java | 109 ------- .../common/config/KafkaProviderConfig.java | 90 ------ .../DeviceActionMessageKafkaConsumer.java | 85 ------ .../DeviceActionMessageRocketmqConsumer.java | 79 ------ .../controller/device/DeviceController.java | 15 +- .../controller/kafka/KafkaController.java | 38 --- .../link/service/device/DeviceService.java | 96 ++++++- .../device/impl/DeviceActionServiceImpl.java | 1 + .../device/impl/DeviceServiceImpl.java | 114 ++++++++ .../product/impl/ProductServiceImpl.java | 11 +- .../impl/RuleDeviceLinkageServiceImpl.java | 4 +- .../src/main/resources/bootstrap.yml | 2 +- 22 files changed, 363 insertions(+), 574 deletions(-) delete mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/KafkaConsumerConfig.java delete mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/KafkaProviderConfig.java delete mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/kafka/DeviceActionMessageKafkaConsumer.java delete mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/rocketmq/DeviceActionMessageRocketmqConsumer.java delete mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/kafka/KafkaController.java diff --git a/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-link.yml b/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-link.yml index abccaa25..1995e460 100755 --- a/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-link.yml +++ b/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-link.yml @@ -13,4 +13,4 @@ mybatis: swagger: title: Link模块接口文档 license: Powered By thinglinks - licenseUrl: https://showdoc.thinglinks.mqttsnet.com \ No newline at end of file + licenseUrl: http://www.mqttsnet.com/ \ No newline at end of file diff --git a/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-rule.yml b/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-rule.yml index 0b5eb36d..83698b81 100755 --- a/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-rule.yml +++ b/doc/nacos-config/DEFAULT_GROUP/thinglinks-modules-rule.yml @@ -14,4 +14,4 @@ mybatis: swagger: title: Link模块接口文档 license: Powered By thinglinks - licenseUrl: https://showdoc.thinglinks.mqttsnet.com \ No newline at end of file + licenseUrl: http://www.mqttsnet.com/ \ No newline at end of file diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/device/DeviceCacheVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/device/DeviceCacheVO.java index f8c8c28d..6d8f2a54 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/device/DeviceCacheVO.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/device/DeviceCacheVO.java @@ -25,7 +25,6 @@ @ToString(callSuper = true) @Accessors(chain = true) @EqualsAndHashCode(callSuper = false) -@Builder @ApiModel(value = "DeviceCacheVO", description = "设备档案缓存VO") public class DeviceCacheVO extends Device implements Serializable { diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductCacheVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductCacheVO.java index 2c00f490..1349b55b 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductCacheVO.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductCacheVO.java @@ -23,7 +23,6 @@ @ToString(callSuper = true) @Accessors(chain = true) @EqualsAndHashCode(callSuper = true) -@Builder @ApiModel(value = "ProductCacheVO", description = "产品模型缓存VO") public class ProductCacheVO extends Product implements Serializable { diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductModelCacheVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductModelCacheVO.java index 940fe0cb..6d095abd 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductModelCacheVO.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductModelCacheVO.java @@ -18,10 +18,9 @@ @Data @NoArgsConstructor -@AllArgsConstructor @ToString(callSuper = true) @Accessors(chain = true) -@EqualsAndHashCode +@EqualsAndHashCode(callSuper = false) @Builder @ApiModel(value = "ProductModelCacheVO", description = "产品模型缓存VO") public class ProductModelCacheVO extends ProductModel implements Serializable { diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoUpdateSubDeviceStatusParam.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoUpdateSubDeviceStatusParam.java index 14aa0596..b36a2ec6 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoUpdateSubDeviceStatusParam.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/param/TopoUpdateSubDeviceStatusParam.java @@ -1,6 +1,6 @@ package com.mqttsnet.thinglinks.link.api.domain.vo.param; -import com.mqttsnet.thinglinks.device.enumeration.DeviceConnectStatusEnum; +import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatusEnum; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.*; diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/CacheConstants.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/CacheConstants.java index 12673b8a..3de55f90 100644 --- a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/CacheConstants.java +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/CacheConstants.java @@ -42,4 +42,11 @@ public class CacheConstants { */ public static final String TDENGINE_SUPERTABLEFILELDS = "tdengine_superTableFields:"; + + /** + * 设备数据转换脚本 cache key + * link-> device_data_reported_agreement_script:deviceIdentification + */ + public static final String DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT = "device_data_reported_agreement_script"; + } diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/ConsumerGroupConstant.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/ConsumerGroupConstant.java index 4d2e1155..99a90555 100644 --- a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/ConsumerGroupConstant.java +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/ConsumerGroupConstant.java @@ -15,5 +15,5 @@ public interface ConsumerGroupConstant { /** * default-consumer-group */ - String THINGLINKS_GROUP = "thinglinks"; + String THINGLINKS_GROUP = "thingLinks"; } diff --git a/thinglinks-modules/thinglinks-modules-link/pom.xml b/thinglinks-modules/thinglinks-modules-link/pom.xml index ade47d50..ef4bea24 100644 --- a/thinglinks-modules/thinglinks-modules-link/pom.xml +++ b/thinglinks-modules/thinglinks-modules-link/pom.xml @@ -73,13 +73,6 @@ ${thinglinks.version} - - - com.mqttsnet - thinglinks-common-kafka - ${thinglinks.version} - - com.mqttsnet diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java index 1571484e..4e6ace25 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java @@ -1,133 +1,133 @@ -package com.mqttsnet.thinglinks.link.common.cache.service; - -import cn.hutool.core.bean.BeanUtil; -import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; -import com.mqttsnet.thinglinks.common.redis.service.RedisService; -import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; -import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductCacheVO; -import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; -import com.mqttsnet.thinglinks.link.common.cache.CacheSuperAbstract; -import com.mqttsnet.thinglinks.link.service.device.DeviceService; -import com.mqttsnet.thinglinks.link.service.product.ProductService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; - -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -/** - * ----------------------------------------------------------------------------- - * File Name: DeviceCacheService.java - * ----------------------------------------------------------------------------- - * Description: - * Service layer for Device cache management. - * ----------------------------------------------------------------------------- - * - * @author ShiHuan Sun - * @version 1.0 - * ----------------------------------------------------------------------------- - * Revision History: - * Date Author Version Description - * -------- -------- ------- -------------------- - *

- * ----------------------------------------------------------------------------- - * @email 13733918655@163.com - * @date 2023-10-21 22:42 - */ -@Service -@RequiredArgsConstructor -@Slf4j -public class DeviceCacheService extends CacheSuperAbstract { - private final RedisService redisService; - private final DeviceService deviceService; - private final ProductService productService; - - /** - * Refresh the cache with device data for a specific tenant. - * - * @param tenantId Identifier of the tenant whose device cache needs to be refreshed. - */ - public void refreshDeviceCacheForTenant(Long tenantId) { - int totalDataCount = deviceService.findDeviceTotal().intValue(); - int totalPages = (int) Math.ceil((double) totalDataCount / PAGE_SIZE); - - List deviceList = IntStream.range(0, totalPages) - .mapToObj(currentPage -> { - Page page = new Page<>(currentPage, PAGE_SIZE); - Page content = deviceService.page(page, null); - return Optional.ofNullable(content) - .map(Page::getRecords) - .orElse(Collections.emptyList()); - }) - .flatMap(Collection::stream) - .collect(Collectors.toList()); - - cacheDevicesForTenant(tenantId, deviceList); - } - - /** - * Cache a list of devices for a specific tenant. - * - * @param tenantId Identifier of the tenant. - * @param deviceList List of devices to be cached. - */ - public void cacheDevicesForTenant(Long tenantId, List deviceList) { - Optional.ofNullable(deviceList) - .orElse(Collections.emptyList()) - .stream() - .filter(Objects::nonNull) - .map(device -> transformToDeviceCacheVO(tenantId, device)) - .filter(Objects::nonNull) - .forEach(deviceCacheVO -> { - cacheDeviceBasedOnIdentification(deviceCacheVO); - cacheDeviceBasedOnClientId(deviceCacheVO); - }); - } - - /** - * Transforms a device object into a DeviceCacheVO object with associated product data. - * - * @param tenantId Identifier of the tenant. - * @param device Device object to be transformed. - * @return Transformed DeviceCacheVO object. - */ - private DeviceCacheVO transformToDeviceCacheVO(Long tenantId, Device device) { - DeviceCacheVO deviceCacheVO = BeanUtil.toBeanIgnoreError(device, DeviceCacheVO.class); - deviceCacheVO.setTenantId(tenantId); - - Optional.ofNullable(deviceCacheVO.getProductIdentification()) - .map(productService::selectProductByProductIdentificationList) - .ifPresent(product -> { - ProductCacheVO productCacheVO = BeanPlusUtil.toBeanIgnoreError(product, ProductCacheVO.class); - productCacheVO.setTenantId(tenantId); - deviceCacheVO.setProductCacheVO(productCacheVO); - }); - - return deviceCacheVO; - } - - /** - * Cache the DeviceCacheVO object based on its identification. - * - * @param deviceCacheVO DeviceCacheVO object to be cached. - */ - private void cacheDeviceBasedOnIdentification(DeviceCacheVO deviceCacheVO) { - CacheKey deviceIdentKey = DeviceCacheKeyBuilder.build(deviceCacheVO.getDeviceIdentification()); - cachePlusOps.del(deviceIdentKey); - cachePlusOps.set(deviceIdentKey, deviceCacheVO); - } - - /** - * Cache the DeviceCacheVO object based on its client ID. - * - * @param deviceCacheVO DeviceCacheVO object to be cached. - */ - private void cacheDeviceBasedOnClientId(DeviceCacheVO deviceCacheVO) { - CacheKey clientIdKey = DeviceCacheKeyBuilder.build(deviceCacheVO.getClientId()); - cachePlusOps.del(clientIdKey); - cachePlusOps.set(clientIdKey, deviceCacheVO); - } - -} +//package com.mqttsnet.thinglinks.link.common.cache.service; +// +//import cn.hutool.core.bean.BeanUtil; +//import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; +//import com.mqttsnet.thinglinks.common.redis.service.RedisService; +//import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; +//import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductCacheVO; +//import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; +//import com.mqttsnet.thinglinks.link.common.cache.CacheSuperAbstract; +//import com.mqttsnet.thinglinks.link.service.device.DeviceService; +//import com.mqttsnet.thinglinks.link.service.product.ProductService; +//import lombok.RequiredArgsConstructor; +//import lombok.extern.slf4j.Slf4j; +//import org.springframework.stereotype.Service; +// +//import java.util.*; +//import java.util.stream.Collectors; +//import java.util.stream.IntStream; +// +///** +// * ----------------------------------------------------------------------------- +// * File Name: DeviceCacheService.java +// * ----------------------------------------------------------------------------- +// * Description: +// * Service layer for Device cache management. +// * ----------------------------------------------------------------------------- +// * +// * @author ShiHuan Sun +// * @version 1.0 +// * ----------------------------------------------------------------------------- +// * Revision History: +// * Date Author Version Description +// * -------- -------- ------- -------------------- +// *

+// * ----------------------------------------------------------------------------- +// * @email 13733918655@163.com +// * @date 2023-10-21 22:42 +// */ +//@Service +//@RequiredArgsConstructor +//@Slf4j +//public class DeviceCacheService extends CacheSuperAbstract { +// private final RedisService redisService; +// private final DeviceService deviceService; +// private final ProductService productService; +// +// /** +// * Refresh the cache with device data for a specific tenant. +// * +// * @param tenantId Identifier of the tenant whose device cache needs to be refreshed. +// */ +// public void refreshDeviceCacheForTenant(Long tenantId) { +// int totalDataCount = deviceService.findDeviceTotal().intValue(); +// int totalPages = (int) Math.ceil((double) totalDataCount / PAGE_SIZE); +// +// List deviceList = IntStream.range(0, totalPages) +// .mapToObj(currentPage -> { +// Page page = new Page<>(currentPage, PAGE_SIZE); +// Page content = deviceService.page(page, null); +// return Optional.ofNullable(content) +// .map(Page::getRecords) +// .orElse(Collections.emptyList()); +// }) +// .flatMap(Collection::stream) +// .collect(Collectors.toList()); +// +// cacheDevicesForTenant(tenantId, deviceList); +// } +// +// /** +// * Cache a list of devices for a specific tenant. +// * +// * @param tenantId Identifier of the tenant. +// * @param deviceList List of devices to be cached. +// */ +// public void cacheDevicesForTenant(Long tenantId, List deviceList) { +// Optional.ofNullable(deviceList) +// .orElse(Collections.emptyList()) +// .stream() +// .filter(Objects::nonNull) +// .map(device -> transformToDeviceCacheVO(tenantId, device)) +// .filter(Objects::nonNull) +// .forEach(deviceCacheVO -> { +// cacheDeviceBasedOnIdentification(deviceCacheVO); +// cacheDeviceBasedOnClientId(deviceCacheVO); +// }); +// } +// +// /** +// * Transforms a device object into a DeviceCacheVO object with associated product data. +// * +// * @param tenantId Identifier of the tenant. +// * @param device Device object to be transformed. +// * @return Transformed DeviceCacheVO object. +// */ +// private DeviceCacheVO transformToDeviceCacheVO(Long tenantId, Device device) { +// DeviceCacheVO deviceCacheVO = BeanUtil.toBeanIgnoreError(device, DeviceCacheVO.class); +// deviceCacheVO.setTenantId(tenantId); +// +// Optional.ofNullable(deviceCacheVO.getProductIdentification()) +// .map(productService::selectProductByProductIdentificationList) +// .ifPresent(product -> { +// ProductCacheVO productCacheVO = BeanPlusUtil.toBeanIgnoreError(product, ProductCacheVO.class); +// productCacheVO.setTenantId(tenantId); +// deviceCacheVO.setProductCacheVO(productCacheVO); +// }); +// +// return deviceCacheVO; +// } +// +// /** +// * Cache the DeviceCacheVO object based on its identification. +// * +// * @param deviceCacheVO DeviceCacheVO object to be cached. +// */ +// private void cacheDeviceBasedOnIdentification(DeviceCacheVO deviceCacheVO) { +// CacheKey deviceIdentKey = DeviceCacheKeyBuilder.build(deviceCacheVO.getDeviceIdentification()); +// cachePlusOps.del(deviceIdentKey); +// cachePlusOps.set(deviceIdentKey, deviceCacheVO); +// } +// +// /** +// * Cache the DeviceCacheVO object based on its client ID. +// * +// * @param deviceCacheVO DeviceCacheVO object to be cached. +// */ +// private void cacheDeviceBasedOnClientId(DeviceCacheVO deviceCacheVO) { +// CacheKey clientIdKey = DeviceCacheKeyBuilder.build(deviceCacheVO.getClientId()); +// cachePlusOps.del(clientIdKey); +// cachePlusOps.set(clientIdKey, deviceCacheVO); +// } +// +//} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/KafkaConsumerConfig.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/KafkaConsumerConfig.java deleted file mode 100644 index d4df6df5..00000000 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/KafkaConsumerConfig.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.mqttsnet.thinglinks.link.common.config; - -import org.apache.kafka.clients.consumer.ConsumerConfig; -import org.apache.kafka.common.serialization.StringDeserializer; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; -import org.springframework.kafka.config.KafkaListenerContainerFactory; -import org.springframework.kafka.core.ConsumerFactory; -import org.springframework.kafka.core.DefaultKafkaConsumerFactory; -import org.springframework.kafka.listener.ConcurrentMessageListenerContainer; -import org.springframework.kafka.listener.ContainerProperties; -import org.springframework.kafka.support.serializer.JsonDeserializer; - -import java.util.HashMap; -import java.util.Map; - -/** - * @program: thinglinks - * @description: KafkaConsumerConfig - * @packagename: com.mqttsnet.thinglinks.common.kafka.config - * @author: ShiHuan Sun - * @e-mainl: 13733918655@163.com - * @date: 2023-06-18 11:29 - **/ -@Configuration -public class KafkaConsumerConfig { - - - @Value("${spring.kafka.thingLinks.consumer.bootstrap-servers}") - private String bootstrapServers; - @Value("${spring.kafka.thingLinks.consumer.group-id}") - private String groupId; - @Value("${spring.kafka.thingLinks.consumer.enable-auto-commit}") - private boolean enableAutoCommit; - @Value("${spring.kafka.thingLinks.properties.session.timeout.ms}") - private String sessionTimeout; - @Value("${spring.kafka.thingLinks.properties.max.poll.interval.ms}") - private String maxPollIntervalTime; - @Value("${spring.kafka.thingLinks.consumer.max-poll-records}") - private String maxPollRecords; - @Value("${spring.kafka.thingLinks.consumer.auto-offset-reset}") - private String autoOffsetReset; - @Value("${spring.kafka.thingLinks.listener.concurrency}") - private Integer concurrency; - @Value("${spring.kafka.thingLinks.listener.missing-topics-fatal}") - private boolean missingTopicsFatal; - @Value("${spring.kafka.thingLinks.listener.poll-timeout}") - private long pollTimeout; - - @Bean - public Map consumerConfigs() { - - Map propsMap = new HashMap<>(16); - propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); - propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, groupId); - //是否自动提交偏移量,默认值是true,为了避免出现重复数据和数据丢失,可以把它设置为false,然后手动提交偏移量 - propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, enableAutoCommit); - //自动提交的时间间隔,自动提交开启时生效 - propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "2000"); - //该属性指定了消费者在读取一个没有偏移量的分区或者偏移量无效的情况下该作何处理: - //earliest:当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,从头开始消费分区的记录 - //latest:当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,消费新产生的该分区下的数据(在消费者启动之后生成的记录) - //none:当各分区都存在已提交的offset时,从提交的offset开始消费;只要有一个分区不存在已提交的offset,则抛出异常 - propsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset); - //两次poll之间的最大间隔,默认值为5分钟。如果超过这个间隔会触发reBalance - propsMap.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, maxPollIntervalTime); - //这个参数定义了poll方法最多可以拉取多少条消息,默认值为500。如果在拉取消息的时候新消息不足500条,那有多少返回多少;如果超过500条,每次只返回500。 - //这个默认值在有些场景下太大,有些场景很难保证能够在5min内处理完500条消息, - //如果消费者无法在5分钟内处理完500条消息的话就会触发reBalance, - //然后这批消息会被分配到另一个消费者中,还是会处理不完,这样这批消息就永远也处理不完。 - //要避免出现上述问题,提前评估好处理一条消息最长需要多少时间,然后覆盖默认的max.poll.records参数 - //注:需要开启BatchListener批量监听才会生效,如果不开启BatchListener则不会出现reBalance情况 - propsMap.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, maxPollRecords); - //当broker多久没有收到consumer的心跳请求后就触发reBalance,默认值是10s - propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, sessionTimeout); - //序列化(建议使用Json,这种序列化方式可以无需额外配置传输实体类) - propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); - propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); - return propsMap; - } - - @Bean - public ConsumerFactory consumerFactory() { - - //配置消费者的 Json 反序列化的可信赖包,反序列化实体类需要 - try (StringDeserializer stringDeserializer = new StringDeserializer()) { - return new DefaultKafkaConsumerFactory<>(consumerConfigs(), new StringDeserializer(), stringDeserializer); - } - } - - @Bean - public KafkaListenerContainerFactory> kafkaListenerContainerFactory() { - - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - factory.setConsumerFactory(consumerFactory()); - //在侦听器容器中运行的线程数,一般设置为 机器数*分区数 - factory.setConcurrency(concurrency); - //消费监听接口监听的主题不存在时,默认会报错,所以设置为false忽略错误 - factory.setMissingTopicsFatal(missingTopicsFatal); - //自动提交关闭,需要设置手动消息确认 - factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE); - factory.getContainerProperties().setPollTimeout(pollTimeout); - //设置为批量监听,需要用List接收 - factory.setBatchListener(true); - return factory; - } -} \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/KafkaProviderConfig.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/KafkaProviderConfig.java deleted file mode 100644 index 92fe8016..00000000 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/config/KafkaProviderConfig.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.mqttsnet.thinglinks.link.common.config; - -import org.apache.kafka.clients.producer.ProducerConfig; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.kafka.core.DefaultKafkaProducerFactory; -import org.springframework.kafka.core.KafkaTemplate; -import org.springframework.kafka.core.ProducerFactory; -import org.springframework.kafka.support.serializer.JsonSerializer; -import org.springframework.kafka.transaction.KafkaTransactionManager; - -import java.util.HashMap; -import java.util.Map; - -/** - * @program: thinglinks - * @description: KafkaProviderConfig - * @packagename: com.mqttsnet.thinglinks.common.kafka.config - * @author: ShiHuan Sun - * @e-mainl: 13733918655@163.com - * @date: 2023-06-18 11:28 - **/ -@Configuration -public class KafkaProviderConfig { - - - @Value("${spring.kafka.thingLinks.producer.bootstrap-servers}") - private String bootstrapServers; - @Value("${spring.kafka.thingLinks.producer.transaction-id-prefix}") - private String transactionIdPrefix; - @Value("${spring.kafka.thingLinks.producer.acks}") - private String acks; - @Value("${spring.kafka.thingLinks.producer.retries}") - private String retries; - @Value("${spring.kafka.thingLinks.producer.batch-size}") - private String batchSize; - @Value("${spring.kafka.thingLinks.producer.buffer-memory}") - private String bufferMemory; - - @Bean - public Map producerConfigs() { - - Map props = new HashMap<>(16); - props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); - //acks=0 : 生产者在成功写入消息之前不会等待任何来自服务器的响应。 - //acks=1 : 只要集群的首领节点收到消息,生产者就会收到一个来自服务器成功响应。 - //acks=all :只有当所有参与复制的节点全部收到消息时,生产者才会收到一个来自服务器的成功响应。 - //开启事务必须设为all - props.put(ProducerConfig.ACKS_CONFIG, acks); - //发生错误后,消息重发的次数,开启事务必须大于0 - props.put(ProducerConfig.RETRIES_CONFIG, retries); - //当多个消息发送到相同分区时,生产者会将消息打包到一起,以减少请求交互. 而不是一条条发送 - //批次的大小可以通过batch.size 参数设置.默认是16KB - //较小的批次大小有可能降低吞吐量(批次大小为0则完全禁用批处理)。 - //比如说,kafka里的消息5秒钟Batch才凑满了16KB,才能发送出去。那这些消息的延迟就是5秒钟 - //实测batchSize这个参数没有用 - props.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize); - //有的时刻消息比较少,过了很久,比如5min也没有凑够16KB,这样延时就很大,所以需要一个参数. 再设置一个时间,到了这个时间, - //即使数据没达到16KB,也将这个批次发送出去 - props.put(ProducerConfig.LINGER_MS_CONFIG, "5000"); - //生产者内存缓冲区的大小 - props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, bufferMemory); - //反序列化,和生产者的序列化方式对应 - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); - props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); - return props; - } - - @Bean - public ProducerFactory producerFactory() { - - DefaultKafkaProducerFactory factory = new DefaultKafkaProducerFactory<>(producerConfigs()); - //开启事务,会导致 LINGER_MS_CONFIG 配置失效 - factory.setTransactionIdPrefix(transactionIdPrefix); - return factory; - } - - @Bean - public KafkaTransactionManager kafkaTransactionManager(ProducerFactory producerFactory) { - - return new KafkaTransactionManager<>(producerFactory); - } - - @Bean - public KafkaTemplate thingLinksKafkaTemplate() { - - return new KafkaTemplate<>(producerFactory()); - } -} \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/kafka/DeviceActionMessageKafkaConsumer.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/kafka/DeviceActionMessageKafkaConsumer.java deleted file mode 100644 index 5b09dc6e..00000000 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/kafka/DeviceActionMessageKafkaConsumer.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.mqttsnet.thinglinks.link.common.consumer.kafka; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.mqttsnet.thinglinks.common.core.enums.MqttEvent; -import com.mqttsnet.thinglinks.common.kafka.constant.ConsumerKafkaTopicConstant; -import com.mqttsnet.thinglinks.link.service.device.DeviceActionService; -import com.mqttsnet.thinglinks.link.service.device.DeviceDatasService; -import lombok.extern.slf4j.Slf4j; -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.kafka.annotation.KafkaListener; -import org.springframework.scheduling.annotation.Async; - -import java.util.Objects; - -/** - * @Description: Mqtt动作消息消费(kafka模式) - * @Author: menffy - * @E-mail: 13733918655@163.com - * @Website: http://thinglinks.mqttsnet.com - * @CreateDate: 2023/08/08 - * @UpdateUser: menffy - * @UpdateDate: 2023/08/08 - * @UpdateRemark: https://mqttsnet.yuque.com/gt6zkc/thinglinks/yhzgnpduyo8adxgs - * @Version: 1.0 - */ -@Slf4j -//@Component -@Deprecated -public class DeviceActionMessageKafkaConsumer { - @Autowired - private DeviceActionService deviceActionService; - @Autowired - private DeviceDatasService deviceDatasService; - - @Async("linkAsync") - @KafkaListener(topics = { - ConsumerKafkaTopicConstant.THINGLINKS_LINK_MQTT_MSG, - ConsumerKafkaTopicConstant.THINGLINKS_CLIENT_CONNECTED_TOPIC, - ConsumerKafkaTopicConstant.THINGLINKS_CLIENT_DISCONNECTED_TOPIC, - ConsumerKafkaTopicConstant.THINGLINKS_SERVER_CONNECTED_TOPIC, - ConsumerKafkaTopicConstant.THINGLINKS_DEVICE_KICKED_TOPIC, - ConsumerKafkaTopicConstant.THINGLINKS_SUBSCRIPTION_ACKED_TOPIC, - ConsumerKafkaTopicConstant.THINGLINKS_UNSUBSCRIPTION_ACKED_TOPIC, - ConsumerKafkaTopicConstant.THINGLINKS_DISTRIBUTION_ERROR_TOPIC, - ConsumerKafkaTopicConstant.THINGLINKS_DISTRIBUTION_COMPLETED_TOPIC}) - public void onMessage(ConsumerRecord record) { - if (null == record) { - log.warn("message cannot be empty {}", record); - return; - } - log.info("ThingLinks物联网平台数据消费-->Received message={}", record); - JSONObject thinglinksMessage = JSON.parseObject(String.valueOf(record.value())); - try { - MqttEvent event = MqttEvent.getMqttEventEnum(thinglinksMessage.get("event").toString()); - switch (Objects.requireNonNull(event)) { - case CONNECT: - deviceActionService.insertEvent(thinglinksMessage); - deviceActionService.connectEvent(thinglinksMessage); - break; - case CLOSE: - case DISCONNECT: - deviceActionService.insertEvent(thinglinksMessage); - deviceActionService.closeEvent(thinglinksMessage); - break; - case PUBLISH: - deviceDatasService.insertBaseDatas(thinglinksMessage); - break; - case SUBSCRIBE: - deviceActionService.insertEvent(thinglinksMessage); - break; - case UNSUBSCRIBE: - deviceActionService.insertEvent(thinglinksMessage); - break; - case PING: - deviceActionService.refreshDeviceCache(thinglinksMessage); - break; - default: - } - } catch (Exception e) { - log.error("ThingLinks物联网平台数据消费-->消费失败,失败原因:{}", e.getMessage()); - } - } -} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/rocketmq/DeviceActionMessageRocketmqConsumer.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/rocketmq/DeviceActionMessageRocketmqConsumer.java deleted file mode 100644 index 0f0bfbb5..00000000 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/consumer/rocketmq/DeviceActionMessageRocketmqConsumer.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.mqttsnet.thinglinks.link.common.consumer.rocketmq; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.mqttsnet.thinglinks.common.core.enums.MqttEvent; -import com.mqttsnet.thinglinks.common.rocketmq.constant.ConsumerGroupConstant; -import com.mqttsnet.thinglinks.common.rocketmq.constant.ConsumerTopicConstant; -import com.mqttsnet.thinglinks.link.service.device.DeviceActionService; -import com.mqttsnet.thinglinks.link.service.device.DeviceDatasService; -import lombok.extern.slf4j.Slf4j; -import org.apache.rocketmq.spring.annotation.MessageModel; -import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; -import org.apache.rocketmq.spring.core.RocketMQListener; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.scheduling.annotation.Async; - -import java.util.Objects; - -/** - * @Description: Mqtt动作消息消费(Rocketmq模式) - * @Author: ShiHuan Sun - * @E-mail: 13733918655@163.com - * @Website: http://thinglinks.mqttsnet.com - * @CreateDate: 2021/11/22$ 16:11$ - * @UpdateUser: ShiHuan Sun - * @UpdateDate: 2021/11/22$ 16:11$ - * @UpdateRemark: 修改内容 - * @Version: 1.0 - */ -@Slf4j -//@Component -@Deprecated -@RocketMQMessageListener(consumerGroup = ConsumerGroupConstant.THINGLINKS_BROKER_GROUP, topic = ConsumerTopicConstant.THINGLINKS_LINK_MQTT_MSG, messageModel = MessageModel.CLUSTERING) -public class DeviceActionMessageRocketmqConsumer implements RocketMQListener { - @Autowired - private DeviceActionService deviceActionService; - @Autowired - private DeviceDatasService deviceDatasService; - - @Async("linkAsync") - @Override - public void onMessage(Object message) { - if (null == message) { - log.warn("message cannot be empty {}", message); - return; - } - log.info("ThingLinks物联网平台数据消费-->Received message={}", message); - JSONObject thinglinksMessage = JSON.parseObject(String.valueOf(message)); - try { - MqttEvent event = MqttEvent.getMqttEventEnum(thinglinksMessage.get("event").toString()); - switch (Objects.requireNonNull(event)) { - case CONNECT: - deviceActionService.insertEvent(thinglinksMessage); - deviceActionService.connectEvent(thinglinksMessage); - break; - case CLOSE: - case DISCONNECT: - deviceActionService.insertEvent(thinglinksMessage); - deviceActionService.closeEvent(thinglinksMessage); - break; - case PUBLISH: - deviceDatasService.insertBaseDatas(thinglinksMessage); - break; - case SUBSCRIBE: - deviceActionService.insertEvent(thinglinksMessage); - break; - case UNSUBSCRIBE: - deviceActionService.insertEvent(thinglinksMessage); - break; - case PING: - deviceActionService.refreshDeviceCache(thinglinksMessage); - break; - default: - } - } catch (Exception e) { - log.error("ThingLinks物联网平台数据消费-->消费失败,失败原因:{}", e.getMessage()); - } - } -} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceController.java index b6e0436d..194834c3 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceController.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceController.java @@ -14,10 +14,7 @@ import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; import com.mqttsnet.thinglinks.link.api.domain.device.model.DeviceParams; import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; -import com.mqttsnet.thinglinks.link.api.domain.vo.param.OtaCommandResponseParam; -import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoAddSubDeviceParam; -import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoQueryDeviceParam; -import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoUpdateSubDeviceStatusParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.*; import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoQueryDeviceResultVO; @@ -26,7 +23,7 @@ import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -446,10 +443,10 @@ public R queryDeviceByHttp(@RequestBody TopoQueryDevice public R saveOtaUpgradeRecordByMqtt(@Valid @RequestBody OtaCommandResponseParam otaCommandResponseParam) { try { // Call the service method to save the record - OtaCommandResponseParam savedRecord = otaUpgradeRecordsService.saveOtaUpgradeRecordByMqtt(otaCommandResponseParam); +// OtaCommandResponseParam savedRecord = otaUpgradeRecordsService.saveOtaUpgradeRecordByMqtt(otaCommandResponseParam); // Return a successful response entity with the saved record - return R.ok(savedRecord); + return R.ok(); } catch (Exception e) { // Log the exception and return an error response entity // Assuming R.fail() is a method to create a failure response @@ -469,10 +466,10 @@ public R saveOtaUpgradeRecordByMqtt(@Valid @RequestBody public R saveUpgradeRecordByHttp(@Valid @RequestBody OtaCommandResponseParam otaCommandResponseParam) { try { // Call the service method to save the record - OtaCommandResponseParam savedRecord = otaUpgradeRecordsService.saveUpgradeRecordByHttp(otaCommandResponseParam); +// OtaCommandResponseParam savedRecord = otaUpgradeRecordsService.saveUpgradeRecordByHttp(otaCommandResponseParam); // Return a successful response wrapper with the saved record - return R.ok(savedRecord); + return R.ok(); } catch (Exception e) { // Log the exception and return a failure response wrapper // Assuming R.fail() is a method to create a failure response diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/kafka/KafkaController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/kafka/KafkaController.java deleted file mode 100644 index 3715d1d6..00000000 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/kafka/KafkaController.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.mqttsnet.thinglinks.link.controller.kafka; - -import org.apache.kafka.clients.producer.ProducerRecord; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.kafka.core.KafkaTemplate; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.Map; - -/** - * @Description: kafka接口 - * @Author: ShiHuan Sun - * @E-mail: 13733918655@163.com - * @Website: http://thinglinks.mqttsnet.com - * @CreateDate: 2021/12/1$ 11:39$ - * @UpdateUser: ShiHuan Sun - * @UpdateDate: 2021/12/1$ 11:39$ - * @UpdateRemark: 修改内容 - * @Version: 1.0 - */ -@RestController -@RequestMapping("/kafkaMessage") -public class KafkaController { - - @Autowired - KafkaTemplate thingLinksProKafkaTemplate; - - @Transactional - @PostMapping("/send") - public String kafkaMessageSend(@RequestBody Map params) { - thingLinksProKafkaTemplate.send(new ProducerRecord<>(String.valueOf(params.get("topic")), String.valueOf(params.get("msg")))); - return "success-" + params.get("topic"); - } -} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/DeviceService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/DeviceService.java index 222f89df..be2835d1 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/DeviceService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/DeviceService.java @@ -1,8 +1,11 @@ package com.mqttsnet.thinglinks.link.service.device; -import com.mqttsnet.thinglinks.common.core.web.page.TableDataInfo; import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; import com.mqttsnet.thinglinks.link.api.domain.device.model.DeviceParams; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.*; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoQueryDeviceResultVO; import java.util.Collection; import java.util.List; @@ -162,7 +165,7 @@ public interface DeviceService { List findAllByProductIdentification(String productIdentification); - Device selectByProductIdentificationAndDeviceIdentification(String productIdentification,String deviceIdentification); + Device selectByProductIdentificationAndDeviceIdentification(String productIdentification, String deviceIdentification); /** * 查询设备详细信息 @@ -175,14 +178,97 @@ public interface DeviceService { /** * 查询普通设备影子数据 * - * @param ids 需要查询的普通设备id + * @param ids 需要查询的普通设备id * @param startTime 开始时间 格式:yyyy-MM-dd HH:mm:ss - * @param endTime 结束时间 格式:yyyy-MM-dd HH:mm:ss + * @param endTime 结束时间 格式:yyyy-MM-dd HH:mm:ss * @return 普通设备影子数据 */ public Map>> getDeviceShadow(String ids, String startTime, String endTime); - public List selectDeviceByDeviceIdentificationList( List deviceIdentificationList); + public List selectDeviceByDeviceIdentificationList(List deviceIdentificationList); + + /** + * MQTT协议下添加子设备 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 添加结果 + */ + TopoAddDeviceResultVO saveSubDeviceByMqtt(TopoAddSubDeviceParam topoAddSubDeviceParam); + + /** + * HTTP协议下添加子设备 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 添加结果 + */ + TopoAddDeviceResultVO saveSubDeviceByHttp(TopoAddSubDeviceParam topoAddSubDeviceParam); + + /** + * MQTT协议下更新子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 更新参数 + * @return {@link TopoDeviceOperationResultVO} 更新结果 + */ + TopoDeviceOperationResultVO updateSubDeviceConnectStatusByMqtt(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam); + + /** + * Http协议下更新子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 更新参数 + * @return {@link TopoDeviceOperationResultVO} 更新结果 + */ + TopoDeviceOperationResultVO updateSubDeviceConnectStatusByHttp(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam); + + /** + * MQTT协议下删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 删除结果 + */ + TopoDeviceOperationResultVO deleteSubDeviceByMqtt(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam); + + + /** + * Http协议下删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 删除结果 + */ + TopoDeviceOperationResultVO deleteSubDeviceByHttp(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam); + + /** + * MQTT协议下上报设备数据 + * + * @param topoDeviceDataReportParam 上报参数 + * @return {@link TopoDeviceOperationResultVO} 上报结果 + */ + TopoDeviceOperationResultVO deviceDataReportByMqtt(TopoDeviceDataReportParam topoDeviceDataReportParam); + + + /** + * Http协议下上报设备数据 + * + * @param topoDeviceDataReportParam 上报参数 + * @return {@link TopoDeviceOperationResultVO} 上报结果 + */ + TopoDeviceOperationResultVO deviceDataReportByHttp(TopoDeviceDataReportParam topoDeviceDataReportParam); + + + /** + * Queries device information using the MQTT protocol. + * + * @param topoQueryDeviceParam The device query parameters. + * @return {@link TopoQueryDeviceResultVO} The result of the device query. + */ + TopoQueryDeviceResultVO queryDeviceByMqtt(TopoQueryDeviceParam topoQueryDeviceParam); + + /** + * Queries device information using the HTTP protocol. + * + * @param topoQueryDeviceParam The device query parameters. + * @return {@link TopoQueryDeviceResultVO} The result of the device query. + */ + TopoQueryDeviceResultVO queryDeviceByHttp(TopoQueryDeviceParam topoQueryDeviceParam); } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceActionServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceActionServiceImpl.java index 294b09de..e181f6a3 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceActionServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceActionServiceImpl.java @@ -2,6 +2,7 @@ import com.alibaba.fastjson.JSONObject; import com.alibaba.nacos.shaded.com.google.gson.Gson; +import com.mqttsnet.thinglinks.common.core.constant.CacheConstants; import com.mqttsnet.thinglinks.common.core.constant.Constants; import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatusEnum; import com.mqttsnet.thinglinks.common.core.utils.DateUtils; diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java index 8e0ce933..46f3bdb0 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java @@ -19,6 +19,10 @@ import com.mqttsnet.thinglinks.link.api.domain.device.model.DeviceParams; import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; import com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductServices; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.*; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoQueryDeviceResultVO; import com.mqttsnet.thinglinks.link.mapper.device.DeviceMapper; import com.mqttsnet.thinglinks.link.service.device.DeviceLocationService; import com.mqttsnet.thinglinks.link.service.device.DeviceService; @@ -557,5 +561,115 @@ public Boolean createCommonDeviceTDSubtable(Device device) { public List selectDeviceByDeviceIdentificationList(List deviceIdentificationList) { return deviceMapper.selectDeviceByDeviceIdentificationList(deviceIdentificationList); } + + /** + * MQTT协议下添加子设备 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 添加结果 + */ + @Override + public TopoAddDeviceResultVO saveSubDeviceByMqtt(TopoAddSubDeviceParam topoAddSubDeviceParam) { + return null; + } + + /** + * HTTP协议下添加子设备 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 添加结果 + */ + @Override + public TopoAddDeviceResultVO saveSubDeviceByHttp(TopoAddSubDeviceParam topoAddSubDeviceParam) { + return null; + } + + /** + * MQTT协议下更新子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 更新参数 + * @return {@link TopoDeviceOperationResultVO} 更新结果 + */ + @Override + public TopoDeviceOperationResultVO updateSubDeviceConnectStatusByMqtt(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { + return null; + } + + /** + * Http协议下更新子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 更新参数 + * @return {@link TopoDeviceOperationResultVO} 更新结果 + */ + @Override + public TopoDeviceOperationResultVO updateSubDeviceConnectStatusByHttp(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { + return null; + } + + /** + * MQTT协议下删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 删除结果 + */ + @Override + public TopoDeviceOperationResultVO deleteSubDeviceByMqtt(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { + return null; + } + + /** + * Http协议下删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 删除结果 + */ + @Override + public TopoDeviceOperationResultVO deleteSubDeviceByHttp(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { + return null; + } + + /** + * MQTT协议下上报设备数据 + * + * @param topoDeviceDataReportParam 上报参数 + * @return {@link TopoDeviceOperationResultVO} 上报结果 + */ + @Override + public TopoDeviceOperationResultVO deviceDataReportByMqtt(TopoDeviceDataReportParam topoDeviceDataReportParam) { + return null; + } + + /** + * Http协议下上报设备数据 + * + * @param topoDeviceDataReportParam 上报参数 + * @return {@link TopoDeviceOperationResultVO} 上报结果 + */ + @Override + public TopoDeviceOperationResultVO deviceDataReportByHttp(TopoDeviceDataReportParam topoDeviceDataReportParam) { + return null; + } + + /** + * Queries device information using the MQTT protocol. + * + * @param topoQueryDeviceParam The device query parameters. + * @return {@link TopoQueryDeviceResultVO} The result of the device query. + */ + @Override + public TopoQueryDeviceResultVO queryDeviceByMqtt(TopoQueryDeviceParam topoQueryDeviceParam) { + return null; + } + + /** + * Queries device information using the HTTP protocol. + * + * @param topoQueryDeviceParam The device query parameters. + * @return {@link TopoQueryDeviceResultVO} The result of the device query. + */ + @Override + public TopoQueryDeviceResultVO queryDeviceByHttp(TopoQueryDeviceParam topoQueryDeviceParam) { + return null; + } } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServiceImpl.java index ba4f3e3c..4b44f868 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServiceImpl.java @@ -16,8 +16,6 @@ import com.mqttsnet.thinglinks.common.core.utils.bean.BeanUtils; import com.mqttsnet.thinglinks.common.core.web.domain.AjaxResult; import com.mqttsnet.thinglinks.common.redis.service.RedisService; -import com.mqttsnet.thinglinks.common.rocketmq.constant.ConsumerTopicConstant; -import com.mqttsnet.thinglinks.common.rocketmq.domain.MQMessage; import com.mqttsnet.thinglinks.common.security.service.TokenService; import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; import com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductProperties; @@ -35,7 +33,6 @@ import com.mqttsnet.thinglinks.tdengine.api.domain.Fields; import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDto; import lombok.extern.slf4j.Slf4j; -import org.apache.rocketmq.spring.core.RocketMQTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; @@ -82,8 +79,6 @@ public class ProductServiceImpl implements ProductService { private RemoteTdEngineService remoteTdEngineService; @Autowired private RedisService redisService; - @Autowired - private RocketMQTemplate rocketMQTemplate; /** * 数据库名称 @@ -658,15 +653,15 @@ public List createSuperTableDataModel(Long[] productIds, Boolean log.info("缓存超级表数据模型:{}", JSON.toJSONString(superTableDto)); superTableDtoList.add(superTableDto); if (Boolean.TRUE.equals(InitializeOrNot)) { - //推送RocketMq消息初始化超级表 - MQMessage mqMessage = new MQMessage(); + //推送RocketMq消息初始化超级表 TODO 改为API调用 + /*MQMessage mqMessage = new MQMessage(); mqMessage.setTopic(ConsumerTopicConstant.PRODUCTSUPERTABLE_CREATEORUPDATE); final JSONObject jsonObject = new JSONObject(); jsonObject.put("type", "create"); jsonObject.put("msg", JSON.toJSONString(superTableDto)); mqMessage.setMessage(jsonObject.toJSONString()); - rocketMQTemplate.convertAndSend(mqMessage.getTopic(), mqMessage.getMessage()); + rocketMQTemplate.convertAndSend(mqMessage.getTopic(), mqMessage.getMessage());*/ } } } diff --git a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/service/impl/RuleDeviceLinkageServiceImpl.java b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/service/impl/RuleDeviceLinkageServiceImpl.java index 78cf36e0..8263258b 100644 --- a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/service/impl/RuleDeviceLinkageServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/service/impl/RuleDeviceLinkageServiceImpl.java @@ -7,8 +7,8 @@ import com.mqttsnet.thinglinks.common.core.enums.FieldTypeEnum; import com.mqttsnet.thinglinks.common.core.enums.OperatorEnum; import com.mqttsnet.thinglinks.common.core.enums.TriggeringEnum; +import com.mqttsnet.thinglinks.common.core.mqs.ConsumerTopicConstant; import com.mqttsnet.thinglinks.common.core.utils.CompareUtil; -import com.mqttsnet.thinglinks.common.rocketmq.constant.ConsumerTopicConstant; import com.mqttsnet.thinglinks.common.rocketmq.domain.MQMessage; import com.mqttsnet.thinglinks.link.api.*; import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; @@ -90,7 +90,7 @@ public class RuleDeviceLinkageServiceImpl implements RuleDeviceLinkageService { @Transactional public void triggerDeviceLinkageByRuleIdentification(String ruleIdentification) { MQMessage mqMessage = new MQMessage(); - mqMessage.setTopic(ConsumerTopicConstant.THINGLINKS_RULE_TRIGGER); + mqMessage.setTopic(ConsumerTopicConstant.Rule.THINGLINKS_RULE_TRIGGER); JSONObject jsonObject = new JSONObject(); jsonObject.put("msg", ruleIdentification); mqMessage.setMessage(jsonObject.toJSONString()); diff --git a/thinglinks-modules/thinglinks-modules-rule/src/main/resources/bootstrap.yml b/thinglinks-modules/thinglinks-modules-rule/src/main/resources/bootstrap.yml index 4a9af6db..34e7f925 100644 --- a/thinglinks-modules/thinglinks-modules-rule/src/main/resources/bootstrap.yml +++ b/thinglinks-modules/thinglinks-modules-rule/src/main/resources/bootstrap.yml @@ -33,7 +33,7 @@ spring: refresh: false - dataId: database.yml refresh: true - - dataId: kafka.yml + - dataId: rocketmq.yml refresh: false username: @nacos.username@ password: @nacos.password@ \ No newline at end of file From fe55dddb7aa22bb47354703236bbd50d50eb5b67 Mon Sep 17 00:00:00 2001 From: wangfan1997 <1624212366@qq.com> Date: Sat, 16 Mar 2024 00:11:36 +0800 Subject: [PATCH 09/35] =?UTF-8?q?add=20ota=E5=9F=BA=E6=9C=AC=E5=8A=9F?= =?UTF-8?q?=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/sql/changeRecord/1.2.0.RELEASE.sql | 12 +- .../cache/product/ProductModelCacheVO.java | 5 + .../thinglinks-modules-link/pom.xml | 4 + .../link/ThingLinksLinkApplication.java | 13 +- .../cache/service/DeviceCacheService.java | 6 +- .../ota/OtaUpgradeRecordsController.java | 102 +++++++++++ .../ota/OtaUpgradeTasksController.java | 91 ++++++++++ .../controller/ota/OtaUpgradesController.java | 77 ++++++++ .../mapper/ota/OtaUpgradeRecordsMapper.java | 24 +++ .../mapper/ota/OtaUpgradeTasksMapper.java | 31 ++++ .../link/mapper/ota/OtaUpgradesMapper.java | 29 +++ .../service/ota/OtaUpgradeRecordsService.java | 40 +++++ .../service/ota/OtaUpgradeTasksService.java | 61 +++++++ .../link/service/ota/OtaUpgradesService.java | 33 ++++ .../impl/OtaUpgradeRecordsServiceImpl.java | 108 +++++++++++ .../ota/impl/OtaUpgradeTasksServiceImpl.java | 169 ++++++++++++++++++ .../ota/impl/OtaUpgradesServiceImpl.java | 145 +++++++++++++++ .../link/ota/OtaUpgradeRecordsMapper.xml | 69 +++++++ .../mapper/link/ota/OtaUpgradeTasksMapper.xml | 66 +++++++ .../mapper/link/ota/OtaUpgradesMapper.xml | 156 ++++++++++++++++ 20 files changed, 1232 insertions(+), 9 deletions(-) create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradeRecordsController.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradeTasksController.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradesController.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/ota/OtaUpgradeRecordsMapper.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/ota/OtaUpgradeTasksMapper.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/ota/OtaUpgradesMapper.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradeRecordsService.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradeTasksService.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradesService.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradeRecordsServiceImpl.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradeTasksServiceImpl.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradesServiceImpl.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/ota/OtaUpgradeRecordsMapper.xml create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/ota/OtaUpgradeTasksMapper.xml create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/ota/OtaUpgradesMapper.xml diff --git a/doc/sql/changeRecord/1.2.0.RELEASE.sql b/doc/sql/changeRecord/1.2.0.RELEASE.sql index ccdad5f8..79f0ebd2 100644 --- a/doc/sql/changeRecord/1.2.0.RELEASE.sql +++ b/doc/sql/changeRecord/1.2.0.RELEASE.sql @@ -22,9 +22,9 @@ CREATE TABLE `ota_upgrades` `description` varchar(255) DEFAULT '' COMMENT '升级包功能描述', `custom_info` longtext COMMENT '自定义信息', `remark` varchar(255) DEFAULT '' COMMENT '描述', - `created_by` bigint(20) DEFAULT NULL COMMENT '创建人', + `created_by` varchar(20) DEFAULT NULL COMMENT '创建人', `created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `updated_by` bigint(20) DEFAULT NULL COMMENT '更新人', + `updated_by` varchar(20) DEFAULT NULL COMMENT '更新人', `updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`) USING BTREE, KEY `idx_app_id` (`app_id`) USING BTREE COMMENT '应用ID', @@ -41,9 +41,9 @@ CREATE TABLE `ota_upgrade_tasks` `scheduled_time` datetime DEFAULT NULL COMMENT '计划执行时间', `description` varchar(255) DEFAULT '' COMMENT '任务描述', `remark` varchar(255) DEFAULT '' COMMENT '描述', - `created_by` bigint(20) DEFAULT NULL COMMENT '创建人', + `created_by` varchar(20) DEFAULT NULL COMMENT '创建人', `created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `updated_by` bigint(20) DEFAULT NULL COMMENT '更新人', + `updated_by` varchar(20) DEFAULT NULL COMMENT '更新人', `updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`) USING BTREE, KEY `idx_upgrade_id` (`upgrade_id`) USING BTREE COMMENT '升级包ID' @@ -64,9 +64,9 @@ CREATE TABLE `ota_upgrade_records` `failure_details` longtext COMMENT '升级失败详细信息', `log_details` longtext COMMENT '升级过程日志', `remark` varchar(255) DEFAULT '' COMMENT '描述', - `created_by` bigint(20) DEFAULT NULL COMMENT '创建人', + `created_by` varchar(20) DEFAULT NULL COMMENT '创建人', `created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '记录创建时间', - `updated_by` bigint(20) DEFAULT NULL COMMENT '更新人', + `updated_by` varchar(20) DEFAULT NULL COMMENT '更新人', `updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`) USING BTREE, UNIQUE KEY `idx_task_id_device_identification` (`task_id`,`device_identification`) USING BTREE, diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductModelCacheVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductModelCacheVO.java index 6d095abd..38fcd65b 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductModelCacheVO.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductModelCacheVO.java @@ -1,11 +1,13 @@ package com.mqttsnet.thinglinks.link.api.domain.cache.product; +import cn.hutool.core.map.MapUtil; import com.mqttsnet.thinglinks.link.api.domain.product.model.ProductModel; import io.swagger.annotations.ApiModel; import lombok.*; import lombok.experimental.Accessors; import java.io.Serializable; +import java.util.Map; /** *

@@ -22,7 +24,10 @@ @Accessors(chain = true) @EqualsAndHashCode(callSuper = false) @Builder +@AllArgsConstructor @ApiModel(value = "ProductModelCacheVO", description = "产品模型缓存VO") public class ProductModelCacheVO extends ProductModel implements Serializable { + private static final long serialVersionUID = 1L; + private Map echoMap = MapUtil.newHashMap(); } diff --git a/thinglinks-modules/thinglinks-modules-link/pom.xml b/thinglinks-modules/thinglinks-modules-link/pom.xml index ef4bea24..6f907f4f 100644 --- a/thinglinks-modules/thinglinks-modules-link/pom.xml +++ b/thinglinks-modules/thinglinks-modules-link/pom.xml @@ -93,6 +93,10 @@ thinglinks-api-broker ${thinglinks.version} + + commons-collections + commons-collections + diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/ThingLinksLinkApplication.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/ThingLinksLinkApplication.java index a1653902..dd2e7f16 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/ThingLinksLinkApplication.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/ThingLinksLinkApplication.java @@ -3,10 +3,15 @@ import com.mqttsnet.thinglinks.common.security.annotation.EnableCustomConfig; import com.mqttsnet.thinglinks.common.security.annotation.EnableRyFeignClients; import com.mqttsnet.thinglinks.common.swagger.annotation.EnableCustomSwagger2; +import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.CrossOrigin; +import java.net.InetAddress; + /** * Link * @@ -20,11 +25,15 @@ //maxAge飞行前响应的缓存持续时间的最大年龄,简单来说就是Cookie的有效期 单位为秒 //若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失 @CrossOrigin(origins = "*", maxAge = 3600) +@Slf4j @SpringBootApplication(scanBasePackages = {"com.mqttsnet.thinglinks"}) public class ThingLinksLinkApplication { public static void main(String[] args) throws Exception { - SpringApplication.run(ThingLinksLinkApplication.class, args); - System.out.println("(♥◠‿◠)ノ゙ Link模块启动成功 ლ(´ڡ`ლ)゙ "); + ConfigurableApplicationContext application = SpringApplication.run(ThingLinksLinkApplication.class, args); + Environment env = application.getEnvironment(); + log.info("\n----------------------------------------------------------\n\t" + "应用 '{}' 启动成功! 访问连接:\n\t" + "Swagger文档: \t\thttp://{}:{}/swagger-ui.html\n\t" + + "数据库监控: \t\thttp://{}:{}/druid\n" + "----------------------------------------------------------", env.getProperty("spring.application.name"), + InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port", "8080"), "127.0.0.1", env.getProperty("server.port", "8080")); } } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java index 4e6ace25..a477ba86 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java @@ -11,6 +11,7 @@ //import com.mqttsnet.thinglinks.link.service.product.ProductService; //import lombok.RequiredArgsConstructor; //import lombok.extern.slf4j.Slf4j; +//import org.apache.ibatis.cache.CacheKey; //import org.springframework.stereotype.Service; // //import java.util.*; @@ -56,7 +57,10 @@ // List deviceList = IntStream.range(0, totalPages) // .mapToObj(currentPage -> { // Page page = new Page<>(currentPage, PAGE_SIZE); -// Page content = deviceService.page(page, null); +// HashMap pageHashMap = new HashMap<>(); +// Device device = new Device(); +// device.setParams(pageHashMap); +// Page content = deviceService.findPageAll(page, null); // return Optional.ofNullable(content) // .map(Page::getRecords) // .orElse(Collections.emptyList()); diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradeRecordsController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradeRecordsController.java new file mode 100644 index 00000000..4ff781bb --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradeRecordsController.java @@ -0,0 +1,102 @@ +package com.mqttsnet.thinglinks.link.controller.ota; + +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.common.core.web.controller.BaseController; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.save.OtaUpgradeRecordsSaveVO; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.update.OtaUpgradeRecordsUpdateVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.OtaCommandResponseParam; +import com.mqttsnet.thinglinks.link.service.ota.OtaUpgradeRecordsService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import javax.validation.Valid; + +/** + *

+ * 前端控制器 + * OTA升级记录表 + *

+ * + * @author mqttsnet + * @date 2024-01-12 22:42:04 + * @create [2024-01-12 22:42:04] [mqttsnet] + */ +@Slf4j +@Validated +@RestController +@RequestMapping("/otaUpgradeRecords") +@Api(value = "OtaUpgradeRecords", tags = "OTA升级记录表") +public class OtaUpgradeRecordsController extends BaseController { + + @Resource + private OtaUpgradeRecordsService otaUpgradeRecordsService; + + @ApiOperation(value = "保存OTA升级记录", httpMethod = "POST", notes = "保存一个新的OTA升级记录") + @PostMapping("/saveOtaUpgradeRecord") + public R saveOtaUpgradeRecord(@Valid @RequestBody OtaUpgradeRecordsSaveVO saveVO) { + // 从服务中保存OTA升级记录 + OtaUpgradeRecordsSaveVO savedRecord = otaUpgradeRecordsService.saveOtaUpgradeRecord(saveVO); + // 返回成功响应实体,包含已保存的记录 + return R.ok(savedRecord); + } + + @ApiOperation(value = "更新OTA升级记录", httpMethod = "PUT", notes = "更新一个现有的OTA升级记录") + @PutMapping("/updateOtaUpgradeRecord") + public R updateOtaUpgradeRecord(@Valid @RequestBody OtaUpgradeRecordsUpdateVO updateVO) { + // 从服务中更新OTA升级记录 + OtaUpgradeRecordsUpdateVO updatedRecord = otaUpgradeRecordsService.updateOtaUpgradeRecord(updateVO); + // 返回成功响应实体,包含已更新的记录 + return R.ok(updatedRecord); + } + + /** + * 从MQTT消息接收并保存新的OTA升级记录。此端点 + * 从MQTT消息体捕获命令响应参数并持久化它们。 + * + * @param otaCommandResponseParam 来自通过MQTT发送的OTA命令的响应参数。 + * @return {@link R< OtaCommandResponseParam >} 包含已保存OTA升级记录的响应实体。 + */ + @ApiOperation(value = "保存OTA升级记录", httpMethod = "POST", notes = "从MQTT消息数据保存一个新的OTA升级记录。") + @PostMapping("/saveOtaUpgradeRecordByMqtt") + public R saveOtaUpgradeRecordByMqtt(@Valid @RequestBody OtaCommandResponseParam otaCommandResponseParam) { + try { + // 调用服务方法保存记录 + OtaCommandResponseParam savedRecord = otaUpgradeRecordsService.saveOtaUpgradeRecordByMqtt(otaCommandResponseParam); + // 返回包含已保存记录的成功响应实体 + return R.ok(savedRecord); + } catch (Exception e) { + // 记录异常并返回错误响应实体 + return R.fail("保存OTA升级记录时出错: " + e.getMessage()); + } + } + + /** + * 从HTTP请求接收并保存新的OTA升级记录。此端点 + * 从请求体捕获命令响应参数并持久化它们。 + * + * @param otaCommandResponseParam 来自通过HTTP发送的OTA命令的响应参数。 + * @return {@link R} 包含已保存OTA升级记录的响应包装器。 + */ + @ApiOperation(value = "通过HTTP保存OTA升级记录", httpMethod = "POST", notes = "从HTTP请求数据保存一个新的OTA升级记录。") + @PostMapping("/saveUpgradeRecordByHttp") + public R saveUpgradeRecordByHttp(@Valid @RequestBody OtaCommandResponseParam otaCommandResponseParam) { + try { + // 调用服务方法保存记录 + OtaCommandResponseParam savedRecord = otaUpgradeRecordsService.saveUpgradeRecordByHttp(otaCommandResponseParam); + // 返回包含已保存记录的成功响应包装器 + return R.ok(savedRecord); + } catch (Exception e) { + // 记录异常并返回失败响应包装器 + return R.fail("通过HTTP保存OTA升级记录时出错: " + e.getMessage()); + } + } + + + +} + + diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradeTasksController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradeTasksController.java new file mode 100644 index 00000000..53972a0f --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradeTasksController.java @@ -0,0 +1,91 @@ +package com.mqttsnet.thinglinks.link.controller.ota; + +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.common.core.web.controller.BaseController; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.result.OtaUpgradeTasksResultVO; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.save.OtaUpgradeTasksSaveVO; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.update.OtaUpgradeTasksUpdateVO; +import com.mqttsnet.thinglinks.link.service.ota.OtaUpgradeTasksService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import javax.validation.Valid; +import java.time.LocalDateTime; +import java.util.List; +@Validated +@RestController +@RequestMapping("/otaUpgradeTasks") +@Api(value = "OtaUpgradeTasks", tags = "OTA升级任务表") +@Slf4j +public class OtaUpgradeTasksController extends BaseController { + + @Resource + private OtaUpgradeTasksService otaUpgradeTasksService; + + @ApiOperation(value = "保存OTA升级任务", httpMethod = "POST", notes = "保存一个新的OTA升级任务") + @PostMapping("/saveUpgradeTask") + public R saveUpgradeTask(@Valid @RequestBody OtaUpgradeTasksSaveVO saveVO) { + OtaUpgradeTasksSaveVO saveUpgradeTask = otaUpgradeTasksService.saveUpgradeTask(saveVO); + return R.ok(saveUpgradeTask); + } + + @ApiOperation(value = "更新OTA升级任务", httpMethod = "PUT", notes = "更新一个现有的OTA升级任务") + @PutMapping("/updateUpgradeTask") + public R updateUpgradeTask(@Valid @RequestBody OtaUpgradeTasksUpdateVO updateVO) { + OtaUpgradeTasksUpdateVO updatedTaskVO = otaUpgradeTasksService.updateUpgradeTask(updateVO); + return R.ok(updatedTaskVO); + } + + @ApiOperation(value = "更改OTA升级任务状态", httpMethod = "PUT", notes = "更改OTA升级任务的状态") + @PutMapping("/changeTaskStatus/{id}") + public R changeTaskStatus( + @ApiParam(value = "任务ID", required = true) @PathVariable("id") Long id, + @ApiParam(value = "新任务状态(0:待处理,1:进行中,2:已完成,3:已取消)", required = true, allowableValues = "0,1,2,3") @RequestParam("status") Integer status) { + log.info("更改任务状态 id:{}, 状态:{}", id, status); + return R.ok(otaUpgradeTasksService.changeTaskStatus(id, status)); + } + + @ApiOperation(value = "删除OTA升级任务", httpMethod = "DELETE", notes = "通过其ID删除OTA升级任务") + @DeleteMapping("/deleteOtaUpgradeTask/{id}") + public R deleteOtaUpgradeTask(@ApiParam(value = "OTA升级任务ID", required = true) @PathVariable("id") Long id) { + log.info("删除OTA升级任务 id: {}", id); + return R.ok(otaUpgradeTasksService.deleteOtaUpgradeTask(id)); + } + + @ApiOperation(value = "批量删除OTA升级任务", httpMethod = "DELETE", notes = "通过它们的ID批量删除OTA升级任务") + @DeleteMapping("/deleteOtaUpgradeTasks") + public R deleteOtaUpgradeTasks(@ApiParam(value = "OTA升级任务ID", required = true) @RequestBody List ids) { + log.info("批量删除OTA升级任务 ids: {}", ids); + boolean allDeleted = ids.stream().distinct().allMatch(id -> otaUpgradeTasksService.deleteOtaUpgradeTask(id)); + return R.ok(allDeleted); + } + + /** + * 根据其ID获取OTA升级任务的详细信息,包括相关升级包信息。 + * + * @param id 要检索的OTA升级任务的ID。 + * @return {@link OtaUpgradeTasksResultVO} OTA升级任务的详细信息。 + */ + @ApiOperation(value = "获取OTA升级任务详情", httpMethod = "GET", notes = "通过ID检索OTA升级任务的详细信息。") + @GetMapping("/details/{id}") + public R getUpgradeTaskDetails(@ApiParam(value = "OTA升级任务的唯一标识符。", required = true) @PathVariable Long id) { + return R.ok(otaUpgradeTasksService.getUpgradeTaskDetails(id)); + } + /** + * 根据开始时间及结束时间执行ota升级任务,包括相关升级包信息。 + * + * @param startTime 开始时间 + * @param endTime 结束时间 + * @return {@link OtaUpgradeTasksResultVO} OTA升级任务的详细信息。 + */ + @ApiOperation(value = " OTA远程升级", httpMethod = "GET", notes = "根据开始时间及结束时间执行ota升级任务,包括相关升级包信息。。") + @GetMapping("/upgrade") + public R> otaUpgradeTasksExecute(@RequestParam("startTime") LocalDateTime startTime, @RequestParam("endTime") LocalDateTime endTime) { + return R.ok(otaUpgradeTasksService.otaUpgradeTasksExecute(startTime, endTime)); + } +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradesController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradesController.java new file mode 100644 index 00000000..857b4c3b --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradesController.java @@ -0,0 +1,77 @@ +package com.mqttsnet.thinglinks.link.controller.ota; + +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.common.core.web.controller.BaseController; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.save.OtaUpgradesSaveVO; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.update.OtaUpgradesUpdateVO; +import com.mqttsnet.thinglinks.link.service.ota.OtaUpgradesService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import javax.validation.Valid; +import java.util.List; +@Validated +@RestController +@RequestMapping("/otaUpgrades") +@Api(value = "OtaUpgrades", tags = "OTA升级包") +@Slf4j +public class OtaUpgradesController extends BaseController { + /** + * 服务对象 + */ + @Resource + private OtaUpgradesService otaUpgradesService; + + @ApiOperation(value = "保存OTA升级包", httpMethod = "POST", notes = "保存一个新的OTA升级包") + @PostMapping("/saveUpgradePackage") + public R saveUpgradePackage(@Valid @RequestBody OtaUpgradesSaveVO saveVO) { + // 从服务中保存OTA升级包 + OtaUpgradesSaveVO createdSaveVO = otaUpgradesService.saveUpgradePackage(saveVO); + return R.ok(createdSaveVO); + } + + @ApiOperation(value = "更新OTA升级包", httpMethod = "PUT", notes = "更新一个现有的OTA升级包") + @PutMapping("/updateUpgradePackage") + public R updateUpgradePackage(@Valid @RequestBody OtaUpgradesUpdateVO updateVO) { + // 从服务中保存OTA升级包 + OtaUpgradesUpdateVO otaUpgradesUpdateVO = otaUpgradesService.updateUpgradePackage(updateVO); + return R.ok(otaUpgradesUpdateVO); + } + + @ApiOperation(value = "更新OTA升级包状态", httpMethod = "PUT", notes = "更新OTA升级包的状态") + @PutMapping("/updateOtaUpgradeStatus/{id}") + public R updateOtaUpgradeStatus( + @ApiParam(value = "包ID", required = true) @PathVariable("id") Long id, + @ApiParam(value = "新状态值(1:启用,-1:禁用)", required = true) @RequestParam("status") Integer status) { + // 记录信息 + log.info("更新OTA升级状态 id:{}, 状态:{}", id, status); + // 返回更新状态的成功响应 + return R.ok(otaUpgradesService.updateOtaUpgradeStatus(id, status)); + } + + @ApiOperation(value = "删除OTA升级包", httpMethod = "DELETE", notes = "通过其ID删除一个OTA升级包") + @DeleteMapping("/deleteOtaUpgrade/{id}") + public R deleteOtaUpgrade(@ApiParam(value = "OTA升级包ID", required = true) @PathVariable("id") Long id) { + // 记录信息 + log.info("删除OTA升级包 id: {}", id); + // 返回删除操作的成功响应 + return R.ok(otaUpgradesService.deleteOtaUpgrade(id)); + } + + @ApiOperation(value = "批量删除OTA升级包", httpMethod = "DELETE", notes = "通过它们的ID批量删除OTA升级包") + @DeleteMapping("/deleteOtaUpgrades") + public R deleteOtaUpgrades(@ApiParam(value = "OTA升级包ID", required = true) @RequestBody List ids) { + // 记录信息 + log.info("批量删除OTA升级包 ids: {}", ids); + // 检查是否所有ID对应的OTA升级包都已被删除 + boolean allDeleted = ids.stream().distinct().allMatch(id -> otaUpgradesService.deleteOtaUpgrade(id)); + // 返回批量删除操作的成功响应 + return R.ok(allDeleted); + } + +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/ota/OtaUpgradeRecordsMapper.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/ota/OtaUpgradeRecordsMapper.java new file mode 100644 index 00000000..2321129b --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/ota/OtaUpgradeRecordsMapper.java @@ -0,0 +1,24 @@ +package com.mqttsnet.thinglinks.link.mapper.ota; + +import com.mqttsnet.thinglinks.link.api.domain.ota.entity.OtaUpgradeRecords; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +@Mapper +public interface OtaUpgradeRecordsMapper { + // 插入一条OTA升级记录 + int insertOtaUpgradeRecords(OtaUpgradeRecords otaUpgradeRecords); + + // 根据ID删除一条OTA升级记录 + int deleteOtaUpgradeRecordsById(Long id); + + // 更新一条OTA升级记录 + int updateOtaUpgradeRecordsById(OtaUpgradeRecords otaUpgradeRecords); + + // 根据ID查询一条OTA升级记录 + OtaUpgradeRecords selectOtaUpgradeRecordsById(Long id); + + // 查询所有OTA升级记录 + List selectAllOtaUpgradeRecords(); +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/ota/OtaUpgradeTasksMapper.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/ota/OtaUpgradeTasksMapper.java new file mode 100644 index 00000000..77d5d144 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/ota/OtaUpgradeTasksMapper.java @@ -0,0 +1,31 @@ +package com.mqttsnet.thinglinks.link.mapper.ota; + +import com.mqttsnet.thinglinks.link.api.domain.ota.entity.OtaUpgradeTasks; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +@Mapper +public interface OtaUpgradeTasksMapper { + // 插入一条记录 + int insertOtaUpgradeTask(OtaUpgradeTasks otaUpgradeTasks); + + // 根据ID删除一条记录 + int deleteOtaUpgradeTaskById(Long id); + + // 更新一条记录 + int updateOtaUpgradeTaskById(OtaUpgradeTasks otaUpgradeTasks); + + // 根据ID查询一条记录 + OtaUpgradeTasks selectOtaUpgradeTaskById(Long id); + + // 查询所有记录 + List selectAllOtaUpgradeTasks(); + + // 根据OtaUpgradeId查询 + int getOtaUpgradeTasksByOtaUpgradeId(Long id); + + //更新状态 + int updateOtaUpgradeTasksByStatus(@Param("id") Long id, @Param("status") Integer status); +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/ota/OtaUpgradesMapper.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/ota/OtaUpgradesMapper.java new file mode 100644 index 00000000..a97e7ebd --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/ota/OtaUpgradesMapper.java @@ -0,0 +1,29 @@ +package com.mqttsnet.thinglinks.link.mapper.ota; + + +import com.mqttsnet.thinglinks.link.api.domain.ota.entity.OtaUpgrades; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +@Mapper +public interface OtaUpgradesMapper { + + // 插入一条记录 + int insertOtaUpgrades(OtaUpgrades otaUpgrades); + // 根据ID删除一条记录 + int deleteOtaUpgradeById(Long id); + + // 更新一条记录 + int updateOtaUpgradeById(OtaUpgrades otaUpgrades); + + // 根据ID查询一条记录 + OtaUpgrades selectOtaUpgradeById(Long id); + + // 查询所有记录 + List selectAllOtaUpgrades(); + + // 根据ID修改状态 + int updateOtaUpgradeByStatus(@Param("id") Long id, @Param("status") Integer status); +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradeRecordsService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradeRecordsService.java new file mode 100644 index 00000000..f38b3667 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradeRecordsService.java @@ -0,0 +1,40 @@ +package com.mqttsnet.thinglinks.link.service.ota; + +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.save.OtaUpgradeRecordsSaveVO; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.update.OtaUpgradeRecordsUpdateVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.OtaCommandResponseParam; + +public interface OtaUpgradeRecordsService { + + /** + * 保存新的OTA升级记录。 + * + * @param saveVO 要保存的记录 + * @return 已保存的记录 + */ + OtaUpgradeRecordsSaveVO saveOtaUpgradeRecord(OtaUpgradeRecordsSaveVO saveVO); + + /** + * 更新现有的OTA升级记录。 + * + * @param updateVO 要更新的记录 + * @return 更新后的记录 + */ + OtaUpgradeRecordsUpdateVO updateOtaUpgradeRecord(OtaUpgradeRecordsUpdateVO updateVO); + + /** + * 从MQTT事件中保存OTA升级记录。 + * + * @param otaCommandResponseParam 包含OTA命令响应的消息主体。 + * @return {@link OtaCommandResponseParam} 已保存的OTA升级记录。 + */ + OtaCommandResponseParam saveOtaUpgradeRecordByMqtt(OtaCommandResponseParam otaCommandResponseParam); + + /** + * 从HTTP事件中保存OTA升级记录。 + * + * @param otaCommandResponseParam 包含OTA命令响应的消息主体。 + * @return {@link OtaCommandResponseParam} 已保存的OTA升级记录。 + */ + OtaCommandResponseParam saveUpgradeRecordByHttp(OtaCommandResponseParam otaCommandResponseParam); +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradeTasksService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradeTasksService.java new file mode 100644 index 00000000..12ed9fe2 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradeTasksService.java @@ -0,0 +1,61 @@ +package com.mqttsnet.thinglinks.link.service.ota; + +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.result.OtaUpgradeTasksResultVO; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.save.OtaUpgradeTasksSaveVO; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.update.OtaUpgradeTasksUpdateVO; + +import java.time.LocalDateTime; +import java.util.List; + +public interface OtaUpgradeTasksService { + + /** + * Save OTA Upgrade Task + * + * @param saveVO 保存参数 + * @return {@link OtaUpgradeTasksSaveVO} 返回结果 + */ + OtaUpgradeTasksSaveVO saveUpgradeTask(OtaUpgradeTasksSaveVO saveVO); + + /** + * Update OTA Upgrade Task + * + * @param updateVO 更新参数 + * @return {@link OtaUpgradeTasksUpdateVO} 返回结果 + */ + OtaUpgradeTasksUpdateVO updateUpgradeTask(OtaUpgradeTasksUpdateVO updateVO); + + /** + * Update OTA Upgrade Task Status + * + * @param id 主键 + * @param status 状态 + * @return {@link Boolean} 返回结果 + */ + boolean changeTaskStatus(Long id, Integer status); + + /** + * Delete OTA Upgrade Task + * + * @param id 主键 + * @return {@link Boolean} 返回结果 + */ + boolean deleteOtaUpgradeTask(Long id); + + /** + * Get OTA Upgrade Task Details + * + * @param id 主键 + * @return {@link OtaUpgradeTasksResultVO} 返回结果 + */ + OtaUpgradeTasksResultVO getUpgradeTaskDetails(Long id); + + /** + * Perform ota upgrade tasks based on the start time and end time, including upgrade package information. + * + * @param startTime 开始时间 + * @param endTime 结束时间 + * @return {@link OtaUpgradeTasksResultVO} OTA升级任务的详细信息。 + */ + List otaUpgradeTasksExecute(LocalDateTime startTime, LocalDateTime endTime); +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradesService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradesService.java new file mode 100644 index 00000000..0f6e1843 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradesService.java @@ -0,0 +1,33 @@ +package com.mqttsnet.thinglinks.link.service.ota; + +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.save.OtaUpgradesSaveVO; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.update.OtaUpgradesUpdateVO; + +public interface OtaUpgradesService { + /** + * Save OTA Upgrade Package + * + * @param saveVO 保存参数 + * @return {@link OtaUpgradesSaveVO} 返回结果 + */ + OtaUpgradesSaveVO saveUpgradePackage(OtaUpgradesSaveVO saveVO); + + /** + * Update OTA Upgrade Package + * + * @param updateVO 更新参数 + * @return {@link OtaUpgradesUpdateVO} 返回结果 + */ + OtaUpgradesUpdateVO updateUpgradePackage(OtaUpgradesUpdateVO updateVO); + + /** + * Update OTA Upgrade Package Status + * + * @param id 主键 + * @param status 状态 + * @return {@link Boolean} 返回结果 + */ + Boolean updateOtaUpgradeStatus(Long id, Integer status); + + Boolean deleteOtaUpgrade(Long id); +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradeRecordsServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradeRecordsServiceImpl.java new file mode 100644 index 00000000..db4f4556 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradeRecordsServiceImpl.java @@ -0,0 +1,108 @@ +package com.mqttsnet.thinglinks.link.service.ota.impl; + +import com.mqttsnet.thinglinks.common.core.exception.ServiceException; +import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; +import com.mqttsnet.thinglinks.common.security.service.TokenService; +import com.mqttsnet.thinglinks.link.api.domain.ota.entity.OtaUpgradeRecords; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.save.OtaUpgradeRecordsSaveVO; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.update.OtaUpgradeRecordsUpdateVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.OtaCommandResponseParam; +import com.mqttsnet.thinglinks.link.mapper.ota.OtaUpgradeRecordsMapper; +import com.mqttsnet.thinglinks.link.service.ota.OtaUpgradeRecordsService; +import com.mqttsnet.thinglinks.system.api.domain.SysUser; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; + +@Slf4j +@Service +public class OtaUpgradeRecordsServiceImpl implements OtaUpgradeRecordsService { + + @Resource + private OtaUpgradeRecordsMapper otaUpgradeRecordsMapper; + + @Resource + private TokenService tokenService; + + /** + * 保存新的OTA升级记录。 + * + * @param saveVO 要保存的记录 + * @return 已保存的记录 + */ + @Override + public OtaUpgradeRecordsSaveVO saveOtaUpgradeRecord(OtaUpgradeRecordsSaveVO saveVO) { + + validateOtaUpgradeRecordsSaveVO(saveVO); + + // Validate and map the saveVO + OtaUpgradeRecords record = buildOtaUpgradeRecordSaveVO(saveVO); + otaUpgradeRecordsMapper.insertOtaUpgradeRecords(record); + return BeanPlusUtil.toBeanIgnoreError(record, OtaUpgradeRecordsSaveVO.class); + } + + + /** + * 更新现有的OTA升级记录。 + * + * @param updateVO 要更新的记录 + * @return 更新后的记录 + */ + @Override + public OtaUpgradeRecordsUpdateVO updateOtaUpgradeRecord(OtaUpgradeRecordsUpdateVO updateVO) { + validateOtaUpgradeRecordsUpdateVO(updateVO); + + // Validate and fetch existing record + OtaUpgradeRecords existingRecord = otaUpgradeRecordsMapper.selectOtaUpgradeRecordsById(updateVO.getId()); + if (existingRecord == null) { + throw new ServiceException("OTA upgrade record not found"); + } + + // Update the record + OtaUpgradeRecords records = buildOtaUpgradeRecordSaveVO(updateVO); + + otaUpgradeRecordsMapper.updateOtaUpgradeRecordsById(records); + + return BeanPlusUtil.toBeanIgnoreError(records, OtaUpgradeRecordsUpdateVO.class); + } + + + + /** + * 从MQTT事件中保存OTA升级记录。 + * + * @param otaCommandResponseParam 包含OTA命令响应的消息主体。 + * @return {@link OtaCommandResponseParam} 已保存的OTA升级记录。 + */ + @Override + public OtaCommandResponseParam saveOtaUpgradeRecordByMqtt(OtaCommandResponseParam otaCommandResponseParam) { + return null; + } + + /** + * 从HTTP事件中保存OTA升级记录。 + * + * @param otaCommandResponseParam 包含OTA命令响应的消息主体。 + * @return {@link OtaCommandResponseParam} 已保存的OTA升级记录。 + */ + @Override + public OtaCommandResponseParam saveUpgradeRecordByHttp(OtaCommandResponseParam otaCommandResponseParam) { + return null; + } + + + private OtaUpgradeRecords buildOtaUpgradeRecordSaveVO(T vo) { + SysUser sysUser = tokenService.getLoginUser().getSysUser(); + OtaUpgradeRecords otaUpgradeRecords = BeanPlusUtil.toBeanIgnoreError(vo, OtaUpgradeRecords.class); + otaUpgradeRecords.setCreatedBy(sysUser.getUserName()); + otaUpgradeRecords.setUpdatedBy(sysUser.getUserName()); + return otaUpgradeRecords; + } + + private void validateOtaUpgradeRecordsSaveVO(OtaUpgradeRecordsSaveVO saveVO) { + } + + private void validateOtaUpgradeRecordsUpdateVO(OtaUpgradeRecordsUpdateVO updateVO) { + } +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradeTasksServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradeTasksServiceImpl.java new file mode 100644 index 00000000..adaed3c6 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradeTasksServiceImpl.java @@ -0,0 +1,169 @@ +package com.mqttsnet.thinglinks.link.service.ota.impl; + +import com.mqttsnet.thinglinks.common.core.exception.ServiceException; +import com.mqttsnet.thinglinks.common.core.utils.ArgumentAssert; +import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; +import com.mqttsnet.thinglinks.common.security.service.TokenService; +import com.mqttsnet.thinglinks.link.api.domain.ota.entity.OtaUpgradeTasks; +import com.mqttsnet.thinglinks.link.api.domain.ota.entity.OtaUpgrades; +import com.mqttsnet.thinglinks.link.api.domain.ota.enumeration.OtaPackageStatusEnum; +import com.mqttsnet.thinglinks.link.api.domain.ota.enumeration.OtaPackageTypeEnum; +import com.mqttsnet.thinglinks.link.api.domain.ota.enumeration.OtaUpgradeTaskStatusEnum; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.result.OtaUpgradeTasksResultVO; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.result.OtaUpgradesResultVO; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.save.OtaUpgradeTasksSaveVO; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.update.OtaUpgradeTasksUpdateVO; +import com.mqttsnet.thinglinks.link.mapper.ota.OtaUpgradeTasksMapper; +import com.mqttsnet.thinglinks.link.mapper.ota.OtaUpgradesMapper; +import com.mqttsnet.thinglinks.link.service.ota.OtaUpgradeTasksService; +import com.mqttsnet.thinglinks.system.api.domain.SysUser; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +@Slf4j +@Service +public class OtaUpgradeTasksServiceImpl implements OtaUpgradeTasksService { + + @Resource + private OtaUpgradeTasksMapper otaUpgradeTasksMapper; + + @Resource + private OtaUpgradesMapper otaUpgradesMapper; + + @Resource + private TokenService tokenService; + + /** + * Save OTA Upgrade Task + * + * @param saveVO 保存参数 + * @return {@link OtaUpgradeTasksSaveVO} 返回结果 + */ + @Override + public OtaUpgradeTasksSaveVO saveUpgradeTask(OtaUpgradeTasksSaveVO saveVO) { + log.info("saveUpgradeTask saveVO: {}", saveVO); + validateOtaUpgradeTasksSaveVO(saveVO); + // Map the saveVO to your OtaUpgradeTask entity + OtaUpgradeTasks otaUpgradeTask = buildOtaUpgradeTaskFromSaveVO(saveVO); + + // Persist the OtaUpgradeTask entity using your manager or repository + otaUpgradeTasksMapper.insertOtaUpgradeTask(otaUpgradeTask); + + // Map the saved entity back to OtaUpgradeTasksSaveVO if needed + return BeanPlusUtil.toBeanIgnoreError(otaUpgradeTask, OtaUpgradeTasksSaveVO.class); + } + + /** + * Update OTA Upgrade Task + * + * @param updateVO 更新参数 + * @return {@link OtaUpgradeTasksUpdateVO} 返回结果 + */ + @Override + public OtaUpgradeTasksUpdateVO updateUpgradeTask(OtaUpgradeTasksUpdateVO updateVO) { + log.info("Updating OTA upgrade task: {}", updateVO); + + // Validate the updateVO object + validateOtaUpgradeTasksUpdateVO(updateVO); + + // Map the saveVO to your OtaUpgrade entity + OtaUpgradeTasks otaUpgradeTasks = buildOtaUpgradeTaskFromSaveVO(updateVO); + + // Save the updated entity + otaUpgradeTasksMapper.updateOtaUpgradeTaskById(otaUpgradeTasks); + + + // Map the updated entity back to OtaUpgradeTasksUpdateVO if needed + return BeanPlusUtil.toBeanIgnoreError(otaUpgradeTasks, OtaUpgradeTasksUpdateVO.class); + } + + @Override + public boolean changeTaskStatus(Long id, Integer status) { + ArgumentAssert.notNull(id, "Package ID cannot be null"); + ArgumentAssert.notNull(status, "Status cannot be null"); + + OtaUpgradeTasks otaUpgradeTasks = otaUpgradeTasksMapper.selectOtaUpgradeTaskById(id); + if (otaUpgradeTasks == null) { + throw new ServiceException("OTA upgrade package does not exist"); + } + if (status == otaUpgradeTasks.getTaskStatus().intValue()) { + throw new ServiceException("The OTA upgrade package status is the same as the current status"); + } + OtaUpgradeTaskStatusEnum.fromValue(status) + .orElseThrow(() -> new ServiceException("Invalid task status")); + + return otaUpgradeTasksMapper.updateOtaUpgradeTasksByStatus(id, status) > 0; + } + + @Override + public boolean deleteOtaUpgradeTask(Long id) { + ArgumentAssert.notNull(id, "Task ID cannot be null"); + + OtaUpgradeTasks task = otaUpgradeTasksMapper.selectOtaUpgradeTaskById(id); + if (task == null) { + throw new ServiceException("OTA upgrade task does not exist"); + } + + // Additional checks can be added here, like if the task is in progress or has dependencies + + return otaUpgradeTasksMapper.deleteOtaUpgradeTaskById(id) > 0; + } + + @Override + public OtaUpgradeTasksResultVO getUpgradeTaskDetails(Long id) { + ArgumentAssert.notNull(id, "Task ID cannot be null"); + + OtaUpgradeTasks otaUpgradeTask = otaUpgradeTasksMapper.selectOtaUpgradeTaskById(id); + if (otaUpgradeTask == null) { + throw new ServiceException("OTA upgrade task not found"); + } + + OtaUpgradeTasksResultVO resultVO = BeanPlusUtil.toBeanIgnoreError(otaUpgradeTask, OtaUpgradeTasksResultVO.class); + + OtaUpgrades otaUpgrade = otaUpgradesMapper.selectOtaUpgradeById(otaUpgradeTask.getUpgradeId()); + if (otaUpgrade == null) { + throw new ServiceException("Associated OTA upgrade package not found"); + } + + OtaUpgradesResultVO otaUpgradesResultVO = BeanPlusUtil.toBeanIgnoreError(otaUpgrade, OtaUpgradesResultVO.class); + resultVO.setOtaUpgradesResultVO(otaUpgradesResultVO); + return resultVO; + } + + @Override + public List otaUpgradeTasksExecute(LocalDateTime startTime, LocalDateTime endTime) { + //TODO 此方法 待实现 + return null; + } + + + private void validateOtaUpgradeTasksUpdateVO(OtaUpgradeTasksUpdateVO updateVO) { + Optional.ofNullable(otaUpgradeTasksMapper.selectOtaUpgradeTaskById(updateVO.getId())).orElseThrow(() -> new ServiceException("OTA upgrade task not found")); + //TODO 如需其他限制 在此添加 + } + + + private void validateOtaUpgradeTasksSaveVO(OtaUpgradeTasksSaveVO saveVO) { + OtaUpgradeTaskStatusEnum.fromValue(saveVO.getTaskStatus()) + .orElseThrow(() -> new ServiceException("Invalid task status")); + + OtaUpgrades otaUpgrades = otaUpgradesMapper.selectOtaUpgradeById(saveVO.getUpgradeId()); + if (otaUpgrades == null) { + throw new ServiceException("OTA upgrade package does not exist"); + } + + } + + private OtaUpgradeTasks buildOtaUpgradeTaskFromSaveVO(T vo) { + SysUser sysUser = tokenService.getLoginUser().getSysUser(); + OtaUpgradeTasks otaUpgradeTasks = BeanPlusUtil.toBeanIgnoreError(vo, OtaUpgradeTasks.class); + otaUpgradeTasks.setCreatedBy(sysUser.getUserName()); + otaUpgradeTasks.setUpdatedBy(sysUser.getUserName()); + return otaUpgradeTasks; + } +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradesServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradesServiceImpl.java new file mode 100644 index 00000000..9dd15ac1 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradesServiceImpl.java @@ -0,0 +1,145 @@ +package com.mqttsnet.thinglinks.link.service.ota.impl; + +import com.mqttsnet.thinglinks.common.core.exception.ServiceException; +import com.mqttsnet.thinglinks.common.core.utils.ArgumentAssert; +import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; +import com.mqttsnet.thinglinks.common.security.service.TokenService; +import com.mqttsnet.thinglinks.link.api.domain.ota.entity.OtaUpgrades; +import com.mqttsnet.thinglinks.link.api.domain.ota.enumeration.OtaPackageStatusEnum; +import com.mqttsnet.thinglinks.link.api.domain.ota.enumeration.OtaPackageTypeEnum; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.save.OtaUpgradesSaveVO; +import com.mqttsnet.thinglinks.link.api.domain.ota.vo.update.OtaUpgradesUpdateVO; +import com.mqttsnet.thinglinks.link.mapper.ota.OtaUpgradeTasksMapper; +import com.mqttsnet.thinglinks.link.mapper.ota.OtaUpgradesMapper; +import com.mqttsnet.thinglinks.link.service.ota.OtaUpgradesService; +import com.mqttsnet.thinglinks.link.service.product.ProductService; +import com.mqttsnet.thinglinks.system.api.domain.SysUser; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.Optional; + +@Slf4j +@Service +public class OtaUpgradesServiceImpl implements OtaUpgradesService { + @Resource + private OtaUpgradesMapper otaUpgradesMapper; + @Resource + private TokenService tokenService; + + @Resource + private ProductService productService; + + @Resource + private OtaUpgradeTasksMapper otaUpgradeTasksMapper; + + /** + * Save OTA Upgrade Package + * + * @param saveVO 保存参数 + * @return {@link OtaUpgradesSaveVO} 返回结果 + */ + @Override + public OtaUpgradesSaveVO saveUpgradePackage(OtaUpgradesSaveVO saveVO) { + log.info("saveUpgradePackage saveVO: {}", saveVO); + // Validate the saveVO object + validateOtaUpgradesSaveVO(saveVO); + + // Map the saveVO to your OtaUpgrade entity + OtaUpgrades otaUpgrade = buildOtaUpgradesFromVO(saveVO); + + // Persist the OtaUpgrade entity using your manager or repository + otaUpgradesMapper.insertOtaUpgrades(otaUpgrade); + + // Map the saved entity back to OtaUpgradesSaveVO if needed + return BeanPlusUtil.toBeanIgnoreError(otaUpgrade, OtaUpgradesSaveVO.class); + + } + + @Override + public OtaUpgradesUpdateVO updateUpgradePackage(OtaUpgradesUpdateVO updateVO) { + log.info("Updating OTA upgrade package: {}", updateVO); + + // Validate the updateVO object + validateOtaUpgradesUpdateVO(updateVO); + + // Map the saveVO to your OtaUpgrade entity + OtaUpgrades otaUpgrade = buildOtaUpgradesFromVO(updateVO); + + // Save the updated entity + otaUpgradesMapper.updateOtaUpgradeById(otaUpgrade); + + // Map the updated entity back to OtaUpgradesUpdateVO if needed + return BeanPlusUtil.toBeanIgnoreError(otaUpgrade, OtaUpgradesUpdateVO.class); + } + + @Override + public Boolean updateOtaUpgradeStatus(Long id, Integer status) { + ArgumentAssert.notNull(id, "Package ID cannot be null"); + ArgumentAssert.notNull(status, "Status cannot be null"); + + OtaUpgrades otaUpgrades = otaUpgradesMapper.selectOtaUpgradeById(id); + if (otaUpgrades == null) { + throw new ServiceException("OTA upgrade package does not exist"); + } + if (status == otaUpgrades.getStatus().intValue()) { + throw new ServiceException("The OTA upgrade package status is the same as the current status"); + } + return otaUpgradesMapper.updateOtaUpgradeByStatus(id, status) > 0; + + } + + /** + * Deletes an OTA upgrade package by its ID if it is not in use. + * + * @param id the ID of the OTA upgrade package to delete + * @return {@code true} if the package was successfully deleted, {@code false} otherwise + * @throws IllegalArgumentException if the {@code id} is null + * @throws ServiceException if the OTA upgrade package does not exist or is in use + */ + @Override + public Boolean deleteOtaUpgrade(Long id) { + ArgumentAssert.notNull(id, "Package ID cannot be null"); + + OtaUpgrades otaUpgrade = otaUpgradesMapper.selectOtaUpgradeById(id); + if (otaUpgrade == null) { + throw new ServiceException("OTA upgrade package does not exist"); + } + + int taskCount = otaUpgradeTasksMapper.getOtaUpgradeTasksByOtaUpgradeId(id); + if (taskCount > 0) { + throw new ServiceException("OTA upgrade package is in use and cannot be deleted"); + } + + boolean deleted = otaUpgradesMapper.deleteOtaUpgradeById(id) > 0; + if (!deleted) { + throw new ServiceException("Failed to delete OTA upgrade package"); + } + + return true; + } + + + + private void validateOtaUpgradesUpdateVO(OtaUpgradesUpdateVO updateVO) { + Optional.ofNullable(otaUpgradesMapper.selectOtaUpgradeById(updateVO.getId())).orElseThrow(() -> new ServiceException("OTA upgrade package not found")); + String productIdentification = updateVO.getProductIdentification(); + Optional.ofNullable(productService.selectByProductIdentification(productIdentification)).orElseThrow(() -> new ServiceException("Product identification not found")); + OtaPackageTypeEnum.fromValue(updateVO.getPackageType()).orElseThrow(() -> new ServiceException("Invalid package type")); + OtaPackageStatusEnum.fromValue(updateVO.getStatus()).orElseThrow(() -> new ServiceException("Invalid status")); + } + + private OtaUpgrades buildOtaUpgradesFromVO(T vo) { + SysUser sysUser = tokenService.getLoginUser().getSysUser(); + OtaUpgrades otaUpgrades = BeanPlusUtil.toBeanIgnoreError(vo, OtaUpgrades.class); + otaUpgrades.setCreatedBy(sysUser.getUserName()); + otaUpgrades.setUpdatedBy(sysUser.getUserName()); + return otaUpgrades; + } + + private void validateOtaUpgradesSaveVO(OtaUpgradesSaveVO saveVO) { + OtaPackageTypeEnum.fromValue(saveVO.getPackageType()).orElseThrow(() -> new ServiceException("Invalid package type")); + OtaPackageStatusEnum.fromValue(saveVO.getStatus()).orElseThrow(() -> new ServiceException("Invalid status")); + } +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/ota/OtaUpgradeRecordsMapper.xml b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/ota/OtaUpgradeRecordsMapper.xml new file mode 100644 index 00000000..44d54bb4 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/ota/OtaUpgradeRecordsMapper.xml @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + id, task_id, device_identification, upgrade_status, progress, error_code, error_message, start_time, end_time, success_details, failure_details, log_details, remark, created_time, created_by, updated_by, updated_time + + + + INSERT INTO ota_upgrade_records + (task_id, device_identification, upgrade_status, progress, error_code, error_message, start_time, end_time, success_details, failure_details, log_details, remark, created_time, created_by, updated_time, updated_by) + VALUES + (#{taskId}, #{deviceIdentification}, #{upgradeStatus}, #{progress}, #{errorCode}, #{errorMessage}, #{startTime}, #{endTime}, #{successDetails}, #{failureDetails}, #{logDetails}, #{remark}, now(), #{createdBy}, now(), #{updatedBy}) + + + + DELETE FROM ota_upgrade_records WHERE id = #{id} + + + + UPDATE ota_upgrade_records + SET task_id = #{taskId}, + device_identification = #{deviceIdentification}, + upgrade_status = #{upgradeStatus}, + progress = #{progress}, + error_code = #{errorCode}, + error_message = #{errorMessage}, + start_time = #{startTime}, + end_time = #{endTime}, + success_details = #{successDetails}, + failure_details = #{failureDetails}, + log_details = #{logDetails}, + remark = #{remark}, + updated_by = #{updatedBy}, + updated_time = now() + WHERE id = #{id} + + + + + + + diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/ota/OtaUpgradeTasksMapper.xml b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/ota/OtaUpgradeTasksMapper.xml new file mode 100644 index 00000000..5ffea372 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/ota/OtaUpgradeTasksMapper.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + id, upgrade_id, task_name, task_status, scheduled_time, description, remark, created_by, created_time, updated_by, updated_time + + + + INSERT INTO ota_upgrade_tasks (upgrade_id, task_name, task_status, scheduled_time, description, remark, created_by, created_time, updated_by, updated_time) + VALUES (#{upgradeId}, #{taskName}, #{taskStatus}, #{scheduledTime}, #{description}, #{remark}, #{createdBy}, now(), #{updatedBy}, now()) + + + + DELETE FROM ota_upgrade_tasks WHERE id = #{id} + + + + UPDATE ota_upgrade_tasks + SET upgrade_id = #{upgradeId}, + task_name = #{taskName}, + task_status = #{taskStatus}, + scheduled_time = #{scheduledTime}, + description = #{description}, + remark = #{remark}, + updated_by = #{updatedBy}, + updated_time = now() + WHERE id = #{id} + + + + + + + + + + UPDATE ota_upgrade_tasks + set task_status = #{status} + WHERE id = #{id} + + diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/ota/OtaUpgradesMapper.xml b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/ota/OtaUpgradesMapper.xml new file mode 100644 index 00000000..e4c85c93 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/ota/OtaUpgradesMapper.xml @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + id, app_id, package_name, package_type, product_identification, version, file_location, status, description, custom_info, remark, created_by, created_time, updated_by, updated_time + + + + INSERT INTO ota_upgrades + + + app_id, + + + package_name, + + + package_type, + + + product_identification, + + + version, + + + file_location, + + + status, + + + description, + + + custom_info, + + + remark, + + + created_by, + + created_time, + + updated_by, + + updated_time, + + + + #{appId,jdbcType=VARCHAR}, + + + #{packageName,jdbcType=VARCHAR}, + + + #{packageType,jdbcType=SMALLINT}, + + + #{productIdentification,jdbcType=VARCHAR}, + + + #{version,jdbcType=VARCHAR}, + + + #{fileLocation,jdbcType=VARCHAR}, + + + #{status,jdbcType=SMALLINT}, + + + #{description,jdbcType=VARCHAR}, + + + #{customInfo,jdbcType=LONGVARCHAR}, + + + #{remark,jdbcType=VARCHAR}, + + + #{createdBy,jdbcType=VARCHAR}, + + now(), + + #{updatedBy,jdbcType=VARCHAR}, + + now(), + + + + + + DELETE + FROM ota_upgrades + WHERE id = #{id} + + + + + UPDATE ota_upgrades + SET app_id = #{appId}, + package_name = #{packageName}, + package_type = #{packageType}, + product_identification = #{productIdentification}, + version = #{version}, + file_location = #{fileLocation}, + status = #{status}, + description = #{description}, + custom_info = #{customInfo}, + remark = #{remark}, + updated_by = #{updatedBy}, + updated_time = now() + WHERE id = #{id} + + + + + + + + + + UPDATE ota_upgrades + set status = #{status} + WHERE id = #{id} + + From 8339d1b7d2ed3958b0baad6ee458a2136190ae66 Mon Sep 17 00:00:00 2001 From: xiaonan <13733918655@163.com> Date: Sat, 23 Mar 2024 15:53:14 +0800 Subject: [PATCH 10/35] =?UTF-8?q?=E5=8D=87=E7=BA=A7mqtt=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E5=8D=8F=E8=AE=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + README.zh_CN.md | 1 + doc/sql/changeRecord/1.2.0.RELEASE.sql | 20 +- doc/sql/thinglinks.sql | 19 +- pom.xml | 1 + .../link/api/RemoteDeviceInfoService.java | 17 +- .../link/api/RemoteDeviceOpenAnyService.java | 168 +++++++ .../link/api/RemoteDeviceService.java | 138 ----- .../cache/product/ProductModelCacheVO.java | 51 +- .../enumeration/DeviceActionStatusEnum.java | 60 +++ .../MqttProtocolTopoStatusEnum.java | 43 ++ .../product/entity/ProductProperties.java | 15 +- .../product/entity/ProductServices.java | 30 +- .../product/enumeration/ProductTypeEnum.java | 71 +++ .../vo/param/ProductCommandParamVO.java | 78 +++ .../param/ProductCommandRequestParamVO.java | 128 +++++ .../param/ProductCommandResponseParamVO.java | 127 +++++ .../vo/param/ProductPropertyParamVO.java | 134 +++++ .../vo/param/ProductServiceParamVO.java | 89 ++++ .../result/ProductCommandRequestResultVO.java | 115 +++++ .../ProductCommandResponseResultVO.java | 115 +++++ .../vo/result/ProductCommandResultVO.java | 76 +++ .../vo/result/ProductPropertyResultVO.java | 131 +++++ .../product/vo/result/ProductResultVO.java | 119 +++++ .../vo/result/ProductServiceResultVO.java | 90 ++++ .../result/ProtocolDataMessageResultVO.java | 2 +- .../vo/result/TopoAddDeviceResultVO.java | 2 +- .../result/TopoDeviceOperationResultVO.java | 2 +- .../vo/result/TopoQueryDeviceResultVO.java | 23 +- .../factory/RemoteDeviceFallbackFactory.java | 138 ----- .../RemoteDeviceInfoFallbackFactory.java | 1 + .../RemoteDeviceOpenAnyFallbackFactory.java | 97 ++++ .../main/resources/META-INF/spring.factories | 1 + .../tdengine/api/RemoteTdEngineService.java | 164 +++++- .../tdengine/api/domain/Fields.java | 57 +-- .../api/domain/SuperTableDescribeVO.java | 2 +- .../tdengine/api/domain/model/FieldsVO.java | 58 +++ .../api/domain/model/SuperTableDTO.java | 53 ++ .../tdengine/api/domain/model/TableDTO.java | 49 ++ .../api/domain/model/TagsSelectDTO.java | 30 ++ .../RemoteTdEngineFallbackFactory.java | 88 +++- .../common/core/constant/Constants.java | 6 + .../common/core/enums/DataTypeEnum.java | 102 +++- .../common/core/enums/DeviceType.java | 11 +- .../factory/ProtocolMessageAdapter.java | 2 +- .../thinglinks-modules-broker/pom.xml | 5 + .../thinglinks-modules-broker/readme.md | 0 .../broker/config/KafkaConsumerConfig.java | 2 +- .../broker/config/KafkaProviderConfig.java | 2 +- .../broker/mqs/event/MqttCloseEvent.java | 2 +- .../broker/mqs/event/MqttConnectEvent.java | 2 +- .../broker/mqs/event/MqttDisconnectEvent.java | 2 +- .../broker/mqs/event/MqttPingEvent.java | 2 +- .../broker/mqs/event/MqttPublishEvent.java | 2 +- .../broker/mqs/event/MqttSubscribeEvent.java | 2 +- .../mqs/event/MqttUnsubscribeEvent.java | 2 +- .../listener/MqttCloseEventListener.java | 2 +- .../listener/MqttConnectEventListener.java | 2 +- .../listener/MqttDisconnectEventListener.java | 2 +- .../event/listener/MqttPingEventListener.java | 2 +- .../listener/MqttPublishEventListener.java | 2 +- .../listener/MqttSubscribeEventListener.java | 2 +- .../MqttUnsubscribeEventListener.java | 2 +- .../event/publisher/MqttEventPublisher.java | 2 +- .../handler/kafka/KafkaSendResultHandler.java | 2 +- .../MqttMessageKafkaConsumerHandler.java | 2 +- .../kafka/MyKafkaListenerErrorHandler.java | 2 +- .../mqs/mqtt/handler/AddSubDeviceHandler.java | 10 +- .../mqtt/handler/CommandResponseHandler.java | 10 +- .../mqs/mqtt/handler/DefaultHandler.java | 2 +- .../mqtt/handler/DeleteSubDeviceHandler.java | 10 +- .../mqs/mqtt/handler/DeviceDatasHandler.java | 53 +- .../handler/OtaCommandResponseHandler.java | 12 +- .../mqs/mqtt/handler/QueryDeviceHandler.java | 10 +- .../mqs/mqtt/handler/SecretKeyHandler.java | 7 +- .../broker/mqs/mqtt/handler/TopicHandler.java | 2 +- .../mqtt/handler/UpdateSubDeviceHandler.java | 14 +- .../mqtt/handler/event/MqttMessageEvent.java | 2 +- .../factory/AbstractMessageHandler.java | 10 +- .../handler/factory/TopicHandlerFactory.java | 2 +- .../handler/listener/MqttMessageListener.java | 2 +- .../mqtt/service/MqttEventActionService.java | 2 +- .../mqtt/service/MqttEventCommandService.java | 2 +- .../MqttEventOtaCommandResponseService.java | 6 +- .../controller/device/DeviceController.java | 197 -------- .../device/DeviceInfoController.java | 30 +- .../device/DeviceOpenAnyController.java | 256 ++++++++++ .../mapper/product/ProductServicesMapper.java | 2 +- .../service/device/DeviceInfoService.java | 57 +++ .../link/service/device/DeviceService.java | 50 -- .../device/impl/DeviceInfoServiceImpl.java | 474 ++++++++++++++++-- .../device/impl/DeviceServiceImpl.java | 134 +++-- .../product/ProductServicesService.java | 2 +- .../impl/ProductServicesServiceImpl.java | 4 +- .../link/product/ProductServicesMapper.xml | 65 ++- .../common/constant/TdsConstants.java | 34 ++ .../controller/TdEngineController.java | 401 +++++++++++++-- .../tdengine/mapper/TdEngineMapper.java | 127 ++++- .../tdengine/service/TdEngineService.java | 153 +++++- .../service/impl/TdEngineServiceImpl.java | 88 +++- .../tdengine/{util => utils}/TaosAspect.java | 2 +- .../thinglinks/tdengine/utils/TdsUtils.java | 219 ++++++++ .../main/resources/mapper/TdEngineMapper.xml | 221 ++++++++ .../src/views/link/product/services/index.vue | 22 +- 104 files changed, 4537 insertions(+), 927 deletions(-) create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceOpenAnyService.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/enumeration/DeviceActionStatusEnum.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/enumeration/MqttProtocolTopoStatusEnum.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/enumeration/ProductTypeEnum.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandParamVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandRequestParamVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandResponseParamVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductPropertyParamVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductServiceParamVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductCommandRequestResultVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductCommandResponseResultVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductCommandResultVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductPropertyResultVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductResultVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductServiceResultVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteDeviceOpenAnyFallbackFactory.java create mode 100644 thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/model/FieldsVO.java create mode 100644 thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/model/SuperTableDTO.java create mode 100644 thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/model/TableDTO.java create mode 100644 thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/model/TagsSelectDTO.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/readme.md create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceOpenAnyController.java create mode 100644 thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/constant/TdsConstants.java rename thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/{util => utils}/TaosAspect.java (96%) create mode 100644 thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/utils/TdsUtils.java diff --git a/README.md b/README.md index 07079b91..001005f6 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,7 @@ Thanks these wonderful people, welcome to join us: llJam
llJam

💻 qianmenfei
qianmenfei

💻 + wangfan1997
wangfan1997

💻 diff --git a/README.zh_CN.md b/README.zh_CN.md index 00ad4a28..1a010a04 100644 --- a/README.zh_CN.md +++ b/README.zh_CN.md @@ -118,6 +118,7 @@ Thanks these wonderful people, welcome to join us: llJam
llJam

💻 qianmenfei
qianmenfei

💻 + wangfan1997
wangfan1997

💻 diff --git a/doc/sql/changeRecord/1.2.0.RELEASE.sql b/doc/sql/changeRecord/1.2.0.RELEASE.sql index 79f0ebd2..a4015f34 100644 --- a/doc/sql/changeRecord/1.2.0.RELEASE.sql +++ b/doc/sql/changeRecord/1.2.0.RELEASE.sql @@ -1,11 +1,17 @@ # 设备表新增字段 -ALTER TABLE thinglinks_test.device ADD encrypt_key varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '加密密钥'; -ALTER TABLE thinglinks_test.device ADD encrypt_vector varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '加密向量'; -ALTER TABLE thinglinks_test.device ADD sign_key varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '签名密钥'; -ALTER TABLE thinglinks_test.device ADD encrypt_method tinyint(4) DEFAULT 0 NOT NULL COMMENT '协议加密方式'; -ALTER TABLE thinglinks_test.device ADD sw_version varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '软件版本'; -ALTER TABLE thinglinks_test.device ADD fw_version varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '固件版本'; -ALTER TABLE thinglinks_test.device ADD device_sdk_version varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT 'v1' NOT NULL COMMENT 'sdk版本'; +ALTER TABLE device ADD encrypt_key varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '加密密钥'; +ALTER TABLE device ADD encrypt_vector varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '加密向量'; +ALTER TABLE device ADD sign_key varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '签名密钥'; +ALTER TABLE device ADD encrypt_method tinyint(4) DEFAULT 0 NOT NULL COMMENT '协议加密方式'; +ALTER TABLE device ADD sw_version varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '软件版本'; +ALTER TABLE device ADD fw_version varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '固件版本'; +ALTER TABLE device ADD device_sdk_version varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT 'v1' NOT NULL COMMENT 'sdk版本'; + + +#产品服务表 +ALTER TABLE product_services MODIFY COLUMN service_name varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '服务名称'; +ALTER TABLE product_services ADD service_code varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NOT NULL COMMENT '服务编码:支持英文大小写、数字、下划线和中划线'; + diff --git a/doc/sql/thinglinks.sql b/doc/sql/thinglinks.sql index 6d838fee..c5b69824 100644 --- a/doc/sql/thinglinks.sql +++ b/doc/sql/thinglinks.sql @@ -1856,15 +1856,16 @@ DROP TABLE IF EXISTS `product_services`; CREATE TABLE `product_services` ( `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT '服务id', - `service_name` varchar(255) NOT NULL COMMENT '服务名称:支持英文大小写、数字、下划线和中划线\r\n', - `template_identification` varchar(100) DEFAULT NULL COMMENT '产品模版标识', - `product_identification` varchar(100) DEFAULT NULL COMMENT '产品标识', - `status` varchar(10) NOT NULL DEFAULT '0' COMMENT '状态(字典值:0启用 1停用)', - `description` varchar(255) DEFAULT NULL COMMENT '服务的描述信息:文本描述,不影响实际功能,可配置为空字符串""。\r\n', - `create_by` varchar(64) DEFAULT 'ununited' COMMENT '创建者', - `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `update_by` varchar(64) DEFAULT '' COMMENT '更新者', - `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `service_code` varchar(255) CHARACTER SET utf8mb4 NOT NULL DEFAULT '' COMMENT '服务编码:支持英文大小写、数字、下划线和中划线', + `service_name` varchar(255) NOT NULL COMMENT '服务名称', + `template_identification` varchar(100) DEFAULT NULL COMMENT '产品模版标识', + `product_identification` varchar(100) DEFAULT NULL COMMENT '产品标识', + `status` varchar(10) NOT NULL DEFAULT '0' COMMENT '状态(字典值:0启用 1停用)', + `description` varchar(255) DEFAULT NULL COMMENT '服务的描述信息:文本描述,不影响实际功能,可配置为空字符串""。\r\n', + `create_by` varchar(64) DEFAULT 'ununited' COMMENT '创建者', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_by` varchar(64) DEFAULT '' COMMENT '更新者', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 72 diff --git a/pom.xml b/pom.xml index 30767838..3d0d8d62 100644 --- a/pom.xml +++ b/pom.xml @@ -276,6 +276,7 @@ thinglinks-api thinglinks-common thinglinks-registry + thinglinks-common/thinglinks-common-tds pom diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceInfoService.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceInfoService.java index 1ef01ffa..df51ea8f 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceInfoService.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceInfoService.java @@ -1,11 +1,18 @@ package com.mqttsnet.thinglinks.link.api; import com.mqttsnet.thinglinks.common.core.constant.ServiceNameConstants; +import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.common.core.web.domain.AjaxResult; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoAddSubDeviceParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoDeleteSubDeviceParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoUpdateSubDeviceStatusParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; import com.mqttsnet.thinglinks.link.api.factory.RemoteDeviceInfoFallbackFactory; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.*; /** * 子设备管理服务 @@ -17,10 +24,14 @@ public interface RemoteDeviceInfoService { /** * 刷新子设备数据模型 + * * @param ids * @return */ @GetMapping("/deviceInfo/refreshDeviceInfoDataModel") - public AjaxResult refreshDeviceInfoDataModel(@RequestParam(name = "ids",required = false) Long[] ids); + public AjaxResult refreshDeviceInfoDataModel(@RequestParam(name = "ids", required = false) Long[] ids); + + + } diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceOpenAnyService.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceOpenAnyService.java new file mode 100644 index 00000000..da3fb97a --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceOpenAnyService.java @@ -0,0 +1,168 @@ + +package com.mqttsnet.thinglinks.link.api; + +import com.mqttsnet.thinglinks.common.core.constant.ServiceNameConstants; +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.*; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoQueryDeviceResultVO; +import com.mqttsnet.thinglinks.link.api.factory.RemoteDeviceOpenAnyFallbackFactory; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; + +import javax.validation.Valid; +import java.util.Map; + +/** + * 设备管理开放服务 + * + * @author shisen + */ +@FeignClient(contextId = "remoteDeviceOpenService", value = ServiceNameConstants.THINGLINKS_LINK, fallbackFactory = RemoteDeviceOpenAnyFallbackFactory.class) +public interface RemoteDeviceOpenAnyService { + + + /** + * 客户端身份认证 + * + * @param params + * @return + */ + @PostMapping("/deviceOpenAny/clientAuthentication") + public R clientAuthentication(@RequestBody Map params); + + /** + * (MQTT)协议新增子设备档案 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 新增结果 + */ + @ApiOperation(value = "(MQTT)协议新增子设备档案", httpMethod = "POST", notes = "(MQTT)协议新增子设备档案") + @PostMapping("/deviceOpenAny/saveSubDeviceByMqtt") + R saveSubDeviceByMqtt(@RequestBody TopoAddSubDeviceParam topoAddSubDeviceParam); + + + /** + * (HTTP)协议新增子设备档案 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 新增结果 + */ + @ApiOperation(value = "(HTTP)协议新增子设备档案", httpMethod = "POST", notes = "(HTTP)协议新增子设备档案") + @PostMapping("/deviceOpenAny/saveSubDeviceByHttp") + public R saveSubDeviceByHttp(@RequestBody TopoAddSubDeviceParam topoAddSubDeviceParam); + + + /** + * MQTT协议修改子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 连接状态参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @ApiOperation(value = "(MQTT)协议修改子设备连接状态", httpMethod = "PUT", notes = "(MQTT)协议修改子设备连接状态") + @PutMapping("/deviceOpenAny/updateSubDeviceConnectStatusByMqtt") + R updateSubDeviceConnectStatusByMqtt(@RequestBody @ApiParam(value = "连接状态参数") TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam); + + + /** + * HTTP协议修改子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 连接状态参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @ApiOperation(value = "(HTTP)协议修改子设备连接状态", httpMethod = "PUT", notes = "(HTTP)协议修改子设备连接状态") + @PutMapping("/deviceOpenAny/updateSubDeviceConnectStatusByHttp") + R updateSubDeviceConnectStatusByHttp(@RequestBody @ApiParam(value = "连接状态参数") TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam); + + /** + * MQTT协议删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @ApiOperation(value = "(MQTT)协议删除子设备", httpMethod = "PUT", notes = "(MQTT)协议删除子设备") + @PutMapping("/deviceOpenAny/deleteSubDeviceByMqtt") + R deleteSubDeviceByMqtt(@RequestBody @ApiParam(value = "删除参数") TopoDeleteSubDeviceParam topoDeleteSubDeviceParam); + + + /** + * HTTP协议删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @ApiOperation(value = "(HTTP)协议删除子设备", httpMethod = "PUT", notes = "(HTTP)协议删除子设备") + @PutMapping("/deviceOpenAny/deleteSubDeviceByHttp") + R deleteSubDeviceByHttp(@RequestBody @ApiParam(value = "删除参数") TopoDeleteSubDeviceParam topoDeleteSubDeviceParam); + + /** + * MQTT协议数据上报 + * + * @param topoDeviceDataReportParam 数据上报参数 + * @return {@link TopoDeviceOperationResultVO} 上报结果 + */ + @ApiOperation(value = "(MQTT)协议数据上报", httpMethod = "PUT", notes = "(MQTT)协议数据上报") + @PostMapping("/deviceDataReportByMqtt") + R deviceDataReportByMqtt(@RequestBody @ApiParam(value = "数据上报参数") TopoDeviceDataReportParam topoDeviceDataReportParam); + + /** + * HTTP协议数据上报 + * + * @param topoDeviceDataReportParam 数据上报参数 + * @return {@link TopoDeviceOperationResultVO} 上报结果 + */ + @ApiOperation(value = "(HTTP)协议数据上报", httpMethod = "PUT", notes = "(HTTP)协议数据上报") + @PostMapping("/deviceOpenAny/deviceDataReportByHttp") + R deviceDataReportByHttp(@RequestBody @ApiParam(value = "数据上报参数") TopoDeviceDataReportParam topoDeviceDataReportParam); + + /** + * Queries device information using the MQTT protocol. + * + * @param topoQueryDeviceParam The device query parameters. + * @return {@link TopoQueryDeviceResultVO} The result of the device query. + */ + @ApiOperation(value = "Query Device Information via MQTT Protocol", httpMethod = "POST", notes = "Queries device information using the MQTT protocol") + @PostMapping("/deviceOpenAny/queryDeviceByMqtt") + public R queryDeviceByMqtt(@RequestBody TopoQueryDeviceParam topoQueryDeviceParam); + + /** + * Queries device information using the HTTP protocol. + * + * @param topoQueryDeviceParam The device query parameters. + * @return {@link TopoQueryDeviceResultVO} The result of the device query. + */ + @ApiOperation(value = "Query Device Information via HTTP Protocol", httpMethod = "POST", notes = "Queries device information using the HTTP protocol") + @PostMapping("/deviceOpenAny/queryDeviceByHttp") + public R queryDeviceByHttp(@RequestBody TopoQueryDeviceParam topoQueryDeviceParam); + + + /** + * Receives and saves a new OTA upgrade record from an MQTT message. This endpoint + * captures the command response parameters from the MQTT message body and persists them. + * + * @param otaCommandResponseParam The response parameters from an OTA command sent via MQTT. + * @return {@link R} A response entity containing the saved OTA upgrade record. + */ + @ApiOperation(value = "Save OTA Upgrade Record", httpMethod = "POST", notes = "Saves a new OTA upgrade record from MQTT message data.") + @PostMapping("/deviceOpenAny/saveUpgradeRecordByMqtt") + public R saveUpgradeRecordByMqtt(@Valid @RequestBody OtaCommandResponseParam otaCommandResponseParam); + + + /** + * Receives and saves a new OTA upgrade record from an HTTP request. This endpoint + * captures the command response parameters from the request body and persists them. + * + * @param otaCommandResponseParam The response parameters from an OTA command sent via HTTP. + * @return {@link R} A response wrapper containing the saved OTA upgrade record. + */ + @ApiOperation(value = "Save OTA Upgrade Record via HTTP", httpMethod = "POST", notes = "Saves a new OTA upgrade record from HTTP request data.") + @PostMapping("/deviceOpenAny/saveUpgradeRecordByHttp") + public R saveUpgradeRecordByHttp(@Valid @RequestBody OtaCommandResponseParam otaCommandResponseParam); + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceService.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceService.java index 00e2b08a..ac5fd4e7 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceService.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceService.java @@ -3,17 +3,10 @@ import com.mqttsnet.thinglinks.common.core.constant.ServiceNameConstants; import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; -import com.mqttsnet.thinglinks.link.api.domain.vo.param.*; -import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; -import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; -import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoQueryDeviceResultVO; import com.mqttsnet.thinglinks.link.api.factory.RemoteDeviceFallbackFactory; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.*; -import javax.validation.Valid; import java.util.List; import java.util.Map; @@ -85,135 +78,4 @@ public R selectByProductIdentificationAndDeviceIdentification(@PathVaria @PostMapping("/device/selectDeviceByDeviceIdentificationList") public R selectDeviceByDeviceIdentificationList(@RequestBody List deviceIdentificationList); - /** - * (MQTT)协议新增子设备档案 - * - * @param topoAddSubDeviceParam 子设备参数 - * @return {@link TopoAddDeviceResultVO} 新增结果 - */ - @ApiOperation(value = "(MQTT)协议新增子设备档案", httpMethod = "POST", notes = "(MQTT)协议新增子设备档案") - @PostMapping("/saveSubDeviceByMqtt") - R saveSubDeviceByMqtt(@RequestBody TopoAddSubDeviceParam topoAddSubDeviceParam); - - - /** - * (HTTP)协议新增子设备档案 - * - * @param topoAddSubDeviceParam 子设备参数 - * @return {@link TopoAddDeviceResultVO} 新增结果 - */ - @ApiOperation(value = "(HTTP)协议新增子设备档案", httpMethod = "POST", notes = "(HTTP)协议新增子设备档案") - @PostMapping("/saveSubDeviceByHttp") - public R saveSubDeviceByHttp(@RequestBody TopoAddSubDeviceParam topoAddSubDeviceParam); - - - /** - * MQTT协议修改子设备连接状态 - * - * @param topoUpdateSubDeviceStatusParam 连接状态参数 - * @return {@link TopoDeviceOperationResultVO} 修改结果 - */ - @ApiOperation(value = "(MQTT)协议修改子设备连接状态", httpMethod = "PUT", notes = "(MQTT)协议修改子设备连接状态") - @PutMapping("/updateSubDeviceConnectStatusByMqtt") - R updateSubDeviceConnectStatusByMqtt(@RequestBody @ApiParam(value = "连接状态参数") TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam); - - - /** - * HTTP协议修改子设备连接状态 - * - * @param topoUpdateSubDeviceStatusParam 连接状态参数 - * @return {@link TopoDeviceOperationResultVO} 修改结果 - */ - @ApiOperation(value = "(HTTP)协议修改子设备连接状态", httpMethod = "PUT", notes = "(HTTP)协议修改子设备连接状态") - @PutMapping("/updateSubDeviceConnectStatusByHttp") - R updateSubDeviceConnectStatusByHttp(@RequestBody @ApiParam(value = "连接状态参数") TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam); - - /** - * MQTT协议删除子设备 - * - * @param topoDeleteSubDeviceParam 删除参数 - * @return {@link TopoDeviceOperationResultVO} 修改结果 - */ - @ApiOperation(value = "(MQTT)协议删除子设备", httpMethod = "PUT", notes = "(MQTT)协议删除子设备") - @PutMapping("/deleteSubDeviceByMqtt") - R deleteSubDeviceByMqtt(@RequestBody @ApiParam(value = "删除参数") TopoDeleteSubDeviceParam topoDeleteSubDeviceParam); - - - /** - * HTTP协议删除子设备 - * - * @param topoDeleteSubDeviceParam 删除参数 - * @return {@link TopoDeviceOperationResultVO} 修改结果 - */ - @ApiOperation(value = "(HTTP)协议删除子设备", httpMethod = "PUT", notes = "(HTTP)协议删除子设备") - @PutMapping("/deleteSubDeviceByHttp") - R deleteSubDeviceByHttp(@RequestBody @ApiParam(value = "删除参数") TopoDeleteSubDeviceParam topoDeleteSubDeviceParam); - - - /** - * MQTT协议数据上报 - * - * @param topoDeviceDataReportParam 数据上报参数 - * @return {@link TopoDeviceOperationResultVO} 上报结果 - */ - @ApiOperation(value = "(MQTT)协议数据上报", httpMethod = "PUT", notes = "(MQTT)协议数据上报") - @PostMapping("/deviceDataReportByMqtt") - R deviceDataReportByMqtt(@RequestBody @ApiParam(value = "数据上报参数") TopoDeviceDataReportParam topoDeviceDataReportParam); - - /** - * HTTP协议数据上报 - * - * @param topoDeviceDataReportParam 数据上报参数 - * @return {@link TopoDeviceOperationResultVO} 上报结果 - */ - @ApiOperation(value = "(HTTP)协议数据上报", httpMethod = "PUT", notes = "(HTTP)协议数据上报") - @PostMapping("/deviceDataReportByHttp") - R deviceDataReportByHttp(@RequestBody @ApiParam(value = "数据上报参数") TopoDeviceDataReportParam topoDeviceDataReportParam); - - /** - * Queries device information using the MQTT protocol. - * - * @param topoQueryDeviceParam The device query parameters. - * @return {@link TopoQueryDeviceResultVO} The result of the device query. - */ - @ApiOperation(value = "Query Device Information via MQTT Protocol", httpMethod = "POST", notes = "Queries device information using the MQTT protocol") - @PostMapping("/queryDeviceByMqtt") - public R queryDeviceByMqtt(@RequestBody TopoQueryDeviceParam topoQueryDeviceParam); - - /** - * Queries device information using the HTTP protocol. - * - * @param topoQueryDeviceParam The device query parameters. - * @return {@link TopoQueryDeviceResultVO} The result of the device query. - */ - @ApiOperation(value = "Query Device Information via HTTP Protocol", httpMethod = "POST", notes = "Queries device information using the HTTP protocol") - @PostMapping("/queryDeviceByHttp") - public R queryDeviceByHttp(@RequestBody TopoQueryDeviceParam topoQueryDeviceParam); - - - /** - * Receives and saves a new OTA upgrade record from an MQTT message. This endpoint - * captures the command response parameters from the MQTT message body and persists them. - * - * @param otaCommandResponseParam The response parameters from an OTA command sent via MQTT. - * @return {@link R} A response entity containing the saved OTA upgrade record. - */ - @ApiOperation(value = "Save OTA Upgrade Record", httpMethod = "POST", notes = "Saves a new OTA upgrade record from MQTT message data.") - @PostMapping("/saveUpgradeRecordByMqtt") - public R saveUpgradeRecordByMqtt(@Valid @RequestBody OtaCommandResponseParam otaCommandResponseParam); - - - /** - * Receives and saves a new OTA upgrade record from an HTTP request. This endpoint - * captures the command response parameters from the request body and persists them. - * - * @param otaCommandResponseParam The response parameters from an OTA command sent via HTTP. - * @return {@link R} A response wrapper containing the saved OTA upgrade record. - */ - @ApiOperation(value = "Save OTA Upgrade Record via HTTP", httpMethod = "POST", notes = "Saves a new OTA upgrade record from HTTP request data.") - @PostMapping("/saveUpgradeRecordByHttp") - public R saveUpgradeRecordByHttp(@Valid @RequestBody OtaCommandResponseParam otaCommandResponseParam); - - - } diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductModelCacheVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductModelCacheVO.java index 38fcd65b..40894c8f 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductModelCacheVO.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductModelCacheVO.java @@ -1,12 +1,14 @@ package com.mqttsnet.thinglinks.link.api.domain.cache.product; import cn.hutool.core.map.MapUtil; -import com.mqttsnet.thinglinks.link.api.domain.product.model.ProductModel; +import com.mqttsnet.thinglinks.link.api.domain.product.vo.param.ProductServiceParamVO; import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import lombok.*; import lombok.experimental.Accessors; import java.io.Serializable; +import java.util.List; import java.util.Map; /** @@ -26,8 +28,53 @@ @Builder @AllArgsConstructor @ApiModel(value = "ProductModelCacheVO", description = "产品模型缓存VO") -public class ProductModelCacheVO extends ProductModel implements Serializable { +public class ProductModelCacheVO implements Serializable { private static final long serialVersionUID = 1L; private Map echoMap = MapUtil.newHashMap(); + + @ApiModelProperty(value = "租户ID") + private Long tenantId; + + @ApiModelProperty(value = "应用ID") + private String appId; + + @ApiModelProperty(value = "产品标识") + private String productIdentification; + + @ApiModelProperty(value = "模板ID") + private Long templateId; + + @ApiModelProperty(value = "产品名称") + private String productName; + + @ApiModelProperty(value = "产品类型") + private Integer productType; + + @ApiModelProperty(value = "厂商ID") + private String manufacturerId; + + @ApiModelProperty(value = "厂商名称") + private String manufacturerName; + + @ApiModelProperty(value = "产品型号") + private String model; + + @ApiModelProperty(value = "数据格式") + private String dataFormat; + + @ApiModelProperty(value = "设备类型") + private String deviceType; + + @ApiModelProperty(value = "协议类型") + private String protocolType; + + @ApiModelProperty(value = "产品版本") + private String productVersion; + + @ApiModelProperty(value = "产品描述") + private String remark; + + @ApiModelProperty(value = "产品模型服务") + private List services; } diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/enumeration/DeviceActionStatusEnum.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/enumeration/DeviceActionStatusEnum.java new file mode 100644 index 00000000..db5c0dd9 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/enumeration/DeviceActionStatusEnum.java @@ -0,0 +1,60 @@ +package com.mqttsnet.thinglinks.link.api.domain.device.enumeration; + +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.Optional; +import java.util.stream.Stream; + +/** + *

+ * 设备动作状态 枚举 + *

+ * + * @author shihuan sun + * @date 2023-08-20 + */ +@Getter +@AllArgsConstructor +@NoArgsConstructor +@ApiModel(value = "DeviceActionStatusEnum", description = "设备动作状态 枚举") +public enum DeviceActionStatusEnum { + /** + * 成功 + */ + SUCCESSFUL("successful", "成功"), + + /** + * 失败 + */ + FAIL("fall", "失败"), + ; + + private String value; + private String desc; + + public void setValue(String value) { + this.value = value; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + + /** + * 根据key获取对应的枚举 + * + * @param value 设备连接的状态值 + * @return 返回对应的枚举,如果没找到则返回 Optional.empty() + */ + public static Optional fromValue(Integer value) { + return Stream.of(DeviceActionStatusEnum.values()) + .filter(status -> status.getValue().equals(value)) + .findFirst(); + } + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/enumeration/MqttProtocolTopoStatusEnum.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/enumeration/MqttProtocolTopoStatusEnum.java new file mode 100644 index 00000000..b4568480 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/enumeration/MqttProtocolTopoStatusEnum.java @@ -0,0 +1,43 @@ +package com.mqttsnet.thinglinks.link.api.domain.device.enumeration; + +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + + +/** + * @program: thinglinks + * @description: MQTT协议Topo 状态枚举 + * @packagename: com.mqttsnet.thinglinks.link.api.domain.device.enumeration + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-05-20 17:51 + **/ +@Getter +@AllArgsConstructor +@NoArgsConstructor +@ApiModel(value = "MqttProtocolTopoStatusEnum", description = "MQTT协议Topo 状态枚举") +public enum MqttProtocolTopoStatusEnum { + /** + * 成功 + */ + SUCCESS(0, "success"), + + /** + * 失败 + */ + FAILURE(1, "failure"), + ; + + private Integer value; + private String desc; + + public void setValue(Integer value) { + this.value = value; + } + + public void setDesc(String desc) { + this.desc = desc; + } +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductProperties.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductProperties.java index f079648a..dcdda37a 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductProperties.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductProperties.java @@ -10,7 +10,7 @@ import lombok.experimental.Accessors; /** - + 产品模型服务属性表 * @Description: java类作用描述 * @Author: ShiHuan Sun * @E-mail: 13733918655@163.com @@ -20,11 +20,7 @@ * @UpdateDate: 2021/12/25$ 23:52$ * @UpdateRemark: 修改内容 * @Version: 1.0 - */ -/** - * 产品模型服务属性表 - */ @ApiModel(value="产品模型服务属性表") @Data @NoArgsConstructor @@ -114,11 +110,10 @@ public class ProductProperties extends BaseEntity implements Serializable { /** * 指示单位。支持长度不超过50。 -取值根据参数确定,如: -•温度单位:“C”或“K” -•百分比单位:“%” -•压强单位:“Pa”或“kPa” - + 取值根据参数确定,如: + •温度单位:“C”或“K” + •百分比单位:“%” + •压强单位:“Pa”或“kPa” */ @ApiModelProperty(value="指示单位。支持长度不超过50。,取值根据参数确定,如:,•温度单位:“C”或“K”,•百分比单位:“%”,•压强单位:“Pa”或“kPa”,") private String unit; diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductServices.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductServices.java index 7002fbb5..a70f2325 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductServices.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductServices.java @@ -2,20 +2,20 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import java.io.Serializable; -import java.time.LocalDateTime; - import lombok.*; import lombok.experimental.Accessors; +import java.io.Serializable; +import java.time.LocalDateTime; + /** -* @program: thinglinks -* @description: ${description} -* @packagename: com.mqttsnet.thinglinks.link.api.domain.product.entity -* @author: ShiHuan Sun -* @e-mainl: 13733918655@163.com -* @date: 2022-11-18 20:38 -**/ + * @program: thinglinks + * @description: ${description} + * @packagename: com.mqttsnet.thinglinks.link.api.domain.product.entity + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2022-11-18 20:38 + **/ /** * 产品模型服务表 @@ -35,9 +35,15 @@ public class ProductServices implements Serializable { private Long id; /** - * 服务名称:支持英文大小写、数字、下划线和中划线 + * 服务编码:支持英文大小写、数字、下划线和中划线 + */ + @ApiModelProperty(value = "服务编码:支持英文大小写、数字、下划线和中划线") + private String serviceCode; + + /** + * 服务名称 */ - @ApiModelProperty(value = "服务名称:支持英文大小写、数字、下划线和中划线,") + @ApiModelProperty(value = "服务名称") private String serviceName; /** diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/enumeration/ProductTypeEnum.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/enumeration/ProductTypeEnum.java new file mode 100644 index 00000000..cb5d2728 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/enumeration/ProductTypeEnum.java @@ -0,0 +1,71 @@ +package com.mqttsnet.thinglinks.link.api.domain.product.enumeration; + +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.NoArgsConstructor; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** + *

+ * 产品类型 + *

+ * + * @author shihuan sun + * @date 2023-04-14 + */ +@AllArgsConstructor +@NoArgsConstructor +@ApiModel(value = "ProductTypeEnum", description = "产品类型") +public enum ProductTypeEnum { + + /** + * 普通产品,需直连设备 + */ + COMMON("COMMON", "COMMON"), + + /** + * 网关产品,可挂载子设备 + */ + GATEWAY("GATEWAY", "GATEWAY"), + + /** + * 未知产品 + */ + UNKNOWN("UNKNOWN", "UNKNOWN"), + + ; + + private String value; + private String desc; + + /** + * 可选值 + */ + public static final List TYPE_COLLECTION = Arrays.asList(COMMON.value, GATEWAY.value, UNKNOWN.value); + + public static ProductTypeEnum valueOf(Integer value) { + return Arrays.stream(values()) + .filter(type -> type.getValue().equals(Optional.ofNullable(value).orElse(-1))) // 使用一个不存在的默认值,如-1 + .findFirst() + .orElse(UNKNOWN); // 或者您可以选择返回一个默认的枚举值,比如UNKNOWN + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandParamVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandParamVO.java new file mode 100644 index 00000000..9d1db60b --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandParamVO.java @@ -0,0 +1,78 @@ +package com.mqttsnet.thinglinks.link.api.domain.product.vo.param; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; +import java.util.List; + +/** + *

+ * 表单保存方法VO + * 产品模型设备服务命令表 + *

+ * + * @author mqttsnet + * @date 2023-03-14 19:39:59 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "ProductCommandParamVO", description = "产品模型设备服务命令参数VO") +public class ProductCommandParamVO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 服务ID + */ + @ApiModelProperty(value = "服务ID") + @NotNull(message = "请填写服务ID") + private Long serviceId; + /** + * 指示命令的编码,如门磁的LOCK命令、摄像头的VIDEO_RECORD命令,命令名与参数共同构成一个完整的命令。支持英文大小写、数字及下划线,长度[2,50]。 + */ + @ApiModelProperty(value = "指示命令的编码,如门磁的LOCK命令、摄像头的VIDEO_RECORD命令,命令名与参数共同构成一个完整的命令。支持英文大小写、数字及下划线,长度[2,50]。") + @NotEmpty(message = "请填写指示命令的编码,如门磁的LOCK命令、摄像头的VIDEO_RECORD命令,命令名与参数共同构成一个完整的命令。支持英文大小写、数字及下划线,长度[2,50]。") + @Size(max = 255, message = "指示命令的编码,如门磁的LOCK命令、摄像头的VIDEO_RECORD命令,命令名与参数共同构成一个完整的命令。支持英文大小写、数字及下划线,长度[2,50]。长度不能超过{max}") + private String commandCode; + /** + * 指示命令名称 + */ + @ApiModelProperty(value = "指示命令名称") + @Size(max = 255, message = "指示命令名称长度不能超过{max}") + private String commandName; + /** + * 命令描述。 + */ + @ApiModelProperty(value = "命令描述") + @Size(max = 255, message = "命令描述。长度不能超过{max}") + private String description; + /** + * 备注 + */ + @ApiModelProperty(value = "备注") + @Size(max = 500, message = "备注长度不能超过{max}") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + @ApiModelProperty(value = "产品请求服务命令属性") + private List requests; + + @ApiModelProperty(value = "产品响应服务命令属性") + private List responses; + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandRequestParamVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandRequestParamVO.java new file mode 100644 index 00000000..d62152d9 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandRequestParamVO.java @@ -0,0 +1,128 @@ +package com.mqttsnet.thinglinks.link.api.domain.product.vo.param; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; + +/** + *

+ * 表单保存方法VO + * 产品模型设备下发服务命令属性表 + *

+ * + * @author mqttsnet + * @date 2023-03-14 19:39:59 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "ProductCommandRequestParamVO", description = "产品模型设备下发服务命令属性表") +public class ProductCommandRequestParamVO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 服务ID + */ + @ApiModelProperty(value = "服务ID") + @NotNull(message = "请填写服务ID") + private Long serviceId; + /** + * 命令ID + */ + @ApiModelProperty(value = "命令ID") + @NotNull(message = "请填写命令ID") + private Long commandId; + /** + * 参数编码 + */ + @ApiModelProperty(value = "参数编码") + @Size(max = 255, message = "参数编码长度不能超过{max}") + private String parameterCode; + /** + * 命令中参数的名字。 + */ + @ApiModelProperty(value = "命令中参数的名字。") + @Size(max = 255, message = "命令中参数的名字。长度不能超过{max}") + private String parameterName; + /** + * 命令中参数的描述,不影响实际功能,可配置为空字符串。 + */ + @ApiModelProperty(value = "命令中参数的描述,不影响实际功能,可配置为空字符串。") + @Size(max = 255, message = "命令中参数的描述,不影响实际功能,可配置为空字符串。长度不能超过{max}") + private String parameterDescription; + /** + * 指示数据类型。取值范围:string、int、decimal + */ + @ApiModelProperty(value = "指示数据类型。取值范围:string、int、decimal") + @NotEmpty(message = "请填写指示数据类型。取值范围:string、int、decimal") + @Size(max = 255, message = "指示数据类型。取值范围:string、int、decimal长度不能超过{max}") + private String datatype; + /** + * 指示枚举值。如开关状态status可有如下取值enumList" : [OPEN,CLOSE]目前本字段是非功能性字段,仅起到描述作用。建议准确定义。 + */ + @ApiModelProperty(value = "指示枚举值。如开关状态status可有如下取值enumList : [OPEN,CLOSE]目前本字段是非功能性字段,仅起到描述作用。建议准确定义。") + @Size(max = 255, message = "指示枚举值。如开关状态status可有如下取值enumList : [OPEN,CLOSE]目前本字段是非功能性字段,仅起到描述作用。建议准确定义。长度不能超过{max}") + private String enumlist; + /** + * 指示最大值。仅当dataType为int、decimal时生效,逻辑小于等于。 + */ + @ApiModelProperty(value = "指示最大值。仅当dataType为int、decimal时生效,逻辑小于等于。") + @Size(max = 255, message = "指示最大值。仅当dataType为int、decimal时生效,逻辑小于等于。长度不能超过{max}") + private String max; + /** + * 指示字符串长度。仅当dataType为string时生效。 + */ + @ApiModelProperty(value = "指示字符串长度。仅当dataType为string时生效。") + @Size(max = 255, message = "指示字符串长度。仅当dataType为string时生效。长度不能超过{max}") + private String maxlength; + /** + * 指示最小值。仅当dataType为int、decimal时生效,逻辑大于等于。 + */ + @ApiModelProperty(value = "指示最小值。仅当dataType为int、decimal时生效,逻辑大于等于。") + @Size(max = 255, message = "指示最小值。仅当dataType为int、decimal时生效,逻辑大于等于。长度不能超过{max}") + private String min; + /** + * 指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。 + */ + @ApiModelProperty(value = "指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。") + @NotEmpty(message = "请填写指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。") + @Size(max = 255, message = "指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。长度不能超过{max}") + private String required; + /** + * 指示步长。 + */ + @ApiModelProperty(value = "指示步长。") + @Size(max = 255, message = "指示步长。长度不能超过{max}") + private String step; + /** + * 指示单位。取值根据参数确定,如:•温度单位:“C”或“K”•百分比单位:“%”•压强单位:“Pa”或“kPa” + */ + @ApiModelProperty(value = "指示单位。取值根据参数确定,如:•温度单位:“C”或“K”•百分比单位:“%”•压强单位:“Pa”或“kPa”") + @Size(max = 255, message = "指示单位。取值根据参数确定,如:•温度单位:“C”或“K”•百分比单位:“%”•压强单位:“Pa”或“kPa”长度不能超过{max}") + private String unit; + /** + * 备注 + */ + @ApiModelProperty(value = "备注") + @Size(max = 500, message = "备注长度不能超过{max}") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandResponseParamVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandResponseParamVO.java new file mode 100644 index 00000000..ab807ea3 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandResponseParamVO.java @@ -0,0 +1,127 @@ +package com.mqttsnet.thinglinks.link.api.domain.product.vo.param; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; + +/** + *

+ * 表单保存方法VO + * 产品模型设备响应服务命令属性表 + *

+ * + * @author mqttsnet + * @date 2023-03-14 19:39:59 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "ProductCommandResponseParamVO", description = "产品模型设备响应服务命令属性表") +public class ProductCommandResponseParamVO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 命令ID + */ + @ApiModelProperty(value = "命令ID") + @NotNull(message = "请填写命令ID") + private Long commandId; + /** + * 服务ID + */ + @ApiModelProperty(value = "服务ID") + private Long serviceId; + /** + * 指示数据类型。取值范围:string、int、decimal + */ + @ApiModelProperty(value = "指示数据类型。取值范围:string、int、decimal") + @NotEmpty(message = "请填写指示数据类型。取值范围:string、int、decimal") + @Size(max = 255, message = "指示数据类型。取值范围:string、int、decimal长度不能超过{max}") + private String datatype; + /** + * 指示枚举值。如开关状态status可有如下取值enumList : [OPEN,CLOSE]目前本字段是非功能性字段,仅起到描述作用。建议准确定义。 + */ + @ApiModelProperty(value = "指示枚举值。如开关状态status可有如下取值enumList : [OPEN,CLOSE]目前本字段是非功能性字段,仅起到描述作用。建议准确定义。") + @Size(max = 255, message = "指示枚举值。如开关状态status可有如下取值enumList : [OPEN,CLOSE]目前本字段是非功能性字段,仅起到描述作用。建议准确定义。长度不能超过{max}") + private String enumlist; + /** + * 指示最大值。仅当dataType为int、decimal时生效,逻辑小于等于。 + */ + @ApiModelProperty(value = "指示最大值。仅当dataType为int、decimal时生效,逻辑小于等于。") + @Size(max = 255, message = "指示最大值。仅当dataType为int、decimal时生效,逻辑小于等于。长度不能超过{max}") + private String max; + /** + * 指示字符串长度。仅当dataType为string时生效。 + */ + @ApiModelProperty(value = "指示字符串长度。仅当dataType为string时生效。") + @Size(max = 255, message = "指示字符串长度。仅当dataType为string时生效。长度不能超过{max}") + private String maxlength; + /** + * 指示最小值。仅当dataType为int、decimal时生效,逻辑大于等于。 + */ + @ApiModelProperty(value = "指示最小值。仅当dataType为int、decimal时生效,逻辑大于等于。") + @Size(max = 255, message = "指示最小值。仅当dataType为int、decimal时生效,逻辑大于等于。长度不能超过{max}") + private String min; + /** + * 命令中参数的描述,不影响实际功能,可配置为空字符串。 + */ + @ApiModelProperty(value = "命令中参数的描述,不影响实际功能,可配置为空字符串。") + @Size(max = 255, message = "命令中参数的描述,不影响实际功能,可配置为空字符串。长度不能超过{max}") + private String parameterDescription; + /** + * 参数编码 + */ + @ApiModelProperty(value = "参数编码") + private String parameterCode; + + /** + * 命令中参数的名字。 + */ + @ApiModelProperty(value = "命令中参数的名字。") + @Size(max = 255, message = "命令中参数的名字。长度不能超过{max}") + private String parameterName; + /** + * 指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。 + */ + @ApiModelProperty(value = "指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。") + @NotEmpty(message = "请填写指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。") + @Size(max = 255, message = "指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。长度不能超过{max}") + private String required; + /** + * 指示步长。 + */ + @ApiModelProperty(value = "指示步长。") + @Size(max = 255, message = "指示步长。长度不能超过{max}") + private String step; + /** + * 指示单位。取值根据参数确定,如:•温度单位:“C”或“K”•百分比单位:“%”•压强单位:“Pa”或“kPa” + */ + @ApiModelProperty(value = "指示单位。取值根据参数确定,如:•温度单位:“C”或“K”•百分比单位:“%”•压强单位:“Pa”或“kPa”") + @Size(max = 255, message = "指示单位。取值根据参数确定,如:•温度单位:“C”或“K”•百分比单位:“%”•压强单位:“Pa”或“kPa”长度不能超过{max}") + private String unit; + /** + * 备注 + */ + @ApiModelProperty(value = "备注") + @Size(max = 500, message = "备注长度不能超过{max}") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductPropertyParamVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductPropertyParamVO.java new file mode 100644 index 00000000..65b73052 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductPropertyParamVO.java @@ -0,0 +1,134 @@ +package com.mqttsnet.thinglinks.link.api.domain.product.vo.param; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; + +/** + *

+ * 表单保存方法VO + * 产品模型服务属性表 + *

+ * + * @author mqttsnet + * @date 2023-03-14 19:39:59 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "ProductPropertyParamVO", description = "产品模型服务属性参数VO") +public class ProductPropertyParamVO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 服务ID + */ + @ApiModelProperty(value = "服务ID") + @NotNull(message = "请填写服务ID") + private Long serviceId; + /** + * 指示属性编码 + */ + @ApiModelProperty(value = "指示属性编码") + @NotEmpty(message = "请填写指示属性编码") + @Size(max = 255, message = "指示属性编码长度不能超过{max}") + private String propertyCode; + /** + * 指示属性名称 + */ + @ApiModelProperty(value = "指示属性名称") + @Size(max = 255, message = "指示属性名称长度不能超过{max}") + private String propertyName; + /** + * 指示数据类型:取值范围:string、int、decimal(float和double都可以使用此类型)、DateTime、jsonObject上报数据时,复杂类型数据格式如下:•DateTime:yyyyMMdd’T’HHmmss’Z’如:20151212T121212Z•jsonObject:自定义json结构体,平台不理解只透传 + */ + @ApiModelProperty(value = "指示数据类型:取值范围:string、int、decimal(float和double都可以使用此类型)、DateTime、jsonObject上报数据时,复杂类型数据格式如下:•DateTime:yyyyMMdd’T’HHmmss’Z’如:20151212T121212Z•jsonObject:自定义json结构体,平台不理解只透传") + @NotEmpty(message = "请填写指示数据类型:取值范围:string、int、decimal(float和double都可以使用此类型)、DateTime、jsonObject上报数据时,复杂类型数据格式如下:•DateTime:yyyyMMdd’T’HHmmss’Z’如:20151212T121212Z•jsonObject:自定义json结构体,平台不理解只透传") + @Size(max = 255, message = "指示数据类型:取值范围:string、int、decimal(float和double都可以使用此类型)、DateTime、jsonObject上报数据时,复杂类型数据格式如下:•DateTime:yyyyMMdd’T’HHmmss’Z’如:20151212T121212Z•jsonObject:自定义json结构体,平台不理解只透传长度不能超过{max}") + private String datatype; + /** + * 属性描述,不影响实际功能,可配置为空字符串。 + */ + @ApiModelProperty(value = "属性描述,不影响实际功能,可配置为空字符串。") + @Size(max = 255, message = "属性描述,不影响实际功能,可配置为空字符串。长度不能超过{max}") + private String description; + /** + * 指示枚举值:如开关状态status可有如下取值enumList: [OPEN,CLOSE]目前本字段是非功能性字段,仅起到描述作用。建议准确定义。 + */ + @ApiModelProperty(value = "指示枚举值:如开关状态status可有如下取值enumList: [OPEN,CLOSE]目前本字段是非功能性字段,仅起到描述作用。建议准确定义。") + @Size(max = 255, message = "指示枚举值:如开关状态status可有如下取值enumList: [OPEN,CLOSE]目前本字段是非功能性字段,仅起到描述作用。建议准确定义。长度不能超过{max}") + private String enumlist; + /** + * 指示最大值。支持长度不超过50的数字。仅当dataType为int、decimal时生效,逻辑小于等于。 + */ + @ApiModelProperty(value = "指示最大值。支持长度不超过50的数字。仅当dataType为int、decimal时生效,逻辑小于等于。") + @Size(max = 255, message = "指示最大值。支持长度不超过50的数字。仅当dataType为int、decimal时生效,逻辑小于等于。长度不能超过{max}") + private String max; + /** + * 指示字符串长度。仅当dataType为string、DateTime时生效。 + */ + @ApiModelProperty(value = "指示字符串长度。仅当dataType为string、DateTime时生效。") + @Size(max = 255, message = "指示字符串长度。仅当dataType为string、DateTime时生效。长度不能超过{max}") + private String maxlength; + /** + * 指示访问模式。R:可读;W:可写;E属性值更改时上报数据取值范围:R、RW、RE、RWE + */ + @ApiModelProperty(value = "指示访问模式。R:可读;W:可写;E属性值更改时上报数据取值范围:R、RW、RE、RWE") + @Size(max = 255, message = "指示访问模式。R:可读;W:可写;E属性值更改时上报数据取值范围:R、RW、RE、RWE长度不能超过{max}") + private String method; + /** + * 指示最小值。支持长度不超过50的数字。仅当dataType为int、decimal时生效,逻辑大于等于。 + */ + @ApiModelProperty(value = "指示最小值。支持长度不超过50的数字。仅当dataType为int、decimal时生效,逻辑大于等于。") + @Size(max = 255, message = "指示最小值。支持长度不超过50的数字。仅当dataType为int、decimal时生效,逻辑大于等于。长度不能超过{max}") + private String min; + /** + * 指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。(字典值link_product_isRequired:0非必填 1必填) + */ + @ApiModelProperty(value = "指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。(字典值link_product_isRequired:0非必填 1必填)") + @NotEmpty(message = "请填写指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。(字典值link_product_isRequired:0非必填 1必填)") + @Size(max = 255, message = "指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。(字典值link_product_isRequired:0非必填 1必填)长度不能超过{max}") + private String required; + /** + * 指示步长。 + */ + @ApiModelProperty(value = "指示步长。") + @Size(max = 255, message = "指示步长。长度不能超过{max}") + private String step; + /** + * 指示单位。支持长度不超过50。取值根据参数确定,如:•温度单位:“C”或“K”•百分比单位:“%”•压强单位:“Pa”或“kPa” + */ + @ApiModelProperty(value = "指示单位。支持长度不超过50。取值根据参数确定,如:•温度单位:“C”或“K”•百分比单位:“%”•压强单位:“Pa”或“kPa”") + @Size(max = 255, message = "指示单位。支持长度不超过50。取值根据参数确定,如:•温度单位:“C”或“K”•百分比单位:“%”•压强单位:“Pa”或“kPa”长度不能超过{max}") + private String unit; + /** + * 图标png图 + */ + @ApiModelProperty(value = "图标png图") + @Size(max = 255, message = "图标png图长度不能超过{max}") + private String icon; + /** + * 备注 + */ + @ApiModelProperty(value = "备注") + @Size(max = 500, message = "备注长度不能超过{max}") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductServiceParamVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductServiceParamVO.java new file mode 100644 index 00000000..e511e2ed --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductServiceParamVO.java @@ -0,0 +1,89 @@ +package com.mqttsnet.thinglinks.link.api.domain.product.vo.param; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; +import java.util.List; + +/** + *

+ * 表单保存方法VO + * 产品模型服务表 + *

+ * + * @author mqttsnet + * @date 2023-03-14 19:39:59 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "ProductServiceParamVO", description = "产品模型服务参数VO") +public class ProductServiceParamVO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 产品ID + */ + @ApiModelProperty(value = "产品ID") + private Long productId; + /** + * 服务编码:支持英文大小写、数字、下划线和中划线 + */ + @ApiModelProperty(value = "服务编码:支持英文大小写、数字、下划线和中划线") + @NotEmpty(message = "请填写服务编码:支持英文大小写、数字、下划线和中划线") + @Size(max = 255, message = "服务编码:支持英文大小写、数字、下划线和中划线长度不能超过{max}") + private String serviceCode; + /** + * 服务名称 + */ + @ApiModelProperty(value = "服务名称") + @Size(max = 255, message = "服务名称长度不能超过{max}") + private String serviceName; + /** + * 服务类型 + */ + @ApiModelProperty(value = "服务类型") + @Size(max = 255, message = "服务类型长度不能超过{max}") + private String serviceType; + /** + * 状态(字典值:0启用 1停用) + */ + @ApiModelProperty(value = "状态(字典值:0启用 1停用)") + @NotNull(message = "请填写状态(字典值:0启用 1停用)") + private Integer serviceStatus; + /** + * 服务的描述信息:文本描述,不影响实际功能,可配置为空字符串。 + */ + @ApiModelProperty(value = "服务的描述信息:文本描述,不影响实际功能,可配置为空字符串。") + @Size(max = 255, message = "服务的描述信息:文本描述,不影响实际功能,可配置为空字符串。长度不能超过{max}") + private String description; + /** + * 备注 + */ + @ApiModelProperty(value = "备注") + @Size(max = 500, message = "备注长度不能超过{max}") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + @ApiModelProperty(value = "产品服务命令") + private List commands; + + @ApiModelProperty(value = "产品服务属性") + private List properties; + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductCommandRequestResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductCommandRequestResultVO.java new file mode 100644 index 00000000..c3d89930 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductCommandRequestResultVO.java @@ -0,0 +1,115 @@ +package com.mqttsnet.thinglinks.link.api.domain.product.vo.result; + +import cn.hutool.core.map.MapUtil; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Map; + +/** + *

+ * 表单查询方法返回值VO + * 产品模型设备下发服务命令属性表 + *

+ * + * @author mqttsnet + * @date 2023-03-14 19:39:59 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode(callSuper = false) +@Builder +@ApiModel(value = "ProductCommandRequestResultVO", description = "产品模型设备下发服务命令属性表") +public class ProductCommandRequestResultVO implements Serializable { + + private static final long serialVersionUID = 1L; + + private Map echoMap = MapUtil.newHashMap(); + + @ApiModelProperty(value = "id") + private Long id; + + /** + * 服务ID + */ + @ApiModelProperty(value = "服务ID") + private Long serviceId; + /** + * 命令ID + */ + @ApiModelProperty(value = "命令ID") + private Long commandId; + /** + * 参数编码 + */ + @ApiModelProperty(value = "参数编码") + private String parameterCode; + /** + * 命令中参数的名字。 + */ + @ApiModelProperty(value = "命令中参数的名字。") + private String parameterName; + /** + * 命令中参数的描述,不影响实际功能,可配置为空字符串。 + */ + @ApiModelProperty(value = "命令中参数的描述,不影响实际功能,可配置为空字符串。") + private String parameterDescription; + /** + * 指示数据类型。取值范围:string、int、decimal + */ + @ApiModelProperty(value = "指示数据类型。取值范围:string、int、decimal") + private String datatype; + /** + * 指示枚举值。如开关状态status可有如下取值enumList" : [OPEN,CLOSE]目前本字段是非功能性字段,仅起到描述作用。建议准确定义。 + */ + @ApiModelProperty(value = "指示枚举值。如开关状态status可有如下取值enumList : [OPEN,CLOSE]目前本字段是非功能性字段,仅起到描述作用。建议准确定义。") + private String enumlist; + /** + * 指示最大值。仅当dataType为int、decimal时生效,逻辑小于等于。 + */ + @ApiModelProperty(value = "指示最大值。仅当dataType为int、decimal时生效,逻辑小于等于。") + private String max; + /** + * 指示字符串长度。仅当dataType为string时生效。 + */ + @ApiModelProperty(value = "指示字符串长度。仅当dataType为string时生效。") + private String maxlength; + /** + * 指示最小值。仅当dataType为int、decimal时生效,逻辑大于等于。 + */ + @ApiModelProperty(value = "指示最小值。仅当dataType为int、decimal时生效,逻辑大于等于。") + private String min; + /** + * 指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。 + */ + @ApiModelProperty(value = "指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。") + private String required; + /** + * 指示步长。 + */ + @ApiModelProperty(value = "指示步长。") + private String step; + /** + * 指示单位。取值根据参数确定,如:•温度单位:“C”或“K”•百分比单位:“%”•压强单位:“Pa”或“kPa” + */ + @ApiModelProperty(value = "指示单位。取值根据参数确定,如:•温度单位:“C”或“K”•百分比单位:“%”•压强单位:“Pa”或“kPa”") + private String unit; + /** + * 备注 + */ + @ApiModelProperty(value = "备注") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductCommandResponseResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductCommandResponseResultVO.java new file mode 100644 index 00000000..402d33b9 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductCommandResponseResultVO.java @@ -0,0 +1,115 @@ +package com.mqttsnet.thinglinks.link.api.domain.product.vo.result; + +import cn.hutool.core.map.MapUtil; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Map; + +/** + *

+ * 表单查询方法返回值VO + * 产品模型设备响应服务命令属性表 + *

+ * + * @author mqttsnet + * @date 2023-03-14 19:39:59 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode(callSuper = false) +@Builder +@ApiModel(value = "ProductCommandResponseResultVO", description = "产品模型设备响应服务命令属性表") +public class ProductCommandResponseResultVO implements Serializable { + + private static final long serialVersionUID = 1L; + + private Map echoMap = MapUtil.newHashMap(); + + @ApiModelProperty(value = "id") + private Long id; + + /** + * 命令ID + */ + @ApiModelProperty(value = "命令ID") + private Long commandId; + /** + * 服务ID + */ + @ApiModelProperty(value = "服务ID") + private Long serviceId; + /** + * 指示数据类型。取值范围:string、int、decimal + */ + @ApiModelProperty(value = "指示数据类型。取值范围:string、int、decimal") + private String datatype; + /** + * 指示枚举值。如开关状态status可有如下取值enumList : [OPEN,CLOSE]目前本字段是非功能性字段,仅起到描述作用。建议准确定义。 + */ + @ApiModelProperty(value = "指示枚举值。如开关状态status可有如下取值enumList : [OPEN,CLOSE]目前本字段是非功能性字段,仅起到描述作用。建议准确定义。") + private String enumlist; + /** + * 指示最大值。仅当dataType为int、decimal时生效,逻辑小于等于。 + */ + @ApiModelProperty(value = "指示最大值。仅当dataType为int、decimal时生效,逻辑小于等于。") + private String max; + /** + * 指示字符串长度。仅当dataType为string时生效。 + */ + @ApiModelProperty(value = "指示字符串长度。仅当dataType为string时生效。") + private String maxlength; + /** + * 指示最小值。仅当dataType为int、decimal时生效,逻辑大于等于。 + */ + @ApiModelProperty(value = "指示最小值。仅当dataType为int、decimal时生效,逻辑大于等于。") + private String min; + /** + * 命令中参数的描述,不影响实际功能,可配置为空字符串。 + */ + @ApiModelProperty(value = "命令中参数的描述,不影响实际功能,可配置为空字符串。") + private String parameterDescription; + /** + * 参数编码 + */ + @ApiModelProperty(value = "参数编码") + private String parameterCode; + /** + * 命令中参数的名字。 + */ + @ApiModelProperty(value = "命令中参数的名字。") + private String parameterName; + /** + * 指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。 + */ + @ApiModelProperty(value = "指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。") + private String required; + /** + * 指示步长。 + */ + @ApiModelProperty(value = "指示步长。") + private String step; + /** + * 指示单位。取值根据参数确定,如:•温度单位:“C”或“K”•百分比单位:“%”•压强单位:“Pa”或“kPa” + */ + @ApiModelProperty(value = "指示单位。取值根据参数确定,如:•温度单位:“C”或“K”•百分比单位:“%”•压强单位:“Pa”或“kPa”") + private String unit; + /** + * 备注 + */ + @ApiModelProperty(value = "备注") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductCommandResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductCommandResultVO.java new file mode 100644 index 00000000..71f86cd2 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductCommandResultVO.java @@ -0,0 +1,76 @@ +package com.mqttsnet.thinglinks.link.api.domain.product.vo.result; + +import cn.hutool.core.map.MapUtil;; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +/** + *

+ * 表单查询方法返回值VO + * 产品模型设备服务命令表 + *

+ * + * @author mqttsnet + * @date 2023-03-14 19:39:59 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode(callSuper = false) +@Builder +@ApiModel(value = "ProductCommandResultVO", description = "产品模型设备服务命令表") +public class ProductCommandResultVO implements Serializable { + + private static final long serialVersionUID = 1L; + + private Map echoMap = MapUtil.newHashMap(); + + @ApiModelProperty(value = "命令id") + private Long id; + + /** + * 服务ID + */ + @ApiModelProperty(value = "服务ID") + private Long serviceId; + /** + * 指示命令的编码,如门磁的LOCK命令、摄像头的VIDEO_RECORD命令,命令名与参数共同构成一个完整的命令。支持英文大小写、数字及下划线,长度[2,50]。 + */ + @ApiModelProperty(value = "指示命令的编码,如门磁的LOCK命令、摄像头的VIDEO_RECORD命令,命令名与参数共同构成一个完整的命令。支持英文大小写、数字及下划线,长度[2,50]。") + private String commandCode; + /** + * 指示命令名称 + */ + @ApiModelProperty(value = "指示命令名称") + private String commandName; + /** + * 命令描述。 + */ + @ApiModelProperty(value = "命令描述。") + private String description; + /** + * 备注 + */ + @ApiModelProperty(value = "备注") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + @ApiModelProperty(value = "产品请求服务命令属性") + private List requests; + + @ApiModelProperty(value = "产品响应服务命令属性") + private List responses; + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductPropertyResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductPropertyResultVO.java new file mode 100644 index 00000000..9df32229 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductPropertyResultVO.java @@ -0,0 +1,131 @@ +package com.mqttsnet.thinglinks.link.api.domain.product.vo.result; + +import cn.hutool.core.collection.ListUtil; +import cn.hutool.core.map.MapUtil; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +/** + *

+ * 表单查询方法返回值VO + * 产品模型服务属性表 + *

+ * + * @author mqttsnet + * @date 2023-03-14 19:39:59 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode(callSuper = false) +@Builder +@ApiModel(value = "ProductPropertyResultVO", description = "产品模型服务属性表") +public class ProductPropertyResultVO implements Serializable { + + private static final long serialVersionUID = 1L; + + private Map echoMap = MapUtil.newHashMap(); + + private List> echoList = ListUtil.toList(); + + @ApiModelProperty(value = "属性id") + private Long id; + + /** + * 服务ID + */ + @ApiModelProperty(value = "服务ID") + private Long serviceId; + /** + * 指示属性编码 + */ + @ApiModelProperty(value = "指示属性编码") + private String propertyCode; + + /** + * 指示属性值 + */ + @ApiModelProperty(value = "指示属性值") + private Object propertyValue; + + /** + * 指示属性名称 + */ + @ApiModelProperty(value = "指示属性名称") + private String propertyName; + /** + * 指示数据类型:取值范围:string、int、decimal(float和double都可以使用此类型)、DateTime、jsonObject上报数据时,复杂类型数据格式如下:•DateTime:yyyyMMdd’T’HHmmss’Z’如:20151212T121212Z•jsonObject:自定义json结构体,平台不理解只透传 + */ + @ApiModelProperty(value = "指示数据类型:取值范围:string、int、decimal(float和double都可以使用此类型)、DateTime、jsonObject上报数据时,复杂类型数据格式如下:•DateTime:yyyyMMdd’T’HHmmss’Z’如:20151212T121212Z•jsonObject:自定义json结构体,平台不理解只透传") + private String datatype; + /** + * 属性描述,不影响实际功能,可配置为空字符串。 + */ + @ApiModelProperty(value = "属性描述,不影响实际功能,可配置为空字符串。") + private String description; + /** + * 指示枚举值:如开关状态status可有如下取值enumList: [OPEN,CLOSE]目前本字段是非功能性字段,仅起到描述作用。建议准确定义。 + */ + @ApiModelProperty(value = "指示枚举值:如开关状态status可有如下取值enumList: [OPEN,CLOSE]目前本字段是非功能性字段,仅起到描述作用。建议准确定义。") + private String enumlist; + /** + * 指示最大值。支持长度不超过50的数字。仅当dataType为int、decimal时生效,逻辑小于等于。 + */ + @ApiModelProperty(value = "指示最大值。支持长度不超过50的数字。仅当dataType为int、decimal时生效,逻辑小于等于。") + private String max; + /** + * 指示字符串长度。仅当dataType为string、DateTime时生效。 + */ + @ApiModelProperty(value = "指示字符串长度。仅当dataType为string、DateTime时生效。") + private String maxlength; + /** + * 指示访问模式。R:可读;W:可写;E属性值更改时上报数据取值范围:R、RW、RE、RWE + */ + @ApiModelProperty(value = "指示访问模式。R:可读;W:可写;E属性值更改时上报数据取值范围:R、RW、RE、RWE") + private String method; + /** + * 指示最小值。支持长度不超过50的数字。仅当dataType为int、decimal时生效,逻辑大于等于。 + */ + @ApiModelProperty(value = "指示最小值。支持长度不超过50的数字。仅当dataType为int、decimal时生效,逻辑大于等于。") + private String min; + /** + * 指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。(字典值link_product_isRequired:0非必填 1必填) + */ + @ApiModelProperty(value = "指示本条属性是否必填,取值为0或1,默认取值1(必填)。目前本字段是非功能性字段,仅起到描述作用。(字典值link_product_isRequired:0非必填 1必填)") + private String required; + /** + * 指示步长。 + */ + @ApiModelProperty(value = "指示步长。") + private String step; + /** + * 指示单位。支持长度不超过50。取值根据参数确定,如:•温度单位:“C”或“K”•百分比单位:“%”•压强单位:“Pa”或“kPa” + */ + @ApiModelProperty(value = "指示单位。支持长度不超过50。取值根据参数确定,如:•温度单位:“C”或“K”•百分比单位:“%”•压强单位:“Pa”或“kPa”") + private String unit; + /** + * 图标png图 + */ + @ApiModelProperty(value = "图标png图") + private String icon; + /** + * 备注 + */ + @ApiModelProperty(value = "备注") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductResultVO.java new file mode 100644 index 00000000..52c66e81 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductResultVO.java @@ -0,0 +1,119 @@ +package com.mqttsnet.thinglinks.link.api.domain.product.vo.result; + +import cn.hutool.core.map.MapUtil; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +/** + *

+ * 表单查询方法返回值VO + * 产品模型 + *

+ * + * @author mqttsnet + * @date 2023-03-14 19:39:59 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode(callSuper = false) +@Builder +@ApiModel(value = "ProductResultVO", description = "产品模型") +public class ProductResultVO implements Serializable { + + private static final long serialVersionUID = 1L; + + private Map echoMap = MapUtil.newHashMap(); + + @ApiModelProperty(value = "id") + private Long id; + + /** + * 应用ID + */ + @ApiModelProperty(value = "应用ID") + private String appId; + /** + * 产品id + */ + @ApiModelProperty(value = "产品id") + private Long templateId; + /** + * 产品名称:自定义,支持中文、英文大小写、数字、下划线和中划线 + */ + @ApiModelProperty(value = "产品名称:自定义,支持中文、英文大小写、数字、下划线和中划线") + private String productName; + /** + * 产品标识 + */ + @ApiModelProperty(value = "产品标识") + private String productIdentification; + /** + * 支持以下两种产品类型1•COMMON:普通产品,需直连设备。2•GATEWAY:网关产品,可挂载子设备。 0其他未知产品 + */ + @ApiModelProperty(value = "支持以下两种产品类型1•COMMON:普通产品,需直连设备。2•GATEWAY:网关产品,可挂载子设备。 0其他未知产品") + private Integer productType; + /** + * 厂商ID:支持英文大小写,数字,下划线和中划线 + */ + @ApiModelProperty(value = "厂商ID:支持英文大小写,数字,下划线和中划线") + private String manufacturerId; + /** + * 厂商名称 :支持中文、英文大小写、数字、下划线和中划线 + */ + @ApiModelProperty(value = "厂商名称 :支持中文、英文大小写、数字、下划线和中划线") + private String manufacturerName; + /** + * 产品型号,建议包含字母或数字来保证可扩展性。支持英文大小写、数字、下划线和中划线 + */ + @ApiModelProperty(value = "产品型号,建议包含字母或数字来保证可扩展性。支持英文大小写、数字、下划线和中划线") + private String model; + /** + * 数据格式,默认为JSON无需修改。 + */ + @ApiModelProperty(value = "数据格式,默认为JSON无需修改。") + private String dataFormat; + /** + * 设备类型:支持英文大小写、数字、下划线和中划线 + */ + @ApiModelProperty(value = "设备类型:支持英文大小写、数字、下划线和中划线") + private String deviceType; + /** + * 设备接入平台的协议类型,默认为MQTT无需修改。 + */ + @ApiModelProperty(value = "设备接入平台的协议类型,默认为MQTT无需修改。") + private String protocolType; + /** + * 状态(字典值:0启用 1停用) + */ + @ApiModelProperty(value = "状态(字典值:0启用 1停用)") + private Integer productStatus; + /** + * 产品版本 + */ + @ApiModelProperty(value = "产品版本") + private String productVersion; + /** + * 产品描述 + */ + @ApiModelProperty(value = "产品描述") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + + @ApiModelProperty(value = "产品模型服务") + private List services; + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductServiceResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductServiceResultVO.java new file mode 100644 index 00000000..f6397820 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/result/ProductServiceResultVO.java @@ -0,0 +1,90 @@ +package com.mqttsnet.thinglinks.link.api.domain.product.vo.result; + +import cn.hutool.core.collection.ListUtil; +import cn.hutool.core.map.MapUtil; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +/** + *

+ * 表单查询方法返回值VO + * 产品模型服务表 + *

+ * + * @author mqttsnet + * @date 2023-03-14 19:39:59 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode(callSuper = false) +@Builder +@ApiModel(value = "ProductServiceResultVO", description = "产品模型服务表") +public class ProductServiceResultVO implements Serializable { + + private static final long serialVersionUID = 1L; + + private Map echoMap = MapUtil.newHashMap(); + + private List> echoList = ListUtil.toList(); + + + @ApiModelProperty(value = "服务id") + private Long id; + + /** + * 产品ID + */ + @ApiModelProperty(value = "产品ID") + private Long productId; + /** + * 服务编码:支持英文大小写、数字、下划线和中划线 + */ + @ApiModelProperty(value = "服务编码:支持英文大小写、数字、下划线和中划线") + private String serviceCode; + /** + * 服务名称 + */ + @ApiModelProperty(value = "服务名称") + private String serviceName; + /** + * 服务类型 + */ + @ApiModelProperty(value = "服务类型") + private String serviceType; + /** + * 状态(字典值:0启用 1停用) + */ + @ApiModelProperty(value = "状态(字典值:0启用 1停用)") + private Integer serviceStatus; + /** + * 服务的描述信息:文本描述,不影响实际功能,可配置为空字符串。 + */ + @ApiModelProperty(value = "服务的描述信息:文本描述,不影响实际功能,可配置为空字符串。") + private String description; + /** + * 备注 + */ + @ApiModelProperty(value = "备注") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + @ApiModelProperty(value = "产品服务命令") + private List commands; + + @ApiModelProperty(value = "产品服务属性") + private List properties; + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/ProtocolDataMessageResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/ProtocolDataMessageResultVO.java index 5b0afee6..22aa6e63 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/ProtocolDataMessageResultVO.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/ProtocolDataMessageResultVO.java @@ -8,7 +8,7 @@ import java.io.Serializable; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: 协议数据内容返回VO * @packagename: com.mqttsnet.thinglinks.device.vo.result * @author: ShiHuan Sun diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoAddDeviceResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoAddDeviceResultVO.java index dd7289af..4cb794c5 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoAddDeviceResultVO.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoAddDeviceResultVO.java @@ -9,7 +9,7 @@ import java.util.List; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: 协议添加网关子设备响应信息 * @packagename: com.mqttsnet.thinglinks.device.vo.result * @author: ShiHuan Sun diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoDeviceOperationResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoDeviceOperationResultVO.java index 80aa939b..da821c49 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoDeviceOperationResultVO.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoDeviceOperationResultVO.java @@ -12,7 +12,7 @@ import java.util.List; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: 设备操作结果数据模型 * @packagename: com.mqttsnet.thinglinks.device.vo.result * @author: ShiHuan Sun diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoQueryDeviceResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoQueryDeviceResultVO.java index 6adad129..263a19da 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoQueryDeviceResultVO.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/vo/result/TopoQueryDeviceResultVO.java @@ -9,7 +9,7 @@ import java.util.List; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: 协议查询设备档案信息响应信息 * @packagename: com.mqttsnet.thinglinks.device.vo.result * @author: ShiHuan Sun @@ -126,6 +126,27 @@ public static class DeviceInfo { */ @ApiModelProperty(value = "设备类型:0普通设备 || 1网关设备 || 2子设备 ") private Integer nodeType; + + /** + * 加密密钥 + */ + @ApiModelProperty(value = "加密密钥") + private String encryptKey; + /** + * 加密向量 + */ + @ApiModelProperty(value = "加密向量") + private String encryptVector; + /** + * 签名密钥 + */ + @ApiModelProperty(value = "签名密钥") + private String signKey; + /** + * 传输协议的加密方式:0-明文传输、1-SM4、2-AES + */ + @ApiModelProperty(value = "传输协议的加密方式:0-明文传输、1-SM4、2-AES ") + private Integer encryptMethod; /** * 备注 */ diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteDeviceFallbackFactory.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteDeviceFallbackFactory.java index ead39d30..59892788 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteDeviceFallbackFactory.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteDeviceFallbackFactory.java @@ -3,10 +3,6 @@ import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; -import com.mqttsnet.thinglinks.link.api.domain.vo.param.*; -import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; -import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; -import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoQueryDeviceResultVO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.openfeign.FallbackFactory; @@ -72,143 +68,9 @@ public R selectAllByProductIdentification(String productIdentification) { @Override public R selectDeviceByDeviceIdentificationList(List deviceIdentificationList) { - return R.fail("根据设备标识列表查询设备失败:" + throwable.getMessage()); } - /** - * (MQTT)协议新增子设备档案 - * - * @param topoAddSubDeviceParam 子设备参数 - * @return {@link TopoAddDeviceResultVO} 新增结果 - */ - @Override - public R saveSubDeviceByMqtt(TopoAddSubDeviceParam topoAddSubDeviceParam) { - return R.fail("新增子设备失败:" + throwable.getMessage()); - } - - /** - * (HTTP)协议新增子设备档案 - * - * @param topoAddSubDeviceParam 子设备参数 - * @return {@link TopoAddDeviceResultVO} 新增结果 - */ - @Override - public R saveSubDeviceByHttp(TopoAddSubDeviceParam topoAddSubDeviceParam) { - return R.fail("新增子设备失败:" + throwable.getMessage()); - } - - /** - * MQTT协议修改子设备连接状态 - * - * @param topoUpdateSubDeviceStatusParam 连接状态参数 - * @return {@link TopoDeviceOperationResultVO} 修改结果 - */ - @Override - public R updateSubDeviceConnectStatusByMqtt(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { - return R.fail("修改子设备连接状态失败:" + throwable.getMessage()); - } - - /** - * HTTP协议修改子设备连接状态 - * - * @param topoUpdateSubDeviceStatusParam 连接状态参数 - * @return {@link TopoDeviceOperationResultVO} 修改结果 - */ - @Override - public R updateSubDeviceConnectStatusByHttp(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { - return R.fail("修改子设备连接状态失败:" + throwable.getMessage()); - } - - /** - * MQTT协议删除子设备 - * - * @param topoDeleteSubDeviceParam 删除参数 - * @return {@link TopoDeviceOperationResultVO} 修改结果 - */ - @Override - public R deleteSubDeviceByMqtt(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { - return R.fail("删除子设备失败:" + throwable.getMessage()); - } - - /** - * HTTP协议删除子设备 - * - * @param topoDeleteSubDeviceParam 删除参数 - * @return {@link TopoDeviceOperationResultVO} 修改结果 - */ - @Override - public R deleteSubDeviceByHttp(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { - return R.fail("删除子设备失败:" + throwable.getMessage()); - } - - /** - * MQTT协议数据上报 - * - * @param topoDeviceDataReportParam 数据上报参数 - * @return {@link TopoDeviceOperationResultVO} 上报结果 - */ - @Override - public R deviceDataReportByMqtt(TopoDeviceDataReportParam topoDeviceDataReportParam) { - return R.fail("数据上报失败:" + throwable.getMessage()); - } - - /** - * HTTP协议数据上报 - * - * @param topoDeviceDataReportParam 数据上报参数 - * @return {@link TopoDeviceOperationResultVO} 上报结果 - */ - @Override - public R deviceDataReportByHttp(TopoDeviceDataReportParam topoDeviceDataReportParam) { - return R.fail("数据上报失败:" + throwable.getMessage()); - } - - /** - * Queries device information using the MQTT protocol. - * - * @param topoQueryDeviceParam The device query parameters. - * @return {@link TopoQueryDeviceResultVO} The result of the device query. - */ - @Override - public R queryDeviceByMqtt(TopoQueryDeviceParam topoQueryDeviceParam) { - return R.fail("查询设备失败:" + throwable.getMessage()); - } - - /** - * Queries device information using the HTTP protocol. - * - * @param topoQueryDeviceParam The device query parameters. - * @return {@link TopoQueryDeviceResultVO} The result of the device query. - */ - @Override - public R queryDeviceByHttp(TopoQueryDeviceParam topoQueryDeviceParam) { - return R.fail("查询设备失败:" + throwable.getMessage()); - } - - /** - * Receives and saves a new OTA upgrade record from an MQTT message. This endpoint - * captures the command response parameters from the MQTT message body and persists them. - * - * @param otaCommandResponseParam The response parameters from an OTA command sent via MQTT. - * @return {@link R} A response entity containing the saved OTA upgrade record. - */ - @Override - public R saveUpgradeRecordByMqtt(OtaCommandResponseParam otaCommandResponseParam) { - return R.fail("保存升级记录失败:" + throwable.getMessage()); - } - - /** - * Receives and saves a new OTA upgrade record from an HTTP request. This endpoint - * captures the command response parameters from the request body and persists them. - * - * @param otaCommandResponseParam The response parameters from an OTA command sent via HTTP. - * @return {@link R} A response wrapper containing the saved OTA upgrade record. - */ - @Override - public R saveUpgradeRecordByHttp(OtaCommandResponseParam otaCommandResponseParam) { - return R.fail("保存升级记录失败:" + throwable.getMessage()); - } }; } } diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteDeviceInfoFallbackFactory.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteDeviceInfoFallbackFactory.java index 9b490049..ee6f492c 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteDeviceInfoFallbackFactory.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteDeviceInfoFallbackFactory.java @@ -30,6 +30,7 @@ public RemoteDeviceInfoService create(Throwable throwable) { public AjaxResult refreshDeviceInfoDataModel(Long[] ids) { return AjaxResult.error("刷新子设备数据模型失败:" + throwable.getMessage()); } + }; } } diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteDeviceOpenAnyFallbackFactory.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteDeviceOpenAnyFallbackFactory.java new file mode 100644 index 00000000..696891db --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteDeviceOpenAnyFallbackFactory.java @@ -0,0 +1,97 @@ + +package com.mqttsnet.thinglinks.link.api.factory; + +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.*; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoQueryDeviceResultVO; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.openfeign.FallbackFactory; +import org.springframework.stereotype.Component; + +import java.util.Map; + +/** + * 设备管理开放服务降级处理 + * + * @author xiaonannet + */ +@Component +public class RemoteDeviceOpenAnyFallbackFactory implements FallbackFactory { + private static final Logger log = LoggerFactory.getLogger(RemoteDeviceOpenAnyFallbackFactory.class); + + @Override + public RemoteDeviceOpenAnyService create(Throwable throwable) { + log.error("设备管理开放服务调用失败:{}", throwable.getMessage()); + return new RemoteDeviceOpenAnyService() { + + @Override + public R clientAuthentication(Map params) { + return R.fail("客户端身份认证失败:" + throwable.getMessage()); + } + + @Override + public R saveSubDeviceByMqtt(TopoAddSubDeviceParam topoAddSubDeviceParam) { + return R.fail("(MQTT)协议新增子设备档案失败:" + throwable.getMessage()); + } + + @Override + public R saveSubDeviceByHttp(TopoAddSubDeviceParam topoAddSubDeviceParam) { + return R.fail("(HTTP)协议新增子设备档案失败:" + throwable.getMessage()); + } + + @Override + public R updateSubDeviceConnectStatusByMqtt(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { + return R.fail("MQTT协议修改子设备连接状态失败:" + throwable.getMessage()); + } + + @Override + public R updateSubDeviceConnectStatusByHttp(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { + return R.fail("HTTP协议修改子设备连接状态失败:" + throwable.getMessage()); + } + + @Override + public R deleteSubDeviceByMqtt(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { + return R.fail("MQTT协议删除子设备失败:" + throwable.getMessage()); + } + + @Override + public R deleteSubDeviceByHttp(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { + return R.fail("HTTP协议删除子设备失败:" + throwable.getMessage()); + } + + @Override + public R deviceDataReportByMqtt(TopoDeviceDataReportParam topoDeviceDataReportParam) { + return R.fail("MQTT协议设备数据上报失败:" + throwable.getMessage()); + } + + @Override + public R deviceDataReportByHttp(TopoDeviceDataReportParam topoDeviceDataReportParam) { + return R.fail("HTTP协议设备数据上报失败:" + throwable.getMessage()); + } + + @Override + public R queryDeviceByMqtt(TopoQueryDeviceParam topoQueryDeviceParam) { + return R.fail("MQTT协议查询设备失败:" + throwable.getMessage()); + } + + @Override + public R queryDeviceByHttp(TopoQueryDeviceParam topoQueryDeviceParam) { + return R.fail("HTTP协议查询设备失败:" + throwable.getMessage()); + } + + @Override + public R saveUpgradeRecordByMqtt(OtaCommandResponseParam otaCommandResponseParam) { + return R.fail("MQTT协议保存升级记录失败:" + throwable.getMessage()); + } + + @Override + public R saveUpgradeRecordByHttp(OtaCommandResponseParam otaCommandResponseParam) { + return R.fail("HTTP协议保存升级记录失败:" + throwable.getMessage()); + } + }; + } +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/resources/META-INF/spring.factories b/thinglinks-api/thinglinks-api-link/src/main/resources/META-INF/spring.factories index 3ec02d70..1113b41e 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/resources/META-INF/spring.factories +++ b/thinglinks-api/thinglinks-api-link/src/main/resources/META-INF/spring.factories @@ -1,5 +1,6 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.mqttsnet.thinglinks.link.api.factory.RemoteDeviceFallbackFactory,\ + com.mqttsnet.thinglinks.link.api.factory.RemoteDeviceOpenAnyFallbackFactory, \ com.mqttsnet.thinglinks.link.api.factory.RemoteDeviceActionFallbackFactory, \ com.mqttsnet.thinglinks.link.api.factory.RemoteDeviceDatasFallbackFactory, \ com.mqttsnet.thinglinks.link.api.factory.RemoteProtocolFallbackFactory,\ diff --git a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/RemoteTdEngineService.java b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/RemoteTdEngineService.java index c9fcb9c4..3f0b053e 100644 --- a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/RemoteTdEngineService.java +++ b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/RemoteTdEngineService.java @@ -8,19 +8,23 @@ * @Version 1.0 */ +import cn.hutool.json.JSONObject; import com.mqttsnet.thinglinks.common.core.constant.ServiceNameConstants; import com.mqttsnet.thinglinks.common.core.domain.R; -import com.mqttsnet.thinglinks.tdengine.api.domain.SelectDto; -import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDto; -import com.mqttsnet.thinglinks.tdengine.api.domain.TableDto; -import com.mqttsnet.thinglinks.tdengine.api.domain.TagsSelectDao; +import com.mqttsnet.thinglinks.tdengine.api.domain.*; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.SuperTableDTO; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; import com.mqttsnet.thinglinks.tdengine.api.factory.RemoteTdEngineFallbackFactory; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; +import java.util.List; import java.util.Map; @FeignClient(contextId = "remoteTdEngineService", value = ServiceNameConstants.THINGLINKS_TDENGINE, fallbackFactory = RemoteTdEngineFallbackFactory.class) @@ -89,6 +93,7 @@ public interface RemoteTdEngineService { /** * 查询最新的数据带标签 + * * @param tagsSelectDao * @return */ @@ -101,7 +106,7 @@ public interface RemoteTdEngineService { * @param superTableDto * @return */ - @PostMapping("/addColumnInStb") + @PostMapping("/dataOperation/addColumnInStb") R addColumnForSuperTable(@RequestBody SuperTableDto superTableDto); /** @@ -110,6 +115,153 @@ public interface RemoteTdEngineService { * @param superTableDto * @return */ - @PostMapping("/dropColumnInStb") + @PostMapping("/dataOperation/dropColumnInStb") R dropColumnForSuperTable(@RequestBody SuperTableDto superTableDto); + + /** + * 创建时序数据库 + * + * @param dataBaseName 数据库名称 + * @return 执行结果 + */ + @PostMapping("/dataOperation/createDatabase") + public R createDatabase(@RequestParam String dataBaseName); + + /** + * 创建超级表 + * + * @param superTableName 超级表名称 + * @return 执行结果 + */ + @PostMapping("/dataOperation/createSuperTable") + public R createSuperTable(@RequestParam String superTableName); + + /** + * 创建超级表及字段 + * + * @param superTableDTO 超级表信息 + * @return 执行结果 + */ + @PostMapping("/dataOperation/createSuperTableAndColumn") + public R createSuperTableAndColumn(@RequestBody SuperTableDTO superTableDTO); + + /** + * 创建超级表及字段-方式二 + * + * @param object 超级表json信息 + * @return 执行结果 + */ + @PostMapping("/dataOperation/createSuperTableAndColumnTwo") + public R createSuperTableAndColumnTwo(@RequestBody JSONObject object); + + /** + * 创建子表 + * + * @param tableDTO 子表信息 + * @return 执行结果 + */ + @PostMapping("/dataOperation/createSubTable") + public R createSubTable(@RequestBody TableDTO tableDTO); + + /** + * 创建子表-方式二 + * + * @param object 子表json信息 + * @return 执行结果 + */ + @PostMapping("/dataOperation/createSubTableTwo") + public R createSubTableTwo(@RequestBody JSONObject object); + + /** + * 删除超级表 + * + * @param superTableName + * @return + */ + @PostMapping("/dataOperation/dropSuperTable") + public R dropSuperTable(@RequestParam String superTableName); + + /** + * 超级表新增字段 + * + * @param superTableDTO 数据信息 + * @return 执行结果 + */ + @PostMapping("/dataOperation/alterSuperTableColumn") + public R alterSuperTableColumn(@RequestBody SuperTableDTO superTableDTO); + + /** + * 超级表删除字段 + * + * @param superTableDTO 数据信息 + * @return 执行结果 + */ + @PostMapping("/dataOperation/dropSuperTableColumn") + public R dropSuperTableColumn(@RequestBody SuperTableDTO superTableDTO); + + /** + * 新增标签 + * + * @param superTableDTO 数据信息 + * @return 执行结果 + */ + @PostMapping("/dataOperation/alterSuperTableTag") + public R alterSuperTableTag(@RequestBody SuperTableDTO superTableDTO); + + /** + * 删除标签 + * + * @param superTableDTO 数据信息 + * @return 执行结果 + */ + @PostMapping("/dataOperation/dropSuperTableTag") + public R dropSuperTableTag(@RequestBody SuperTableDTO superTableDTO); + + /** + * 修改标签名称 + * + * @param superTableName + * @param oldName + * @param newName + * @return + */ + @PostMapping("/dataOperation/alterSuperTableTagRename") + public R alterSuperTableTagRename(@RequestParam String superTableName, @RequestParam String oldName, @RequestParam String newName); + + + /** + * 查询超级表、子表结构 + * + * @param tableName + * @return + */ + @GetMapping("/dataOperation/describeSuperOrSubTable") + public R> describeSuperOrSubTable(@RequestParam(value = "tableName") String tableName); + + /** + * 新增数据 + * + * @param tableDTO 数据信息 + * @return 执行结果 + */ + @PostMapping("/dataOperation/insertTableData") + public R insertTableData(@RequestBody TableDTO tableDTO); + + + /** + * Retrieves the latest data from a regular table. It fetches the most recent record + * within the specified time range or the last recorded data if the time range is not specified. + * + * @param tableName The name of the table. + * @param startTime The start time for the query range (optional). + * @param endTime The end time for the query range (optional). + * @return {@link R>>} The query result. + */ + @ApiOperation(value = "Query Data from a Regular Table Within a Time Range", notes = "Fetches data within the specified time range if both start and end times are provided; otherwise, retrieves the latest record.") + @GetMapping("/dataOperation/getDataInRangeOrLastRecord") + public R>> getDataInRangeOrLastRecord( + @ApiParam(value = "Name of the regular table", required = true) @RequestParam(value = "tableName") String tableName, + @ApiParam(value = "Start time for the query", example = "1634572800000", required = false) @RequestParam(value = "startTime", required = false) Long startTime, + @ApiParam(value = "End time for the query", example = "1634659200000", required = false) @RequestParam(value = "endTime", required = false) Long endTime); + } diff --git a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/Fields.java b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/Fields.java index 96afbb38..08defdc2 100644 --- a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/Fields.java +++ b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/Fields.java @@ -3,6 +3,8 @@ import com.mqttsnet.thinglinks.common.core.enums.DataTypeEnum; import lombok.Data; +import java.io.Serializable; + /** * @ClassDescription: 建表的字段实体类 * @ClassName: Fields @@ -11,8 +13,9 @@ * @Version 1.0 */ @Data -public class Fields { - private static final long serialVersionUID = 1L; +public class Fields implements Serializable { + + private static final long serialVersionUID = -1L; /** * 字段名称 @@ -37,37 +40,25 @@ public class Fields { public Fields() { } - public Fields(String fieldName, String dataType, Integer size) { + public Fields(String fieldName) { + this.fieldName = fieldName; + } + + public Fields(String fieldName, DataTypeEnum dataType) { + this.fieldName = fieldName; + this.dataType = dataType; + } + + public Fields(String fieldName, DataTypeEnum dataType, Integer size) { + this.fieldName = fieldName; + this.dataType = dataType; + this.size = size; + } + + public Fields(String fieldName, Object fieldValue, DataTypeEnum dataType, Integer size) { this.fieldName = fieldName; - //根据规则匹配字段数据类型 - switch (dataType.toLowerCase()) { - case ("json"): - this.dataType = DataTypeEnum.JSON; - this.size = size; - break; - case ("string"): - this.dataType = DataTypeEnum.NCHAR; - this.size = size; - break; - case ("binary"): - this.dataType = DataTypeEnum.BINARY; - this.size = size; - break; - case ("int"): - this.dataType = DataTypeEnum.INT; - break; - case ("bool"): - this.dataType = DataTypeEnum.BOOL; - break; - case ("decimal"): - this.dataType = DataTypeEnum.DOUBLE; - break; - case ("timestamp"): - if ("eventTime".equals(fieldName)) { - this.fieldName = "eventTime"; - } - this.dataType = DataTypeEnum.TIMESTAMP; - break; - } + this.fieldValue = fieldValue; + this.dataType = dataType; + this.size = size; } } diff --git a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/SuperTableDescribeVO.java b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/SuperTableDescribeVO.java index 7a05343e..e70f6f3a 100644 --- a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/SuperTableDescribeVO.java +++ b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/SuperTableDescribeVO.java @@ -10,7 +10,7 @@ import java.util.Map; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: 超级表结构VO * @packagename: com.mqttsnet.thinglinks.tds.vo.result * @author: ShiHuan Sun diff --git a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/model/FieldsVO.java b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/model/FieldsVO.java new file mode 100644 index 00000000..bac54aee --- /dev/null +++ b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/model/FieldsVO.java @@ -0,0 +1,58 @@ +package com.mqttsnet.thinglinks.tdengine.api.domain.model; + +import cn.hutool.core.bean.BeanUtil; +import com.mqttsnet.thinglinks.tdengine.api.domain.Fields; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; +import java.util.stream.Collectors; + +@Data +public class FieldsVO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 字段名称 + */ + private String fieldName; + + /** + * 字段数据类型 + */ + private String dataType; + + /** + * 字段字节大小 + */ + private Integer size; + + public FieldsVO() { + } + + public FieldsVO(String fieldName) { + this.fieldName = fieldName; + } + + public FieldsVO(String fieldName, String dataType) { + this.fieldName = fieldName; + this.dataType = dataType; + } + + public FieldsVO(String fieldName, String dataType, Integer size) { + this.fieldName = fieldName; + this.dataType = dataType; + this.size = size; + } + + public static List toFieldsList(List fieldsVOList) { + return fieldsVOList.stream() + .map(fieldsVO -> BeanUtil.toBeanIgnoreError(fieldsVO, Fields.class)) + .collect(Collectors.toList()); + } + + public static Fields toFields(FieldsVO fieldsVo) { + return BeanUtil.toBeanIgnoreError(fieldsVo, Fields.class); + } +} diff --git a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/model/SuperTableDTO.java b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/model/SuperTableDTO.java new file mode 100644 index 00000000..e610a655 --- /dev/null +++ b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/model/SuperTableDTO.java @@ -0,0 +1,53 @@ +package com.mqttsnet.thinglinks.tdengine.api.domain.model; + +import com.mqttsnet.thinglinks.tdengine.api.domain.Fields; +import lombok.Builder; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + + +@Data +@Builder +public class SuperTableDTO implements Serializable { + + private static final long serialVersionUID = -1L; + + /** + * 超级表的表结构(业务相关) 第一个字段的数据类型必须为timestamp 字符相关数据类型必须指定大小 字段名称和字段数据类型不能为空 + */ + private List schemaFields; + + /** + * 超级表的标签字段,可以作为子表在超级表里的标识 字符相关数据类型必须指定大小 字段名称和字段数据类型不能为空 + */ + private List tagsFields; + + /** + * 字段信息对象,超级表添加列时使用该属性 + */ + private Fields fields; + + /** + * 数据库名称 + */ + private String dataBaseName; + + /** + * 超级表名称 + */ + private String superTableName; + + public SuperTableDTO() { + + } + + public SuperTableDTO(List schemaFields, List tagsFields, Fields fields, String dataBaseName, String superTableName) { + this.schemaFields = schemaFields; + this.tagsFields = tagsFields; + this.fields = fields; + this.dataBaseName = dataBaseName; + this.superTableName = superTableName; + } +} diff --git a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/model/TableDTO.java b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/model/TableDTO.java new file mode 100644 index 00000000..0f57db99 --- /dev/null +++ b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/model/TableDTO.java @@ -0,0 +1,49 @@ +package com.mqttsnet.thinglinks.tdengine.api.domain.model; + +import com.mqttsnet.thinglinks.tdengine.api.domain.Fields; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +@Data +public class TableDTO implements Serializable { + + private static final long serialVersionUID = -1L; + /** + * 超级表普通列字段的值 值需要与创建超级表时普通列字段的数据类型对应上 + */ + private List schemaFieldValues; + + /** + * 超级表标签字段的值 值需要与创建超级表时标签字段的数据类型对应上 + */ + private List tagsFieldValues; + + /** + * 子表名称 + */ + private String tableName; + + /** + * 数据库名称 + */ + private String dataBaseName; + + /** + * 超级表名称 + */ + private String superTableName; + + public TableDTO() { + + } + + public TableDTO(List schemaFieldValues, List tagsFieldValues, String tableName, String dataBaseName, String superTableName) { + this.schemaFieldValues = schemaFieldValues; + this.tagsFieldValues = tagsFieldValues; + this.tableName = tableName; + this.dataBaseName = dataBaseName; + this.superTableName = superTableName; + } +} diff --git a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/model/TagsSelectDTO.java b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/model/TagsSelectDTO.java new file mode 100644 index 00000000..4fbf2944 --- /dev/null +++ b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/model/TagsSelectDTO.java @@ -0,0 +1,30 @@ +package com.mqttsnet.thinglinks.tdengine.api.domain.model; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +/** + * @program: thinglinks + * @description: 标签查询模型 + * @packagename: com.mqttsnet.thinglinks.tdengine.api.domain.rule + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2022-07-27 18:40 + **/ +@Data +public class TagsSelectDTO { + + private String dataBaseName; + + @NotBlank(message = "invalid operation: stableName can not be empty") + private String stableName; + + @NotBlank(message = "invalid operation: tagsName can not be empty") + private String tagsName; + + private Long startTime; + + private Long endTime; + +} diff --git a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/factory/RemoteTdEngineFallbackFactory.java b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/factory/RemoteTdEngineFallbackFactory.java index b665177d..13c7581a 100644 --- a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/factory/RemoteTdEngineFallbackFactory.java +++ b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/factory/RemoteTdEngineFallbackFactory.java @@ -1,16 +1,19 @@ package com.mqttsnet.thinglinks.tdengine.api.factory; +import cn.hutool.json.JSONObject; import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.tdengine.api.RemoteTdEngineService; -import com.mqttsnet.thinglinks.tdengine.api.domain.SelectDto; -import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDto; -import com.mqttsnet.thinglinks.tdengine.api.domain.TableDto; -import com.mqttsnet.thinglinks.tdengine.api.domain.TagsSelectDao; +import com.mqttsnet.thinglinks.tdengine.api.domain.*; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.SuperTableDTO; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.openfeign.FallbackFactory; import org.springframework.stereotype.Component; +import java.util.List; +import java.util.Map; + /** * @ClassDescription: 时序数据库服务降级处理 * @ClassName: RemoteTdEngineFallbackFactory @@ -89,6 +92,83 @@ public R addColumnForSuperTable(SuperTableDto superTableDto) { public R dropColumnForSuperTable(SuperTableDto superTableDto) { return R.fail("删除列字段失败:{}", throwable.getMessage()); } + + @Override + public R createDatabase(String dataBaseName) { + return R.fail("创建数据库失败:{}", throwable.getMessage()); + } + + @Override + public R createSuperTable(String superTableName) { + return R.fail("创建超级表失败:{}", throwable.getMessage()); + } + + @Override + public R createSuperTableAndColumn(SuperTableDTO superTableDTO) { + return R.fail("创建超级表及字段失败:{}", throwable.getMessage()); + } + + @Override + public R createSuperTableAndColumnTwo(JSONObject object) { + return R.fail("创建超级表及字段-方式二失败:{}", throwable.getMessage()); + } + + @Override + public R createSubTable(TableDTO tableDTO) { + return R.fail("创建子表失败:{}", throwable.getMessage()); + } + + @Override + public R createSubTableTwo(JSONObject object) { + return R.fail("创建子表-方式二失败:{}", throwable.getMessage()); + } + + @Override + public R dropSuperTable(String superTableName) { + return R.fail("删除超级表失败:{}", throwable.getMessage()); + } + + @Override + public R alterSuperTableColumn(SuperTableDTO superTableDTO) { + return R.fail("修改超级表列失败:{}", throwable.getMessage()); + } + + @Override + public R dropSuperTableColumn(SuperTableDTO superTableDTO) { + return R.fail("删除超级表列失败:{}", throwable.getMessage()); + } + + @Override + public R alterSuperTableTag(SuperTableDTO superTableDTO) { + return R.fail("修改超级表Tag失败:{}", throwable.getMessage()); + } + + @Override + public R dropSuperTableTag(SuperTableDTO superTableDTO) { + return R.fail("删除超级表Tag失败:{}", throwable.getMessage()); + } + + @Override + public R alterSuperTableTagRename(String superTableName, String oldName, String newName) { + return R.fail("修改超级表Tag名称失败:{}", throwable.getMessage()); + } + + @Override + public R> describeSuperOrSubTable(String tableName) { + log.error("查询超级表、子表结构失败:{}", throwable.getMessage()); + return R.fail(); + } + + @Override + public R insertTableData(TableDTO tableDTO) { + return R.fail("新增数据失败:{}", throwable.getMessage()); + } + + @Override + public R>> getDataInRangeOrLastRecord(String tableName, Long startTime, Long endTime) { + log.error("查询超级表、子表结构失败:{}", throwable.getMessage()); + return R.fail(); + } }; } } diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/Constants.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/Constants.java index d42c11d4..224175ee 100644 --- a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/Constants.java +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/Constants.java @@ -146,4 +146,10 @@ public class Constants { */ public static final String RESUBMIT_URL_KEY = "resubmit_url:"; + /** + * 下划线 + */ + public static final String UNDERLINE = "_"; + + } diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/enums/DataTypeEnum.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/enums/DataTypeEnum.java index b5929940..fbe68217 100644 --- a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/enums/DataTypeEnum.java +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/enums/DataTypeEnum.java @@ -1,75 +1,149 @@ package com.mqttsnet.thinglinks.common.core.enums; +import io.swagger.annotations.ApiModel; +import lombok.Getter; + +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + /** * @EnumDescription: tdEngine支持的数据类型的枚举类 * @EnumName: DataTypeEnum * @Author: thinglinks * @Date: 2021-12-27 16:32:53 */ +@Getter +@ApiModel(value = "DataTypeEnum", description = "TD数据类型-枚举") public enum DataTypeEnum { - /** * 时间戳 缺省精度毫秒(格林威治时间开始) */ - TIMESTAMP("timestamp"), + TIMESTAMP("timestamp", false), /** * 单字节整形 范围[-127, 127] -128用作于NULL */ - TINYINT("tinyint"), + TINYINT("tinyint", false), /** * 短整型 范围[-32767, 32767] -32768用作于NULL */ - SMALLINT("smallint"), + SMALLINT("smallint", false), /** * 整形 范围[-2^31+1, 2^31-1] -2^31用作于NULL */ - INT("int"), + INT("int", false), /** * 长整型 范围[-2^63+1, 2^63-1] -2^63用作于NULL */ - BIGINT("bigint"), + BIGINT("bigint", false), /** * 浮点型 有效位数6-7 范围[-3.4E38, 3.4E38] */ - FLOAT("float"), + FLOAT("float", false), /** * 双精度浮点型 有效位数15-16 范围[-1.7E308, 1.7E308] */ - DOUBLE("double"), + DOUBLE("double", false), /** * 单字节字符串(建议只用于处理ASCII可见字符)最大长度16000 */ - BINARY("binary"), + BINARY("binary", true), /** * 记录包含多字节字符在内的字符串(如中文字符)最大长度4093 */ - NCHAR("nchar"), + NCHAR("nchar", true), /** * 布尔型 {true, false} */ - BOOL("bool"), + BOOL("bool", false), /** * json数据类型 只有tag类型可以是json格式 */ - JSON("json"); + JSON("json", true), + + /** + * 可变长的二进制数据 + */ + VARBINARY("varBinary", true); private final String dataType; + private final boolean quoted; - DataTypeEnum(String dataType) { + private static final ConcurrentHashMap DATA_TYPE_MAPPING = new ConcurrentHashMap<>(); + + static { + // 标准映射关系 + for (DataTypeEnum type : values()) { + DATA_TYPE_MAPPING.put(type.dataType.toLowerCase(), type); + } + + // 特殊映射关系或别名 + DATA_TYPE_MAPPING.put("string", NCHAR); + DATA_TYPE_MAPPING.put("varchar", NCHAR); + DATA_TYPE_MAPPING.put("decimal", DOUBLE); + DATA_TYPE_MAPPING.put("nvarchar", NCHAR); + DATA_TYPE_MAPPING.put("jsonObject", NCHAR); + DATA_TYPE_MAPPING.put("int", INT); + DATA_TYPE_MAPPING.put("bigint", BIGINT); + DATA_TYPE_MAPPING.put("DateTime", NCHAR); + DATA_TYPE_MAPPING.put("timestamp", TIMESTAMP); + DATA_TYPE_MAPPING.put("bool", BOOL); + + // 这里添加其他映射关系。例如: + DATA_TYPE_MAPPING.put("text", NCHAR); // 例如:将"text"也映射到NCHAR + // 可以继续根据需要增加更多映射 + } + + /** + * 通过dataType返回对应的枚举 + * + * @param dataType 数据类型字符串 + * @return 对应的枚举,如果没有找到则返回null + */ + public static DataTypeEnum valueOfByDataType(String dataType) { + if (dataType == null) { + return NCHAR; // 可替换为默认枚举值,如 UNKNOWN + } + + return DATA_TYPE_MAPPING.computeIfAbsent(dataType.trim().toLowerCase(), key -> { + // 这里处理未知的dataType,默认返回null,也可以返回例如:UNKNOWN。 + return NCHAR; + }); + } + + + /** + * 判断类型是否一致 + * + * @param otherDataType + * @return {@link Boolean} ture|false + */ + public boolean isTypeEqual(String otherDataType) { + return Optional.ofNullable(otherDataType) + .map(String::trim) + .map(this.dataType::equalsIgnoreCase) + .orElse(false); + } + + DataTypeEnum(String dataType, boolean quoted) { this.dataType = dataType; + this.quoted = quoted; } public String getDataType() { return dataType; } -} + + public boolean isQuoted() { + return quoted; + } +} \ No newline at end of file diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/enums/DeviceType.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/enums/DeviceType.java index fd284fc2..a61b60f1 100644 --- a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/enums/DeviceType.java +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/enums/DeviceType.java @@ -2,6 +2,7 @@ import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; /** * @Description: 设备类型 @@ -20,18 +21,18 @@ public enum DeviceType { /** * 普通设备(无子设备也无父设备) */ - COMMON("COMMON","COMMON"), + COMMON("COMMON", "COMMON"), /** * 网关设备(可挂载子设备) */ - GATEWAY("GATEWAY","GATEWAY"), + GATEWAY("GATEWAY", "GATEWAY"), /** * 子设备(归属于某个网关设备) */ - SUBSET("SUBSET","SUBSET"); + SUBSET("SUBSET", "SUBSET"); - private String key; - private String value; + private String key; + private String value; } diff --git a/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/factory/ProtocolMessageAdapter.java b/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/factory/ProtocolMessageAdapter.java index 1a5ab6c9..027ff84b 100644 --- a/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/factory/ProtocolMessageAdapter.java +++ b/thinglinks-common/thinglinks-common-protocol/src/main/java/com/mqttsnet/basic/protocol/factory/ProtocolMessageAdapter.java @@ -13,7 +13,7 @@ import org.springframework.stereotype.Component; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: 协议信息适配器 * @packagename: com.mqttsnet.thinglinks.mqtt.handler * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/pom.xml b/thinglinks-modules/thinglinks-modules-broker/pom.xml index cb237e9f..27ee1299 100644 --- a/thinglinks-modules/thinglinks-modules-broker/pom.xml +++ b/thinglinks-modules/thinglinks-modules-broker/pom.xml @@ -98,6 +98,11 @@ thinglinks-modules-link ${thinglinks.version} + + com.mqttsnet + thinglinks-modules-tdengine + ${thinglinks.version} + diff --git a/thinglinks-modules/thinglinks-modules-broker/readme.md b/thinglinks-modules/thinglinks-modules-broker/readme.md new file mode 100644 index 00000000..e69de29b diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/config/KafkaConsumerConfig.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/config/KafkaConsumerConfig.java index 14ffa5ab..0a06499a 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/config/KafkaConsumerConfig.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/config/KafkaConsumerConfig.java @@ -17,7 +17,7 @@ import java.util.Map; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: KafkaConsumerConfig * @packagename: com.mqttsnet.thinglinks.config.kafka * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/config/KafkaProviderConfig.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/config/KafkaProviderConfig.java index 5a2cca04..d650e249 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/config/KafkaProviderConfig.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/config/KafkaProviderConfig.java @@ -14,7 +14,7 @@ import java.util.Map; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: KafkaProviderConfig * @packagename: com.mqttsnet.thinglinks.config.kafka * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttCloseEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttCloseEvent.java index b50b4864..d303e952 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttCloseEvent.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttCloseEvent.java @@ -4,7 +4,7 @@ import org.springframework.context.ApplicationEvent; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: * @packagename: com.mqttsnet.thinglinks.mqtt.event * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttConnectEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttConnectEvent.java index 090cdd45..093d600a 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttConnectEvent.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttConnectEvent.java @@ -4,7 +4,7 @@ import org.springframework.context.ApplicationEvent; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: * @packagename: com.mqttsnet.thinglinks.mqtt.event * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttDisconnectEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttDisconnectEvent.java index 95c2aedf..d50b6283 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttDisconnectEvent.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttDisconnectEvent.java @@ -4,7 +4,7 @@ import org.springframework.context.ApplicationEvent; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MqttDisconnectEvent * @packagename: com.mqttsnet.thinglinks.mqtt.event * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPingEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPingEvent.java index 9fd98460..cc31e446 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPingEvent.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPingEvent.java @@ -4,7 +4,7 @@ import org.springframework.context.ApplicationEvent; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MqttPingEvent * @packagename: com.mqttsnet.thinglinks.mqtt.event * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPublishEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPublishEvent.java index d64d908f..19bdf4e1 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPublishEvent.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPublishEvent.java @@ -4,7 +4,7 @@ import org.springframework.context.ApplicationEvent; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MqttPublishEvent * @packagename: com.mqttsnet.thinglinks.mqtt.event * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttSubscribeEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttSubscribeEvent.java index 82f2293a..6b24374d 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttSubscribeEvent.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttSubscribeEvent.java @@ -4,7 +4,7 @@ import org.springframework.context.ApplicationEvent; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MqttSubscribeEvent * @packagename: com.mqttsnet.thinglinks.mqtt.event * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttUnsubscribeEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttUnsubscribeEvent.java index 82987257..31051bef 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttUnsubscribeEvent.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttUnsubscribeEvent.java @@ -4,7 +4,7 @@ import org.springframework.context.ApplicationEvent; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MqttUnsubscribeEvent * @packagename: com.mqttsnet.thinglinks.mqtt.event * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttCloseEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttCloseEventListener.java index 057d4375..18a956a3 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttCloseEventListener.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttCloseEventListener.java @@ -21,7 +21,7 @@ import java.util.Optional; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MQTT CLOSE事件监听器 * @packagename: com.mqttsnet.thinglinks.mqtt.listener * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttConnectEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttConnectEventListener.java index 361047e2..4c17644b 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttConnectEventListener.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttConnectEventListener.java @@ -21,7 +21,7 @@ import java.util.Optional; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MQTT CONNECT事件监听器 * @packagename: com.mqttsnet.thinglinks.mqtt.listener * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttDisconnectEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttDisconnectEventListener.java index 524e0ae4..6849df7d 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttDisconnectEventListener.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttDisconnectEventListener.java @@ -21,7 +21,7 @@ import java.util.Optional; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MQTT DISCONNECT事件监听器 * @packagename: com.mqttsnet.thinglinks.mqtt.listener * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPingEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPingEventListener.java index d0598b4e..b79dc140 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPingEventListener.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPingEventListener.java @@ -7,7 +7,7 @@ import org.springframework.stereotype.Component; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MQTT PING事件监听器 * @packagename: com.mqttsnet.thinglinks.mqtt.listener * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPublishEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPublishEventListener.java index 8862421c..117a6a71 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPublishEventListener.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPublishEventListener.java @@ -14,7 +14,7 @@ import org.springframework.stereotype.Component; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MqttPublish事件监听器 * @packagename: com.mqttsnet.thinglinks.consumer.mqtt.listener * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttSubscribeEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttSubscribeEventListener.java index e2ec4041..2d8e4a37 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttSubscribeEventListener.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttSubscribeEventListener.java @@ -10,7 +10,7 @@ import org.springframework.stereotype.Component; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MQTT SUBSCRIBE事件监听器 * @packagename: com.mqttsnet.thinglinks.mqtt.listener * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttUnsubscribeEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttUnsubscribeEventListener.java index c264ffdb..6c9958e9 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttUnsubscribeEventListener.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttUnsubscribeEventListener.java @@ -10,7 +10,7 @@ import org.springframework.stereotype.Component; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MQTT UNSUBSCRIBE事件监听器 * @packagename: com.mqttsnet.thinglinks.mqtt.listener * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/publisher/MqttEventPublisher.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/publisher/MqttEventPublisher.java index 07167d16..fb1dafea 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/publisher/MqttEventPublisher.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/publisher/MqttEventPublisher.java @@ -8,7 +8,7 @@ import org.springframework.stereotype.Component; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MQTT事件发布器 用于发布MQTT事件 TODO MqttEventEnum 事件枚举类 用于定义MQTT事件 预留 * @packagename: com.mqttsnet.thinglinks.consumer.mqtt.publisher * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaSendResultHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaSendResultHandler.java index b0da2eeb..ee0d2df1 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaSendResultHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaSendResultHandler.java @@ -8,7 +8,7 @@ import org.springframework.stereotype.Component; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: kafka消息发送回调 * @packagename: com.mqttsnet.thinglinks.common.kafka.handler * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MqttMessageKafkaConsumerHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MqttMessageKafkaConsumerHandler.java index 2e63b4fc..249ff394 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MqttMessageKafkaConsumerHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MqttMessageKafkaConsumerHandler.java @@ -19,7 +19,7 @@ import java.util.Optional; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: Mqtt Message kafka监听消息 * @packagename: com.mqttsnet.thinglinks.kafka * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MyKafkaListenerErrorHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MyKafkaListenerErrorHandler.java index e11696ad..efb1801f 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MyKafkaListenerErrorHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MyKafkaListenerErrorHandler.java @@ -9,7 +9,7 @@ import org.springframework.stereotype.Component; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: kafkaListener异常处理 * @packagename: com.mqttsnet.thinglinks.common.kafka.handler * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/AddSubDeviceHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/AddSubDeviceHandler.java index 5b8e5644..d5bd07f2 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/AddSubDeviceHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/AddSubDeviceHandler.java @@ -8,7 +8,7 @@ import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; import com.mqttsnet.thinglinks.common.core.domain.R; -import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoAddSubDeviceParam; import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; @@ -19,7 +19,7 @@ import java.util.Map; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: 处理ADD_SUB_DEVICE主题 * @packagename: com.mqttsnet.thinglinks.mqtt.handler * @author: ShiHuan Sun @@ -33,10 +33,10 @@ public class AddSubDeviceHandler extends AbstractMessageHandler implements Topic private static final ObjectMapper objectMapper = new ObjectMapper(); public AddSubDeviceHandler(CacheDataHelper cacheDataHelper, - RemoteDeviceService remoteDeviceService, + RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, remoteDeviceService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + super(cacheDataHelper, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } /** @@ -108,7 +108,7 @@ protected String processingTopicMessage(Object topoAddSubDeviceParam) throws Exc } TopoAddSubDeviceParam addParam = (TopoAddSubDeviceParam) topoAddSubDeviceParam; - R mqttTopoAddDeviceResultVOR = remoteDeviceService.saveSubDeviceByMqtt(addParam); + R mqttTopoAddDeviceResultVOR = remoteDeviceOpenAnyService.saveSubDeviceByMqtt(addParam); log.info("Processing /topo/add Topic result: {}", JSON.toJSONString(mqttTopoAddDeviceResultVOR)); return JSON.toJSONString(mqttTopoAddDeviceResultVOR.getData()); diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/CommandResponseHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/CommandResponseHandler.java index 9be09dae..56d3aead 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/CommandResponseHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/CommandResponseHandler.java @@ -2,8 +2,10 @@ import com.mqttsnet.basic.protocol.factory.ProtocolMessageAdapter; import com.mqttsnet.basic.protocol.model.EncryptionDetailsDTO; +import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventCommandService; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; import lombok.extern.slf4j.Slf4j; @@ -13,7 +15,7 @@ import java.util.Map; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: 处理COMMAND_RESPONSE主题 * @packagename: com.mqttsnet.thinglinks.mqtt.handler * @author: ShiHuan Sun @@ -24,10 +26,10 @@ @Service public class CommandResponseHandler extends AbstractMessageHandler implements TopicHandler { public CommandResponseHandler(CacheDataHelper cacheDataHelper, - DeviceOpenAnyTenantApi deviceOpenAnyTenantApi, - MqttBrokerOpenAnyTenantApi mqttBrokerOpenAnyTenantApi, + RemoteDeviceService remoteDeviceService, + RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, deviceOpenAnyTenantApi, mqttBrokerOpenAnyTenantApi, protocolMessageAdapter); + super(cacheDataHelper, remoteDeviceService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } @Autowired diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DefaultHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DefaultHandler.java index 5164ebca..a6f25b3b 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DefaultHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DefaultHandler.java @@ -4,7 +4,7 @@ import org.springframework.stereotype.Service; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: 其他默认Topic处理器 * @packagename: com.mqttsnet.thinglinks.mqtt.handler * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeleteSubDeviceHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeleteSubDeviceHandler.java index df94f290..64489e9a 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeleteSubDeviceHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeleteSubDeviceHandler.java @@ -8,7 +8,7 @@ import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; import com.mqttsnet.thinglinks.common.core.domain.R; -import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoDeleteSubDeviceParam; import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; @@ -19,7 +19,7 @@ import java.util.Map; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: 处理DELETE_SUB_DEVICE主题 * @packagename: com.mqttsnet.thinglinks.mqtt.handler * @author: ShiHuan Sun @@ -33,10 +33,10 @@ public class DeleteSubDeviceHandler extends AbstractMessageHandler implements To private static final ObjectMapper objectMapper = new ObjectMapper(); public DeleteSubDeviceHandler(CacheDataHelper cacheDataHelper, - RemoteDeviceService remoteDeviceService, + RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, remoteDeviceService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + super(cacheDataHelper, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } /** @@ -102,7 +102,7 @@ public void handle(String topic, String qos, String body) { */ @Override protected String processingTopicMessage(Object topoDeleteSubDeviceParam) throws Exception { - R mqttTopoDeleteDeviceResultVOR = remoteDeviceService.deleteSubDeviceByMqtt((TopoDeleteSubDeviceParam) topoDeleteSubDeviceParam); + R mqttTopoDeleteDeviceResultVOR = remoteDeviceOpenAnyService.deleteSubDeviceByMqtt((TopoDeleteSubDeviceParam) topoDeleteSubDeviceParam); log.info("processingTopoDeleteTopic Processing result:{}", JSON.toJSONString(mqttTopoDeleteDeviceResultVOR)); return JSON.toJSONString(mqttTopoDeleteDeviceResultVOR.getData()); } diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeviceDatasHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeviceDatasHandler.java index f4739c01..a91e78a1 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeviceDatasHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeviceDatasHandler.java @@ -7,21 +7,37 @@ import com.mqttsnet.basic.protocol.model.ProtocolDataMessageDTO; import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.common.core.enums.DataTypeEnum; +import com.mqttsnet.thinglinks.common.core.enums.ResultEnum; +import com.mqttsnet.thinglinks.common.core.utils.DateUtils; +import com.mqttsnet.thinglinks.common.core.utils.StringUtils; import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; -import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductModelCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.product.enumeration.ProductTypeEnum; +import com.mqttsnet.thinglinks.link.api.domain.product.vo.param.ProductServiceParamVO; +import com.mqttsnet.thinglinks.link.api.domain.product.vo.result.ProductPropertyResultVO; +import com.mqttsnet.thinglinks.link.api.domain.product.vo.result.ProductResultVO; +import com.mqttsnet.thinglinks.link.api.domain.product.vo.result.ProductServiceResultVO; import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoDeviceDataReportParam; import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; +import com.mqttsnet.thinglinks.tdengine.api.RemoteTdEngineService; +import com.mqttsnet.thinglinks.tdengine.api.domain.Fields; +import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDescribeVO; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; +import com.mqttsnet.thinglinks.tdengine.common.constant.TdsConstants; +import com.mqttsnet.thinglinks.tdengine.utils.TdsUtils; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import javax.annotation.Resource; import java.util.*; import java.util.stream.Collectors; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: 处理DEVICE_DATA主题 * @packagename: com.mqttsnet.thinglinks.mqtt.handler * @author: ShiHuan Sun @@ -33,14 +49,14 @@ public class DeviceDatasHandler extends AbstractMessageHandler implements TopicHandler { public DeviceDatasHandler(CacheDataHelper cacheDataHelper, - RemoteDeviceService remoteDeviceService, - RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, - ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, remoteDeviceService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, + RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, + ProtocolMessageAdapter protocolMessageAdapter) { + super(cacheDataHelper, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } - @Autowired - private TdsApi tdsApi; + @Resource + private RemoteTdEngineService remoteTdEngineService; /** @@ -141,7 +157,7 @@ protected String processingTopicMessage(Object deviceDataParam) throws Exception //如果是空,需要做设备的初始化动作,并缓存模型表结构 if (CollUtil.isEmpty(productModelSuperTableCacheVO)) { - R> superTableDescribeVOListR = tdsApi.describeSuperOrSubTable(subTableName); + R> superTableDescribeVOListR = remoteTdEngineService.describeSuperOrSubTable(subTableName); List existingFields = Optional.ofNullable(superTableDescribeVOListR.getData()).orElse(Collections.emptyList()); @@ -157,12 +173,12 @@ protected String processingTopicMessage(Object deviceDataParam) throws Exception fields.setDataType(DataTypeEnum.BINARY); tagsFieldValues.add(fields); tableDTO.setTagsFieldValues(tagsFieldValues); - R subTable = tdsApi.createSubTable(tableDTO); - if (Boolean.TRUE.equals(subTable.getIsSuccess())) { + R subTable = remoteTdEngineService.createSubTable(tableDTO); + if (ResultEnum.SUCCESS.getCode() == subTable.getCode()) { log.info("设备初始化,设备标识:{},服务标识:{},初始化成功", deviceCacheVO.getDeviceIdentification(), service.getServiceCode()); // 查询新的表结构信息存redis setProductModelSuperTableCacheVO(Optional.ofNullable(deviceCacheVO.getProductIdentification()).orElse(""), - service.getServiceCode(), deviceCacheVO.getDeviceIdentification(), tdsApi.describeSuperOrSubTable(superTableName).getData()); + service.getServiceCode(), deviceCacheVO.getDeviceIdentification(), remoteTdEngineService.describeSuperOrSubTable(superTableName).getData()); } else { log.warn("设备初始化 ,设备标识:{},服务标识:{},初始化失败", deviceCacheVO.getDeviceIdentification(), service.getServiceCode()); @@ -235,9 +251,9 @@ protected String processingTopicMessage(Object deviceDataParam) throws Exception tableDTO.setSchemaFieldValues(schemaFieldsStream); tableDTO.setTagsFieldValues(tagsFieldsStream); - R insertedResult = tdsApi.insertTableData(tableDTO); + R insertedResult = remoteTdEngineService.insertTableData(tableDTO); - if (Boolean.TRUE.equals(insertedResult.getIsSuccess())) { + if (ResultEnum.SUCCESS.getCode() == insertedResult.getCode()) { log.info("insert table data success, tableName:{}", subTableName); } else { log.error("insert table data failed, tableName:{}", subTableName); @@ -262,8 +278,11 @@ protected String processingTopicMessage(Object deviceDataParam) throws Exception }); log.info("productResultVO: {}", JSON.toJSONString(productResultVO)); - setDeviceDataCollectionPoolCacheVO(Optional.ofNullable(deviceCacheVO.getProductIdentification()).orElse(""), - deviceCacheVO.getDeviceIdentification(), productResultVO); + + + // TODO 后续处理数据收集池缓存 + /*setDeviceDataCollectionPoolCacheVO(Optional.ofNullable(deviceCacheVO.getProductIdentification()).orElse(""), + deviceCacheVO.getDeviceIdentification(), productResultVO);*/ }); return JSON.toJSONString(""); diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/OtaCommandResponseHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/OtaCommandResponseHandler.java index 67015df9..5c3ee2ca 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/OtaCommandResponseHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/OtaCommandResponseHandler.java @@ -5,7 +5,7 @@ import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventOtaCommandResponseService; -import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; import lombok.extern.slf4j.Slf4j; @@ -15,7 +15,7 @@ import java.util.Map; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: 处理OTA_COMMAND_RESPONSE主题 * @packagename: com.mqttsnet.thinglinks.mqtt.handler * @author: ShiHuan Sun @@ -26,10 +26,10 @@ @Service public class OtaCommandResponseHandler extends AbstractMessageHandler implements TopicHandler { public OtaCommandResponseHandler(CacheDataHelper cacheDataHelper, - RemoteDeviceService remoteDeviceService, - RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, - ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, remoteDeviceService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, + RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, + ProtocolMessageAdapter protocolMessageAdapter) { + super(cacheDataHelper, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } @Autowired diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/QueryDeviceHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/QueryDeviceHandler.java index a53f457b..5277b405 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/QueryDeviceHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/QueryDeviceHandler.java @@ -8,7 +8,7 @@ import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; import com.mqttsnet.thinglinks.common.core.domain.R; -import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoQueryDeviceParam; import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoQueryDeviceResultVO; @@ -19,7 +19,7 @@ import java.util.Map; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: 处理QUERY_DEVICE主题 * @packagename: com.mqttsnet.thinglinks.mqtt.handler * @author: ShiHuan Sun @@ -33,10 +33,10 @@ public class QueryDeviceHandler extends AbstractMessageHandler implements TopicH private static final ObjectMapper objectMapper = new ObjectMapper(); public QueryDeviceHandler(CacheDataHelper cacheDataHelper, - RemoteDeviceService remoteDeviceService, + RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, remoteDeviceService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + super(cacheDataHelper, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } /** @@ -106,7 +106,7 @@ protected String processingTopicMessage(Object topoQueryDeviceParam) throws Exce } TopoQueryDeviceParam queryParam = (TopoQueryDeviceParam) topoQueryDeviceParam; - R topoQueryDeviceResultVOR = remoteDeviceService.queryDeviceByMqtt(queryParam); + R topoQueryDeviceResultVOR = remoteDeviceOpenAnyService.queryDeviceByMqtt(queryParam); log.info("Processing /topo/query result: {}", JSON.toJSONString(topoQueryDeviceResultVOR)); return JSON.toJSONString(topoQueryDeviceResultVOR.getData()); diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/SecretKeyHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/SecretKeyHandler.java index 5408ad73..5583c4d5 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/SecretKeyHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/SecretKeyHandler.java @@ -5,6 +5,7 @@ import com.mqttsnet.basic.protocol.factory.ProtocolMessageAdapter; import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; @@ -14,7 +15,7 @@ import java.util.Map; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: 处理SECRET_KEY主题 * @packagename: com.mqttsnet.thinglinks.mqtt.handler * @author: ShiHuan Sun @@ -28,10 +29,10 @@ public class SecretKeyHandler extends AbstractMessageHandler implements TopicHan private static final ObjectMapper objectMapper = new ObjectMapper(); public SecretKeyHandler(CacheDataHelper cacheDataHelper, - RemoteDeviceService remoteDeviceService, + RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, remoteDeviceService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + super(cacheDataHelper, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } /** diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/TopicHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/TopicHandler.java index 09c460f2..f25bba85 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/TopicHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/TopicHandler.java @@ -1,7 +1,7 @@ package com.mqttsnet.thinglinks.broker.mqs.mqtt.handler; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: * @packagename: com.mqttsnet.thinglinks.mqtt.handler * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/UpdateSubDeviceHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/UpdateSubDeviceHandler.java index 1dd8f0be..de008715 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/UpdateSubDeviceHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/UpdateSubDeviceHandler.java @@ -8,7 +8,7 @@ import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; import com.mqttsnet.thinglinks.common.core.domain.R; -import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoUpdateSubDeviceStatusParam; import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; @@ -19,7 +19,7 @@ import java.util.Map; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: 处理UPDATE_SUB_DEVICE主题 * @packagename: com.mqttsnet.thinglinks.mqtt.handler * @author: ShiHuan Sun @@ -33,10 +33,10 @@ public class UpdateSubDeviceHandler extends AbstractMessageHandler implements To private static final ObjectMapper objectMapper = new ObjectMapper(); public UpdateSubDeviceHandler(CacheDataHelper cacheDataHelper, - RemoteDeviceService remoteDeviceService, - RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, - ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, remoteDeviceService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, + RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, + ProtocolMessageAdapter protocolMessageAdapter) { + super(cacheDataHelper, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } /** @@ -102,7 +102,7 @@ public void handle(String topic, String qos, String body) { @Override protected String processingTopicMessage(Object topoUpdateSubDeviceParam) throws Exception { R topoDeviceOperationResultVOR = - remoteDeviceService.updateSubDeviceConnectStatusByMqtt((TopoUpdateSubDeviceStatusParam) topoUpdateSubDeviceParam); + remoteDeviceOpenAnyService.updateSubDeviceConnectStatusByMqtt((TopoUpdateSubDeviceStatusParam) topoUpdateSubDeviceParam); log.info("processingTopoUpdateTopic Processing result:{}", JSON.toJSONString(topoDeviceOperationResultVOR)); return JSON.toJSONString(topoDeviceOperationResultVOR.getData()); } diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/event/MqttMessageEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/event/MqttMessageEvent.java index 77c5bba0..efe983c0 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/event/MqttMessageEvent.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/event/MqttMessageEvent.java @@ -3,7 +3,7 @@ import org.springframework.context.ApplicationEvent; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MessageEvent * @packagename: com.mqttsnet.thinglinks.mqtt.handle.event * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/AbstractMessageHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/AbstractMessageHandler.java index 51fab2bb..a50aad38 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/AbstractMessageHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/AbstractMessageHandler.java @@ -5,7 +5,7 @@ import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.api.domain.vo.PublishMessageRequestVO; import com.mqttsnet.thinglinks.common.core.utils.SnowflakeIdUtil; -import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductModelCacheVO; import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; @@ -15,7 +15,7 @@ import java.util.List; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: 通用逻辑处理器 * @packagename: com.mqttsnet.thinglinks.mqtt.handler * @author: ShiHuan Sun @@ -26,16 +26,16 @@ public abstract class AbstractMessageHandler { protected final CacheDataHelper cacheDataHelper; - protected final RemoteDeviceService remoteDeviceService; + protected final RemoteDeviceOpenAnyService remoteDeviceOpenAnyService; protected final RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi; protected final ProtocolMessageAdapter protocolMessageAdapter; public AbstractMessageHandler(CacheDataHelper cacheDataHelper, - RemoteDeviceService remoteDeviceService, + RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, ProtocolMessageAdapter protocolMessageAdapter) { this.cacheDataHelper = cacheDataHelper; - this.remoteDeviceService = remoteDeviceService; + this.remoteDeviceOpenAnyService = remoteDeviceOpenAnyService; this.remoteMqttBrokerOpenApi = remoteMqttBrokerOpenApi; this.protocolMessageAdapter = protocolMessageAdapter; } diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/TopicHandlerFactory.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/TopicHandlerFactory.java index a5fc13c4..440bf519 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/TopicHandlerFactory.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/TopicHandlerFactory.java @@ -11,7 +11,7 @@ import java.util.regex.Pattern; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MQTT系统Topic 处理工厂类 * @packagename: com.mqttsnet.thinglinks.handler.factory * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/listener/MqttMessageListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/listener/MqttMessageListener.java index 47a03a38..1e8af1b5 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/listener/MqttMessageListener.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/listener/MqttMessageListener.java @@ -10,7 +10,7 @@ /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: * @packagename: com.mqttsnet.thinglinks.mqtt.handle.listener * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventActionService.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventActionService.java index 00073186..fabcd7b7 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventActionService.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventActionService.java @@ -15,7 +15,7 @@ import java.util.Map; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MqttEventActionHandler * @packagename: com.mqttsnet.thinglinks.mqtt.handler * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventCommandService.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventCommandService.java index 21e2a06d..c8139b5a 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventCommandService.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventCommandService.java @@ -7,7 +7,7 @@ import org.springframework.stereotype.Service; /** - * @program: thinglinks-cloud-pro-datasource-column + * @program: thinglinks * @description: MqttEventCommandService * @packagename: com.mqttsnet.thinglinks.mqtt.handler * @author: ShiHuan Sun diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventOtaCommandResponseService.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventOtaCommandResponseService.java index 052e8083..6f3d98de 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventOtaCommandResponseService.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventOtaCommandResponseService.java @@ -2,7 +2,7 @@ import com.alibaba.fastjson.JSON; import com.mqttsnet.thinglinks.common.core.domain.R; -import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.api.domain.vo.param.OtaCommandResponseParam; import lombok.RequiredArgsConstructor; @@ -35,7 +35,7 @@ public class MqttEventOtaCommandResponseService { @Autowired - private RemoteDeviceService remoteDeviceService; + private RemoteDeviceOpenAnyService remoteDeviceOpenAnyService; /** @@ -67,7 +67,7 @@ public void saveMqttEventOtaCommandResponse(DeviceCacheVO deviceCacheVO, String // This is a placeholder for the actual saving logic private void saveOtaCommandResponse(OtaCommandResponseParam responseParam) { // Implementation for saving the response in your system - R otaCommandResponseParamR = remoteDeviceService.saveUpgradeRecordByMqtt(responseParam); + R otaCommandResponseParamR = remoteDeviceOpenAnyService.saveUpgradeRecordByMqtt(responseParam); log.info("otaCommandResponseParamR:{}", JSON.toJSONString(otaCommandResponseParamR)); } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceController.java index 194834c3..cfe3b7cf 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceController.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceController.java @@ -14,14 +14,8 @@ import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; import com.mqttsnet.thinglinks.link.api.domain.device.model.DeviceParams; import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; -import com.mqttsnet.thinglinks.link.api.domain.vo.param.*; -import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; -import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; -import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoQueryDeviceResultVO; import com.mqttsnet.thinglinks.link.service.device.DeviceService; import com.mqttsnet.thinglinks.link.service.product.ProductService; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -30,7 +24,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; import java.io.IOException; import java.util.HashMap; import java.util.List; @@ -256,34 +249,6 @@ public ResponseEntity clientAuthentication(@RequestBody Map params) { - - final Object clientIdentifier = params.get("clientIdentifier"); - final Object username = params.get("username"); - final Object password = params.get("password"); - final Object deviceStatus = "ENABLE";// params.get("deviceStatus"); - final Object protocolType = "MQTT";// params.get("protocolType"); - Device device = deviceService.clientAuthentication(clientIdentifier.toString(), username.toString(), password.toString(), deviceStatus.toString(), protocolType.toString()); - log.info("{} 协议设备正在进行身份认证,客户端ID:{},用户名:{},密码:{},认证结果:{}", protocolType, clientIdentifier, username, password, device != null ? "成功" : "失败"); - - Map resultValue = new HashMap<>(); - resultValue.put("clientId", clientIdentifier.toString()); - Map result = new HashMap<>(); - result.put("certificationResult", device == null ? false : true); - result.put("tenantId", device == null ? "" : device.getAppId()); - result.put("deviceResult", resultValue); - - return ResponseEntity.ok().body(result); - } - - /** * 根据客户端标识获取设备信息 * @@ -314,166 +279,4 @@ public R selectDeviceByDeviceIdentificationList(@RequestBody List dev } - /** - * (MQTT)协议新增子设备档案 - * - * @param topoAddSubDeviceParam 子设备参数 - * @return {@link TopoAddDeviceResultVO} 新增结果 - */ - @ApiOperation(value = "(MQTT)协议新增子设备档案", httpMethod = "POST", notes = "(MQTT)协议新增子设备档案") - @PostMapping("/saveSubDeviceByMqtt") - public R saveSubDeviceByMqtt(@RequestBody TopoAddSubDeviceParam topoAddSubDeviceParam) { - return R.ok(deviceService.saveSubDeviceByMqtt(topoAddSubDeviceParam)); - } - - /** - * (HTTP)协议新增子设备档案 - * - * @param topoAddSubDeviceParam 子设备参数 - * @return {@link TopoAddDeviceResultVO} 新增结果 - */ - @ApiOperation(value = "(HTTP)协议新增子设备档案", httpMethod = "POST", notes = "(HTTP)协议新增子设备档案") - @PostMapping("/saveSubDeviceByHttp") - public R saveSubDeviceByHttp(@RequestBody TopoAddSubDeviceParam topoAddSubDeviceParam) { - return R.ok(deviceService.saveSubDeviceByHttp(topoAddSubDeviceParam)); - } - - /** - * MQTT协议修改子设备连接状态 - * - * @param topoUpdateSubDeviceStatusParam 连接状态参数 - * @return {@link TopoDeviceOperationResultVO} 修改结果 - */ - @ApiOperation(value = "(MQTT)协议修改子设备连接状态", httpMethod = "PUT", notes = "(MQTT)协议修改子设备连接状态") - @PutMapping("/updateSubDeviceConnectStatusByMqtt") - public R updateSubDeviceConnectStatusByMqtt( - @RequestBody @ApiParam(value = "连接状态参数") TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { - TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceService.updateSubDeviceConnectStatusByMqtt(topoUpdateSubDeviceStatusParam); - return R.ok(topoDeviceOperationResultVO); - } - - /** - * HTTP协议修改子设备连接状态 - * - * @param topoUpdateSubDeviceStatusParam 连接状态参数 - * @return {@link TopoDeviceOperationResultVO} 修改结果 - */ - @ApiOperation(value = "(HTTP)协议修改子设备连接状态", httpMethod = "PUT", notes = "(HTTP)协议修改子设备连接状态") - @PutMapping("/updateSubDeviceConnectStatusByHttp") - public R updateSubDeviceConnectStatusByHttp( - @RequestBody @ApiParam(value = "连接状态参数") TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { - TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceService.updateSubDeviceConnectStatusByHttp(topoUpdateSubDeviceStatusParam); - return R.ok(topoDeviceOperationResultVO); - } - - /** - * MQTT协议删除子设备 - * - * @param topoDeleteSubDeviceParam 删除参数 - * @return {@link TopoDeviceOperationResultVO} 修改结果 - */ - @ApiOperation(value = "(MQTT)协议删除子设备", httpMethod = "PUT", notes = "(MQTT)协议删除子设备") - @PutMapping("/deleteSubDeviceByMqtt") - public R deleteSubDeviceByMqtt(@RequestBody @ApiParam(value = "删除参数") TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { - TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceService.deleteSubDeviceByMqtt(topoDeleteSubDeviceParam); - return R.ok(topoDeviceOperationResultVO); - } - - /** - * HTTP协议删除子设备 - * - * @param topoDeleteSubDeviceParam 删除参数 - * @return {@link TopoDeviceOperationResultVO} 修改结果 - */ - @ApiOperation(value = "(HTTP)协议删除子设备", httpMethod = "PUT", notes = "(HTTP)协议删除子设备") - @PutMapping("/deleteSubDeviceByHttp") - public R deleteSubDeviceByHttp(@RequestBody @ApiParam(value = "删除参数") TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { - TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceService.deleteSubDeviceByHttp(topoDeleteSubDeviceParam); - return R.ok(topoDeviceOperationResultVO); - } - - - /** - * MQTT协议数据上报 - * - * @param topoDeviceDataReportParam 数据上报参数 - * @return {@link TopoDeviceOperationResultVO} 上报结果 - */ - @ApiOperation(value = "(MQTT)协议数据上报", httpMethod = "POST", notes = "(MQTT)协议数据上报") - @PostMapping("/deviceDataReportByMqtt") - public R deviceDataReportByMqtt(@RequestBody @ApiParam(value = "数据上报参数") TopoDeviceDataReportParam topoDeviceDataReportParam) { - TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceService.deviceDataReportByMqtt(topoDeviceDataReportParam); - return R.ok(topoDeviceOperationResultVO); - } - - /** - * HTTP协议数据上报 - * - * @param topoDeviceDataReportParam 数据上报参数 - * @return {@link TopoDeviceOperationResultVO} 上报结果 - */ - @ApiOperation(value = "(HTTP)协议数据上报", httpMethod = "POST", notes = "(HTTP)协议数据上报") - @PostMapping("/deviceDataReportByHttp") - public R deviceDataReportByHttp(@RequestBody @ApiParam(value = "数据上报参数") TopoDeviceDataReportParam topoDeviceDataReportParam) { - TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceService.deviceDataReportByHttp(topoDeviceDataReportParam); - return R.ok(topoDeviceOperationResultVO); - } - - /** - * Queries device information using the HTTP protocol. - * - * @param topoQueryDeviceParam The device query parameters. - * @return {@link TopoQueryDeviceResultVO} The result of the device query. - */ - @ApiOperation(value = "Query Device Information via HTTP Protocol", httpMethod = "POST", notes = "Queries device information using the HTTP protocol") - @PostMapping("/queryDeviceByHttp") - public R queryDeviceByHttp(@RequestBody TopoQueryDeviceParam topoQueryDeviceParam) { - return R.ok(deviceService.queryDeviceByHttp(topoQueryDeviceParam)); - } - - /** - * Receives and saves a new OTA upgrade record from an MQTT message. This endpoint - * captures the command response parameters from the MQTT message body and persists them. - * - * @param otaCommandResponseParam The response parameters from an OTA command sent via MQTT. - * @return {@link R} A response entity containing the saved OTA upgrade record. - */ - @ApiOperation(value = "Save OTA Upgrade Record", httpMethod = "POST", notes = "Saves a new OTA upgrade record from MQTT message data.") - @PostMapping("/saveOtaUpgradeRecordByMqtt") - public R saveOtaUpgradeRecordByMqtt(@Valid @RequestBody OtaCommandResponseParam otaCommandResponseParam) { - try { - // Call the service method to save the record -// OtaCommandResponseParam savedRecord = otaUpgradeRecordsService.saveOtaUpgradeRecordByMqtt(otaCommandResponseParam); - - // Return a successful response entity with the saved record - return R.ok(); - } catch (Exception e) { - // Log the exception and return an error response entity - // Assuming R.fail() is a method to create a failure response - return R.fail("Error saving OTA upgrade record: " + e.getMessage()); - } - } - - /** - * Receives and saves a new OTA upgrade record from an HTTP request. This endpoint - * captures the command response parameters from the request body and persists them. - * - * @param otaCommandResponseParam The response parameters from an OTA command sent via HTTP. - * @return {@link R} A response wrapper containing the saved OTA upgrade record. - */ - @ApiOperation(value = "Save OTA Upgrade Record via HTTP", httpMethod = "POST", notes = "Saves a new OTA upgrade record from HTTP request data.") - @PostMapping("/saveUpgradeRecordByHttp") - public R saveUpgradeRecordByHttp(@Valid @RequestBody OtaCommandResponseParam otaCommandResponseParam) { - try { - // Call the service method to save the record -// OtaCommandResponseParam savedRecord = otaUpgradeRecordsService.saveUpgradeRecordByHttp(otaCommandResponseParam); - - // Return a successful response wrapper with the saved record - return R.ok(); - } catch (Exception e) { - // Log the exception and return a failure response wrapper - // Assuming R.fail() is a method to create a failure response - return R.fail("Error saving OTA upgrade record via HTTP: " + e.getMessage()); - } - } } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceInfoController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceInfoController.java index d66c9f2a..313eba3d 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceInfoController.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceInfoController.java @@ -28,8 +28,7 @@ */ @RestController @RequestMapping("/deviceInfo") -public class DeviceInfoController extends BaseController -{ +public class DeviceInfoController extends BaseController { @Autowired private DeviceInfoService deviceInfoService; @@ -38,8 +37,7 @@ public class DeviceInfoController extends BaseController */ @PreAuthorize(hasPermi = "link:deviceInfo:list") @GetMapping("/list") - public TableDataInfo list(DeviceInfo deviceInfo) - { + public TableDataInfo list(DeviceInfo deviceInfo) { startPage(); List list = deviceInfoService.selectDeviceInfoList(deviceInfo); return getDataTable(list); @@ -51,8 +49,7 @@ public TableDataInfo list(DeviceInfo deviceInfo) @PreAuthorize(hasPermi = "link:deviceInfo:export") @Log(title = "子设备管理", businessType = BusinessType.EXPORT) @PostMapping("/export") - public void export(HttpServletResponse response, DeviceInfo deviceInfo) throws IOException - { + public void export(HttpServletResponse response, DeviceInfo deviceInfo) throws IOException { List list = deviceInfoService.selectDeviceInfoList(deviceInfo); ExcelUtil util = new ExcelUtil(DeviceInfo.class); util.exportExcel(response, list, "子设备管理数据"); @@ -63,8 +60,7 @@ public void export(HttpServletResponse response, DeviceInfo deviceInfo) throws I */ @PreAuthorize(hasPermi = "link:deviceInfo:query") @GetMapping(value = "/{id}") - public AjaxResult getInfo(@PathVariable("id") Long id) - { + public AjaxResult getInfo(@PathVariable("id") Long id) { return AjaxResult.success(deviceInfoService.selectDeviceInfoById(id)); } @@ -74,8 +70,7 @@ public AjaxResult getInfo(@PathVariable("id") Long id) @PreAuthorize(hasPermi = "link:deviceInfo:add") @Log(title = "子设备管理", businessType = BusinessType.INSERT) @PostMapping - public AjaxResult add(@RequestBody @Valid DeviceInfoParams deviceInfoParams) - { + public AjaxResult add(@RequestBody @Valid DeviceInfoParams deviceInfoParams) { return toAjax(deviceInfoService.insertDeviceInfo(deviceInfoParams)); } @@ -85,8 +80,7 @@ public AjaxResult add(@RequestBody @Valid DeviceInfoParams deviceInfoParams) @PreAuthorize(hasPermi = "link:deviceInfo:edit") @Log(title = "子设备管理", businessType = BusinessType.UPDATE) @PutMapping - public AjaxResult edit(@RequestBody @Valid DeviceInfoParams deviceInfoParams) - { + public AjaxResult edit(@RequestBody @Valid DeviceInfoParams deviceInfoParams) { return toAjax(deviceInfoService.updateDeviceInfo(deviceInfoParams)); } @@ -96,20 +90,19 @@ public AjaxResult edit(@RequestBody @Valid DeviceInfoParams deviceInfoParams) @PreAuthorize(hasPermi = "link:deviceInfo:remove") @Log(title = "子设备管理", businessType = BusinessType.DELETE) @DeleteMapping("/{ids}") - public AjaxResult remove(@PathVariable("ids") Long[] ids) - { + public AjaxResult remove(@PathVariable("ids") Long[] ids) { return toAjax(deviceInfoService.deleteDeviceInfoByIds(ids)); } /** * 查询子设备影子数据 + * * @param params * @return */ @PreAuthorize(hasPermi = "link:deviceInfo:shadow") @PostMapping(value = "/getDeviceInfoShadow") - public AjaxResult getDeviceInfoShadow(@RequestBody Map params) - { + public AjaxResult getDeviceInfoShadow(@RequestBody Map params) { final Object ids = params.get("ids"); final Object startTime = params.get("startTime"); final Object endTime = params.get("endTime"); @@ -118,14 +111,15 @@ public AjaxResult getDeviceInfoShadow(@RequestBody Map params) /** * 刷新子设备数据模型 + * * @param ids * @return */ @PreAuthorize(hasPermi = "link:deviceInfo:initialize") @GetMapping("/refreshDeviceInfoDataModel/{ids}") - public AjaxResult refreshDeviceInfoDataModel(@PathVariable("ids") Long[] ids) - { + public AjaxResult refreshDeviceInfoDataModel(@PathVariable("ids") Long[] ids) { return toAjax(deviceInfoService.refreshDeviceInfoDataModel(Arrays.asList(ids))); } + } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceOpenAnyController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceOpenAnyController.java new file mode 100644 index 00000000..a82dc9fe --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceOpenAnyController.java @@ -0,0 +1,256 @@ + +package com.mqttsnet.thinglinks.link.controller.device; + +import com.mqttsnet.thinglinks.common.core.constant.Constants; +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.common.core.web.controller.BaseController; +import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.*; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoQueryDeviceResultVO; +import com.mqttsnet.thinglinks.link.service.device.DeviceInfoService; +import com.mqttsnet.thinglinks.link.service.device.DeviceService; +import com.mqttsnet.thinglinks.link.service.product.ProductService; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.HashMap; +import java.util.Map; + +/** + * 设备管理开放Controller + * 用于设备接入协议通用入口 + * + * @author thinglinks + * @date 2024-03-22 + */ +@RestController +@RequestMapping("/deviceOpenAny") +@Slf4j +public class DeviceOpenAnyController extends BaseController { + @Autowired + private DeviceService deviceService; + @Autowired + private DeviceInfoService deviceInfoService; + @Autowired + private ProductService productService; + + + /** + * 客户端连接认证 + * + * @param request + * @param params clientIdentifier 客户端标识 + * username 用户名 + * password 密码 + * authMode 认证方式 + * protocolType 协议类型 + * @return 认证结果 + */ + @RequestMapping("/clientConnectionAuthentication") + public ResponseEntity clientConnectionAuthentication(HttpServletRequest request, @RequestBody Map params) { + + final Object clientIdentifier = params.get("clientIdentifier"); + final Object username = params.get("username"); + final Object password = params.get("password"); + final Object deviceStatus = "ENABLE";// params.get("deviceStatus"); + final Object protocolType = "MQTT";// params.get("protocolType"); + Device device = deviceService.clientAuthentication(clientIdentifier.toString(), username.toString(), password.toString(), deviceStatus.toString(), protocolType.toString()); + log.info("{} 协议设备正在进行身份认证,客户端ID:{},用户名:{},密码:{},认证结果:{}", protocolType, clientIdentifier, username, password, device != null ? "成功" : "失败"); + + Map result = new HashMap<>(); + result.put("certificationResult", device != null); + result.put("tenantId", device == null ? Constants.PROJECT_PREFIX : device.getAppId()); + + Map resultValue = new HashMap<>(); + resultValue.put("clientId", clientIdentifier.toString()); + result.put("deviceResult", resultValue); + + return ResponseEntity.ok().body(result); + } + + + /** + * (MQTT)协议新增子设备档案 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 新增结果 + */ + @ApiOperation(value = "(MQTT)协议新增子设备档案", httpMethod = "POST", notes = "(MQTT)协议新增子设备档案") + @PostMapping("/saveSubDeviceByMqtt") + public R saveSubDeviceByMqtt(@RequestBody TopoAddSubDeviceParam topoAddSubDeviceParam) { + return R.ok(deviceInfoService.saveSubDeviceByMqtt(topoAddSubDeviceParam)); + } + + /** + * (HTTP)协议新增子设备档案 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 新增结果 + */ + @ApiOperation(value = "(HTTP)协议新增子设备档案", httpMethod = "POST", notes = "(HTTP)协议新增子设备档案") + @PostMapping("/saveSubDeviceByHttp") + public R saveSubDeviceByHttp(@RequestBody TopoAddSubDeviceParam topoAddSubDeviceParam) { + return R.ok(deviceInfoService.saveSubDeviceByHttp(topoAddSubDeviceParam)); + } + + /** + * MQTT协议修改子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 连接状态参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @ApiOperation(value = "(MQTT)协议修改子设备连接状态", httpMethod = "PUT", notes = "(MQTT)协议修改子设备连接状态") + @PutMapping("/updateSubDeviceConnectStatusByMqtt") + public R updateSubDeviceConnectStatusByMqtt( + @RequestBody @ApiParam(value = "连接状态参数") TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { + TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceInfoService.updateSubDeviceConnectStatusByMqtt(topoUpdateSubDeviceStatusParam); + return R.ok(topoDeviceOperationResultVO); + } + + /** + * HTTP协议修改子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 连接状态参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @ApiOperation(value = "(HTTP)协议修改子设备连接状态", httpMethod = "PUT", notes = "(HTTP)协议修改子设备连接状态") + @PutMapping("/updateSubDeviceConnectStatusByHttp") + public R updateSubDeviceConnectStatusByHttp( + @RequestBody @ApiParam(value = "连接状态参数") TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { + TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceInfoService.updateSubDeviceConnectStatusByHttp(topoUpdateSubDeviceStatusParam); + return R.ok(topoDeviceOperationResultVO); + } + + /** + * MQTT协议删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @ApiOperation(value = "(MQTT)协议删除子设备", httpMethod = "PUT", notes = "(MQTT)协议删除子设备") + @PutMapping("/deleteSubDeviceByMqtt") + public R deleteSubDeviceByMqtt(@RequestBody @ApiParam(value = "删除参数") TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { + TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceInfoService.deleteSubDeviceByMqtt(topoDeleteSubDeviceParam); + return R.ok(topoDeviceOperationResultVO); + } + + /** + * HTTP协议删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 修改结果 + */ + @ApiOperation(value = "(HTTP)协议删除子设备", httpMethod = "PUT", notes = "(HTTP)协议删除子设备") + @PutMapping("/deleteSubDeviceByHttp") + public R deleteSubDeviceByHttp(@RequestBody @ApiParam(value = "删除参数") TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { + TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceInfoService.deleteSubDeviceByHttp(topoDeleteSubDeviceParam); + return R.ok(topoDeviceOperationResultVO); + } + + + /** + * MQTT协议数据上报 + * + * @param topoDeviceDataReportParam 数据上报参数 + * @return {@link TopoDeviceOperationResultVO} 上报结果 + */ + @ApiOperation(value = "(MQTT)协议数据上报", httpMethod = "POST", notes = "(MQTT)协议数据上报") + @PostMapping("/deviceDataReportByMqtt") + public R deviceDataReportByMqtt(@RequestBody @ApiParam(value = "数据上报参数") TopoDeviceDataReportParam topoDeviceDataReportParam) { + TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceService.deviceDataReportByMqtt(topoDeviceDataReportParam); + return R.ok(topoDeviceOperationResultVO); + } + + /** + * HTTP协议数据上报 + * + * @param topoDeviceDataReportParam 数据上报参数 + * @return {@link TopoDeviceOperationResultVO} 上报结果 + */ + @ApiOperation(value = "(HTTP)协议数据上报", httpMethod = "POST", notes = "(HTTP)协议数据上报") + @PostMapping("/deviceDataReportByHttp") + public R deviceDataReportByHttp(@RequestBody @ApiParam(value = "数据上报参数") TopoDeviceDataReportParam topoDeviceDataReportParam) { + TopoDeviceOperationResultVO topoDeviceOperationResultVO = deviceService.deviceDataReportByHttp(topoDeviceDataReportParam); + return R.ok(topoDeviceOperationResultVO); + } + + /** + * Queries device information using the MQTT protocol. + * + * @param topoQueryDeviceParam The device query parameters. + * @return {@link TopoQueryDeviceResultVO} The result of the device query. + */ + @ApiOperation(value = "Query Device Information via MQTT Protocol", httpMethod = "POST", notes = "Queries device information using the MQTT protocol") + @PostMapping("/deviceOpenAny/queryDeviceByMqtt") + public R queryDeviceByMqtt(@RequestBody TopoQueryDeviceParam topoQueryDeviceParam) { + return R.ok(deviceService.queryDeviceByMqtt(topoQueryDeviceParam)); + } + + /** + * Queries device information using the HTTP protocol. + * + * @param topoQueryDeviceParam The device query parameters. + * @return {@link TopoQueryDeviceResultVO} The result of the device query. + */ + @ApiOperation(value = "Query Device Information via HTTP Protocol", httpMethod = "POST", notes = "Queries device information using the HTTP protocol") + @PostMapping("/queryDeviceByHttp") + public R queryDeviceByHttp(@RequestBody TopoQueryDeviceParam topoQueryDeviceParam) { + return R.ok(deviceService.queryDeviceByHttp(topoQueryDeviceParam)); + } + + /** + * Receives and saves a new OTA upgrade record from an MQTT message. This endpoint + * captures the command response parameters from the MQTT message body and persists them. + * + * @param otaCommandResponseParam The response parameters from an OTA command sent via MQTT. + * @return {@link R< OtaCommandResponseParam >} A response entity containing the saved OTA upgrade record. + */ + @ApiOperation(value = "Save OTA Upgrade Record", httpMethod = "POST", notes = "Saves a new OTA upgrade record from MQTT message data.") + @PostMapping("/saveOtaUpgradeRecordByMqtt") + public R saveOtaUpgradeRecordByMqtt(@Valid @RequestBody OtaCommandResponseParam otaCommandResponseParam) { + try { + // Call the service method to save the record +// OtaCommandResponseParam savedRecord = otaUpgradeRecordsService.saveOtaUpgradeRecordByMqtt(otaCommandResponseParam); + + // Return a successful response entity with the saved record + return R.ok(); + } catch (Exception e) { + // Log the exception and return an error response entity + // Assuming R.fail() is a method to create a failure response + return R.fail("Error saving OTA upgrade record: " + e.getMessage()); + } + } + + /** + * Receives and saves a new OTA upgrade record from an HTTP request. This endpoint + * captures the command response parameters from the request body and persists them. + * + * @param otaCommandResponseParam The response parameters from an OTA command sent via HTTP. + * @return {@link R} A response wrapper containing the saved OTA upgrade record. + */ + @ApiOperation(value = "Save OTA Upgrade Record via HTTP", httpMethod = "POST", notes = "Saves a new OTA upgrade record from HTTP request data.") + @PostMapping("/saveUpgradeRecordByHttp") + public R saveUpgradeRecordByHttp(@Valid @RequestBody OtaCommandResponseParam otaCommandResponseParam) { + try { + // Call the service method to save the record +// OtaCommandResponseParam savedRecord = otaUpgradeRecordsService.saveUpgradeRecordByHttp(otaCommandResponseParam); + + // Return a successful response wrapper with the saved record + return R.ok(); + } catch (Exception e) { + // Log the exception and return a failure response wrapper + // Assuming R.fail() is a method to create a failure response + return R.fail("Error saving OTA upgrade record via HTTP: " + e.getMessage()); + } + } + + +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductServicesMapper.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductServicesMapper.java index bc3d1398..57060e43 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductServicesMapper.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductServicesMapper.java @@ -78,7 +78,7 @@ public interface ProductServicesMapper { List findAllByProductIdentificationIdAndStatus(@Param("productIdentification") String productIdentification, @Param("status") String status); - List findAllByProductIdentificationAndServiceNameAndStatus(@Param("productIdentification") String productIdentification, @Param("serviceName") String serviceName, @Param("status") String status); + List findAllByProductIdentificationAndServiceCodeAndStatus(@Param("productIdentification") String productIdentification, @Param("serviceCode") String serviceCode, @Param("status") String status); /** * 查询产品模型服务 diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/DeviceInfoService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/DeviceInfoService.java index a917d747..8d173e0c 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/DeviceInfoService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/DeviceInfoService.java @@ -2,6 +2,11 @@ import com.mqttsnet.thinglinks.link.api.domain.deviceInfo.entity.DeviceInfo; import com.mqttsnet.thinglinks.link.api.domain.deviceInfo.model.DeviceInfoParams; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoAddSubDeviceParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoDeleteSubDeviceParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoUpdateSubDeviceStatusParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; import java.util.Collection; import java.util.List; @@ -127,6 +132,58 @@ public interface DeviceInfoService { List findAllByStatus(String status); + + /** + * MQTT协议下添加子设备 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 添加结果 + */ + TopoAddDeviceResultVO saveSubDeviceByMqtt(TopoAddSubDeviceParam topoAddSubDeviceParam); + + /** + * HTTP协议下添加子设备 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 添加结果 + */ + TopoAddDeviceResultVO saveSubDeviceByHttp(TopoAddSubDeviceParam topoAddSubDeviceParam); + + + /** + * MQTT协议下更新子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 更新参数 + * @return {@link TopoDeviceOperationResultVO} 更新结果 + */ + TopoDeviceOperationResultVO updateSubDeviceConnectStatusByMqtt(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam); + + /** + * Http协议下更新子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 更新参数 + * @return {@link TopoDeviceOperationResultVO} 更新结果 + */ + TopoDeviceOperationResultVO updateSubDeviceConnectStatusByHttp(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam); + + /** + * MQTT协议下删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 删除结果 + */ + TopoDeviceOperationResultVO deleteSubDeviceByMqtt(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam); + + + /** + * Http协议下删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 删除结果 + */ + TopoDeviceOperationResultVO deleteSubDeviceByHttp(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam); + + } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/DeviceService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/DeviceService.java index be2835d1..65fcbf90 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/DeviceService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/DeviceService.java @@ -187,56 +187,6 @@ public interface DeviceService { public List selectDeviceByDeviceIdentificationList(List deviceIdentificationList); - - /** - * MQTT协议下添加子设备 - * - * @param topoAddSubDeviceParam 子设备参数 - * @return {@link TopoAddDeviceResultVO} 添加结果 - */ - TopoAddDeviceResultVO saveSubDeviceByMqtt(TopoAddSubDeviceParam topoAddSubDeviceParam); - - /** - * HTTP协议下添加子设备 - * - * @param topoAddSubDeviceParam 子设备参数 - * @return {@link TopoAddDeviceResultVO} 添加结果 - */ - TopoAddDeviceResultVO saveSubDeviceByHttp(TopoAddSubDeviceParam topoAddSubDeviceParam); - - /** - * MQTT协议下更新子设备连接状态 - * - * @param topoUpdateSubDeviceStatusParam 更新参数 - * @return {@link TopoDeviceOperationResultVO} 更新结果 - */ - TopoDeviceOperationResultVO updateSubDeviceConnectStatusByMqtt(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam); - - /** - * Http协议下更新子设备连接状态 - * - * @param topoUpdateSubDeviceStatusParam 更新参数 - * @return {@link TopoDeviceOperationResultVO} 更新结果 - */ - TopoDeviceOperationResultVO updateSubDeviceConnectStatusByHttp(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam); - - /** - * MQTT协议下删除子设备 - * - * @param topoDeleteSubDeviceParam 删除参数 - * @return {@link TopoDeviceOperationResultVO} 删除结果 - */ - TopoDeviceOperationResultVO deleteSubDeviceByMqtt(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam); - - - /** - * Http协议下删除子设备 - * - * @param topoDeleteSubDeviceParam 删除参数 - * @return {@link TopoDeviceOperationResultVO} 删除结果 - */ - TopoDeviceOperationResultVO deleteSubDeviceByHttp(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam); - /** * MQTT协议下上报设备数据 * diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java index fbf65740..30ac15ec 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java @@ -1,22 +1,37 @@ package com.mqttsnet.thinglinks.link.service.device.impl; +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.bean.copier.CopyOptions; +import cn.hutool.core.text.CharSequenceUtil; import com.alibaba.fastjson.JSON; import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.common.core.constant.Constants; import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatusEnum; +import com.mqttsnet.thinglinks.common.core.enums.DeviceType; import com.mqttsnet.thinglinks.common.core.enums.ResultEnum; import com.mqttsnet.thinglinks.common.core.text.UUID; import com.mqttsnet.thinglinks.common.core.utils.DateUtils; +import com.mqttsnet.thinglinks.common.core.utils.SnowflakeIdUtil; import com.mqttsnet.thinglinks.common.core.utils.StringUtils; +import com.mqttsnet.thinglinks.common.core.utils.tdengine.TdUtils; import com.mqttsnet.thinglinks.common.security.service.TokenService; import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; +import com.mqttsnet.thinglinks.link.api.domain.device.entity.DeviceAction; +import com.mqttsnet.thinglinks.link.api.domain.device.enumeration.DeviceActionStatusEnum; +import com.mqttsnet.thinglinks.link.api.domain.device.enumeration.DeviceActionTypeEnum; +import com.mqttsnet.thinglinks.link.api.domain.device.enumeration.MqttProtocolTopoStatusEnum; import com.mqttsnet.thinglinks.link.api.domain.deviceInfo.entity.DeviceInfo; import com.mqttsnet.thinglinks.link.api.domain.deviceInfo.model.DeviceInfoParams; import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; import com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductServices; -import com.mqttsnet.thinglinks.common.core.utils.tdengine.TdUtils; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoAddSubDeviceParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoDeleteSubDeviceParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoUpdateSubDeviceStatusParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; import com.mqttsnet.thinglinks.link.mapper.device.DeviceInfoMapper; +import com.mqttsnet.thinglinks.link.service.device.DeviceActionService; import com.mqttsnet.thinglinks.link.service.device.DeviceInfoService; import com.mqttsnet.thinglinks.link.service.device.DeviceService; import com.mqttsnet.thinglinks.link.service.product.ProductService; @@ -66,6 +81,9 @@ public class DeviceInfoServiceImpl implements DeviceInfoService { @Resource private RemoteTdEngineService remoteTdEngineService; + @Autowired + private DeviceActionService deviceActionService; + @Resource private RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi; @@ -122,15 +140,15 @@ public int batchInsert(List list) { return deviceInfoMapper.batchInsert(list); } - @Override - public int deleteByDeviceId(String deviceId){ - return deviceInfoMapper.deleteByDeviceId(deviceId); - } + @Override + public int deleteByDeviceId(String deviceId) { + return deviceInfoMapper.deleteByDeviceId(deviceId); + } - @Override - public DeviceInfo findOneByDeviceId(String deviceId){ - return deviceInfoMapper.findOneByDeviceId(deviceId); - } + @Override + public DeviceInfo findOneByDeviceId(String deviceId) { + return deviceInfoMapper.findOneByDeviceId(deviceId); + } /** * 查询子设备管理 @@ -139,12 +157,11 @@ public DeviceInfo findOneByDeviceId(String deviceId){ * @return 子设备管理 */ @Override - public DeviceInfo selectDeviceInfoById(Long id) - { + public DeviceInfo selectDeviceInfoById(Long id) { DeviceInfo deviceInfo = deviceInfoMapper.selectDeviceInfoById(id); if (StringUtils.isNotNull(deviceInfo)) { Device oneById = deviceService.findOneById(deviceInfo.getDid()); - deviceInfo.setEdgeDevicesIdentification(StringUtils.isNotNull(oneById)?oneById.getDeviceIdentification():""); + deviceInfo.setEdgeDevicesIdentification(StringUtils.isNotNull(oneById) ? oneById.getDeviceIdentification() : ""); } return deviceInfo; } @@ -156,12 +173,11 @@ public DeviceInfo selectDeviceInfoById(Long id) * @return 子设备管理 */ @Override - public List selectDeviceInfoList(DeviceInfo deviceInfo) - { + public List selectDeviceInfoList(DeviceInfo deviceInfo) { List deviceInfoList = deviceInfoMapper.selectDeviceInfoList(deviceInfo); deviceInfoList.forEach(deviceInfo1 -> { Device oneById = deviceService.findOneById(deviceInfo1.getDid()); - deviceInfo1.setEdgeDevicesIdentification(StringUtils.isNotNull(oneById)?oneById.getDeviceIdentification():""); + deviceInfo1.setEdgeDevicesIdentification(StringUtils.isNotNull(oneById) ? oneById.getDeviceIdentification() : ""); }); return deviceInfoList; } @@ -173,8 +189,7 @@ public List selectDeviceInfoList(DeviceInfo deviceInfo) * @return 结果 */ @Override - public int insertDeviceInfo(DeviceInfoParams deviceInfoParams) - { + public int insertDeviceInfo(DeviceInfoParams deviceInfoParams) { DeviceInfo deviceInfo = new DeviceInfo(); deviceInfo.convertEntity(deviceInfoParams); LoginUser loginUser = tokenService.getLoginUser(); @@ -193,8 +208,7 @@ public int insertDeviceInfo(DeviceInfoParams deviceInfoParams) * @return 结果 */ @Override - public int updateDeviceInfo(DeviceInfoParams deviceInfoParams) - { + public int updateDeviceInfo(DeviceInfoParams deviceInfoParams) { DeviceInfo deviceInfo = deviceInfoMapper.selectByPrimaryKey(deviceInfoParams.getId()); deviceInfo.convertEntity(deviceInfoParams); LoginUser loginUser = tokenService.getLoginUser(); @@ -235,7 +249,7 @@ public int deleteDeviceInfoByIds(Long[] ids) { Device device = deviceService.findOneById(deviceInfo.getDid()); if (StringUtils.isNotNull(device)) { final Map param = new HashMap<>(); - param.put("topic", "/v1/devices/"+device.getDeviceIdentification()+"/topo/deleteResponse"); + param.put("topic", "/v1/devices/" + device.getDeviceIdentification() + "/topo/deleteResponse"); param.put("qos", 2); param.put("retain", false); param.put("message", JSON.toJSONString(responseMaps)); @@ -253,21 +267,20 @@ public int deleteDeviceInfoByIds(Long[] ids) { * @return 结果 */ @Override - public int deleteDeviceInfoById(Long id) - { + public int deleteDeviceInfoById(Long id) { return deviceInfoMapper.deleteDeviceInfoById(id); } /** * 查询子设备影子数据 * - * @param ids 需要查询的子设备id + * @param ids 需要查询的子设备id * @param startTime 开始时间 格式:yyyy-MM-dd HH:mm:ss - * @param endTime 结束时间 格式:yyyy-MM-dd HH:mm:ss + * @param endTime 结束时间 格式:yyyy-MM-dd HH:mm:ss * @return 子设备影子数据 */ @Override - public Map>> getDeviceInfoShadow(String ids,String startTime,String endTime) { + public Map>> getDeviceInfoShadow(String ids, String startTime, String endTime) { List idCollection = Arrays.stream(ids.split(",")).mapToLong(Long::parseLong).boxed().collect(Collectors.toList()); List deviceInfos = deviceInfoMapper.findAllByIdInAndStatus(idCollection, Constants.ENABLE); if (StringUtils.isNull(deviceInfos)) { @@ -292,16 +305,16 @@ public Map>> getDeviceInfoShadow(String ids,Str R dataByTimestamp = remoteTdEngineService.getDataByTimestamp(selectDto); if (StringUtils.isNull(dataByTimestamp)) { log.error("查询子设备影子数据失败,子设备影子数据不存在"); - }else { + } else { map.put(shadowTableName, (List>) dataByTimestamp.getData()); log.info("查询子设备影子数据成功,子设备影子数据:{}", dataByTimestamp.getData()); } - }else{ + } else { R lastData = remoteTdEngineService.getLastData(selectDto); if (StringUtils.isNull(lastData)) { log.error("查询子设备影子数据失败,子设备影子数据不存在"); - }else { + } else { map.put(shadowTableName, (List>) lastData.getData()); log.info("查询子设备影子数据成功,子设备影子数据:{}", lastData.getData()); @@ -313,18 +326,19 @@ public Map>> getDeviceInfoShadow(String ids,Str return map; } - @Override - public List findAllByIdInAndStatus(Collection idCollection, String status){ - return deviceInfoMapper.findAllByIdInAndStatus(idCollection,status); - } + @Override + public List findAllByIdInAndStatus(Collection idCollection, String status) { + return deviceInfoMapper.findAllByIdInAndStatus(idCollection, status); + } - @Override - public List findAllByIdIn(Collection idCollection){ - return deviceInfoMapper.findAllByIdIn(idCollection); - } + @Override + public List findAllByIdIn(Collection idCollection) { + return deviceInfoMapper.findAllByIdIn(idCollection); + } /** * 刷新子设备数据模型 + * * @param idCollection * @return */ @@ -333,10 +347,10 @@ public Boolean refreshDeviceInfoDataModel(Collection idCollection) { List allByIdInAndStatus = null; if (StringUtils.isNotEmpty(idCollection)) { allByIdInAndStatus = deviceInfoMapper.findAllByIdInAndStatus(idCollection, Constants.ENABLE); - }else { + } else { allByIdInAndStatus = deviceInfoMapper.findAllByStatus(Constants.ENABLE); } - allByIdInAndStatus.forEach(item->{ + allByIdInAndStatus.forEach(item -> { final Device device = deviceService.findOneById(item.getDid()); if (StringUtils.isNull(device)) { log.error("刷新子设备数据模型失败,子设备不存在"); @@ -355,10 +369,10 @@ public Boolean refreshDeviceInfoDataModel(Collection idCollection) { tableDto = new TableDto(); tableDto.setDataBaseName(dataBaseName); //超级表命名规则 : 产品类型_产品标识_服务名称 - String superTableName = TdUtils.getSuperTableName(product.getProductType(),product.getProductIdentification(),productServices.getServiceName()); + String superTableName = TdUtils.getSuperTableName(product.getProductType(), product.getProductIdentification(), productServices.getServiceName()); tableDto.setSuperTableName(superTableName); //子表命名规则 : 产品类型_产品标识_服务名称_设备标识(设备唯一标识) - tableDto.setTableName(TdUtils.getSubTableName(superTableName,item.getDeviceId())); + tableDto.setTableName(TdUtils.getSubTableName(superTableName, item.getDeviceId())); //Tag的处理 List tagsFieldValues = new ArrayList<>(); Fields fields = new Fields(); @@ -383,10 +397,382 @@ public Boolean refreshDeviceInfoDataModel(Collection idCollection) { return true; } - @Override - public List findAllByStatus(String status){ - return deviceInfoMapper.findAllByStatus(status); - } + @Override + public List findAllByStatus(String status) { + return deviceInfoMapper.findAllByStatus(status); + } + + + /** + * MQTT协议下添加子设备 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 添加结果 + */ + @Override + public TopoAddDeviceResultVO saveSubDeviceByMqtt(TopoAddSubDeviceParam topoAddSubDeviceParam) { + return saveSubDevice(topoAddSubDeviceParam); + } + + /** + * HTTP协议下添加子设备 + * + * @param topoAddSubDeviceParam 子设备参数 + * @return {@link TopoAddDeviceResultVO} 添加结果 + */ + @Override + public TopoAddDeviceResultVO saveSubDeviceByHttp(TopoAddSubDeviceParam topoAddSubDeviceParam) { + return saveSubDevice(topoAddSubDeviceParam); + } + + + /** + * 添加网关子设备 + * + * @param topoAddSubDeviceParam TopoAddDeviceParam,添加设备的参数信息 + * @return {@link TopoAddDeviceResultVO} 添加设备的结果信息 + */ + private TopoAddDeviceResultVO saveSubDevice(TopoAddSubDeviceParam topoAddSubDeviceParam) { + + // 根据网关ID查找网关设备 + Device gatewayDevice = deviceService.findOneByDeviceIdentification(topoAddSubDeviceParam.getGatewayIdentification()); + + // 假设 gatewayDevice.getType() 方法返回设备类型,且 DeviceType.GATEWAY 代表网关设备类型 + MqttProtocolTopoStatusEnum statusEnum = MqttProtocolTopoStatusEnum.FAILURE; + + if (DeviceType.GATEWAY.getValue().equals(gatewayDevice.getDeviceType())) { + statusEnum = MqttProtocolTopoStatusEnum.SUCCESS; + } else { + statusEnum = MqttProtocolTopoStatusEnum.FAILURE; + } + + // 创建返回结果实例并设置状态码和状态描述 + TopoAddDeviceResultVO mqttTopoAddDeviceResultVO = TopoAddDeviceResultVO.builder() + .statusCode(statusEnum.getValue()) + .statusDesc(statusEnum.getDesc()) + .build(); + + // 创建一个设备列表用于存储处理结果 + List deviceList = new ArrayList<>(); + + // 检查设备信息列表是否为空 + List deviceInfos = topoAddSubDeviceParam.getDeviceInfos(); + if (!deviceInfos.isEmpty() && MqttProtocolTopoStatusEnum.SUCCESS.equals(statusEnum)) { + // 遍历添加设备的参数信息列表 + for (TopoAddSubDeviceParam.DeviceInfos item : deviceInfos) { + try { + // 创建数据项实例并验证设备参数 + TopoAddDeviceResultVO.DataItem dataItem = new TopoAddDeviceResultVO.DataItem(); + checkedTopoAddDeviceParam(item, dataItem); + // 将参数对象转换为设备信息对象并设置到数据项中 + dataItem.setDeviceInfo(BeanUtil.toBean(item, TopoAddDeviceResultVO.DataItem.DeviceInfo.class, CopyOptions.create().ignoreError())); + + // 如果设备参数验证不通过,添加到设备列表并继续下一次循环 + if (!MqttProtocolTopoStatusEnum.SUCCESS.getValue().equals(dataItem.getStatusCode())) { + deviceList.add(dataItem); + continue; + } + + // 转换并保存子设备信息 + DeviceInfoParams deviceInfoParams = conversionDeviceBySaveSubDevice(gatewayDevice, item); + int insertCount = this.insertDeviceInfo(deviceInfoParams); + + // TODO 存储子设备经纬度信息 + /*DeviceLocationPageQuery deviceLocationPageQuery = new DeviceLocationPageQuery(); + deviceLocationPageQuery.setDeviceIdentification(gatewayDevice.getDeviceIdentification()); + + List deviceLocationResultVOList = deviceLocationService.getDeviceLocationResultVOList(deviceLocationPageQuery); + + Optional.ofNullable(deviceLocationResultVOList) + .filter(list -> !list.isEmpty()) + .map(list -> list.get(0)) + .map(deviceLocationResultVO -> BeanPlusUtil.toBeanIgnoreError(deviceLocationResultVO, DeviceLocationSaveVO.class)) + .ifPresent(deviceLocationSaveVO -> { + deviceLocationSaveVO.setDeviceIdentification(subDeviceDO.getDeviceIdentification()); + deviceLocationService.saveDeviceLocation(deviceLocationSaveVO); + });*/ + + // 设置平台生成的设备标识 + dataItem.getDeviceInfo().setDeviceId(deviceInfoParams.getDeviceId()); + + // 根据保存结果设置状态码和状态描述 + MqttProtocolTopoStatusEnum saveStatusEnum = insertCount > 0 ? MqttProtocolTopoStatusEnum.SUCCESS : MqttProtocolTopoStatusEnum.FAILURE; + dataItem.setStatusCode(saveStatusEnum.getValue()) + .setStatusDesc(saveStatusEnum.getDesc()); + + // 添加数据项到设备列表 + deviceList.add(dataItem); + } catch (Exception e) { + // 处理异常情况,将异常信息设置到数据项中 + TopoAddDeviceResultVO.DataItem dataItem = new TopoAddDeviceResultVO.DataItem(); + dataItem.setStatusCode(MqttProtocolTopoStatusEnum.FAILURE.getValue()) + .setStatusDesc(e.getMessage()); + deviceList.add(dataItem); + } + } + } + + // 将设备列表设置到返回结果实例中 + mqttTopoAddDeviceResultVO.setData(deviceList); + return mqttTopoAddDeviceResultVO; + } + + /** + * 添加网关子设备转换DO Device + * + * @param deviceDO 网关设备信息 + * @param item 子设备信息 + * @return {@link DeviceInfoParams} 子设备信息 + */ + private DeviceInfoParams conversionDeviceBySaveSubDevice(Device deviceDO, TopoAddSubDeviceParam.DeviceInfos item) { + DeviceInfoParams deviceInfoParams = new DeviceInfoParams(); + deviceInfoParams.setAppId(deviceDO.getAppId()); + deviceInfoParams.setDid(deviceDO.getId()); + deviceInfoParams.setDeviceId(SnowflakeIdUtil.nextId()); + deviceInfoParams.setNodeId(item.getNodeId()); + deviceInfoParams.setNodeName(item.getName()); + deviceInfoParams.setManufacturerId(item.getManufacturerId()); + deviceInfoParams.setModel(item.getModel()); + deviceInfoParams.setDescription(item.getDescription()); + deviceInfoParams.setConnectStatus(DeviceConnectStatusEnum.INIT.getValue()); + deviceInfoParams.setShadowEnable(true); + return deviceInfoParams; + } + + /** + * 验证Topo添加设备参数,并设置对应的状态码和状态描述。 + * + * @param item TopoAddDeviceParam.DeviceInfos,添加设备的参数信息 + * @param dataItem MqttTopoAddDeviceResultVO.DataItem,用于存储设备添加结果的数据项 + */ + private void checkedTopoAddDeviceParam(TopoAddSubDeviceParam.DeviceInfos item, + TopoAddDeviceResultVO.DataItem dataItem) { + // 根据设备标识查找子设备 + Device subDevice = deviceService.findOneByDeviceIdentification(item.getNodeId()); + // 用于拼接错误消息的StringBuilder + StringBuilder errorMessage = new StringBuilder(); + + // 检查各参数是否为空,并将错误消息追加到StringBuilder中 + appendErrorMessageIfEmpty(errorMessage, item.getName(), "name is null; "); + appendErrorMessageIfEmpty(errorMessage, item.getNodeId(), "nodeId is null; "); + appendErrorMessageIfEmpty(errorMessage, item.getManufacturerId(), "manufacturerId is null; "); + appendErrorMessageIfEmpty(errorMessage, item.getModel(), "model is null; "); + + // 检查设备节点ID是否已经存在 + if (subDevice != null) { + errorMessage.append("nodeId is exist; "); + } + + // 根据错误消息长度判断是否有错误,并设置相应的状态码和状态描述 + if (errorMessage.length() > 0) { + dataItem.setStatusCode(MqttProtocolTopoStatusEnum.FAILURE.getValue()) + .setStatusDesc(errorMessage.toString()); + } else { + dataItem.setStatusCode(MqttProtocolTopoStatusEnum.SUCCESS.getValue()) + .setStatusDesc(MqttProtocolTopoStatusEnum.SUCCESS.getDesc()); + } + } + + /** + * 检查参数值是否为空,如果为空,将错误消息追加到StringBuilder中。 + * + * @param errorMessage StringBuilder,用于拼接错误消息 + * @param value CharSequence,待检查的参数值 + * @param message String,错误消息 + */ + private void appendErrorMessageIfEmpty(StringBuilder errorMessage, CharSequence value, String message) { + if (CharSequenceUtil.isEmpty(value)) { + errorMessage.append(message); + } + } + + + /** + * MQTT协议下更新子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 更新参数 + * @return {@link TopoDeviceOperationResultVO} 更新结果 + */ + @Override + public TopoDeviceOperationResultVO updateSubDeviceConnectStatusByMqtt(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { + return updateSubDeviceConnectStatus(topoUpdateSubDeviceStatusParam); + } + + /** + * Http协议下更新子设备连接状态 + * + * @param topoUpdateSubDeviceStatusParam 更新参数 + * @return {@link TopoDeviceOperationResultVO} 更新结果 + */ + @Override + public TopoDeviceOperationResultVO updateSubDeviceConnectStatusByHttp(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { + return updateSubDeviceConnectStatus(topoUpdateSubDeviceStatusParam); + } + + /** + * Updates the connection status of sub-devices and logs their actions. + * + * @param topoUpdateSubDeviceStatusParam the parameters containing device statuses to be updated + * @return an object containing the operation results + */ + private TopoDeviceOperationResultVO updateSubDeviceConnectStatus(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { + List operationRsps = topoUpdateSubDeviceStatusParam.getDeviceStatuses().stream() + .map(this::processSubDeviceStatus) + .collect(Collectors.toList()); + + return TopoDeviceOperationResultVO.builder() + .statusCode(MqttProtocolTopoStatusEnum.SUCCESS.getValue()) + .statusDesc(MqttProtocolTopoStatusEnum.SUCCESS.getDesc()) + .data(operationRsps) + .build(); + } + + /** + * Processes the status of a single sub-device, updates it, and logs the action. + * + * @param subDeviceStatus the status of the sub-device to be processed + * @return an operation response object for the sub-device + */ + private TopoDeviceOperationResultVO.OperationRsp processSubDeviceStatus(TopoUpdateSubDeviceStatusParam.DeviceStatus subDeviceStatus) { + DeviceInfo deviceInfo = this.findOneByDeviceId(subDeviceStatus.getDeviceId()); + TopoDeviceOperationResultVO.OperationRsp dataItem = new TopoDeviceOperationResultVO.OperationRsp() + .setDeviceId(subDeviceStatus.getDeviceId()); + + if (deviceInfo != null) { + deviceInfo.setConnectStatus(subDeviceStatus.getStatus().getValue()); + int updateCount = deviceInfoMapper.updateByPrimaryKey(deviceInfo); + recordDeviceAction(deviceInfo, subDeviceStatus.getStatus()); + + MqttProtocolTopoStatusEnum updateStatusEnum = updateCount > 0 ? MqttProtocolTopoStatusEnum.SUCCESS : MqttProtocolTopoStatusEnum.FAILURE; + dataItem.setStatusCode(updateStatusEnum.getValue()) + .setStatusDesc(updateStatusEnum.getDesc()); + } else { + dataItem.setStatusCode(MqttProtocolTopoStatusEnum.FAILURE.getValue()) + .setStatusDesc(MqttProtocolTopoStatusEnum.FAILURE.getDesc()); + } + + return dataItem; + } + + /** + * Records an action taken on a device and saves it to the database. + * + * @param deviceInfo the device information + * @param connectStatus the new connection status of the device + */ + private void recordDeviceAction(DeviceInfo deviceInfo, DeviceConnectStatusEnum connectStatus) { + // 构建设备动作描述和类型 + String describable = getDescriptionForStatus(connectStatus); + DeviceActionTypeEnum actionType = getActionTypeForStatus(connectStatus); + + // 构建并保存设备动作记录 + DeviceAction deviceActionSaveVO = new DeviceAction(); + deviceActionSaveVO.setDeviceIdentification(deviceInfo.getDeviceId()); + deviceActionSaveVO.setActionType(actionType.getAction()); + deviceActionSaveVO.setMessage(describable); + deviceActionSaveVO.setStatus(DeviceActionStatusEnum.SUCCESSFUL.getValue()); + + try { + int insertDeviceActionCount = deviceActionService.insertDeviceAction(deviceActionSaveVO); + log.info("Saved device action for device ID: {}, insert count: {}", deviceInfo.getDeviceId(), insertDeviceActionCount); + } catch (Exception e) { + log.error("Failed to save device action for device ID: {}", deviceInfo.getDeviceId(), e); + } + } + + /** + * Determines the action type based on the device connection status. + * + * @param status the device connection status + * @return the corresponding action type + */ + private DeviceActionTypeEnum getActionTypeForStatus(DeviceConnectStatusEnum status) { + if (DeviceConnectStatusEnum.OFFLINE.equals(status)) { + return DeviceActionTypeEnum.CLOSE; + } else if (DeviceConnectStatusEnum.ONLINE.equals(status)) { + return DeviceActionTypeEnum.CONNECT; + } else { + // Handle unexpected status here + log.warn("Unexpected status: {}", status); + return DeviceActionTypeEnum.UNKNOWN; + } + } + + /** + * Gets a descriptive text based on the device connection status. + * + * @param status the device connection status + * @return a string description for the status + */ + private String getDescriptionForStatus(DeviceConnectStatusEnum status) { + String desc = Optional.ofNullable(status) + .map(DeviceConnectStatusEnum::getValue) + .orElse("Unknown Status"); + + return "The device connection status is updated to " + desc; + } + + /** + * MQTT协议下删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 删除结果 + */ + @Override + public TopoDeviceOperationResultVO deleteSubDeviceByMqtt(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { + return deleteSubDevice(topoDeleteSubDeviceParam); + } + + /** + * Http协议下删除子设备 + * + * @param topoDeleteSubDeviceParam 删除参数 + * @return {@link TopoDeviceOperationResultVO} 删除结果 + */ + @Override + public TopoDeviceOperationResultVO deleteSubDeviceByHttp(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { + return deleteSubDevice(topoDeleteSubDeviceParam); + } + + private TopoDeviceOperationResultVO deleteSubDevice(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { + // 创建一个操作结果列表用于存储处理结果 + List operationResultList = new ArrayList<>(); + + // 遍历子设备标识集合 + for (String deviceId : topoDeleteSubDeviceParam.getDeviceIds()) { + // 根据子设备唯一标识查找设备 + DeviceInfo deviceInfo = this.findOneByDeviceId(deviceId); + + // 创建操作结果实例 + TopoDeviceOperationResultVO.OperationRsp operationRsp = new TopoDeviceOperationResultVO.OperationRsp() + .setDeviceId(deviceId); + + // 判断设备是否存在 + if (deviceInfo != null) { + // 删除设备 + int deleteCount = deviceInfoMapper.deleteByDeviceId(deviceInfo.getDeviceId()); + + // 根据删除结果设置状态码和状态描述 + MqttProtocolTopoStatusEnum deleteStatusEnum = deleteCount > 0 ? MqttProtocolTopoStatusEnum.SUCCESS : MqttProtocolTopoStatusEnum.FAILURE; + operationRsp.setStatusCode(deleteStatusEnum.getValue()) + .setStatusDesc(deleteStatusEnum.getDesc()); + } else { + // 如果设备不存在,设置状态码和状态描述为FAILURE + operationRsp.setStatusCode(MqttProtocolTopoStatusEnum.FAILURE.getValue()) + .setStatusDesc(MqttProtocolTopoStatusEnum.FAILURE.getDesc()); + } + + // 添加操作结果到操作结果列表 + operationResultList.add(operationRsp); + } + + // 创建返回结果实例并设置状态码、状态描述和操作结果列表 + return TopoDeviceOperationResultVO.builder() + .statusCode(MqttProtocolTopoStatusEnum.SUCCESS.getValue()) + .statusDesc(MqttProtocolTopoStatusEnum.SUCCESS.getDesc()) + .data(operationResultList) + .build(); + } } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java index 46f3bdb0..c83ca208 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java @@ -1,5 +1,8 @@ package com.mqttsnet.thinglinks.link.service.device.impl; +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.bean.copier.CopyOptions; +import cn.hutool.core.text.CharSequenceUtil; import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.common.core.constant.CacheConstants; import com.mqttsnet.thinglinks.common.core.constant.Constants; @@ -9,6 +12,7 @@ import com.mqttsnet.thinglinks.common.core.enums.DeviceType; import com.mqttsnet.thinglinks.common.core.enums.ResultEnum; import com.mqttsnet.thinglinks.common.core.utils.DateUtils; +import com.mqttsnet.thinglinks.common.core.utils.SnowflakeIdUtil; import com.mqttsnet.thinglinks.common.core.utils.StringUtils; import com.mqttsnet.thinglinks.common.core.utils.tdengine.TdUtils; import com.mqttsnet.thinglinks.common.redis.service.RedisService; @@ -16,7 +20,9 @@ import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; import com.mqttsnet.thinglinks.link.api.domain.device.entity.DeviceLocation; import com.mqttsnet.thinglinks.link.api.domain.device.entity.DeviceTopic; +import com.mqttsnet.thinglinks.link.api.domain.device.enumeration.MqttProtocolTopoStatusEnum; import com.mqttsnet.thinglinks.link.api.domain.device.model.DeviceParams; +import com.mqttsnet.thinglinks.link.api.domain.deviceInfo.model.DeviceInfoParams; import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; import com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductServices; import com.mqttsnet.thinglinks.link.api.domain.vo.param.*; @@ -45,13 +51,7 @@ import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; +import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @@ -440,8 +440,8 @@ public List findAllByProductIdentification(String productIdentification) } @Override - public Device selectByProductIdentificationAndDeviceIdentification(String productIdentification,String deviceIdentification) { - return deviceMapper.selectByProductIdentificationAndDeviceIdentification(productIdentification,deviceIdentification); + public Device selectByProductIdentificationAndDeviceIdentification(String productIdentification, String deviceIdentification) { + return deviceMapper.selectByProductIdentificationAndDeviceIdentification(productIdentification, deviceIdentification); } /** @@ -562,71 +562,6 @@ public List selectDeviceByDeviceIdentificationList(List deviceId return deviceMapper.selectDeviceByDeviceIdentificationList(deviceIdentificationList); } - /** - * MQTT协议下添加子设备 - * - * @param topoAddSubDeviceParam 子设备参数 - * @return {@link TopoAddDeviceResultVO} 添加结果 - */ - @Override - public TopoAddDeviceResultVO saveSubDeviceByMqtt(TopoAddSubDeviceParam topoAddSubDeviceParam) { - return null; - } - - /** - * HTTP协议下添加子设备 - * - * @param topoAddSubDeviceParam 子设备参数 - * @return {@link TopoAddDeviceResultVO} 添加结果 - */ - @Override - public TopoAddDeviceResultVO saveSubDeviceByHttp(TopoAddSubDeviceParam topoAddSubDeviceParam) { - return null; - } - - /** - * MQTT协议下更新子设备连接状态 - * - * @param topoUpdateSubDeviceStatusParam 更新参数 - * @return {@link TopoDeviceOperationResultVO} 更新结果 - */ - @Override - public TopoDeviceOperationResultVO updateSubDeviceConnectStatusByMqtt(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { - return null; - } - - /** - * Http协议下更新子设备连接状态 - * - * @param topoUpdateSubDeviceStatusParam 更新参数 - * @return {@link TopoDeviceOperationResultVO} 更新结果 - */ - @Override - public TopoDeviceOperationResultVO updateSubDeviceConnectStatusByHttp(TopoUpdateSubDeviceStatusParam topoUpdateSubDeviceStatusParam) { - return null; - } - - /** - * MQTT协议下删除子设备 - * - * @param topoDeleteSubDeviceParam 删除参数 - * @return {@link TopoDeviceOperationResultVO} 删除结果 - */ - @Override - public TopoDeviceOperationResultVO deleteSubDeviceByMqtt(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { - return null; - } - - /** - * Http协议下删除子设备 - * - * @param topoDeleteSubDeviceParam 删除参数 - * @return {@link TopoDeviceOperationResultVO} 删除结果 - */ - @Override - public TopoDeviceOperationResultVO deleteSubDeviceByHttp(TopoDeleteSubDeviceParam topoDeleteSubDeviceParam) { - return null; - } /** * MQTT协议下上报设备数据 @@ -658,7 +593,7 @@ public TopoDeviceOperationResultVO deviceDataReportByHttp(TopoDeviceDataReportPa */ @Override public TopoQueryDeviceResultVO queryDeviceByMqtt(TopoQueryDeviceParam topoQueryDeviceParam) { - return null; + return queryDeviceInfo(topoQueryDeviceParam); } /** @@ -669,7 +604,54 @@ public TopoQueryDeviceResultVO queryDeviceByMqtt(TopoQueryDeviceParam topoQueryD */ @Override public TopoQueryDeviceResultVO queryDeviceByHttp(TopoQueryDeviceParam topoQueryDeviceParam) { - return null; + return queryDeviceInfo(topoQueryDeviceParam); + } + + + + /** + * Queries device information based on provided parameters. + * + * @param topoQueryDeviceParam Parameters for querying device information. + * @return {@link TopoQueryDeviceResultVO} containing the results of the device query. + */ + private TopoQueryDeviceResultVO queryDeviceInfo(TopoQueryDeviceParam topoQueryDeviceParam) { + // Create an instance for the result + TopoQueryDeviceResultVO topoQueryDeviceResultVO = new TopoQueryDeviceResultVO(); + + // Create a list to store the results of device information queries + List deviceInfoList = Optional.ofNullable(topoQueryDeviceParam.getDeviceIds()) + .orElse(Collections.emptyList()) + .stream() + .distinct() + .map(deviceIdentification -> { + TopoQueryDeviceResultVO.DataItem dataItem = new TopoQueryDeviceResultVO.DataItem(); + try { + dataItem.setDeviceId(deviceIdentification); + // Attempt to find device information based on the identification + Optional optionalDevice = Optional.ofNullable(deviceMapper.findOneByDeviceIdentification(deviceIdentification)); + TopoQueryDeviceResultVO.DataItem.DeviceInfo deviceInfo = optionalDevice + .map(device -> BeanUtil.toBean(device, TopoQueryDeviceResultVO.DataItem.DeviceInfo.class)) + .orElse(new TopoQueryDeviceResultVO.DataItem.DeviceInfo()); + + // Set device information and status based on query result + dataItem.setDeviceInfo(deviceInfo) + .setStatusCode(optionalDevice.isPresent() ? MqttProtocolTopoStatusEnum.SUCCESS.getValue() : MqttProtocolTopoStatusEnum.FAILURE.getValue()) + .setStatusDesc(optionalDevice.isPresent() ? MqttProtocolTopoStatusEnum.SUCCESS.getDesc() : "Device not found"); + } catch (Exception e) { + // Handle any exceptions and set the error information in the data item + dataItem.setStatusCode(MqttProtocolTopoStatusEnum.FAILURE.getValue()) + .setStatusDesc("Error querying device: " + e.getMessage()); + } + return dataItem; + }) + .collect(Collectors.toList()); + + // Set the list of device information into the result instance + topoQueryDeviceResultVO.setData(deviceInfoList) + .setStatusCode(MqttProtocolTopoStatusEnum.SUCCESS.getValue()) + .setStatusDesc("Query completed"); + return topoQueryDeviceResultVO; } } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductServicesService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductServicesService.java index cb7543f6..282c406f 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductServicesService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductServicesService.java @@ -46,7 +46,7 @@ public interface ProductServicesService { List findAllByProductIdentificationIdAndStatus(String productIdentification, String status); - List findAllByProductIdentificationAndServiceNameAndStatus(String productIdentification, String serviceName, String status); + List findAllByProductIdentificationAndServiceCodeAndStatus(String productIdentification, String serviceCode, String status); /** diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServicesServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServicesServiceImpl.java index 88dc5ad5..cd47ad5a 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServicesServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServicesServiceImpl.java @@ -91,8 +91,8 @@ public List findAllByProductIdentificationIdAndStatus(String pr } @Override - public List findAllByProductIdentificationAndServiceNameAndStatus(String productIdentification, String serviceName, String status) { - return productServicesMapper.findAllByProductIdentificationAndServiceNameAndStatus(productIdentification, serviceName, status); + public List findAllByProductIdentificationAndServiceCodeAndStatus(String productIdentification, String serviceCode, String status) { + return productServicesMapper.findAllByProductIdentificationAndServiceCodeAndStatus(productIdentification, serviceCode, status); } /** diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductServicesMapper.xml b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductServicesMapper.xml index 51e78de8..c442fdd0 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductServicesMapper.xml +++ b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductServicesMapper.xml @@ -5,6 +5,7 @@ + @@ -18,6 +19,7 @@ id, + service_code, service_name, template_identification, product_identification, @@ -48,11 +50,11 @@ parameterType="com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductServices" useGeneratedKeys="true"> - insert into product_services (service_name, template_identification, + insert into product_services (service_code, service_name, template_identification, product_identification, `status`, description, create_by, create_time, update_by, update_time) - values (#{serviceName,jdbcType=VARCHAR}, #{templateIdentification,jdbcType=VARCHAR}, + values (#{serviceCode,jdbcType=VARCHAR},#{serviceName,jdbcType=VARCHAR}, #{templateIdentification,jdbcType=VARCHAR}, #{productIdentification,jdbcType=VARCHAR}, #{status,jdbcType=VARCHAR}, #{description,jdbcType=VARCHAR}, #{createBy,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{updateBy,jdbcType=VARCHAR}, #{updateTime,jdbcType=TIMESTAMP}) @@ -63,6 +65,9 @@ insert into product_services + + service_code, + service_name, @@ -92,6 +97,9 @@ + + #{serviceCode,jdbcType=VARCHAR}, + #{serviceName,jdbcType=VARCHAR}, @@ -126,6 +134,9 @@ update product_services + + service_code = #{serviceName,jdbcType=VARCHAR}, + service_name = #{serviceName,jdbcType=VARCHAR}, @@ -160,7 +171,8 @@ parameterType="com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductServices"> update product_services - set service_name = #{serviceName,jdbcType=VARCHAR}, + set service_code = #{serviceCode,jdbcType=VARCHAR}, + service_name = #{serviceName,jdbcType=VARCHAR}, template_identification = #{templateIdentification,jdbcType=VARCHAR}, product_identification = #{productIdentification,jdbcType=VARCHAR}, `status` = #{status,jdbcType=VARCHAR}, @@ -175,6 +187,11 @@ update product_services + + + when id = #{item.id,jdbcType=BIGINT} then #{item.serviceCode,jdbcType=VARCHAR} + + when id = #{item.id,jdbcType=BIGINT} then #{item.serviceName,jdbcType=VARCHAR} @@ -230,6 +247,13 @@ update product_services + + + + when id = #{item.id,jdbcType=BIGINT} then #{item.serviceCode,jdbcType=VARCHAR} + + + @@ -302,11 +326,11 @@ insert into product_services - (service_name, template_identification, product_identification, `status`, description, + (service_code,service_name, template_identification, product_identification, `status`, description, create_by, create_time, update_by, update_time) values - (#{item.serviceName,jdbcType=VARCHAR}, #{item.templateIdentification,jdbcType=VARCHAR}, + (#{item.serviceName,jdbcType=VARCHAR},#{item.serviceCode,jdbcType=VARCHAR}, #{item.templateIdentification,jdbcType=VARCHAR}, #{item.productIdentification,jdbcType=VARCHAR}, #{item.status,jdbcType=VARCHAR}, #{item.description,jdbcType=VARCHAR}, #{item.createBy,jdbcType=VARCHAR}, #{item.createTime,jdbcType=TIMESTAMP}, @@ -322,6 +346,7 @@ id, + service_code, service_name, template_identification, product_identification, @@ -337,6 +362,7 @@ #{id,jdbcType=BIGINT}, + #{serviceCode,jdbcType=VARCHAR}, #{serviceName,jdbcType=VARCHAR}, #{templateIdentification,jdbcType=VARCHAR}, #{productIdentification,jdbcType=VARCHAR}, @@ -352,6 +378,7 @@ id = #{id,jdbcType=BIGINT}, + service_code = #{serviceCode,jdbcType=VARCHAR}, service_name = #{serviceName,jdbcType=VARCHAR}, template_identification = #{templateIdentification,jdbcType=VARCHAR}, product_identification = #{productIdentification,jdbcType=VARCHAR}, @@ -372,6 +399,9 @@ id, + + service_code, + service_name, @@ -405,6 +435,9 @@ #{id,jdbcType=BIGINT}, + + #{serviceCode,jdbcType=VARCHAR}, + #{serviceName,jdbcType=VARCHAR}, @@ -438,6 +471,9 @@ id = #{id,jdbcType=BIGINT}, + + service_code = #{serviceCode,jdbcType=VARCHAR}, + service_name = #{serviceName,jdbcType=VARCHAR}, @@ -500,7 +536,7 @@ - select from product_services @@ -508,8 +544,8 @@ and product_identification = #{productIdentification,jdbcType=VARCHAR} - - and service_name = #{serviceName,jdbcType=VARCHAR} + + and service_code = #{serviceCode,jdbcType=VARCHAR} and `status` = #{status,jdbcType=VARCHAR} @@ -520,6 +556,7 @@ select id, + service_code, service_name, product_identification, template_identification, @@ -537,6 +574,9 @@ resultMap="BaseResultMap"> + + and service_code like concat('%', #{serviceCode}, '%') + and service_name like concat('%', #{serviceName}, '%') @@ -565,6 +605,9 @@ useGeneratedKeys="true"> insert into product_services + + service_code, + service_name, @@ -594,6 +637,9 @@ + + #{serviceCode}, + #{serviceName}, @@ -628,6 +674,9 @@ parameterType="com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductServices"> update product_services + + service_code = #{serviceCode}, + service_name = #{serviceName}, diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/constant/TdsConstants.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/constant/TdsConstants.java new file mode 100644 index 00000000..03faed1b --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/constant/TdsConstants.java @@ -0,0 +1,34 @@ +package com.mqttsnet.thinglinks.tdengine.common.constant; + +/** + * 全局基础常量 + * + * @author mqttsnet + * @version v1.0 + * @date 2022/4/12 11:05 PM + * @create [2022/4/12 11:05 PM ] [mqttsnet] [初始创建] + */ +public interface TdsConstants { + + String DATA_BASE = "thinglinks"; + + /** + * 时序数据库主键ID + */ + String TS = "ts"; + + /** + * 时序数据库标签 + */ + String TAG = "TAG"; + + /** + * 事件上报时间 + */ + String EVENT_TIME = "event_time"; + + /** + * TAG ——》设备标签名 + */ + String DEVICE_IDENTIFICATION = "device_identification"; +} diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/controller/TdEngineController.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/controller/TdEngineController.java index 849a5a3f..729b43ea 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/controller/TdEngineController.java +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/controller/TdEngineController.java @@ -1,20 +1,25 @@ package com.mqttsnet.thinglinks.tdengine.controller; +import cn.hutool.core.util.StrUtil; +import cn.hutool.json.JSONObject; import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.common.core.enums.DataTypeEnum; import com.mqttsnet.thinglinks.common.core.utils.StringUtils; import com.mqttsnet.thinglinks.tdengine.api.domain.*; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.SuperTableDTO; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; import com.mqttsnet.thinglinks.tdengine.api.domain.visual.SelectVisualDto; +import com.mqttsnet.thinglinks.tdengine.common.constant.TdsConstants; import com.mqttsnet.thinglinks.tdengine.service.TdEngineService; +import com.mqttsnet.thinglinks.tdengine.utils.TdsUtils; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.UncategorizedSQLException; import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; @@ -50,11 +55,12 @@ public R createDataBase(@RequestBody() String dataBaseName) { this.tdEngineService.createDateBase(dataBaseName); log.info("successful operation: created database '" + dataBaseName + "' success"); return R.ok(); - }catch (UncategorizedSQLException e) { + } catch (UncategorizedSQLException e) { String message = e.getCause().getMessage(); try { message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) {} + } catch (Exception ex) { + } log.error(message); return R.fail(message); } catch (Exception e) { @@ -100,7 +106,8 @@ public R createSuperTable(@Validated @RequestBody SuperTableDto superTableDto String message = e.getCause().getMessage(); try { message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) {} + } catch (Exception ex) { + } log.error(message); return R.fail(message); } catch (Exception e) { @@ -111,6 +118,7 @@ public R createSuperTable(@Validated @RequestBody SuperTableDto superTableDto /** * 添加列字段 + * * @param superTableDto * @return */ @@ -136,7 +144,8 @@ public R addColumnForSuperTable(@RequestBody SuperTableDto superTableDto) { String message = e.getCause().getMessage(); try { message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) {} + } catch (Exception ex) { + } log.error(message); return R.fail(message); } catch (Exception e) { @@ -147,6 +156,7 @@ public R addColumnForSuperTable(@RequestBody SuperTableDto superTableDto) { /** * 删除列字段 + * * @param superTableDto * @return */ @@ -172,7 +182,8 @@ public R dropColumnForSuperTable(@RequestBody SuperTableDto superTableDto) { String message = e.getCause().getMessage(); try { message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) {} + } catch (Exception ex) { + } log.error(message); return R.fail(message); } catch (Exception e) { @@ -182,19 +193,19 @@ public R dropColumnForSuperTable(@RequestBody SuperTableDto superTableDto) { } /** - *@MethodDescription 创建超级表的子表 - *@param tableDto 创建超级表的子表需要的入参的实体类 - *@return R - *@author thinglinks - *@Date 2021/12/30 14:15 - */ + * @param tableDto 创建超级表的子表需要的入参的实体类 + * @return R + * @MethodDescription 创建超级表的子表 + * @author thinglinks + * @Date 2021/12/30 14:15 + */ @PostMapping("/createTb") public R createTable(@Validated @RequestBody TableDto tableDto) { try { this.tdEngineService.createTable(tableDto); log.info("successful operation: create table success"); return R.ok("successful operation: create table success"); - } catch (Exception e) { + } catch (Exception e) { String message = e.getCause().getMessage(); try { message = message.substring(message.lastIndexOf("invalid operation")); @@ -207,12 +218,12 @@ public R createTable(@Validated @RequestBody TableDto tableDto) { } /** - *@MethodDescription 插入数据 - *@param tableDto 插入数据需要的入参的实体类 - *@return R - *@author thinglinks - *@Date 2022/1/10 14:43 - */ + * @param tableDto 插入数据需要的入参的实体类 + * @return R + * @MethodDescription 插入数据 + * @author thinglinks + * @Date 2022/1/10 14:43 + */ @PostMapping("/insertData") public R insertData(@Validated @RequestBody TableDto tableDto) { try { @@ -230,7 +241,8 @@ public R insertData(@Validated @RequestBody TableDto tableDto) { String message = e.getCause().getMessage(); try { message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) {} + } catch (Exception ex) { + } log.error(message); return R.fail(message); } catch (Exception e) { @@ -240,21 +252,22 @@ public R insertData(@Validated @RequestBody TableDto tableDto) { } /** - *@MethodDescription 根据时间戳查询数据 - *@param selectDto 查询数据需要的入参的实体类 - *@return R - *@author thinglinks - *@Date 2022/1/10 14:44 - */ + * @param selectDto 查询数据需要的入参的实体类 + * @return R + * @MethodDescription 根据时间戳查询数据 + * @author thinglinks + * @Date 2022/1/10 14:44 + */ @PostMapping("/getDataByTimestamp") public R getDataByTimestamp(@Validated @RequestBody SelectDto selectDto) { try { return R.ok(this.tdEngineService.selectByTimesTamp(selectDto)); - }catch (UncategorizedSQLException e) { + } catch (UncategorizedSQLException e) { String message = e.getCause().getMessage(); try { message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) {} + } catch (Exception ex) { + } log.error(message); return R.fail(message); } catch (Exception e) { @@ -267,11 +280,12 @@ public R getDataByTimestamp(@Validated @RequestBody SelectDto selectDto) { public R getCountByTimestamp(@Validated @RequestBody SelectDto selectDto) { try { return R.ok(this.tdEngineService.getCountByTimesTamp(selectDto)); - }catch (UncategorizedSQLException e) { + } catch (UncategorizedSQLException e) { String message = e.getCause().getMessage(); try { message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) {} + } catch (Exception ex) { + } log.error(message); return R.fail(message); } catch (Exception e) { @@ -282,19 +296,20 @@ public R getCountByTimestamp(@Validated @RequestBody SelectDto selectDto) { /** - * @MethodDescription 查询最新数据 * @param selectDto * @return R + * @MethodDescription 查询最新数据 */ @PostMapping("/getLastData") public R getLastData(@Validated @RequestBody SelectDto selectDto) { try { return R.ok(this.tdEngineService.getLastData(selectDto)); - }catch (UncategorizedSQLException e) { + } catch (UncategorizedSQLException e) { String message = e.getCause().getMessage(); try { message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) {} + } catch (Exception ex) { + } log.error(message); return R.fail(message); } catch (Exception e) { @@ -318,9 +333,9 @@ public R getVisualizeData(@Validated @RequestBody SelectVisualDto selectVisua try { if (selectVisualDto.getType() == 0) {//查询历史 return R.ok(this.tdEngineService.getHistoryData(selectVisualDto)); - }else if(selectVisualDto.getType() == 1) {//查询实时 + } else if (selectVisualDto.getType() == 1) {//查询实时 return R.ok(this.tdEngineService.getRealtimeData(selectVisualDto)); - }else {//查询聚合 + } else {//查询聚合 return R.ok(this.tdEngineService.getAggregateData(selectVisualDto)); } } catch (UncategorizedSQLException e) { @@ -336,20 +351,22 @@ public R getVisualizeData(@Validated @RequestBody SelectVisualDto selectVisua return R.fail(e.getMessage()); } } + /** - * @MethodDescription 根据超级表查询包含Tags的最新数据集合 * @param tagsSelectDao * @return R + * @MethodDescription 根据超级表查询包含Tags的最新数据集合 */ @PostMapping("/getLastDataByTags") public R>> getLastDataByTags(@Validated @RequestBody TagsSelectDao tagsSelectDao) { try { return R.ok(this.tdEngineService.getLastDataByTags(tagsSelectDao)); - }catch (UncategorizedSQLException e) { + } catch (UncategorizedSQLException e) { String message = e.getCause().getMessage(); try { message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) {} + } catch (Exception ex) { + } log.error(message); return R.fail(message); } catch (Exception e) { @@ -357,4 +374,306 @@ public R>> getLastDataByTags(@Validated @Request return R.fail(e.getMessage()); } } + + + /** + * 创建超级表 + * + * @param superTableName 超级表名称 + * @return 执行结果 + */ + @ApiOperation(value = "创建超级表", notes = "创建超级表") + @PostMapping("/createSuperTable") + public R createSuperTable(@RequestParam String superTableName) { + try { + tdEngineService.createSuperTable(TdsConstants.DATA_BASE, superTableName); + } catch (Exception e) { + log.error("创建超级表失败{}", e.getMessage()); + return R.fail(e.getMessage()); + } + return R.ok(); + } + + /** + * 创建超级表及字段 + * + * @param superTableDTO 超级表信息 + * @return 执行结果 + */ + @ApiOperation(value = "创建超级表及字段", notes = "创建超级表及字段") + @PostMapping("/createSuperTableAndColumn") + public R createSuperTableAndColumn(@RequestBody SuperTableDTO superTableDTO) { + if (StrUtil.isBlank(superTableDTO.getDataBaseName())) { + superTableDTO.setDataBaseName(TdsConstants.DATA_BASE); + } + try { + tdEngineService.createSuperTableAndColumn(superTableDTO); + } catch (Exception e) { + log.error("创建超级表及字段失败{}", e.getMessage()); + return R.fail(e.getMessage()); + } + return R.ok(); + } + + /** + * 创建超级表及字段-方式二 + * + * @param object 超级表json信息 + * @return 执行结果 + */ + @ApiOperation(value = "创建超级表及字段-方式二", notes = "创建超级表及字段-方式二") + @PostMapping("/createSuperTableAndColumnTwo") + public R createSuperTableAndColumnOne(@RequestBody JSONObject object) { + try { + Map superTableDTOMap = TdsUtils.handleSuperTable(object); + for (Map.Entry entry : superTableDTOMap.entrySet()) { + SuperTableDTO value = entry.getValue(); + value.setDataBaseName(TdsConstants.DATA_BASE); + // 进行相应的操作 + tdEngineService.createSuperTableAndColumn(value); + } + } catch (Exception e) { + log.error("创建超级表及字段失败{}", e.getMessage()); + return R.fail(e.getMessage()); + } + return R.ok(); + } + + /** + * 创建子表 + * + * @param tableDTO 子表信息 + * @return 执行结果 + */ + @ApiOperation(value = "创建子表", notes = "创建子表") + @PostMapping("/createSubTable") + public R createSubTable(@RequestBody TableDTO tableDTO) { + try { + if (StrUtil.isBlank(tableDTO.getDataBaseName())) { + tableDTO.setDataBaseName(TdsConstants.DATA_BASE); + } + tdEngineService.createSubTable(tableDTO); + } catch (Exception e) { + log.error("创建子表失败{}", e.getMessage()); + return R.fail(e.getMessage()); + } + return R.ok(); + } + + /** + * 创建子表-方式二 + * + * @param object 子表json信息 + * @return 执行结果 + */ + @ApiOperation(value = "创建子表-方式二", notes = "创建子表-方式二") + @PostMapping("/createSubTableTwo") + public R createSubTableTwo(@RequestBody JSONObject object) { + try { + Map subTableMap = TdsUtils.handleSubTable(object); + for (Map.Entry entry : subTableMap.entrySet()) { + TableDTO value = entry.getValue(); + value.setDataBaseName(TdsConstants.DATA_BASE); + // 进行相应的操作 + tdEngineService.createSubTable(value); + } + } catch (Exception e) { + log.error("创建子表失败{}", e.getMessage()); + return R.fail(e.getMessage()); + } + return R.ok(); + } + + /** + * 删除超级表 + * + * @param superTableName + * @return + */ + @ApiOperation(value = "删除超级表", notes = "删除超级表") + @PostMapping("/dropSuperTable") + public R dropSuperTable(@RequestParam String superTableName) { + try { + tdEngineService.dropSuperTable(TdsConstants.DATA_BASE, superTableName); + } catch (Exception e) { + log.error("删除超级表失败{}", e.getMessage()); + return R.fail(e.getMessage()); + } + return R.ok(); + } + + /** + * 超级表新增字段 + * + * @param superTableDTO 数据信息 + * @return 执行结果 + */ + @ApiOperation(value = "超级表新增字段", notes = "超级表新增字段") + @PostMapping("/alterSuperTableColumn") + public R alterSuperTableColumn(@RequestBody SuperTableDTO superTableDTO) { + try { + if (StrUtil.isBlank(superTableDTO.getDataBaseName())) { + superTableDTO.setDataBaseName(TdsConstants.DATA_BASE); + } + tdEngineService.alterSuperTableColumn(superTableDTO.getDataBaseName(), superTableDTO.getSuperTableName(), superTableDTO.getFields()); + } catch (Exception e) { + log.error("超级表新增字段失败{}", e.getMessage()); + return R.fail(e.getMessage()); + } + return R.ok(); + } + + /** + * 超级表删除字段 + * + * @param superTableDTO 数据信息 + * @return 执行结果 + */ + @ApiOperation(value = "超级表删除字段", notes = "超级表删除字段") + @PostMapping("/dropSuperTableColumn") + public R dropSuperTableColumn(@RequestBody SuperTableDTO superTableDTO) { + try { + if (StrUtil.isBlank(superTableDTO.getDataBaseName())) { + superTableDTO.setDataBaseName(TdsConstants.DATA_BASE); + } + tdEngineService.dropSuperTableColumn(superTableDTO.getDataBaseName(), superTableDTO.getSuperTableName(), superTableDTO.getFields()); + } catch (Exception e) { + log.error("超级表删除字段失败{}", e.getMessage()); + return R.fail(e.getMessage()); + } + return R.ok(); + } + + /** + * 新增标签 + * + * @param superTableDTO 数据信息 + * @return 执行结果 + */ + @ApiOperation(value = "新增标签", notes = "新增标签") + @PostMapping("/alterSuperTableTag") + public R alterSuperTableTag(@RequestBody SuperTableDTO superTableDTO) { + try { + if (StrUtil.isBlank(superTableDTO.getDataBaseName())) { + superTableDTO.setDataBaseName(TdsConstants.DATA_BASE); + } + tdEngineService.alterSuperTableTag(superTableDTO.getDataBaseName(), superTableDTO.getSuperTableName(), superTableDTO.getFields()); + } catch (Exception e) { + log.error("新增标签失败{}", e.getMessage()); + return R.fail(e.getMessage()); + } + return R.ok(); + } + + /** + * 删除标签 + * + * @param superTableDTO 数据信息 + * @return 执行结果 + */ + @ApiOperation(value = "删除标签", notes = "删除标签") + @PostMapping("/dropSuperTableTag") + public R dropSuperTableTag(@RequestBody SuperTableDTO superTableDTO) { + try { + if (StrUtil.isBlank(superTableDTO.getDataBaseName())) { + superTableDTO.setDataBaseName(TdsConstants.DATA_BASE); + } + tdEngineService.dropSuperTableTag(superTableDTO.getDataBaseName(), superTableDTO.getSuperTableName(), superTableDTO.getFields()); + } catch (Exception e) { + log.error("删除标签失败{}", e.getMessage()); + return R.fail(e.getMessage()); + } + return R.ok(); + } + + /** + * 修改标签名称 + * + * @param superTableName + * @param oldName + * @param newName + * @return + */ + @ApiOperation(value = "修改标签名称", notes = "修改标签名称") + @PostMapping("/alterSuperTableTagRename") + public R alterSuperTableTagRename(@RequestParam String superTableName, @RequestParam String oldName, @RequestParam String newName) { + try { + tdEngineService.alterSuperTableTagRename(TdsConstants.DATA_BASE, superTableName, oldName, newName); + } catch (Exception e) { + log.error("修改标签名称失败{}", e.getMessage()); + return R.fail(e.getMessage()); + } + return R.ok(); + } + + + /** + * 查询超级表、子表结构 + * + * @param tableName + * @return + */ + @ApiOperation(value = "查询超级表、子表结构", notes = "查询超级表、子表结构") + @GetMapping("/describeSuperOrSubTable") + public R> describeSuperOrSubTable(@RequestParam(value = "tableName") String tableName) { + try { + if (StrUtil.isBlank(tableName)) { + return R.fail("表名不能为空"); + } + List superTableDescribeVOS = tdEngineService.describeSuperOrSubTable(TdsConstants.DATA_BASE, tableName); + return R.ok(superTableDescribeVOS); + } catch (Exception e) { + log.error("查询超级表、子表结构失败{}", e.getMessage()); + return R.fail(e.getMessage()); + } + } + + /** + * 新增数据 + * + * @param tableDTO 数据信息 + * @return 执行结果 + */ + @ApiOperation(value = "新增数据", notes = "新增数据") + @PostMapping("/insertTableData") + public R insertTableData(@RequestBody TableDTO tableDTO) { + try { + if (StrUtil.isBlank(tableDTO.getDataBaseName())) { + tableDTO.setDataBaseName(TdsConstants.DATA_BASE); + } + tdEngineService.insertTableData(tableDTO); + } catch (Exception e) { + log.error("新增数据失败{}", e.getMessage()); + return R.fail(e.getMessage()); + } + return R.ok(); + } + + /** + * Retrieves the latest data from a regular table. It fetches the most recent record + * within the specified time range or the last recorded data if the time range is not specified. + * + * @param tableName The name of the table. + * @param startTime The start time for the query range (optional). + * @param endTime The end time for the query range (optional). + * @return {@link R>>} The query result. + */ + @ApiOperation(value = "Query Data from a Regular Table Within a Time Range", notes = "Fetches data within the specified time range if both start and end times are provided; otherwise, retrieves the latest record.") + @GetMapping("/getDataInRangeOrLastRecord") + public R>> getDataInRangeOrLastRecord( + @ApiParam(value = "Name of the regular table", required = true) @RequestParam(value = "tableName") String tableName, + @ApiParam(value = "Start time for the query", example = "1634572800000", required = false) @RequestParam(value = "startTime", required = false) Long startTime, + @ApiParam(value = "End time for the query", example = "1634659200000", required = false) @RequestParam(value = "endTime", required = false) Long endTime) { + try { + if (StrUtil.isBlank(tableName)) { + return R.fail("Table name cannot be empty"); + } + List> dataInRangeOrLastRecord = tdEngineService.getDataInRangeOrLastRecord(TdsConstants.DATA_BASE, tableName, startTime, endTime); + return R.ok(dataInRangeOrLastRecord); + } catch (Exception e) { + log.error("Failed to query the latest record from the table", e); + return R.fail("Query failed: " + e.getMessage()); + } + } + } diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/mapper/TdEngineMapper.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/mapper/TdEngineMapper.java index 0d3a9e1a..0da599c3 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/mapper/TdEngineMapper.java +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/mapper/TdEngineMapper.java @@ -1,9 +1,9 @@ package com.mqttsnet.thinglinks.tdengine.mapper; -import com.mqttsnet.thinglinks.tdengine.api.domain.FieldsVo; -import com.mqttsnet.thinglinks.tdengine.api.domain.SelectDto; -import com.mqttsnet.thinglinks.tdengine.api.domain.TableDto; -import com.mqttsnet.thinglinks.tdengine.api.domain.TagsSelectDao; +import com.mqttsnet.thinglinks.tdengine.api.domain.*; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.SuperTableDTO; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TagsSelectDTO; import com.mqttsnet.thinglinks.tdengine.api.domain.visual.SelectVisualDto; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @@ -65,4 +65,123 @@ void dropTagForSuperTable(@Param("superTableName") String superTableName, List> getAggregateData(SelectVisualDto selectVisualDto); List> getLastDataByTags(TagsSelectDao tagsSelectDao); + + + /** + * 创建超级表 + * + * @param dataBaseName + * @param superTableName + */ + void createSuperTable(@Param("dataBaseName") String dataBaseName, @Param("superTableName") String superTableName); + + /** + * 创建超级表及字段 + * + * @param superTableDTO + */ + void createSuperTableAndColumn(SuperTableDTO superTableDTO); + + + /** + * 创建子表 + * + * @param tableDTO + */ + void createSubTable(TableDTO tableDTO); + + /** + * 删除超级表 + * + * @param dataBaseName + * @param superTableName + */ + void dropSuperTable(@Param("dataBaseName") String dataBaseName, @Param("superTableName") String superTableName); + + /** + * 新增字段 + * + * @param dataBaseName + * @param superTableName + * @param fields + */ + void alterSuperTableColumn(@Param("dataBaseName") String dataBaseName, @Param("superTableName") String superTableName, @Param("fields") Fields fields); + + /** + * 删除字段 + * + * @param dataBaseName + * @param superTableName + * @param fields + */ + void dropSuperTableColumn(@Param("dataBaseName") String dataBaseName, @Param("superTableName") String superTableName, @Param("fields") Fields fields); + + /** + * 查询表结构 + * + * @param dataBaseName + * @param tableName + */ + List describeSuperOrSubTable(@Param("dataBaseName") String dataBaseName, @Param("tableName") String tableName); + + /** + * 添加标签 + * + * @param dataBaseName + * @param superTableName + * @param fields + */ + void alterSuperTableTag(@Param("dataBaseName") String dataBaseName, @Param("superTableName") String superTableName, @Param("fields") Fields fields); + + /** + * 删除标签 + * + * @param dataBaseName + * @param superTableName + * @param fields + */ + void dropSuperTableTag(@Param("dataBaseName") String dataBaseName, @Param("superTableName") String superTableName, @Param("fields") Fields fields); + + /** + * 修改标签名 + * + * @param dataBaseName + * @param superTableName + * @param oldName + * @param newName + */ + void alterSuperTableTagRename(@Param("dataBaseName") String dataBaseName, @Param("superTableName") String superTableName, @Param("oldName") String oldName, + @Param("newName") String newName); + + /** + * 新增数据 + * + * @param tableDTO + */ + void insertTableData(TableDTO tableDTO); + + /** + * 查询最新数据 + * + * @param tagsSelectDTO + * @return + */ + List> getLastDataByTags(TagsSelectDTO tagsSelectDTO); + + /** + * Retrieves the latest data from the specified table within the given database. + * If both startTime and endTime are provided, it fetches records within that time range. + * Otherwise, it retrieves the last recorded data. + * + * @param dataBaseName The name of the database. + * @param tableName The name of the table. + * @param startTime The start time for the query range (can be null). + * @param endTime The end time for the query range (can be null). + * @return A {@link List>} containing the latest data. + */ + List> getDataInRangeOrLastRecord( + @Param("dataBaseName") String dataBaseName, + @Param("tableName") String tableName, + @Param("startTime") Long startTime, + @Param("endTime") Long endTime); } diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/TdEngineService.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/TdEngineService.java index 45f0ba58..67c79287 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/TdEngineService.java +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/TdEngineService.java @@ -1,11 +1,12 @@ package com.mqttsnet.thinglinks.tdengine.service; -import com.mqttsnet.thinglinks.tdengine.api.domain.FieldsVo; -import com.mqttsnet.thinglinks.tdengine.api.domain.SelectDto; -import com.mqttsnet.thinglinks.tdengine.api.domain.TableDto; -import com.mqttsnet.thinglinks.tdengine.api.domain.TagsSelectDao; +import com.mqttsnet.thinglinks.tdengine.api.domain.*; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.SuperTableDTO; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TagsSelectDTO; import com.mqttsnet.thinglinks.tdengine.api.domain.visual.SelectVisualDto; +import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; @@ -39,10 +40,152 @@ public interface TdEngineService { List> getLastData(SelectDto selectDto) throws Exception; Map> getLastDataByTags(TagsSelectDao tagsSelectDao); - + List> getHistoryData(SelectVisualDto selectVisualDto); List> getRealtimeData(SelectVisualDto selectVisualDto); List> getAggregateData(SelectVisualDto selectVisualDto); + + /** + * 创建超级表 + * + * @param dataBaseName + * @param superTableName + */ + default void createSuperTable(@Param("dataBaseName") String dataBaseName, @Param("superTableName") String superTableName) { + + } + + /** + * 创建超级表及字段 + * + * @param superTableDTO + */ + default void createSuperTableAndColumn(SuperTableDTO superTableDTO) { + + } + + /** + * 创建子表 + * + * @param tableDTO + */ + default void createSubTable(TableDTO tableDTO) { + + } + + /** + * 删除超级表 + * + * @param dataBaseName + * @param superTableName + */ + default void dropSuperTable(@Param("dataBaseName") String dataBaseName, @Param("superTableName") String superTableName) { + + } + + /** + * 新增字段 + * + * @param superTableName + * @param fields + */ + default void alterSuperTableColumn(@Param("dataBaseName") String dataBaseName, @Param("superTableName") String superTableName, + @Param("fields") Fields fields) { + + } + + /** + * 删除字段 + * + * @param dataBaseName + * @param superTableName + * @param fields + */ + default void dropSuperTableColumn(@Param("dataBaseName") String dataBaseName, @Param("superTableName") String superTableName, + @Param("fields") Fields fields) { + + } + + /** + * 查询表结构 + * + * @param dataBaseName + * @param tableName + */ + default List describeSuperOrSubTable(@Param("dataBaseName") String dataBaseName, @Param("tableName") String tableName) { + + return null; + } + + /** + * 添加标签 + * + * @param dataBaseName + * @param superTableName + * @param fields + */ + default void alterSuperTableTag(@Param("dataBaseName") String dataBaseName, @Param("superTableName") String superTableName, + @Param("fields") Fields fields) { + + } + + /** + * 删除标签 + * + * @param dataBaseName + * @param superTableName + * @param fields + */ + default void dropSuperTableTag(@Param("dataBaseName") String dataBaseName, @Param("superTableName") String superTableName, @Param("fields") Fields fields) { + + } + + /** + * 修改标签名 + * + * @param dataBaseName + * @param superTableName + * @param oldName + * @param newName + */ + default void alterSuperTableTagRename(@Param("dataBaseName") String dataBaseName, @Param("superTableName") String superTableName, + @Param("oldName") String oldName, @Param("newName") String newName) { + + } + + /** + * 新增数据 + * + * @param tableDTO + */ + default void insertTableData(TableDTO tableDTO) { + + } + + /** + * 查询最新数据 + * + * @param tagsSelectDTO + * @return + */ + default Map> getLastDataByTags(TagsSelectDTO tagsSelectDTO) { + return null; + } + + /** + * Retrieves the latest data from the specified table within the given database. + * If both startTime and endTime are provided, it fetches records within that time range. + * Otherwise, it retrieves the last recorded data. + * + * @param dataBaseName The name of the database. + * @param tableName The name of the table. + * @param startTime The start time for the query range (can be null). + * @param endTime The end time for the query range (can be null). + * @return A {@link List>} containing the latest data. + */ + default List> getDataInRangeOrLastRecord(String dataBaseName, String tableName, Long startTime, Long endTime) { + return null; + } } diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/impl/TdEngineServiceImpl.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/impl/TdEngineServiceImpl.java index c99d0853..896f485b 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/impl/TdEngineServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/impl/TdEngineServiceImpl.java @@ -1,9 +1,13 @@ package com.mqttsnet.thinglinks.tdengine.service.impl; import com.alibaba.fastjson.JSONObject; +import com.baomidou.dynamic.datasource.annotation.DS; import com.mqttsnet.thinglinks.common.core.enums.DataTypeEnum; import com.mqttsnet.thinglinks.common.redis.service.RedisService; import com.mqttsnet.thinglinks.tdengine.api.domain.*; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.SuperTableDTO; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TagsSelectDTO; import com.mqttsnet.thinglinks.tdengine.api.domain.visual.SelectVisualDto; import com.mqttsnet.thinglinks.tdengine.mapper.TdEngineMapper; import com.mqttsnet.thinglinks.tdengine.service.TdEngineService; @@ -14,9 +18,7 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.stream.Collectors; /** @@ -190,4 +192,84 @@ public List> getAggregateData(SelectVisualDto selectVisualDt return maps; } + @Override + public void createSuperTable(String dataBaseName, String superTableName) { + tdEngineMapper.createSuperTable(dataBaseName, superTableName); + } + + @Override + public void createSuperTableAndColumn(SuperTableDTO superTableDTO) { + tdEngineMapper.createSuperTableAndColumn(superTableDTO); + } + + @Override + public void createSubTable(TableDTO tableDTO) { + tdEngineMapper.createSubTable(tableDTO); + } + + @Override + public void dropSuperTable(String dataBaseName, String superTableName) { + tdEngineMapper.dropSuperTable(dataBaseName, superTableName); + } + + @Override + public void alterSuperTableColumn(String dataBaseName, String superTableName, Fields fields) { + tdEngineMapper.alterSuperTableColumn(dataBaseName, superTableName, fields); + } + + @Override + public void dropSuperTableColumn(String dataBaseName, String superTableName, Fields fields) { + tdEngineMapper.dropSuperTableColumn(dataBaseName, superTableName, fields); + } + + @Override + public List describeSuperOrSubTable(String dataBaseName, String tableName) { + List superTableDescribeVOS = new ArrayList<>(); + try { + superTableDescribeVOS = tdEngineMapper.describeSuperOrSubTable(dataBaseName, tableName); + } catch (Exception e) { + log.warn("describeSuperTable error:{}", e.getMessage()); + } + return superTableDescribeVOS; + } + + @Override + public void alterSuperTableTag(String dataBaseName, String superTableName, Fields fields) { + tdEngineMapper.alterSuperTableTag(dataBaseName, superTableName, fields); + } + + @Override + public void dropSuperTableTag(String dataBaseName, String superTableName, Fields fields) { + tdEngineMapper.dropSuperTableTag(dataBaseName, superTableName, fields); + } + + @Override + public void alterSuperTableTagRename(String dataBaseName, String superTableName, String oldName, String newName) { + tdEngineMapper.alterSuperTableTagRename(dataBaseName, superTableName, oldName, newName); + } + + @Override + public void insertTableData(TableDTO tableDTO) { + tdEngineMapper.insertTableData(tableDTO); + } + + @Override + public Map> getLastDataByTags(TagsSelectDTO tagsSelectDTO) { + List> maps = tdEngineMapper.getLastDataByTags(tagsSelectDTO); + Map> objectHashMap = new HashMap<>(); + + for (Map map : maps) { + Optional.ofNullable(map.get(tagsSelectDTO.getTagsName())) + .map(Object::toString) + .ifPresent(key -> objectHashMap.put(key, map)); + } + return objectHashMap; + } + + + @Override + public List> getDataInRangeOrLastRecord(String dataBaseName, String tableName, Long startTime, Long endTime) { + return tdEngineMapper.getDataInRangeOrLastRecord(dataBaseName, tableName, startTime, endTime); + } + } diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/util/TaosAspect.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/utils/TaosAspect.java similarity index 96% rename from thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/util/TaosAspect.java rename to thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/utils/TaosAspect.java index 88ff5073..0767abc9 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/util/TaosAspect.java +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/utils/TaosAspect.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.tdengine.util; +package com.mqttsnet.thinglinks.tdengine.utils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/utils/TdsUtils.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/utils/TdsUtils.java new file mode 100644 index 00000000..c47f7fae --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/utils/TdsUtils.java @@ -0,0 +1,219 @@ +package com.mqttsnet.thinglinks.tdengine.utils; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.json.JSONObject; +import cn.hutool.json.JSONUtil; +import com.mqttsnet.thinglinks.common.core.constant.Constants; +import com.mqttsnet.thinglinks.common.core.enums.DataTypeEnum; +import com.mqttsnet.thinglinks.common.core.exception.base.BaseException; +import com.mqttsnet.thinglinks.tdengine.api.domain.Fields; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.FieldsVO; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.SuperTableDTO; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; +import lombok.extern.slf4j.Slf4j; + +import java.util.*; + +/** + * 处理超级表和子表 + */ +@Slf4j +public class TdsUtils { + + // 创建一个静态集合 + private static List defaultList; + private static List defaultTagList; + // 排除类型 + private static List excludeTypeList; + + // 静态代码块,在类加载时只执行一次 + static { + // 预置必备字段 + defaultList = new ArrayList<>(); + defaultTagList = new ArrayList<>(); + excludeTypeList = new ArrayList<>(); + excludeTypeList.addAll(Arrays.asList("TINYINT", "SMALLINT", "INT", "BIGINT")); + defaultList.add(new FieldsVO("ts", DataTypeEnum.TIMESTAMP.getDataType())); + defaultList.add(new FieldsVO("event_time", DataTypeEnum.TIMESTAMP.getDataType())); + defaultTagList.add(new FieldsVO("device_identificaiton", DataTypeEnum.BINARY.getDataType(), 64)); + } + + + /** + * 处理超级表 + * + * @param obj + * @return + */ + public static Map handleSuperTable(JSONObject obj) { + Map superTableDtoHashMap = new HashMap<>(); + if (Objects.isNull(obj)) { + return superTableDtoHashMap; + } + // 产品标识 + String productIdentification = Optional.ofNullable(obj.getStr("productIdentification")) + .orElseThrow(() -> new BaseException("productIdentification cannot be null")); + + // 产品类型 + String productType = Optional.ofNullable(obj.getStr("productType")).orElseThrow(() -> new BaseException("productType cannot be null")); + + // 获取服务 + List serviceList = Optional.ofNullable(obj.getBeanList("serviceList", JSONObject.class)) + .orElseThrow(() -> new BaseException("serviceList cannot be null")); + + for (int i = 0; i < serviceList.size(); i++) { + // 获取每个服务信息 + JSONObject serviceObject = Optional.ofNullable(serviceList.get(i)).orElseThrow(() -> new BaseException("serviceObject cannot be null")); + // 获取服务编码 + String serviceCode = Optional.ofNullable(serviceObject.getStr("serviceCode")).orElseThrow(() -> new BaseException("serviceCode cannot be null")); + // 超级表名称 + String superTableName = superTableName(productType, productIdentification, serviceCode); + // 获取服务属性 + List propertyList = Optional.ofNullable(serviceObject.getBeanList("propertyList", JSONObject.class)) + .orElseThrow(() -> new BaseException("propertyList cannot be null")); + // 定义字段结构 + List schemaFieldsVOList = BeanUtil.copyToList(defaultList, FieldsVO.class); + FieldsVO fieldsVo = null; + for (int j = 0; j < propertyList.size(); j++) { + JSONObject serviceData = propertyList.get(j); + fieldsVo = new FieldsVO(); + fieldsVo.setFieldName(serviceData.getStr("propertyCode")); + fieldsVo.setDataType(DataTypeEnum.valueOfByDataType(serviceData.getStr("datatype")).getDataType()); + boolean exists = excludeTypeList.stream().anyMatch(str -> str.equalsIgnoreCase(serviceData.getStr("datatype"))); + if (!exists) { + fieldsVo.setSize(serviceData.getInt("maxlength")); + } + schemaFieldsVOList.add(fieldsVo); + } + // tags + List tagsSchemaFieldsVOList = BeanUtil.copyToList(defaultTagList, FieldsVO.class); + SuperTableDTO superTableDto = new SuperTableDTO(FieldsVO.toFieldsList(schemaFieldsVOList), + FieldsVO.toFieldsList(tagsSchemaFieldsVOList), null, null, superTableName); + superTableDtoHashMap.put(superTableName, superTableDto); + } + return superTableDtoHashMap; + } + + /** + * 处理子表 + * + * @param obj + * @return + */ + public static Map handleSubTable(JSONObject obj) { + Map tableDtoMap = new HashMap<>(); + if (Objects.isNull(obj)) { + return tableDtoMap; + } + // 产品标识 + String productIdentification = Optional.ofNullable(obj.getStr("productIdentification")) + .orElseThrow(() -> new BaseException("productIdentification cannot be null")); + // 产品类型 + String productType = Optional.ofNullable(obj.getStr("productType")).orElseThrow(() -> new BaseException("productType cannot be null")); + // 设备标识集合 + List deviceList = Optional.ofNullable(obj.getBeanList("devices", String.class)).orElseThrow(() -> new BaseException("devices cannot be null")); + // 获取服务集合 + List serviceList = Optional.ofNullable(obj.getBeanList("serviceList", String.class)) + .orElseThrow(() -> new BaseException("serviceList cannot be null")); + for (int i = 0; i < serviceList.size(); i++) { + // 获取每个服务信息 + String serviceStr = serviceList.get(i); + // 超级表名称 + String superTableName = superTableName(productType, productIdentification, serviceStr); + Fields fields; + TableDTO tableDto; + for (int j = 0; j < deviceList.size(); j++) { + // 获取每个设备 + String deviceStr = deviceList.get(j); + // 子表名称 + String subTableName = subTableName(superTableName, deviceStr); + // Tag的处理 + List tagsFieldValues = new ArrayList<>(); + // 字段 + fields = new Fields(); + fields.setFieldValue(deviceStr); + tagsFieldValues.add(fields); + // 子实体 + tableDto = new TableDTO(); + tableDto.setTableName(subTableName); + tableDto.setSuperTableName(superTableName); + tableDto.setTagsFieldValues(tagsFieldValues); + tableDtoMap.put(subTableName, tableDto); + } + } + return tableDtoMap; + } + + /** + * 处理产品服务定义 + * + * @param o + * @return + */ + public static String handleProductService(Object o) { + JSONObject jsonObject = JSONUtil.parseObj(o); + String productType = jsonObject.getStr("productType"); + String productIdentification = jsonObject.getStr("productIdentification"); + String serviceCode = jsonObject.getStr("serviceCode"); + return superTableName(productType, productIdentification, serviceCode); + } + + /** + * 处理产品属性定义 + * + * @param o + * @return + */ + public static Map handleProductProperty(Object o) { + JSONObject jsonObject = JSONUtil.parseObj(o); + String productType = jsonObject.getStr("productType"); + String productIdentification = jsonObject.getStr("productIdentification"); + String serviceCode = jsonObject.getStr("serviceCode"); + Map map = new HashMap<>(5); + FieldsVO fieldsVo = new FieldsVO(); + fieldsVo.setFieldName(jsonObject.getStr("propertyCode")); + fieldsVo.setDataType(DataTypeEnum.valueOfByDataType(jsonObject.getStr("datatype")).getDataType()); + boolean exists = excludeTypeList.stream().anyMatch(str -> str.equalsIgnoreCase(jsonObject.getStr("datatype"))); + if (!exists) { + fieldsVo.setSize(jsonObject.getInt("maxlength")); + } + map.put(superTableName(productType, productIdentification, serviceCode), FieldsVO.toFields(fieldsVo)); + return map; + } + + + /** + * 拼接超级表名称 + * + * @param productType + * @param productIdentification + * @param serviceCode + * @return + */ + public static String superTableName(String productType, String productIdentification, String serviceCode) { + StringBuilder tableNameBuilder = new StringBuilder(); + tableNameBuilder.append(productType) + .append(Constants.UNDERLINE) + .append(productIdentification) + .append(Constants.UNDERLINE) + .append(serviceCode); + return tableNameBuilder.toString(); + } + + /** + * 拼接子表名称 + * + * @param superTableName + * @param deviceIdentificaiton + * @return + */ + public static String subTableName(String superTableName, String deviceIdentificaiton) { + return superTableName + "_" + deviceIdentificaiton; + } + + +} + + + + diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/mapper/TdEngineMapper.xml b/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/mapper/TdEngineMapper.xml index 21247ba4..6b2dbc7e 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/mapper/TdEngineMapper.xml +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/mapper/TdEngineMapper.xml @@ -303,4 +303,225 @@ SELECT #{aggregate}(${fieldName}) FROM #{dataBaseName}.#{tableName} WHERE ts BETWEEN #{startTime} AND #{endTime} interval(${interval}) LIMIT #{num} + + + + + create table if not exists #{dataBaseName}.#{superTableName} + + + ${item.fieldName} + + + ${item.dataType} + + + (#{item.size}) + + + + tags + + + + ${item.fieldName} + + + ${item.dataType} + + + (#{item.size}) + + + + + + + + create table if not exists #{dataBaseName}.#{tableName} + using #{dataBaseName}.#{superTableName} + tags + + + + + '${item.fieldValue}' + + + + ${item.fieldValue} + + + + ${item.fieldValue} + + + + + + + ALTER + STABLE + #{dataBaseName}.#{superTableName} + ADD + COLUMN + + ${fields.fieldName} + + + ${fields.dataType} + + + (#{fields.size}) + + + + + + ALTER + STABLE + #{dataBaseName}.#{superTableName} + ADD + TAG + + ${fields.fieldName} + + + ${fields.dataType} + + + (#{fields.size}) + + + + + + ALTER + #{dataBaseName}. + #{superTableName} + RENAME + TAG + ${oldName} + ${newName}; + + + + create table if not exists #{dataBaseName}.#{superTableName} + + + + DROP + STABLE IF EXISTS + #{dataBaseName} + . + #{superTableName} + + + + ALTER + STABLE + #{dataBaseName}.#{superTableName} + DROP + COLUMN + + ${fields.fieldName} + + + + + ALTER + STABLE + #{dataBaseName}.#{superTableName} + DROP + TAG + + ${fields.fieldName} + + + + + + + insert into #{dataBaseName}.#{tableName} + + ${item.fieldName} + + using #{dataBaseName}.#{superTableName} + tags + + + + + '${item.fieldValue}' + + + + ${item.fieldValue} + + + + ${item.fieldValue} + + + + values + + + + + '${item.fieldValue}' + + + + ${item.fieldValue} + + + + ${item.fieldValue} + + + + + + + + diff --git a/thinglinks-ui/src/views/link/product/services/index.vue b/thinglinks-ui/src/views/link/product/services/index.vue index 46fe3e78..e2d7385a 100644 --- a/thinglinks-ui/src/views/link/product/services/index.vue +++ b/thinglinks-ui/src/views/link/product/services/index.vue @@ -86,12 +86,23 @@ + + + + + + + + + + - @@ -156,11 +167,13 @@ export default { // 是否显示弹出层 openProp: false, serviceId: null, + serviceCode: null, serviceName: null, // 查询参数 queryParams: { pageNum: 1, pageSize: 10, + serviceCode: null, serviceName: null, productIdentification: null, templateIdentification: null, @@ -175,7 +188,7 @@ export default { form: {}, // 表单校验 rules: { - serviceName: [ + serviceCode: [ { required: true, message: "服务名称不能为空", trigger: "blur" }, { min: 2, max: 50, message: '服务名称长度必须介于 2 和 50 之间', trigger: 'blur' }, { @@ -184,6 +197,10 @@ export default { trigger: "blur" } ], + serviceName: [ + { required: true, message: "服务名称不能为空", trigger: "blur" }, + { min: 2, max: 50, message: '服务名称长度必须介于 2 和 50 之间', trigger: 'blur' } + ], status: [ { required: true, message: "状态不能为空", trigger: "blur" } ], @@ -252,6 +269,7 @@ export default { reset() { this.form = { id: null, + serviceCode: null, serviceName: null, productIdentification: null, templateIdentification: null, From af7d6587b3f9bf6f1eae4748c6d58d7458e7ae50 Mon Sep 17 00:00:00 2001 From: xiaonan <13733918655@163.com> Date: Sat, 23 Mar 2024 16:25:48 +0800 Subject: [PATCH 11/35] =?UTF-8?q?=E8=AE=BE=E5=A4=87=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E5=AF=86=E5=8D=8F=E8=AE=AE=EF=BC=8C=E8=BD=AF=E7=A1=AC?= =?UTF-8?q?=E4=BB=B6=E7=89=88=E6=9C=AC=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/sql/changeRecord/1.2.0.RELEASE.sql | 2 +- doc/sql/thinglinks.sql | 2 +- .../link/api/domain/device/entity/Device.java | 2 +- .../mqtt/handler/CommandResponseHandler.java | 5 +- .../mapper/link/device/DeviceMapper.xml | 384 +++++++++++++++++- 5 files changed, 387 insertions(+), 8 deletions(-) diff --git a/doc/sql/changeRecord/1.2.0.RELEASE.sql b/doc/sql/changeRecord/1.2.0.RELEASE.sql index a4015f34..1d946b3e 100644 --- a/doc/sql/changeRecord/1.2.0.RELEASE.sql +++ b/doc/sql/changeRecord/1.2.0.RELEASE.sql @@ -2,7 +2,7 @@ ALTER TABLE device ADD encrypt_key varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '加密密钥'; ALTER TABLE device ADD encrypt_vector varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '加密向量'; ALTER TABLE device ADD sign_key varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '签名密钥'; -ALTER TABLE device ADD encrypt_method tinyint(4) DEFAULT 0 NOT NULL COMMENT '协议加密方式'; +ALTER TABLE device ADD encrypt_method varchar(4) DEFAULT 0 NOT NULL COMMENT '协议加密方式'; ALTER TABLE device ADD sw_version varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '软件版本'; ALTER TABLE device ADD fw_version varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '固件版本'; ALTER TABLE device ADD device_sdk_version varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT 'v1' NOT NULL COMMENT 'sdk版本'; diff --git a/doc/sql/thinglinks.sql b/doc/sql/thinglinks.sql index c5b69824..e44a0dc7 100644 --- a/doc/sql/thinglinks.sql +++ b/doc/sql/thinglinks.sql @@ -479,7 +479,7 @@ CREATE TABLE `device` `encrypt_key` varchar(255) CHARACTER SET utf8mb4 DEFAULT '' COMMENT '加密密钥', `encrypt_vector` varchar(255) CHARACTER SET utf8mb4 DEFAULT '' COMMENT '加密向量', `sign_key` varchar(255) CHARACTER SET utf8mb4 DEFAULT '' COMMENT '签名密钥', - `encrypt_method` tinyint(4) NOT NULL DEFAULT '0' COMMENT '协议加密方式', + `encrypt_method` varchar(4) NOT NULL DEFAULT '0' COMMENT '协议加密方式', `sw_version` varchar(255) CHARACTER SET utf8mb4 DEFAULT '' COMMENT '软件版本', `fw_version` varchar(255) CHARACTER SET utf8mb4 DEFAULT '' COMMENT '固件版本', `device_sdk_version` varchar(255) CHARACTER SET utf8mb4 NOT NULL DEFAULT 'v1' COMMENT 'sdk版本', diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/Device.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/Device.java index b567a462..89994bab 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/Device.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/device/entity/Device.java @@ -179,7 +179,7 @@ public class Device extends BaseEntity implements Serializable{ */ @Excel(name = "传输协议的加密方式") @ApiModelProperty(value = "传输协议的加密方式:0-明文传输、1-SM4、2-AES ") - private Integer encryptMethod; + private String encryptMethod; /** * 软件版本 diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/CommandResponseHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/CommandResponseHandler.java index 56d3aead..8d414c63 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/CommandResponseHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/CommandResponseHandler.java @@ -5,6 +5,7 @@ import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventCommandService; +import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; @@ -26,10 +27,10 @@ @Service public class CommandResponseHandler extends AbstractMessageHandler implements TopicHandler { public CommandResponseHandler(CacheDataHelper cacheDataHelper, - RemoteDeviceService remoteDeviceService, + RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, remoteDeviceService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + super(cacheDataHelper, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } @Autowired diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/device/DeviceMapper.xml b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/device/DeviceMapper.xml index 6653eb6c..697289a1 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/device/DeviceMapper.xml +++ b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/device/DeviceMapper.xml @@ -21,6 +21,13 @@ + + + + + + + @@ -46,6 +53,13 @@ product_identification, protocol_type, device_type, + encrypt_key, + encrypt_vector, + sign_key, + encrypt_method, + sw_version, + fw_version, + device_sdk_version, create_by, create_time, update_by, @@ -73,7 +87,13 @@ device_name, connector, device_description, device_status, connect_status, is_will, device_tags, product_identification, protocol_type, - device_type, create_by, create_time, + device_type,encrypt_key, + encrypt_vector, + sign_key, + encrypt_method, + sw_version, + fw_version, + device_sdk_version, create_by, create_time, update_by, update_time, remark) values (#{clientId,jdbcType=VARCHAR}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{appId,jdbcType=VARCHAR}, #{authMode,jdbcType=VARCHAR}, #{deviceIdentification,jdbcType=VARCHAR}, @@ -81,7 +101,7 @@ #{deviceStatus,jdbcType=VARCHAR}, #{connectStatus,jdbcType=VARCHAR}, #{isWill,jdbcType=VARCHAR}, #{deviceTags,jdbcType=VARCHAR}, #{productIdentification,jdbcType=VARCHAR}, #{protocolType,jdbcType=VARCHAR}, - #{deviceType,jdbcType=VARCHAR}, #{createBy,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, + #{deviceType,jdbcType=VARCHAR},#{encryptKey,jdbcType=VARCHAR},#{encryptVector,jdbcType=VARCHAR},#{signKey,jdbcType=VARCHAR},#{encryptMethod,jdbcType=VARCHAR},#{swVersion,jdbcType=VARCHAR},#{fwVersion,jdbcType=VARCHAR},#{deviceSdkVersion,jdbcType=VARCHAR}, #{createBy,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{updateBy,jdbcType=VARCHAR}, #{updateTime,jdbcType=TIMESTAMP}, #{remark,jdbcType=VARCHAR}) device_type, + + encrypt_key, + + + encrypt_vector, + + + sign_key, + + + encrypt_method, + + + sw_version, + + + fw_version, + + + device_sdk_version, + create_by, @@ -202,6 +243,27 @@ #{deviceType,jdbcType=VARCHAR}, + + #{encryptKey,jdbcType=VARCHAR}, + + + #{encryptVector,jdbcType=VARCHAR}, + + + #{signKey,jdbcType=VARCHAR}, + + + #{encryptMethod,jdbcType=VARCHAR}, + + + #{swVersion,jdbcType=VARCHAR}, + + + #{fwVersion,jdbcType=VARCHAR}, + + + #{deviceSdkVersion,jdbcType=VARCHAR}, + #{createBy,jdbcType=VARCHAR}, @@ -272,6 +334,27 @@ device_type = #{deviceType,jdbcType=VARCHAR}, + + encrypt_key = #{encryptKey,jdbcType=VARCHAR}, + + + encrypt_vector = #{encryptVector,jdbcType=VARCHAR}, + + + sign_key = #{signKey,jdbcType=VARCHAR}, + + + encrypt_method = #{encryptMethod,jdbcType=VARCHAR}, + + + sw_version = #{swVersion,jdbcType=VARCHAR}, + + + fw_version = #{fwVersion,jdbcType=VARCHAR}, + + + device_sdk_version = #{deviceSdkVersion,jdbcType=VARCHAR}, + create_by = #{createBy,jdbcType=VARCHAR}, @@ -309,6 +392,13 @@ product_identification = #{productIdentification,jdbcType=VARCHAR}, protocol_type = #{protocolType,jdbcType=VARCHAR}, device_type = #{deviceType,jdbcType=VARCHAR}, + encrypt_key = #{encryptKey,jdbcType=VARCHAR}, + encrypt_vector = #{encryptVector,jdbcType=VARCHAR}, + sign_key = #{signKey,jdbcType=VARCHAR}, + encrypt_method = #{encryptMethod,jdbcType=VARCHAR}, + sw_version = #{swVersion,jdbcType=VARCHAR}, + fw_version = #{fwVersion,jdbcType=VARCHAR}, + device_sdk_version = #{deviceSdkVersion,jdbcType=VARCHAR}, create_by = #{createBy,jdbcType=VARCHAR}, create_time = #{createTime,jdbcType=TIMESTAMP}, update_by = #{updateBy,jdbcType=VARCHAR}, @@ -400,6 +490,41 @@ when id = #{item.id,jdbcType=BIGINT} then #{item.deviceType,jdbcType=VARCHAR} + + + when id = #{item.id,jdbcType=BIGINT} then #{item.encryptKey,jdbcType=VARCHAR} + + + + + when id = #{item.id,jdbcType=BIGINT} then #{item.encryptVector,jdbcType=VARCHAR} + + + + + when id = #{item.id,jdbcType=BIGINT} then #{item.signKey,jdbcType=VARCHAR} + + + + + when id = #{item.id,jdbcType=BIGINT} then #{item.encryptMethod,jdbcType=VARCHAR} + + + + + when id = #{item.id,jdbcType=BIGINT} then #{item.swVersion,jdbcType=VARCHAR} + + + + + when id = #{item.id,jdbcType=BIGINT} then #{item.fwVersion,jdbcType=VARCHAR} + + + + + when id = #{item.id,jdbcType=BIGINT} then #{item.deviceSdkVersion,jdbcType=VARCHAR} + + when id = #{item.id,jdbcType=BIGINT} then #{item.createBy,jdbcType=VARCHAR} @@ -547,6 +672,55 @@ + + + + when id = #{item.id,jdbcType=BIGINT} then #{item.encryptKey,jdbcType=VARCHAR} + + + + + + + when id = #{item.id,jdbcType=BIGINT} then #{item.encryptVector,jdbcType=VARCHAR} + + + + + + + when id = #{item.id,jdbcType=BIGINT} then #{item.signKey,jdbcType=VARCHAR} + + + + + + + when id = #{item.id,jdbcType=BIGINT} then #{item.encryptMethod,jdbcType=VARCHAR} + + + + + + + when id = #{item.id,jdbcType=BIGINT} then #{item.swVersion,jdbcType=VARCHAR} + + + + + + + when id = #{item.id,jdbcType=BIGINT} then #{item.fwVersion,jdbcType=VARCHAR} + + + + + + + when id = #{item.id,jdbcType=BIGINT} then #{item.deviceSdkVersion,jdbcType=VARCHAR} + + + @@ -593,7 +767,8 @@ insert into device (client_id, user_name, `password`, app_id, auth_mode, device_identification, device_name, connector, device_description, device_status, connect_status, is_will, device_tags, - product_identification, protocol_type, device_type, create_by, create_time, update_by, + product_identification, protocol_type, device_type, encryptKey, encryptVector, signKey, encryptMethod, swVersion, fwVersion, deviceSdkVersion, + create_by, create_time, update_by, update_time, remark) values @@ -606,6 +781,10 @@ #{item.isWill,jdbcType=VARCHAR}, #{item.deviceTags,jdbcType=VARCHAR}, #{item.productIdentification,jdbcType=VARCHAR}, #{item.protocolType,jdbcType=VARCHAR}, #{item.deviceType,jdbcType=VARCHAR}, + #{item.encryptKey,jdbcType=VARCHAR}, #{item.encryptVector,jdbcType=VARCHAR}, + #{item.signKey,jdbcType=VARCHAR}, #{item.encryptMethod,jdbcType=VARCHAR}, + #{item.swVersion,jdbcType=VARCHAR}, #{item.fwVersion,jdbcType=VARCHAR}, + #{item.deviceSdkVersion,jdbcType=VARCHAR}, #{item.createBy,jdbcType=VARCHAR}, #{item.createTime,jdbcType=TIMESTAMP}, #{item.updateBy,jdbcType=VARCHAR}, #{item.updateTime,jdbcType=TIMESTAMP}, @@ -636,6 +815,13 @@ product_identification, protocol_type, device_type, + encrypt_key, + encrypt_vector, + sign_key, + encrypt_method, + sw_version, + fw_version, + device_sdk_version, create_by, create_time, update_by, @@ -663,6 +849,13 @@ #{productIdentification,jdbcType=VARCHAR}, #{protocolType,jdbcType=VARCHAR}, #{deviceType,jdbcType=VARCHAR}, + #{encryptKey,jdbcType=VARCHAR}, + #{encryptVector,jdbcType=VARCHAR}, + #{signKey,jdbcType=VARCHAR}, + #{encryptMethod,jdbcType=VARCHAR}, + #{swVersion,jdbcType=VARCHAR}, + #{fwVersion,jdbcType=VARCHAR}, + #{deviceSdkVersion,jdbcType=VARCHAR}, #{createBy,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{updateBy,jdbcType=VARCHAR}, @@ -690,6 +883,13 @@ product_identification = #{productIdentification,jdbcType=VARCHAR}, protocol_type = #{protocolType,jdbcType=VARCHAR}, device_type = #{deviceType,jdbcType=VARCHAR}, + encrypt_key = #{encryptKey,jdbcType=VARCHAR}, + encrypt_vector = #{encryptVector,jdbcType=VARCHAR}, + sign_key = #{signKey,jdbcType=VARCHAR}, + encrypt_method = #{encryptMethod,jdbcType=VARCHAR}, + sw_version = #{swVersion,jdbcType=VARCHAR}, + fw_version = #{fwVersion,jdbcType=VARCHAR}, + device_sdk_version = #{deviceSdkVersion,jdbcType=VARCHAR}, create_by = #{createBy,jdbcType=VARCHAR}, create_time = #{createTime,jdbcType=TIMESTAMP}, update_by = #{updateBy,jdbcType=VARCHAR}, @@ -753,6 +953,27 @@ device_type, + + encrypt_key, + + + encrypt_vector, + + + sign_key, + + + encrypt_method, + + + sw_version, + + + fw_version, + + + device_sdk_version, + create_by, @@ -822,6 +1043,27 @@ #{deviceType,jdbcType=VARCHAR}, + + #{encryptKey,jdbcType=VARCHAR}, + + + #{encryptVector,jdbcType=VARCHAR}, + + + #{signKey,jdbcType=VARCHAR}, + + + #{encryptMethod,jdbcType=VARCHAR}, + + + #{swVersion,jdbcType=VARCHAR}, + + + #{fwVersion,jdbcType=VARCHAR}, + + + #{deviceSdkVersion,jdbcType=VARCHAR}, + #{createBy,jdbcType=VARCHAR}, @@ -891,6 +1133,27 @@ device_type = #{deviceType,jdbcType=VARCHAR}, + + encrypt_key = #{encryptKey,jdbcType=VARCHAR}, + + + encrypt_vector = #{encryptVector,jdbcType=VARCHAR}, + + + sign_key = #{signKey,jdbcType=VARCHAR}, + + + encrypt_method = #{encryptMethod,jdbcType=VARCHAR}, + + + sw_version = #{swVersion,jdbcType=VARCHAR}, + + + fw_version = #{fwVersion,jdbcType=VARCHAR}, + + + device_sdk_version = #{deviceSdkVersion,jdbcType=VARCHAR}, + create_by = #{createBy,jdbcType=VARCHAR}, @@ -1002,6 +1265,27 @@ and device_type = #{deviceType,jdbcType=VARCHAR} + + and encrypt_key = #{encryptKey,jdbcType=VARCHAR} + + + and encrypt_vector = #{encryptVector,jdbcType=VARCHAR} + + + and sign_key = #{signKey,jdbcType=VARCHAR} + + + and encrypt_method = #{encryptMethod,jdbcType=VARCHAR} + + + and sw_version = #{swVersion,jdbcType=VARCHAR} + + + and fw_version = #{fwVersion,jdbcType=VARCHAR} + + + and device_sdk_version = #{deviceSdkVersion,jdbcType=VARCHAR} + and create_by = #{createBy,jdbcType=VARCHAR} @@ -1049,6 +1333,13 @@ product_identification, protocol_type, device_type, + encrypt_key, + encrypt_vector, + sign_key, + encrypt_method, + sw_version, + fw_version, + device_sdk_version, create_by, create_time, update_by, @@ -1094,6 +1385,30 @@ and device_type = #{deviceType} + + and encrypt_key = #{encryptKey} + + + and encrypt_vector = #{encryptVector} + + + and sign_key = #{signKey} + + + and encrypt_method = #{encryptMethod} + + + and sw_version = #{swVersion} + + + and fw_version = #{fwVersion} + + + and device_sdk_version = #{deviceSdkVersion} + + + and create_by = #{createBy} + and create_time = #{createTime} @@ -1158,6 +1473,27 @@ device_type, + + encrypt_key, + + + encrypt_vector, + + + sign_key, + + + encrypt_method, + + + sw_version, + + + fw_version, + + + device_sdk_version, + create_by, @@ -1223,6 +1559,27 @@ #{deviceType}, + + #{encryptKey}, + + + #{encryptVector}, + + + #{signKey}, + + + #{encryptMethod}, + + + #{swVersion}, + + + #{fwVersion}, + + + #{deviceSdkVersion}, + #{createBy}, @@ -1292,6 +1649,27 @@ device_type = #{deviceType}, + + encrypt_key = #{encryptKey}, + + + encrypt_vector = #{encryptVector}, + + + sign_key = #{signKey}, + + + encrypt_method = #{encryptMethod}, + + + sw_version = #{swVersion}, + + + fw_version = #{fwVersion}, + + + device_sdk_version = #{deviceSdkVersion}, + create_by = #{createBy}, From 1fc29f2c9cfdec82ac10c3dc794caaef328a6a35 Mon Sep 17 00:00:00 2001 From: xiaonan <13733918655@163.com> Date: Sat, 23 Mar 2024 22:21:56 +0800 Subject: [PATCH 12/35] fix kafka topic --- .../core/mqs/ConsumerTopicConstant.java | 20 ++++----- .../MqttMessageKafkaConsumerHandler.java | 18 ++++---- .../mqtt/service/MqttEventCommandService.java | 45 ++++++++++--------- 3 files changed, 42 insertions(+), 41 deletions(-) diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/ConsumerTopicConstant.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/ConsumerTopicConstant.java index 03907be1..7439097d 100644 --- a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/ConsumerTopicConstant.java +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/mqs/ConsumerTopicConstant.java @@ -25,48 +25,48 @@ interface Mqtt { /** * 设备上线 */ - String THINGLINKS_CLIENT_CONNECTED_TOPIC = "client.connected.topic"; + String THINGLINKS_MQTT_CLIENT_CONNECTED_TOPIC = "mqtt.client.connected.topic"; /** * 客户端设备离线 */ - String THINGLINKS_CLIENT_DISCONNECTED_TOPIC = "client.disconnect.topic"; + String THINGLINKS_MQTT_CLIENT_DISCONNECTED_TOPIC = "mqtt.client.disconnect.topic"; /** - * 服务端设备离线 + * 服务端主动断开了与客户端的连接 */ - String THINGLINKS_SERVER_CONNECTED_TOPIC = "server.disconnect.topic"; + String THINGLINKS_MQTT_SERVER_CONNECTED_TOPIC = "mqtt.server.disconnect.topic"; /** * 设备离线 */ - String THINGLINKS_DEVICE_KICKED_TOPIC = "device.kicked.topic"; + String THINGLINKS_MQTT_DEVICE_KICKED_TOPIC = "mqtt.device.kicked.topic"; /** * 消息订阅 */ - String THINGLINKS_SUBSCRIPTION_ACKED_TOPIC = "subscription.acked.topic"; + String THINGLINKS_MQTT_SUBSCRIPTION_ACKED_TOPIC = "mqtt.subscription.acked.topic"; /** * 取消订阅 */ - String THINGLINKS_UNSUBSCRIPTION_ACKED_TOPIC = "unsubscription.acked.topic"; + String THINGLINKS_MQTT_UNSUBSCRIPTION_ACKED_TOPIC = "mqtt.unsubscription.acked.topic"; /** * 消息分发错误 */ - String THINGLINKS_DISTRIBUTION_ERROR_TOPIC = "distribution.error.topic"; + String THINGLINKS_MQTT_DISTRIBUTION_ERROR_TOPIC = "mqtt.distribution.error.topic"; /** * 消息分发 */ - String THINGLINKS_DISTRIBUTION_COMPLETED_TOPIC = "distribution.completed.topic"; + String THINGLINKS_MQTT_DISTRIBUTION_COMPLETED_TOPIC = "mqtt.distribution.completed.topic"; /** * PING 请求 */ - String THINGLINKS_PING_REQ_TOPIC = "ping.req.topic"; + String THINGLINKS_MQTT_PING_REQ_TOPIC = "mqtt.ping.req.topic"; } diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MqttMessageKafkaConsumerHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MqttMessageKafkaConsumerHandler.java index 249ff394..0c922a14 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MqttMessageKafkaConsumerHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MqttMessageKafkaConsumerHandler.java @@ -43,15 +43,15 @@ public class MqttMessageKafkaConsumerHandler { * @param ack kafka的消息确认 */ @KafkaListener(topics = {ConsumerTopicConstant.Mqtt.THINGLINKS_MQS_MQTT_MSG, - ConsumerTopicConstant.Mqtt.THINGLINKS_CLIENT_CONNECTED_TOPIC, - ConsumerTopicConstant.Mqtt.THINGLINKS_CLIENT_DISCONNECTED_TOPIC, - ConsumerTopicConstant.Mqtt.THINGLINKS_SERVER_CONNECTED_TOPIC, - ConsumerTopicConstant.Mqtt.THINGLINKS_DEVICE_KICKED_TOPIC, - ConsumerTopicConstant.Mqtt.THINGLINKS_SUBSCRIPTION_ACKED_TOPIC, - ConsumerTopicConstant.Mqtt.THINGLINKS_UNSUBSCRIPTION_ACKED_TOPIC, - ConsumerTopicConstant.Mqtt.THINGLINKS_DISTRIBUTION_ERROR_TOPIC, - ConsumerTopicConstant.Mqtt.THINGLINKS_DISTRIBUTION_COMPLETED_TOPIC, - ConsumerTopicConstant.Mqtt.THINGLINKS_PING_REQ_TOPIC + ConsumerTopicConstant.Mqtt.THINGLINKS_MQTT_CLIENT_CONNECTED_TOPIC, + ConsumerTopicConstant.Mqtt.THINGLINKS_MQTT_CLIENT_DISCONNECTED_TOPIC, + ConsumerTopicConstant.Mqtt.THINGLINKS_MQTT_SERVER_CONNECTED_TOPIC, + ConsumerTopicConstant.Mqtt.THINGLINKS_MQTT_DEVICE_KICKED_TOPIC, + ConsumerTopicConstant.Mqtt.THINGLINKS_MQTT_SUBSCRIPTION_ACKED_TOPIC, + ConsumerTopicConstant.Mqtt.THINGLINKS_MQTT_UNSUBSCRIPTION_ACKED_TOPIC, + ConsumerTopicConstant.Mqtt.THINGLINKS_MQTT_DISTRIBUTION_ERROR_TOPIC, + ConsumerTopicConstant.Mqtt.THINGLINKS_MQTT_DISTRIBUTION_COMPLETED_TOPIC, + ConsumerTopicConstant.Mqtt.THINGLINKS_MQTT_PING_REQ_TOPIC }, errorHandler = "myKafkaListenerErrorHandler", containerFactory = "kafkaListenerContainerFactory") @KafkaHandler public void handleBatchMessages(List> records, Acknowledgment ack) { diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventCommandService.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventCommandService.java index c8139b5a..c1d87aa4 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventCommandService.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventCommandService.java @@ -19,7 +19,7 @@ @RequiredArgsConstructor public class MqttEventCommandService { - private final DeviceCommandApi deviceCommandApi; +// private final DeviceCommandApi deviceCommandApi; /** * Processes the received message, converts it to a DeviceCommandSaveVO, and saves the command. @@ -29,16 +29,17 @@ public class MqttEventCommandService { * @return A JSON string representing the saved device command. */ public String processCommand(DeviceCacheVO deviceCacheVO, String dataBody) { - DeviceCommandSaveVO saveVO = convertToSaveVO(deviceCacheVO, dataBody); - R response = deviceCommandApi.saveDeviceCommand(saveVO); - - if (Boolean.FALSE.equals(response.getIsSuccess())) { - log.error("Failed to process device command: {}", JSON.toJSONString(response)); - throw new IllegalStateException("Failed to save device command"); - } - - log.info("Device command processed and saved: {}", JSON.toJSONString(response.getData())); - return JSON.toJSONString(response.getData()); +// DeviceCommandSaveVO saveVO = convertToSaveVO(deviceCacheVO, dataBody); +// R response = deviceCommandApi.saveDeviceCommand(saveVO); +// +// if (Boolean.FALSE.equals(response.getIsSuccess())) { +// log.error("Failed to process device command: {}", JSON.toJSONString(response)); +// throw new IllegalStateException("Failed to save device command"); +// } +// +// log.info("Device command processed and saved: {}", JSON.toJSONString(response.getData())); +// return JSON.toJSONString(response.getData()); + return "Device command processed and saved"; } /** @@ -48,15 +49,15 @@ public String processCommand(DeviceCacheVO deviceCacheVO, String dataBody) { * @param dataBody The body of the MQTT message. * @return The DeviceCommandSaveVO object. */ - private DeviceCommandSaveVO convertToSaveVO(DeviceCacheVO deviceCacheVO, String dataBody) { - // Your conversion logic here - // For now, creating a new object with some default values - DeviceCommandSaveVO saveVO = new DeviceCommandSaveVO(); - saveVO.setDeviceIdentification(deviceCacheVO.getDeviceIdentification()); - saveVO.setCommandType(DeviceCommandTypeEnum.COMMAND_RESPONSE.getValue()); - saveVO.setStatus(DeviceCommandStatusEnum.SUCCESS.getValue()); - saveVO.setContent(dataBody); - saveVO.setRemark("Processed command response"); - return saveVO; - } +// private DeviceCommandSaveVO convertToSaveVO(DeviceCacheVO deviceCacheVO, String dataBody) { +// // Your conversion logic here +// // For now, creating a new object with some default values +// DeviceCommandSaveVO saveVO = new DeviceCommandSaveVO(); +// saveVO.setDeviceIdentification(deviceCacheVO.getDeviceIdentification()); +// saveVO.setCommandType(DeviceCommandTypeEnum.COMMAND_RESPONSE.getValue()); +// saveVO.setStatus(DeviceCommandStatusEnum.SUCCESS.getValue()); +// saveVO.setContent(dataBody); +// saveVO.setRemark("Processed command response"); +// return saveVO; +// } } \ No newline at end of file From 6f02c0d83e99ae376ea28cf436b848815d5508a3 Mon Sep 17 00:00:00 2001 From: wangfan1997 <1624212366@qq.com> Date: Sat, 23 Mar 2024 22:46:30 +0800 Subject: [PATCH 13/35] =?UTF-8?q?add=20ota=E5=9F=BA=E6=9C=AC=E5=8A=9F?= =?UTF-8?q?=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 1 - .../domain/ota/entity/OtaUpgradeRecords.java | 74 ++++++ .../domain/ota/entity/OtaUpgradeTasks.java | 56 ++++ .../api/domain/ota/entity/OtaUpgrades.java | 81 ++++++ .../ota/enumeration/OtaPackageStatusEnum.java | 49 ++++ .../ota/enumeration/OtaPackageTypeEnum.java | 56 ++++ .../enumeration/OtaUpgradeTaskStatusEnum.java | 63 +++++ .../vo/result/OtaUpgradeTasksResultVO.java | 81 ++++++ .../ota/vo/result/OtaUpgradesResultVO.java | 95 +++++++ .../ota/vo/save/OtaUpgradeRecordsSaveVO.java | 114 ++++++++ .../ota/vo/save/OtaUpgradeTasksSaveVO.java | 79 ++++++ .../domain/ota/vo/save/OtaUpgradesSaveVO.java | 107 ++++++++ .../vo/update/OtaUpgradeRecordsUpdateVO.java | 117 +++++++++ .../vo/update/OtaUpgradeTasksUpdateVO.java | 82 ++++++ .../ota/vo/update/OtaUpgradesUpdateVO.java | 110 ++++++++ .../link/common/cache/CacheSuperAbstract.java | 2 +- .../cache/service/DeviceCacheService.java | 247 ++++++++---------- .../cache/service/ProductCacheService.java | 111 ++++++++ .../service/ProductModelCacheService.java | 107 ++++++++ .../link/mapper/device/DeviceMapper.java | 5 + .../link/service/device/DeviceService.java | 7 + .../device/impl/DeviceServiceImpl.java | 9 + .../link/service/product/ProductService.java | 13 + .../mapper/link/device/DeviceMapper.xml | 10 + 24 files changed, 1537 insertions(+), 139 deletions(-) create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/entity/OtaUpgradeRecords.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/entity/OtaUpgradeTasks.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/entity/OtaUpgrades.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/enumeration/OtaPackageStatusEnum.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/enumeration/OtaPackageTypeEnum.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/enumeration/OtaUpgradeTaskStatusEnum.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/result/OtaUpgradeTasksResultVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/result/OtaUpgradesResultVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/save/OtaUpgradeRecordsSaveVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/save/OtaUpgradeTasksSaveVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/save/OtaUpgradesSaveVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/update/OtaUpgradeRecordsUpdateVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/update/OtaUpgradeTasksUpdateVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/update/OtaUpgradesUpdateVO.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/ProductCacheService.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/ProductModelCacheService.java diff --git a/pom.xml b/pom.xml index 3d0d8d62..30767838 100644 --- a/pom.xml +++ b/pom.xml @@ -276,7 +276,6 @@ thinglinks-api thinglinks-common thinglinks-registry - thinglinks-common/thinglinks-common-tds pom diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/entity/OtaUpgradeRecords.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/entity/OtaUpgradeRecords.java new file mode 100644 index 00000000..fc994d1f --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/entity/OtaUpgradeRecords.java @@ -0,0 +1,74 @@ +package com.mqttsnet.thinglinks.link.api.domain.ota.entity; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + * OTA升级记录模型 + */ +@ApiModel(value = "OTA升级记录模型") +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder +public class OtaUpgradeRecords implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "主键") + private Long id; + + @ApiModelProperty(value = "任务ID,关联ota_upgrade_tasks表") + private Long taskId; + + @ApiModelProperty(value = "设备标识") + private String deviceIdentification; + + @ApiModelProperty(value = "升级状态(0:待升级、1:升级中、2:升级成功、3:升级失败)") + private Short upgradeStatus; + + @ApiModelProperty(value = "升级进度(百分比)") + private Short progress; + + @ApiModelProperty(value = "错误代码") + private String errorCode; + + @ApiModelProperty(value = "错误信息") + private String errorMessage; + + @ApiModelProperty(value = "升级开始时间") + private LocalDateTime startTime; + + @ApiModelProperty(value = "升级结束时间") + private LocalDateTime endTime; + + @ApiModelProperty(value = "升级成功详细信息") + private String successDetails; + + @ApiModelProperty(value = "升级失败详细信息") + private String failureDetails; + + @ApiModelProperty(value = "升级过程日志") + private String logDetails; + + @ApiModelProperty(value = "描述") + private String remark; + + @ApiModelProperty(value = "记录创建时间") + private LocalDateTime createdTime; + + @ApiModelProperty(value = "创建人") + private String createdBy; + + @ApiModelProperty(value = "更新人") + private String updatedBy; + + @ApiModelProperty(value = "更新时间") + private LocalDateTime updatedTime; +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/entity/OtaUpgradeTasks.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/entity/OtaUpgradeTasks.java new file mode 100644 index 00000000..5803577b --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/entity/OtaUpgradeTasks.java @@ -0,0 +1,56 @@ +package com.mqttsnet.thinglinks.link.api.domain.ota.entity; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + * OTA升级任务模型 + */ +@ApiModel(value = "OTA升级任务模型") +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder +public class OtaUpgradeTasks implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "主键") + private Long id; + + @ApiModelProperty(value = "升级包ID,关联ota_upgrades表") + private Long upgradeId; + + @ApiModelProperty(value = "任务名称") + private String taskName; + + @ApiModelProperty(value = "任务状态(0:待发布、1:进行中、2:已完成、3:已取消)") + private Short taskStatus; + + @ApiModelProperty(value = "计划执行时间") + private LocalDateTime scheduledTime; + + @ApiModelProperty(value = "任务描述") + private String description; + + @ApiModelProperty(value = "描述") + private String remark; + + @ApiModelProperty(value = "创建人") + private String createdBy; + + @ApiModelProperty(value = "创建时间") + private LocalDateTime createdTime; + + @ApiModelProperty(value = "更新人") + private String updatedBy; + + @ApiModelProperty(value = "更新时间") + private LocalDateTime updatedTime; +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/entity/OtaUpgrades.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/entity/OtaUpgrades.java new file mode 100644 index 00000000..9d6046a3 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/entity/OtaUpgrades.java @@ -0,0 +1,81 @@ +package com.mqttsnet.thinglinks.link.api.domain.ota.entity; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Date; + +/** + * OTA升级包实体类 + */ +@ApiModel(value = "OTA升级包模型") +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder +public class OtaUpgrades implements Serializable { + private static final long serialVersionUID = 1L; + + + @ApiModelProperty(value = "主键") + private Long id; + + @ApiModelProperty(value = "应用ID") + private String appId; + + + @ApiModelProperty(value = "包名称") + private String packageName; + + + @ApiModelProperty(value = "升级包类型(0:软件包、1:固件包)") + private Short packageType; + + + @ApiModelProperty(value = "产品标识") + private String productIdentification; + + + @ApiModelProperty(value = "升级包版本号") + private String version; + + + @ApiModelProperty(value = "升级包的位置") + private String fileLocation; + + + @ApiModelProperty(value = "状态") + private Short status; + + + @ApiModelProperty(value = "升级包功能描述") + private String description; + + + @ApiModelProperty(value = "自定义信息") + private String customInfo; + + + @ApiModelProperty(value = "描述") + private String remark; + + + @ApiModelProperty(value = "创建人") + private String createdBy; + + + @ApiModelProperty(value = "创建时间") + private Date createdTime; + + + @ApiModelProperty(value = "更新人") + private String updatedBy; + + @ApiModelProperty(value = "更新时间") + private Date updatedTime; +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/enumeration/OtaPackageStatusEnum.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/enumeration/OtaPackageStatusEnum.java new file mode 100644 index 00000000..330bd7e6 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/enumeration/OtaPackageStatusEnum.java @@ -0,0 +1,49 @@ +package com.mqttsnet.thinglinks.link.api.domain.ota.enumeration; + +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.Optional; +import java.util.stream.Stream; + +/** + *

+ * OTA升级包状态 + *

+ * + * @author shihuan sun + * @date 2023-04-14 + */ +@Getter +@AllArgsConstructor +@NoArgsConstructor +@ApiModel(value = "ProductStatusEnum", description = "OTA升级包状态,字典标识:LINK_OTA_PACKAGES_STATUS") +public enum OtaPackageStatusEnum { + + ENABLE(0, "启用"), + + DISABLE(1, "禁用"), + + ; + + private Integer value; + private String desc; + + public static Optional fromValue(Integer value) { + return Optional.ofNullable(value) + .flatMap(val -> Stream.of(OtaPackageStatusEnum.values()) + .filter(e -> e.getValue().equals(val)) + .findFirst()); + } + + + public void setValue(Integer value) { + this.value = value; + } + + public void setDesc(String desc) { + this.desc = desc; + } +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/enumeration/OtaPackageTypeEnum.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/enumeration/OtaPackageTypeEnum.java new file mode 100644 index 00000000..7b37dc57 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/enumeration/OtaPackageTypeEnum.java @@ -0,0 +1,56 @@ +package com.mqttsnet.thinglinks.link.api.domain.ota.enumeration; + +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.Optional; +import java.util.stream.Stream; + +/** + * ----------------------------------------------------------------------------- + * File Name: OtaPackageTypeEnum + * ----------------------------------------------------------------------------- + * Description: + * PackageType + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/1/17 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/1/17 14:34 + */ +@Getter +@AllArgsConstructor +@NoArgsConstructor +@ApiModel(value = "OtaPackageTypeEnum", description = "OTA升级包类型,字典标识:LINK_OTA_PACKAGES_TYPE") +public enum OtaPackageTypeEnum { + SOFTWARE(0, "software"), + FIRMWARE(1, "firmware"); + + private Integer value; + private String desc; + + public void setValue(Integer value) { + this.value = value; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public static Optional fromValue(Integer value) { + return Optional.ofNullable(value) + .flatMap(val -> Stream.of(OtaPackageTypeEnum.values()) + .filter(e -> e.getValue().equals(val)) + .findFirst()); + } + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/enumeration/OtaUpgradeTaskStatusEnum.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/enumeration/OtaUpgradeTaskStatusEnum.java new file mode 100644 index 00000000..a49be92a --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/enumeration/OtaUpgradeTaskStatusEnum.java @@ -0,0 +1,63 @@ +package com.mqttsnet.thinglinks.link.api.domain.ota.enumeration; + +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.Optional; +import java.util.stream.Stream; + +/** + * ----------------------------------------------------------------------------- + * File Name: OtaUpgradeTaskStatusEnum + * ----------------------------------------------------------------------------- + * Description: + * Ota upgrade task status + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/1/18 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/1/18 17:38 + */ +@Getter +@AllArgsConstructor +@NoArgsConstructor +@ApiModel(value = "OtaUpgradeTaskStatusEnum", description = "OTA升级任务状态,字典标识:LINK_OTA_UPGRADE_TASKS_STATUS") +public enum OtaUpgradeTaskStatusEnum { + PENDING(0, "待发布"), + IN_PROGRESS(1, "进行中"), + COMPLETED(2, "已完成"), + CANCELLED(3, "已取消"); + + private Integer value; + private String desc; + + /** + * Get the enum value from an integer. + * + * @param value Integer value representing the status. + * @return An Optional of OtaTaskStatusEnum. + */ + public static Optional fromValue(Integer value) { + return Optional.ofNullable(value) + .flatMap(val -> Stream.of(OtaUpgradeTaskStatusEnum.values()) + .filter(e -> e.getValue().equals(val)) + .findFirst()); + } + + public void setValue(Integer value) { + this.value = value; + } + + public void setDesc(String desc) { + this.desc = desc; + } +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/result/OtaUpgradeTasksResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/result/OtaUpgradeTasksResultVO.java new file mode 100644 index 00000000..afd1a8b9 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/result/OtaUpgradeTasksResultVO.java @@ -0,0 +1,81 @@ +package com.mqttsnet.thinglinks.link.api.domain.ota.vo.result; + +import cn.hutool.core.map.MapUtil; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.time.LocalDateTime; +import java.util.Map; + +/** + *

+ * 表单查询方法返回值VO + * OTA升级任务表 + *

+ * + * @author mqttsnet + * @date 2024-01-12 22:40:04 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder +@ApiModel(value = "OtaUpgradeTasksResultVO", description = "OTA升级任务表") +public class OtaUpgradeTasksResultVO implements Serializable { + + private static final long serialVersionUID = 1L; + + private Map echoMap = MapUtil.newHashMap(); + + @ApiModelProperty(value = "主键") + private Long id; + + /** + * 升级包ID,关联ota_upgrades表 + */ + @ApiModelProperty(value = "升级包ID,关联ota_upgrades表") + private Long upgradeId; + /** + * 任务名称 + */ + @ApiModelProperty(value = "任务名称") + private String taskName; + /** + * 任务状态(0:待发布、1:进行中、2:已完成、3:已取消) + */ + @ApiModelProperty(value = "任务状态(0:待发布、1:进行中、2:已完成、3:已取消)") + private Integer taskStatus; + /** + * 计划执行时间 + */ + @ApiModelProperty(value = "计划执行时间") + private LocalDateTime scheduledTime; + /** + * 任务描述 + */ + @ApiModelProperty(value = "任务描述") + private String description; + /** + * 描述 + */ + @ApiModelProperty(value = "描述") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + + /** + * 升级包信息 + */ + @ApiModelProperty(value = "升级包信息") + private OtaUpgradesResultVO otaUpgradesResultVO; + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/result/OtaUpgradesResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/result/OtaUpgradesResultVO.java new file mode 100644 index 00000000..99382df7 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/result/OtaUpgradesResultVO.java @@ -0,0 +1,95 @@ +package com.mqttsnet.thinglinks.link.api.domain.ota.vo.result; + +import cn.hutool.core.map.MapUtil; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Map; + +/** + *

+ * 表单查询方法返回值VO + * OTA升级包 + *

+ * + * @author mqttsnet + * @date 2024-01-12 22:36:27 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@Builder +@ApiModel(value = "OtaUpgradesResultVO", description = "OTA升级包") +public class OtaUpgradesResultVO implements Serializable { + + private static final long serialVersionUID = 1L; + + private Map echoMap = MapUtil.newHashMap(); + + @ApiModelProperty(value = "主键") + private Long id; + + /** + * 应用ID + */ + @ApiModelProperty(value = "应用ID") + private String appId; + /** + * 包名称 + */ + @ApiModelProperty(value = "包名称") + private String packageName; + /** + * 升级包类型(0:软件包、1:固件包) + */ + @ApiModelProperty(value = "升级包类型(0:软件包、1:固件包)") + private Integer packageType; + /** + * 产品标识 + */ + @ApiModelProperty(value = "产品标识") + private String productIdentification; + /** + * 升级包版本号 + */ + @ApiModelProperty(value = "升级包版本号") + private String version; + /** + * 升级包的位置 + */ + @ApiModelProperty(value = "升级包的位置") + private String fileLocation; + /** + * 状态 + */ + @ApiModelProperty(value = "状态") + private Integer status; + /** + * 升级包功能描述 + */ + @ApiModelProperty(value = "升级包功能描述") + private String description; + /** + * 自定义信息 + */ + @ApiModelProperty(value = "自定义信息") + private String customInfo; + /** + * 描述 + */ + @ApiModelProperty(value = "描述") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/save/OtaUpgradeRecordsSaveVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/save/OtaUpgradeRecordsSaveVO.java new file mode 100644 index 00000000..0f3b3598 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/save/OtaUpgradeRecordsSaveVO.java @@ -0,0 +1,114 @@ +package com.mqttsnet.thinglinks.link.api.domain.ota.vo.save; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + *

+ * 表单保存方法VO + * OTA升级记录表 + *

+ * + * @author mqttsnet + * @date 2024-01-12 22:42:04 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "OtaUpgradeRecordsSaveVO", description = "OTA升级记录表") +public class OtaUpgradeRecordsSaveVO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 任务ID,关联ota_upgrade_tasks表 + */ + @ApiModelProperty(value = "任务ID,关联ota_upgrade_tasks表") + @NotNull(message = "请填写任务ID,关联ota_upgrade_tasks表") + private Long taskId; + /** + * 设备标识 + */ + @ApiModelProperty(value = "设备标识") + @NotEmpty(message = "请填写设备标识") + @Size(max = 100, message = "设备标识长度不能超过{max}") + private String deviceIdentification; + /** + * 升级状态(0:待升级、1:升级中、2:升级成功、3:升级失败) + */ + @ApiModelProperty(value = "升级状态(0:待升级、1:升级中、2:升级成功、3:升级失败)") + @NotNull(message = "请填写升级状态(0:待升级、1:升级中、2:升级成功、3:升级失败)") + private Integer upgradeStatus; + /** + * 升级进度(百分比) + */ + @ApiModelProperty(value = "升级进度(百分比)") + @NotNull(message = "请填写升级进度(百分比)") + private Integer progress; + /** + * 错误代码 + */ + @ApiModelProperty(value = "错误代码") + @Size(max = 100, message = "错误代码长度不能超过{max}") + private String errorCode; + /** + * 错误信息 + */ + @ApiModelProperty(value = "错误信息") + @Size(max = 255, message = "错误信息长度不能超过{max}") + private String errorMessage; + /** + * 升级开始时间 + */ + @ApiModelProperty(value = "升级开始时间") + private LocalDateTime startTime; + /** + * 升级结束时间 + */ + @ApiModelProperty(value = "升级结束时间") + private LocalDateTime endTime; + /** + * 升级成功详细信息 + */ + @ApiModelProperty(value = "升级成功详细信息") + @Size(max = 2147483647, message = "升级成功详细信息长度不能超过{max}") + private String successDetails; + /** + * 升级失败详细信息 + */ + @ApiModelProperty(value = "升级失败详细信息") + @Size(max = 2147483647, message = "升级失败详细信息长度不能超过{max}") + private String failureDetails; + /** + * 升级过程日志 + */ + @ApiModelProperty(value = "升级过程日志") + @Size(max = 2147483647, message = "升级过程日志长度不能超过{max}") + private String logDetails; + /** + * 描述 + */ + @ApiModelProperty(value = "描述") + @Size(max = 255, message = "描述长度不能超过{max}") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/save/OtaUpgradeTasksSaveVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/save/OtaUpgradeTasksSaveVO.java new file mode 100644 index 00000000..d8254ebe --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/save/OtaUpgradeTasksSaveVO.java @@ -0,0 +1,79 @@ +package com.mqttsnet.thinglinks.link.api.domain.ota.vo.save; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + *

+ * 表单保存方法VO + * OTA升级任务表 + *

+ * + * @author mqttsnet + * @date 2024-01-12 22:40:04 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "OtaUpgradeTasksSaveVO", description = "OTA升级任务表") +public class OtaUpgradeTasksSaveVO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 升级包ID,关联ota_upgrades表 + */ + @ApiModelProperty(value = "升级包ID,关联ota_upgrades表") + @NotNull(message = "请填写升级包ID,关联ota_upgrades表") + private Long upgradeId; + /** + * 任务名称 + */ + @ApiModelProperty(value = "任务名称") + @NotEmpty(message = "请填写任务名称") + @Size(max = 100, message = "任务名称长度不能超过{max}") + private String taskName; + /** + * 任务状态(0:待发布、1:进行中、2:已完成、3:已取消) + */ + @ApiModelProperty(value = "任务状态(0:待发布、1:进行中、2:已完成、3:已取消)") + @NotNull(message = "请填写任务状态(0:待发布、1:进行中、2:已完成、3:已取消)") + private Integer taskStatus; + /** + * 计划执行时间 + */ + @ApiModelProperty(value = "计划执行时间") + private LocalDateTime scheduledTime; + /** + * 任务描述 + */ + @ApiModelProperty(value = "任务描述") + @Size(max = 255, message = "任务描述长度不能超过{max}") + private String description; + /** + * 描述 + */ + @ApiModelProperty(value = "描述") + @Size(max = 255, message = "描述长度不能超过{max}") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/save/OtaUpgradesSaveVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/save/OtaUpgradesSaveVO.java new file mode 100644 index 00000000..a7e63f3f --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/save/OtaUpgradesSaveVO.java @@ -0,0 +1,107 @@ +package com.mqttsnet.thinglinks.link.api.domain.ota.vo.save; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; + +/** + *

+ * 表单保存方法VO + * OTA升级包 + *

+ * + * @author mqttsnet + * @date 2024-01-12 22:36:27 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "OtaUpgradesSaveVO", description = "OTA升级包") +public class OtaUpgradesSaveVO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 应用ID + */ + @ApiModelProperty(value = "应用ID") + @NotEmpty(message = "请填写应用ID") + @Size(max = 64, message = "应用ID长度不能超过{max}") + private String appId; + /** + * 包名称 + */ + @ApiModelProperty(value = "包名称") + @NotEmpty(message = "请填写包名称") + @Size(max = 100, message = "包名称长度不能超过{max}") + private String packageName; + /** + * 升级包类型(0:软件包、1:固件包) + */ + @ApiModelProperty(value = "升级包类型(0:软件包、1:固件包)") + @NotNull(message = "请填写升级包类型(0:软件包、1:固件包)") + private Integer packageType; + /** + * 产品标识 + */ + @ApiModelProperty(value = "产品标识") + @NotEmpty(message = "请填写产品标识") + @Size(max = 100, message = "产品标识长度不能超过{max}") + private String productIdentification; + /** + * 升级包版本号 + */ + @ApiModelProperty(value = "升级包版本号") + @NotEmpty(message = "请填写升级包版本号") + @Size(max = 255, message = "升级包版本号长度不能超过{max}") + private String version; + /** + * 升级包的位置 + */ + @ApiModelProperty(value = "升级包的位置") + @NotEmpty(message = "请填写升级包的位置") + @Size(max = 255, message = "升级包的位置长度不能超过{max}") + private String fileLocation; + /** + * 状态 + */ + @ApiModelProperty(value = "状态") + @NotNull(message = "请填写状态") + private Integer status; + /** + * 升级包功能描述 + */ + @ApiModelProperty(value = "升级包功能描述") + @Size(max = 255, message = "升级包功能描述长度不能超过{max}") + private String description; + /** + * 自定义信息 + */ + @ApiModelProperty(value = "自定义信息") + @Size(max = 2147483647, message = "自定义信息长度不能超过{max}") + private String customInfo; + /** + * 描述 + */ + @ApiModelProperty(value = "描述") + @Size(max = 255, message = "描述长度不能超过{max}") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/update/OtaUpgradeRecordsUpdateVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/update/OtaUpgradeRecordsUpdateVO.java new file mode 100644 index 00000000..a44f9526 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/update/OtaUpgradeRecordsUpdateVO.java @@ -0,0 +1,117 @@ +package com.mqttsnet.thinglinks.link.api.domain.ota.vo.update; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + *

+ * 表单修改方法VO + * OTA升级记录表 + *

+ * + * @author mqttsnet + * @date 2024-01-12 22:42:04 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "OtaUpgradeRecordsUpdateVO", description = "OTA升级记录表") +public class OtaUpgradeRecordsUpdateVO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "主键") + @NotNull(message = "请填写主键") + private Long id; + + /** + * 任务ID,关联ota_upgrade_tasks表 + */ + @ApiModelProperty(value = "任务ID,关联ota_upgrade_tasks表") + @NotNull(message = "请填写任务ID,关联ota_upgrade_tasks表") + private Long taskId; + /** + * 设备标识 + */ + @ApiModelProperty(value = "设备标识") + @NotEmpty(message = "请填写设备标识") + @Size(max = 100, message = "设备标识长度不能超过{max}") + private String deviceIdentification; + /** + * 升级状态(0:待升级、1:升级中、2:升级成功、3:升级失败) + */ + @ApiModelProperty(value = "升级状态(0:待升级、1:升级中、2:升级成功、3:升级失败)") + @NotNull(message = "请填写升级状态(0:待升级、1:升级中、2:升级成功、3:升级失败)") + private Integer upgradeStatus; + /** + * 升级进度(百分比) + */ + @ApiModelProperty(value = "升级进度(百分比)") + @NotNull(message = "请填写升级进度(百分比)") + private Integer progress; + /** + * 错误代码 + */ + @ApiModelProperty(value = "错误代码") + @Size(max = 100, message = "错误代码长度不能超过{max}") + private String errorCode; + /** + * 错误信息 + */ + @ApiModelProperty(value = "错误信息") + @Size(max = 255, message = "错误信息长度不能超过{max}") + private String errorMessage; + /** + * 升级开始时间 + */ + @ApiModelProperty(value = "升级开始时间") + private LocalDateTime startTime; + /** + * 升级结束时间 + */ + @ApiModelProperty(value = "升级结束时间") + private LocalDateTime endTime; + /** + * 升级成功详细信息 + */ + @ApiModelProperty(value = "升级成功详细信息") + @Size(max = 2147483647, message = "升级成功详细信息长度不能超过{max}") + private String successDetails; + /** + * 升级失败详细信息 + */ + @ApiModelProperty(value = "升级失败详细信息") + @Size(max = 2147483647, message = "升级失败详细信息长度不能超过{max}") + private String failureDetails; + /** + * 升级过程日志 + */ + @ApiModelProperty(value = "升级过程日志") + @Size(max = 2147483647, message = "升级过程日志长度不能超过{max}") + private String logDetails; + /** + * 描述 + */ + @ApiModelProperty(value = "描述") + @Size(max = 255, message = "描述长度不能超过{max}") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/update/OtaUpgradeTasksUpdateVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/update/OtaUpgradeTasksUpdateVO.java new file mode 100644 index 00000000..bf177141 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/update/OtaUpgradeTasksUpdateVO.java @@ -0,0 +1,82 @@ +package com.mqttsnet.thinglinks.link.api.domain.ota.vo.update; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + *

+ * 表单修改方法VO + * OTA升级任务表 + *

+ * + * @author mqttsnet + * @date 2024-01-12 22:40:04 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "OtaUpgradeTasksUpdateVO", description = "OTA升级任务表") +public class OtaUpgradeTasksUpdateVO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "主键") + @NotNull(message = "请填写主键") + private Long id; + + /** + * 升级包ID,关联ota_upgrades表 + */ + @ApiModelProperty(value = "升级包ID,关联ota_upgrades表") + @NotNull(message = "请填写升级包ID,关联ota_upgrades表") + private Long upgradeId; + /** + * 任务名称 + */ + @ApiModelProperty(value = "任务名称") + @NotEmpty(message = "请填写任务名称") + @Size(max = 100, message = "任务名称长度不能超过{max}") + private String taskName; + /** + * 任务状态(0:待发布、1:进行中、2:已完成、3:已取消) + */ + @ApiModelProperty(value = "任务状态(0:待发布、1:进行中、2:已完成、3:已取消)") + @NotNull(message = "请填写任务状态(0:待发布、1:进行中、2:已完成、3:已取消)") + private Integer taskStatus; + /** + * 计划执行时间 + */ + @ApiModelProperty(value = "计划执行时间") + private LocalDateTime scheduledTime; + /** + * 任务描述 + */ + @ApiModelProperty(value = "任务描述") + @Size(max = 255, message = "任务描述长度不能超过{max}") + private String description; + /** + * 描述 + */ + @ApiModelProperty(value = "描述") + @Size(max = 255, message = "描述长度不能超过{max}") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/update/OtaUpgradesUpdateVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/update/OtaUpgradesUpdateVO.java new file mode 100644 index 00000000..66a0db6c --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/ota/vo/update/OtaUpgradesUpdateVO.java @@ -0,0 +1,110 @@ +package com.mqttsnet.thinglinks.link.api.domain.ota.vo.update; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; + +/** + *

+ * 表单修改方法VO + * OTA升级包 + *

+ * + * @author mqttsnet + * @date 2024-01-12 22:36:27 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "OtaUpgradesUpdateVO", description = "OTA升级包") +public class OtaUpgradesUpdateVO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "主键") + @NotNull(message = "请填写主键") + private Long id; + + /** + * 应用ID + */ + @ApiModelProperty(value = "应用ID") + @NotEmpty(message = "请填写应用ID") + @Size(max = 64, message = "应用ID长度不能超过{max}") + private String appId; + /** + * 包名称 + */ + @ApiModelProperty(value = "包名称") + @NotEmpty(message = "请填写包名称") + @Size(max = 100, message = "包名称长度不能超过{max}") + private String packageName; + /** + * 升级包类型(0:软件包、1:固件包) + */ + @ApiModelProperty(value = "升级包类型(0:软件包、1:固件包)") + @NotNull(message = "请填写升级包类型(0:软件包、1:固件包)") + private Integer packageType; + /** + * 产品标识 + */ + @ApiModelProperty(value = "产品标识") + @NotEmpty(message = "请填写产品标识") + @Size(max = 100, message = "产品标识长度不能超过{max}") + private String productIdentification; + /** + * 升级包版本号 + */ + @ApiModelProperty(value = "升级包版本号") + @NotEmpty(message = "请填写升级包版本号") + @Size(max = 255, message = "升级包版本号长度不能超过{max}") + private String version; + /** + * 升级包的位置 + */ + @ApiModelProperty(value = "升级包的位置") + @NotEmpty(message = "请填写升级包的位置") + @Size(max = 255, message = "升级包的位置长度不能超过{max}") + private String fileLocation; + /** + * 状态 + */ + @ApiModelProperty(value = "状态") + @NotNull(message = "请填写状态") + private Integer status; + /** + * 升级包功能描述 + */ + @ApiModelProperty(value = "升级包功能描述") + @Size(max = 255, message = "升级包功能描述长度不能超过{max}") + private String description; + /** + * 自定义信息 + */ + @ApiModelProperty(value = "自定义信息") + @Size(max = 2147483647, message = "自定义信息长度不能超过{max}") + private String customInfo; + /** + * 描述 + */ + @ApiModelProperty(value = "描述") + @Size(max = 255, message = "描述长度不能超过{max}") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/CacheSuperAbstract.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/CacheSuperAbstract.java index 4c37a80c..dab89ff7 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/CacheSuperAbstract.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/CacheSuperAbstract.java @@ -7,5 +7,5 @@ public abstract class CacheSuperAbstract { public static int PAGE_SIZE = 5000; - + public static final Long THIRTY_MINUTES = 30L; } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java index a477ba86..3d361e25 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java @@ -1,137 +1,110 @@ -//package com.mqttsnet.thinglinks.link.common.cache.service; -// -//import cn.hutool.core.bean.BeanUtil; -//import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; -//import com.mqttsnet.thinglinks.common.redis.service.RedisService; -//import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; -//import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductCacheVO; -//import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; -//import com.mqttsnet.thinglinks.link.common.cache.CacheSuperAbstract; -//import com.mqttsnet.thinglinks.link.service.device.DeviceService; -//import com.mqttsnet.thinglinks.link.service.product.ProductService; -//import lombok.RequiredArgsConstructor; -//import lombok.extern.slf4j.Slf4j; -//import org.apache.ibatis.cache.CacheKey; -//import org.springframework.stereotype.Service; -// -//import java.util.*; -//import java.util.stream.Collectors; -//import java.util.stream.IntStream; -// -///** -// * ----------------------------------------------------------------------------- -// * File Name: DeviceCacheService.java -// * ----------------------------------------------------------------------------- -// * Description: -// * Service layer for Device cache management. -// * ----------------------------------------------------------------------------- -// * -// * @author ShiHuan Sun -// * @version 1.0 -// * ----------------------------------------------------------------------------- -// * Revision History: -// * Date Author Version Description -// * -------- -------- ------- -------------------- -// *

-// * ----------------------------------------------------------------------------- -// * @email 13733918655@163.com -// * @date 2023-10-21 22:42 -// */ -//@Service -//@RequiredArgsConstructor -//@Slf4j -//public class DeviceCacheService extends CacheSuperAbstract { -// private final RedisService redisService; -// private final DeviceService deviceService; -// private final ProductService productService; -// -// /** -// * Refresh the cache with device data for a specific tenant. -// * -// * @param tenantId Identifier of the tenant whose device cache needs to be refreshed. -// */ -// public void refreshDeviceCacheForTenant(Long tenantId) { -// int totalDataCount = deviceService.findDeviceTotal().intValue(); -// int totalPages = (int) Math.ceil((double) totalDataCount / PAGE_SIZE); -// -// List deviceList = IntStream.range(0, totalPages) -// .mapToObj(currentPage -> { -// Page page = new Page<>(currentPage, PAGE_SIZE); -// HashMap pageHashMap = new HashMap<>(); -// Device device = new Device(); -// device.setParams(pageHashMap); -// Page content = deviceService.findPageAll(page, null); -// return Optional.ofNullable(content) -// .map(Page::getRecords) -// .orElse(Collections.emptyList()); -// }) -// .flatMap(Collection::stream) -// .collect(Collectors.toList()); -// -// cacheDevicesForTenant(tenantId, deviceList); -// } -// -// /** -// * Cache a list of devices for a specific tenant. -// * -// * @param tenantId Identifier of the tenant. -// * @param deviceList List of devices to be cached. -// */ -// public void cacheDevicesForTenant(Long tenantId, List deviceList) { -// Optional.ofNullable(deviceList) -// .orElse(Collections.emptyList()) -// .stream() -// .filter(Objects::nonNull) -// .map(device -> transformToDeviceCacheVO(tenantId, device)) -// .filter(Objects::nonNull) -// .forEach(deviceCacheVO -> { -// cacheDeviceBasedOnIdentification(deviceCacheVO); -// cacheDeviceBasedOnClientId(deviceCacheVO); -// }); -// } -// -// /** -// * Transforms a device object into a DeviceCacheVO object with associated product data. -// * -// * @param tenantId Identifier of the tenant. -// * @param device Device object to be transformed. -// * @return Transformed DeviceCacheVO object. -// */ -// private DeviceCacheVO transformToDeviceCacheVO(Long tenantId, Device device) { -// DeviceCacheVO deviceCacheVO = BeanUtil.toBeanIgnoreError(device, DeviceCacheVO.class); -// deviceCacheVO.setTenantId(tenantId); -// -// Optional.ofNullable(deviceCacheVO.getProductIdentification()) -// .map(productService::selectProductByProductIdentificationList) -// .ifPresent(product -> { -// ProductCacheVO productCacheVO = BeanPlusUtil.toBeanIgnoreError(product, ProductCacheVO.class); -// productCacheVO.setTenantId(tenantId); -// deviceCacheVO.setProductCacheVO(productCacheVO); -// }); -// -// return deviceCacheVO; -// } -// -// /** -// * Cache the DeviceCacheVO object based on its identification. -// * -// * @param deviceCacheVO DeviceCacheVO object to be cached. -// */ -// private void cacheDeviceBasedOnIdentification(DeviceCacheVO deviceCacheVO) { -// CacheKey deviceIdentKey = DeviceCacheKeyBuilder.build(deviceCacheVO.getDeviceIdentification()); -// cachePlusOps.del(deviceIdentKey); -// cachePlusOps.set(deviceIdentKey, deviceCacheVO); -// } -// -// /** -// * Cache the DeviceCacheVO object based on its client ID. -// * -// * @param deviceCacheVO DeviceCacheVO object to be cached. -// */ -// private void cacheDeviceBasedOnClientId(DeviceCacheVO deviceCacheVO) { -// CacheKey clientIdKey = DeviceCacheKeyBuilder.build(deviceCacheVO.getClientId()); -// cachePlusOps.del(clientIdKey); -// cachePlusOps.set(clientIdKey, deviceCacheVO); -// } -// -//} +package com.mqttsnet.thinglinks.link.common.cache.service; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.collection.CollUtil; +import com.github.pagehelper.PageHelper; +import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; +import com.mqttsnet.thinglinks.common.redis.service.RedisService; +import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; +import com.mqttsnet.thinglinks.link.common.cache.CacheSuperAbstract; +import com.mqttsnet.thinglinks.link.service.device.DeviceService; +import com.mqttsnet.thinglinks.link.service.product.ProductService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + + + + +@Service +@RequiredArgsConstructor +@Slf4j +public class DeviceCacheService extends CacheSuperAbstract { + private final RedisService redisService; + private final DeviceService deviceService; + private final ProductService productService; + + + /** + * Refresh the cache with device data for a specific tenant. + */ + public void refreshDeviceCacheForTenant() { + int totalDataCount = deviceService.findDeviceTotal().intValue(); + int totalPages = (int) Math.ceil((double) totalDataCount / PAGE_SIZE); + List deviceList = IntStream.range(0, totalPages).mapToObj(currentPage -> { + PageHelper.startPage(currentPage+1, PAGE_SIZE); + List pageDevices = deviceService.findDevices(); + return pageDevices; + }) + .flatMap(Collection::stream) + .collect(Collectors.toList()); + + cacheDevicesForTenant(deviceList); + } + + /** + * Cache a list of devices for a specific tenant. + * + * @param deviceList List of devices to be cached. + */ + public void cacheDevicesForTenant(List deviceList) { + Optional.ofNullable(deviceList) + .orElse(Collections.emptyList()) + .stream() + .filter(Objects::nonNull) + .map(this::transformToDeviceCacheVO) + .forEach(deviceCacheVO -> { + cacheDeviceBasedOnIdentification(deviceCacheVO); + cacheDeviceBasedOnClientId(deviceCacheVO); + }); + } + + /** + * Transforms a device object into a DeviceCacheVO object with associated product data. + * + * @param device Device object to be transformed. + * @return Transformed DeviceCacheVO object. + */ + private DeviceCacheVO transformToDeviceCacheVO(Device device) { + DeviceCacheVO deviceCacheVO = BeanUtil.toBeanIgnoreError(device, DeviceCacheVO.class); + + Optional.ofNullable(deviceCacheVO.getProductIdentification()) + .map(productService::findOneByProductIdentification) + .ifPresent(product -> { + ProductCacheVO productCacheVO = BeanPlusUtil.toBeanIgnoreError(product, ProductCacheVO.class); + deviceCacheVO.setProductCacheVO(productCacheVO); + }); + + return deviceCacheVO; + } + + /** + * Cache the DeviceCacheVO object based on its identification. + * + * @param deviceCacheVO DeviceCacheVO object to be cached. + */ + private void cacheDeviceBasedOnIdentification(DeviceCacheVO deviceCacheVO) { + String deviceIdentKey = deviceCacheVO.getDeviceIdentification(); + redisService.delete(deviceIdentKey); + redisService.setCacheObject(deviceIdentKey, deviceCacheVO, THIRTY_MINUTES, TimeUnit.MINUTES); + } + + /** + * Cache the DeviceCacheVO object based on its client ID. + * + * @param deviceCacheVO DeviceCacheVO object to be cached. + */ + private void cacheDeviceBasedOnClientId(DeviceCacheVO deviceCacheVO) { + String clientId = deviceCacheVO.getClientId(); + redisService.delete(clientId); + redisService.setCacheObject(clientId, deviceCacheVO, THIRTY_MINUTES, TimeUnit.MINUTES); + } + +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/ProductCacheService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/ProductCacheService.java new file mode 100644 index 00000000..53172624 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/ProductCacheService.java @@ -0,0 +1,111 @@ +package com.mqttsnet.thinglinks.link.common.cache.service; + + +import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; +import com.mqttsnet.thinglinks.common.redis.service.RedisService; +import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; +import com.mqttsnet.thinglinks.link.common.cache.CacheSuperAbstract; +import com.mqttsnet.thinglinks.link.service.product.ProductService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.Collection; +import java.util.Collections; + +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +/** + * ----------------------------------------------------------------------------- + * File Name: ProductCacheService.java + * ----------------------------------------------------------------------------- + * Description: + * Service layer for Product cache management. + * ----------------------------------------------------------------------------- + * + * @author ShiHuan Sun + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + *

+ * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2023-10-21 22:45 + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class ProductCacheService extends CacheSuperAbstract { + private final RedisService redisService; + + private final ProductService productService; + + /** + * Refreshes the product cache for a specific tenant. + * + */ + public void refreshProductCacheForTenant() { + int totalDataCount = productService.findProductTotal().intValue(); + int totalPages = (int) Math.ceil((double) totalDataCount / PAGE_SIZE); + + List productList = IntStream.range(0, totalPages) + .mapToObj(this::fetchProductPageContent) + .flatMap(Collection::stream) + .collect(Collectors.toList()); + + if (!productList.isEmpty()) { + cacheProductsForTenant(productList); + } + } + + /** + * Fetches products from a specific page. + * + * @param currentPage The page number to fetch products from. + * @return List of products from the specified page. + */ + private List fetchProductPageContent(int currentPage) { + int offset = currentPage * PAGE_SIZE; + List products = productService.findProductsByPage(offset, PAGE_SIZE); + return products != null ? products : Collections.emptyList(); + } + + /** + * Caches a list of products for a specific tenant. + * + * @param productList List of products to be cached. + */ + private void cacheProductsForTenant( List productList) { + productList.stream() + .map(this::transformToProductCacheVO) + .forEach(this::cacheProduct); + } + + /** + * Transforms a product object into a ProductCacheVO object. + * + * @param product Product object to be transformed. + * @return Transformed ProductCacheVO object. + */ + private ProductCacheVO transformToProductCacheVO( Product product) { + return BeanPlusUtil.toBeanIgnoreError(product, ProductCacheVO.class); + } + + /** + * Caches the ProductCacheVO object. + * + * @param productCacheVO ProductCacheVO object to be cached. + */ + private void cacheProduct(ProductCacheVO productCacheVO) { + String cacheKey = productCacheVO.getProductIdentification(); + redisService.delete(cacheKey); + redisService.setCacheObject(cacheKey, productCacheVO,THIRTY_MINUTES, TimeUnit.MINUTES); + } + +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/ProductModelCacheService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/ProductModelCacheService.java new file mode 100644 index 00000000..5bc4354e --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/ProductModelCacheService.java @@ -0,0 +1,107 @@ +package com.mqttsnet.thinglinks.link.common.cache.service; + +import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; +import com.mqttsnet.thinglinks.common.redis.service.RedisService; +import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductModelCacheVO; +import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; +import com.mqttsnet.thinglinks.link.common.cache.CacheSuperAbstract; +import com.mqttsnet.thinglinks.link.service.product.ProductService; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.ibatis.cache.CacheKey; +import org.springframework.stereotype.Service; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +/** + * ----------------------------------------------------------------------------- + * File Name: ProductModelCacheService.java + * ----------------------------------------------------------------------------- + * Description: + * Service layer for Product Model cache management. + * ----------------------------------------------------------------------------- + * + * @author ShiHuan Sun + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + *

+ * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2023-10-21 22:47 + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class ProductModelCacheService extends CacheSuperAbstract { + + private final RedisService redisService; + private final ProductService productService; + + /** + * Refreshes the product model cache for a specific tenant. + * + */ + public void refreshProductModelCache() { + int totalDataCount = productService.findProductTotal().intValue(); + int totalPages = (int) Math.ceil((double) totalDataCount / PAGE_SIZE); + + List productList = IntStream.range(0, totalPages) + .mapToObj(this::fetchProductPageContent) + .flatMap(Collection::stream) + .collect(Collectors.toList()); + + if (!productList.isEmpty()) { + cacheProductModelsForTenant(productList); + } + } + + /** + * Fetches products from a specific page. + * + * @param currentPage The page number to fetch products from. + * @return List of products from the specified page. + */ + private List fetchProductPageContent(int currentPage) { + return null; + } + + /** + * Caches a list of product models for a specific tenant. + * + * @param productList List of products to be cached as product models. + */ + private void cacheProductModelsForTenant( List productList) { + productList.stream() + .map(this::transformToProductModelCacheVO) + .forEach(this::cacheProductModel); + } + + /** + * Transforms a product object into a ProductModelCacheVO object. + * + * @param product Product object to be transformed. + * @return Transformed ProductModelCacheVO object. + */ + private ProductModelCacheVO transformToProductModelCacheVO( Product product) { + return null; + } + + /** + * Caches the ProductModelCacheVO object. + * + * @param productModelCacheVO ProductModelCacheVO object to be cached. + */ + private void cacheProductModel(ProductModelCacheVO productModelCacheVO) { + + } + +} \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/device/DeviceMapper.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/device/DeviceMapper.java index 6f313f22..1c082adb 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/device/DeviceMapper.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/device/DeviceMapper.java @@ -172,4 +172,9 @@ Device selectByProductIdentificationAndDeviceIdentification(@Param("productIdent List selectDeviceByDeviceIdentificationList(@Param("deviceIdentificationList") List deviceIdentificationList); + Long findDeviceTotal(); + + + + List findDevices(); } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/DeviceService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/DeviceService.java index 65fcbf90..438f6743 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/DeviceService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/DeviceService.java @@ -220,5 +220,12 @@ public interface DeviceService { * @return {@link TopoQueryDeviceResultVO} The result of the device query. */ TopoQueryDeviceResultVO queryDeviceByHttp(TopoQueryDeviceParam topoQueryDeviceParam); + + Long findDeviceTotal(); + + + + List findDevices(); + } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java index c83ca208..c2c801ea 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java @@ -653,5 +653,14 @@ private TopoQueryDeviceResultVO queryDeviceInfo(TopoQueryDeviceParam topoQueryDe .setStatusDesc("Query completed"); return topoQueryDeviceResultVO; } + @Override + public Long findDeviceTotal() { + return deviceMapper.findDeviceTotal(); + } + + @Override + public List findDevices() { + return deviceMapper.findDevices(); + } } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductService.java index 22642060..bea78d2c 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductService.java @@ -5,6 +5,7 @@ import com.mqttsnet.thinglinks.common.core.web.domain.AjaxResult; import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; import com.mqttsnet.thinglinks.link.api.domain.product.model.ProductModel; +import com.mqttsnet.thinglinks.link.api.domain.product.vo.result.ProductResultVO; import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDto; import org.springframework.web.multipart.MultipartFile; @@ -185,5 +186,17 @@ public interface ProductService { List selectAllProductByStatus(String status); List selectProductByProductIdentificationList(List productIdentificationList); + + /** + * 根据产品标识查询产品详情 + * + * @param productIdentification 产品标识 + * @return {@link ProductResultVO} 产品详情 + */ + ProductResultVO findOneByProductIdentification(String productIdentification); + + Long findProductTotal(); + + List findProductsByPage(int offset, int pageSize); } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/device/DeviceMapper.xml b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/device/DeviceMapper.xml index 697289a1..de814f4a 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/device/DeviceMapper.xml +++ b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/device/DeviceMapper.xml @@ -1840,4 +1840,14 @@ + + + + From c203298d664ac4c88c98c2615306444865bf8a83 Mon Sep 17 00:00:00 2001 From: xiaonan <13733918655@163.com> Date: Sun, 24 Mar 2024 21:58:52 +0800 Subject: [PATCH 14/35] =?UTF-8?q?add=EF=BC=9A=E4=BA=A7=E5=93=81=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B=E8=B5=8B=E8=83=BD=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/sql/changeRecord/1.2.0.RELEASE.sql | 11 + doc/sql/thinglinks.sql | 3 +- .../api/domain/entity/MqttMessageEvent.java | 76 ++ ...{MqttEvent.java => MqttProtocolEvent.java} | 10 +- .../broker/api/domain/protocol/HttpEvent.java | 26 + .../broker/api/domain/protocol/MqttEvent.java | 26 + .../api/domain/protocol/ProtocolEvent.java | 35 + .../broker/api/domain/protocol/TcpEvent.java | 26 + .../api/domain/protocol/WebSocketEvent.java | 26 + .../link/api/RemoteCacheOpenAnyService.java | 52 + .../link/api/RemoteDeviceActionService.java | 5 +- .../domain/cache/device/DeviceCacheVO.java | 144 ++- .../domain/cache/product/ProductCacheVO.java | 116 +- .../enumeration/EmpowermentStatusEnum.java | 63 + .../enumeration/EmpowermentTypeEnum.java | 72 ++ .../vo/result/EmpowermentRecordResultVO.java | 101 ++ .../product/entity/ProductProperties.java | 13 +- .../product/enumeration/ProtocolTypeEnum.java | 54 + .../domain/product/model/ProductModel.java | 1 + .../api/domain/product/model/Properties.java | 3 +- .../api/domain/product/model/Services.java | 1 + .../vo/param/ProductCommandParamVO.java | 7 + .../param/ProductCommandRequestParamVO.java | 7 + .../param/ProductCommandResponseParamVO.java | 7 + .../product/vo/param/ProductParamVO.java | 81 ++ .../vo/param/ProductPropertyParamVO.java | 7 + .../vo/param/ProductServiceParamVO.java | 20 +- .../RemoteCacheOpenAnyFallbackFactory.java | 46 + .../main/resources/META-INF/spring.factories | 3 +- .../tdengine/api/RemoteTdEngineService.java | 164 +-- .../tdengine/api}/constant/TdsConstants.java | 2 +- .../tdengine/api/domain/TableDto.java | 36 - .../RemoteTdEngineFallbackFactory.java | 83 +- .../tdengine/api}/utils/TdsUtils.java | 2 +- .../auth/ThingLinksAuthApplication.java | 25 +- .../common/core/constant/CacheConstants.java | 18 +- .../common/core/constant/Constants.java | 12 + .../core/exception/ArgumentException.java | 38 + .../core/exception/BaseCheckedException.java | 48 + .../exception/BaseUncheckedException.java | 63 + .../common/core/utils/ArgumentAssert.java | 1108 +++++++++++++++++ .../thinglinks/common/core/utils/StrPool.java | 141 +++ .../gateway/ThingLinksGatewayApplication.java | 25 +- .../thinglinks-modules-broker/pom.xml | 42 +- .../broker/ThingLinksBrokerApplication.java | 15 +- .../common/asyncthread/BrokerAsyncConfig.java | 61 + .../kafka/KafkaProducerService.java | 2 +- .../kafka/KafkaSendResultHandler.java | 2 +- .../MqttMessageKafkaConsumerHandler.java | 67 +- .../kafka/MyKafkaListenerErrorHandler.java | 2 +- .../MqttMessageRocketmqConsumerHandler.java | 82 ++ .../mqs/{ => mqtt}/event/MqttCloseEvent.java | 2 +- .../{ => mqtt}/event/MqttConnectEvent.java | 2 +- .../{ => mqtt}/event/MqttDisconnectEvent.java | 2 +- .../mqs/{ => mqtt}/event/MqttPingEvent.java | 2 +- .../{ => mqtt}/event/MqttPublishEvent.java | 2 +- .../{ => mqtt}/event/MqttSubscribeEvent.java | 2 +- .../event/MqttUnsubscribeEvent.java | 2 +- .../listener/MqttCloseEventListener.java | 4 +- .../listener/MqttConnectEventListener.java | 4 +- .../listener/MqttDisconnectEventListener.java | 4 +- .../event/listener/MqttPingEventListener.java | 4 +- .../listener/MqttPublishEventListener.java | 4 +- .../listener/MqttSubscribeEventListener.java | 4 +- .../MqttUnsubscribeEventListener.java | 4 +- .../event/publisher/MqttEventPublisher.java | 4 +- .../mqs/mqtt/handler/AddSubDeviceHandler.java | 6 +- .../mqtt/handler/CommandResponseHandler.java | 7 +- .../mqtt/handler/DeleteSubDeviceHandler.java | 6 +- .../mqs/mqtt/handler/DeviceDatasHandler.java | 10 +- .../handler/OtaCommandResponseHandler.java | 6 +- .../mqs/mqtt/handler/QueryDeviceHandler.java | 6 +- .../mqs/mqtt/handler/SecretKeyHandler.java | 7 +- .../mqtt/handler/UpdateSubDeviceHandler.java | 6 +- .../factory/AbstractMessageHandler.java | 69 +- .../mqtt/service/MqttEventActionService.java | 4 +- .../mqs/protocol/ProtocolHandlerFactory.java | 63 + .../event/listener/HttpEventListener.java | 46 + .../event/listener/MqttEventListener.java | 102 ++ .../event/listener/TcpEventListener.java | 46 + .../listener/WebSocketEventListener.java | 47 + .../ProtocolMessageEventPublisher.java | 68 + .../mqs/protocol/handler/HttpHandler.java | 53 + .../mqs/protocol/handler/MqttHandler.java | 53 + .../mqs/protocol/handler/ProtocolHandler.java | 41 + .../mqs/protocol/handler/TcpHandler.java | 53 + .../protocol/handler/WebSocketHandler.java | 53 + .../broker/websocket/LoggingWSServer.java | 146 --- .../broker/websocket/MyEndpointConfigure.java | 26 - .../broker/websocket/WebSocketConfig.java | 30 - .../src/main/resources/bootstrap.yml | 4 +- .../file/ThingLinksFileApplication.java | 25 +- .../gen/ThingLinksGenApplication.java | 23 +- .../job/ThingLinksJobApplication.java | 24 +- ...InfoTask.java => CacheDeviceInfoTask.java} | 23 +- .../job/task/link/CacheDeviceTask.java | 51 + .../job/task/link/CacheProductModelTask.java | 51 + .../job/task/link/CacheProductTask.java | 51 + .../link/common/cache/CacheSuperAbstract.java | 2 +- .../common/cache/helper/CacheDataHelper.java | 14 +- .../cache/service/DeviceCacheService.java | 21 +- .../cache/service/ProductCacheService.java | 13 +- .../service/ProductModelCacheService.java | 25 +- .../link/common/init/InitDataBase.java | 44 - .../listener/RedisKeyExpirationListener.java | 4 +- .../cache/CacheOpenAnyController.java | 100 ++ .../device/DeviceActionController.java | 2 - .../controller/device/DeviceController.java | 2 +- .../device/DeviceInfoController.java | 13 - .../ota/OtaUpgradeTasksController.java | 35 +- .../controller/ota/OtaUpgradesController.java | 39 +- .../controller/product/ProductController.java | 37 +- .../mapper/product/ProductCommandsMapper.java | 2 + .../ProductCommandsRequestsMapper.java | 3 + .../ProductCommandsResponseMapper.java | 7 +- .../link/mapper/product/ProductMapper.java | 6 +- .../product/ProductPropertiesMapper.java | 3 + .../device/impl/DeviceActionServiceImpl.java | 2 +- .../device/impl/DeviceDatasServiceImpl.java | 24 +- .../device/impl/DeviceInfoServiceImpl.java | 8 +- .../device/impl/DeviceServiceImpl.java | 121 +- .../service/ota/OtaUpgradeTasksService.java | 7 +- .../link/service/ota/OtaUpgradesService.java | 5 +- .../ota/impl/OtaUpgradeTasksServiceImpl.java | 7 +- .../ota/impl/OtaUpgradesServiceImpl.java | 5 +- .../ProductCommandsRequestsService.java | 3 + .../ProductCommandsResponseService.java | 3 + .../product/ProductCommandsService.java | 5 +- .../product/ProductPropertiesService.java | 9 +- .../link/service/product/ProductService.java | 46 +- .../ProductCommandsRequestsServiceImpl.java | 5 + .../ProductCommandsResponseServiceImpl.java | 5 + .../impl/ProductCommandsServiceImpl.java | 5 + .../impl/ProductPropertiesServiceImpl.java | 5 + .../product/impl/ProductServiceImpl.java | 549 +++++--- .../protocol/impl/ProtocolServiceImpl.java | 6 +- .../link/product/ProductCommandsMapper.xml | 18 +- .../product/ProductCommandsRequestsMapper.xml | 16 + .../product/ProductCommandsResponseMapper.xml | 113 +- .../mapper/link/product/ProductMapper.xml | 22 +- .../link/product/ProductPropertiesMapper.xml | 231 ++-- .../link/product/ProductServicesMapper.xml | 2 +- ...ThingLinksProtocolAnalysisApplication.java | 19 +- .../rule/ThingLinksRuleApplication.java | 15 +- .../RuleTriggerMessageRocketmqConsumer.java | 6 + .../rule/controller/RuleController.java | 5 +- .../impl/RuleDeviceLinkageServiceImpl.java | 14 +- .../system/ThingLinksSystemApplication.java | 24 +- .../thinglinks-modules-tdengine/pom.xml | 219 ++-- .../ThingLinksTdengineApplication.java | 19 +- ...eateSuperTableMessageRocketmqConsumer.java | 57 - .../tdengine/common/init/InitDataBase.java | 51 - .../controller/TdEngineController.java | 429 ++----- ...ProductSuperTableCreateOrUpdateMapper.java | 24 - .../tdengine/mapper/TdEngineMapper.java | 54 +- ...roductSuperTableCreateOrUpdateService.java | 40 - .../tdengine/service/TdEngineService.java | 48 +- ...ctSuperTableCreateOrUpdateServiceImpl.java | 45 - .../service/impl/TdEngineServiceImpl.java | 228 +--- .../src/main/resources/bootstrap.yml | 4 +- .../ProductSuperTableCreateOrUpdateMapper.xml | 30 - .../main/resources/mapper/TdEngineMapper.xml | 328 +---- thinglinks-ui/src/api/link/deviceInfo.js | 7 - thinglinks-ui/src/api/link/product/product.js | 7 +- .../src/views/link/deviceInfo/index.vue | 28 - .../src/views/link/product/index.vue | 44 +- .../views/link/product/properties/index.vue | 39 +- 167 files changed, 5125 insertions(+), 2585 deletions(-) create mode 100644 thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/entity/MqttMessageEvent.java rename thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/entity/{MqttEvent.java => MqttProtocolEvent.java} (67%) create mode 100644 thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/HttpEvent.java create mode 100644 thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/MqttEvent.java create mode 100644 thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/ProtocolEvent.java create mode 100644 thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/TcpEvent.java create mode 100644 thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/WebSocketEvent.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteCacheOpenAnyService.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/empowerment/enumeration/EmpowermentStatusEnum.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/empowerment/enumeration/EmpowermentTypeEnum.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/empowerment/vo/result/EmpowermentRecordResultVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/enumeration/ProtocolTypeEnum.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductParamVO.java create mode 100644 thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteCacheOpenAnyFallbackFactory.java rename {thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common => thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api}/constant/TdsConstants.java (90%) delete mode 100644 thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/TableDto.java rename {thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine => thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api}/utils/TdsUtils.java (99%) create mode 100755 thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/exception/ArgumentException.java create mode 100755 thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/exception/BaseCheckedException.java create mode 100755 thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/exception/BaseUncheckedException.java create mode 100755 thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/ArgumentAssert.java create mode 100755 thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/StrPool.java rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{handler => consumer}/kafka/KafkaProducerService.java (96%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{handler => consumer}/kafka/KafkaSendResultHandler.java (94%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{handler => consumer}/kafka/MqttMessageKafkaConsumerHandler.java (52%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{handler => consumer}/kafka/MyKafkaListenerErrorHandler.java (95%) create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/consumer/rocketmq/MqttMessageRocketmqConsumerHandler.java rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{ => mqtt}/event/MqttCloseEvent.java (93%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{ => mqtt}/event/MqttConnectEvent.java (93%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{ => mqtt}/event/MqttDisconnectEvent.java (93%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{ => mqtt}/event/MqttPingEvent.java (93%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{ => mqtt}/event/MqttPublishEvent.java (93%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{ => mqtt}/event/MqttSubscribeEvent.java (93%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{ => mqtt}/event/MqttUnsubscribeEvent.java (93%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{ => mqtt}/event/listener/MqttCloseEventListener.java (95%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{ => mqtt}/event/listener/MqttConnectEventListener.java (95%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{ => mqtt}/event/listener/MqttDisconnectEventListener.java (95%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{ => mqtt}/event/listener/MqttPingEventListener.java (85%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{ => mqtt}/event/listener/MqttPublishEventListener.java (93%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{ => mqtt}/event/listener/MqttSubscribeEventListener.java (90%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{ => mqtt}/event/listener/MqttUnsubscribeEventListener.java (90%) rename thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/{ => mqtt}/event/publisher/MqttEventPublisher.java (95%) create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/ProtocolHandlerFactory.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/listener/HttpEventListener.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/listener/MqttEventListener.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/listener/TcpEventListener.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/listener/WebSocketEventListener.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/publisher/ProtocolMessageEventPublisher.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/HttpHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/MqttHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/ProtocolHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/TcpHandler.java create mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/WebSocketHandler.java delete mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/websocket/LoggingWSServer.java delete mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/websocket/MyEndpointConfigure.java delete mode 100644 thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/websocket/WebSocketConfig.java rename thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/{DeviceInfoTask.java => CacheDeviceInfoTask.java} (55%) create mode 100644 thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/CacheDeviceTask.java create mode 100644 thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/CacheProductModelTask.java create mode 100644 thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/CacheProductTask.java delete mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/init/InitDataBase.java create mode 100644 thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/cache/CacheOpenAnyController.java delete mode 100644 thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/consumer/rocketmq/ProductCreateSuperTableMessageRocketmqConsumer.java delete mode 100644 thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/init/InitDataBase.java delete mode 100644 thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/mapper/ProductSuperTableCreateOrUpdateMapper.java delete mode 100644 thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/ProductSuperTableCreateOrUpdateService.java delete mode 100644 thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/impl/ProductSuperTableCreateOrUpdateServiceImpl.java delete mode 100644 thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/mapper/ProductSuperTableCreateOrUpdateMapper.xml diff --git a/doc/sql/changeRecord/1.2.0.RELEASE.sql b/doc/sql/changeRecord/1.2.0.RELEASE.sql index 1d946b3e..e87a4f5b 100644 --- a/doc/sql/changeRecord/1.2.0.RELEASE.sql +++ b/doc/sql/changeRecord/1.2.0.RELEASE.sql @@ -12,6 +12,17 @@ ALTER TABLE device ADD device_sdk_version varchar(255) CHARACTER SET utf8mb4 COL ALTER TABLE product_services MODIFY COLUMN service_name varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '服务名称'; ALTER TABLE product_services ADD service_code varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NOT NULL COMMENT '服务编码:支持英文大小写、数字、下划线和中划线'; +UPDATE product_services SET service_code = service_name; + + +#产品属性 +ALTER TABLE product_properties ADD property_code varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NOT NULL COMMENT '属性编码'; +ALTER TABLE product_properties CHANGE name property_name varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '指示属性名称。'; + +UPDATE product_properties SET property_code = property_name; + + + diff --git a/doc/sql/thinglinks.sql b/doc/sql/thinglinks.sql index e44a0dc7..2929d21f 100644 --- a/doc/sql/thinglinks.sql +++ b/doc/sql/thinglinks.sql @@ -1821,7 +1821,8 @@ DROP TABLE IF EXISTS `product_properties`; CREATE TABLE `product_properties` ( `id` bigint(19) NOT NULL AUTO_INCREMENT COMMENT '属性id', - `name` varchar(255) NOT NULL COMMENT '指示属性名称。', + `property_name` varchar(255) NOT NULL COMMENT '指示属性名称。', + `property_code` varchar(255) CHARACTER SET utf8mb4 NOT NULL DEFAULT '' COMMENT '属性编码', `service_id` bigint(19) NOT NULL COMMENT '服务ID', `datatype` varchar(255) NOT NULL COMMENT '指示数据类型:取值范围:string、int、decimal(float和double都可以使用此类型)、DateTime、jsonObject上报数据时,复杂类型数据格式如下:\r\n•DateTime:yyyyMMdd’T’HHmmss’Z’如:20151212T121212Z•jsonObject:自定义json结构体,平台不理解只透传\r\n', `description` varchar(255) DEFAULT NULL COMMENT '属性描述,不影响实际功能,可配置为空字符串""。', diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/entity/MqttMessageEvent.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/entity/MqttMessageEvent.java new file mode 100644 index 00000000..817493da --- /dev/null +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/entity/MqttMessageEvent.java @@ -0,0 +1,76 @@ +package com.mqttsnet.thinglinks.broker.api.domain.entity; + +import lombok.Getter; +import org.springframework.context.ApplicationEvent; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: MqttMessageEvent + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-04-28 14:42 + **/ +@Getter +public class MqttMessageEvent extends ApplicationEvent { + private final String topic; + private final String qos; + private final String message; + private final String time; + + public MqttMessageEvent(Object source, String topic, String qos, String message, String time) { + super(source); + this.topic = topic; + this.qos = qos; + this.message = message; + this.time = time; + } + + + public class AddSubDeviceEvent extends MqttMessageEvent { + public AddSubDeviceEvent(Object source, String topic, String qos, String body, String time) { + super(source, topic, qos, body, time); + } + } + + public class AddSubDeviceResponseEvent extends MqttMessageEvent { + public AddSubDeviceResponseEvent(Object source, String topic, String qos, String body, String time) { + super(source, topic, qos, body, time); + } + } + + public class DeviceStatusEvent extends MqttMessageEvent { + public DeviceStatusEvent(Object source, String topic, String qos, String body, String time) { + super(source, topic, qos, body, time); + } + } + + public class DeviceStatusResponseEvent extends MqttMessageEvent { + public DeviceStatusResponseEvent(Object source, String topic, String qos, String body, String time) { + super(source, topic, qos, body, time); + } + } + + public class DeviceControlEvent extends MqttMessageEvent { + public DeviceControlEvent(Object source, String topic, String qos, String body, String time) { + super(source, topic, qos, body, time); + } + } + + public class DeviceControlResponseEvent extends MqttMessageEvent { + public DeviceControlResponseEvent(Object source, String topic, String qos, String body, String time) { + super(source, topic, qos, body, time); + } + } + + public class DeviceDataReportEvent extends MqttMessageEvent { + public DeviceDataReportEvent(Object source, String topic, String qos, String body, String time) { + super(source, topic, qos, body, time); + } + } + + public class DeviceDataReportResponseEvent extends MqttMessageEvent { + public DeviceDataReportResponseEvent(Object source, String topic, String qos, String body, String time) { + super(source, topic, qos, body, time); + } + } +} diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/entity/MqttEvent.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/entity/MqttProtocolEvent.java similarity index 67% rename from thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/entity/MqttEvent.java rename to thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/entity/MqttProtocolEvent.java index cfb719cd..60903477 100644 --- a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/entity/MqttEvent.java +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/entity/MqttProtocolEvent.java @@ -4,18 +4,18 @@ import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; /** - * @program: thinglinks - * @description: MQTT事件类 - * @packagename: com.mqttsnet.thinglinks.broker.api.domain.entity + * @program: thinglinks-cloud-pro-datasource-column + * @description: MQTT协议事件类 + * @packagename: com.mqttsnet.thinglinks.mqtt.entity * @author: ShiHuan Sun * @e-mainl: 13733918655@163.com * @date: 2023-04-28 00:10 **/ -public class MqttEvent { +public class MqttProtocolEvent { private final MqttEventEnum eventEnum; private final String message; - public MqttEvent(MqttEventEnum eventEnum, String message) { + public MqttProtocolEvent(MqttEventEnum eventEnum, String message) { this.eventEnum = eventEnum; this.message = message; } diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/HttpEvent.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/HttpEvent.java new file mode 100644 index 00000000..6c4da7cd --- /dev/null +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/HttpEvent.java @@ -0,0 +1,26 @@ +package com.mqttsnet.thinglinks.broker.api.domain.protocol; + +/** + * ----------------------------------------------------------------------------- + * File Name: HttpEvent + * ----------------------------------------------------------------------------- + * Description: + * HTTP事件 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/11 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/11 15:05 + */ +public class HttpEvent extends ProtocolEvent { + public HttpEvent(Object source, String message) { + super(source, message); + } +} diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/MqttEvent.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/MqttEvent.java new file mode 100644 index 00000000..e702920c --- /dev/null +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/MqttEvent.java @@ -0,0 +1,26 @@ +package com.mqttsnet.thinglinks.broker.api.domain.protocol; + +/** + * ----------------------------------------------------------------------------- + * File Name: MqttEvent + * ----------------------------------------------------------------------------- + * Description: + * MQTT事件 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/11 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/11 15:05 + */ +public class MqttEvent extends ProtocolEvent { + public MqttEvent(Object source, String message) { + super(source, message); + } +} diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/ProtocolEvent.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/ProtocolEvent.java new file mode 100644 index 00000000..0a3937cd --- /dev/null +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/ProtocolEvent.java @@ -0,0 +1,35 @@ +package com.mqttsnet.thinglinks.broker.api.domain.protocol; + +import org.springframework.context.ApplicationEvent; + +/** + * ----------------------------------------------------------------------------- + * File Name: ProtocolEvent + * ----------------------------------------------------------------------------- + * Description: + * 协议事件类 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/11 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/11 15:03 + */ +public class ProtocolEvent extends ApplicationEvent { + private final String message; + + public ProtocolEvent(Object source, String message) { + super(source); + this.message = message; + } + + public String getMessage() { + return message; + } +} diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/TcpEvent.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/TcpEvent.java new file mode 100644 index 00000000..1ef36d96 --- /dev/null +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/TcpEvent.java @@ -0,0 +1,26 @@ +package com.mqttsnet.thinglinks.broker.api.domain.protocol; + +/** + * ----------------------------------------------------------------------------- + * File Name: TcpEvent + * ----------------------------------------------------------------------------- + * Description: + * Tcp事件 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/11 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/11 15:10 + */ +public class TcpEvent extends ProtocolEvent { + public TcpEvent(Object source, String message) { + super(source, message); + } +} \ No newline at end of file diff --git a/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/WebSocketEvent.java b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/WebSocketEvent.java new file mode 100644 index 00000000..21120b7a --- /dev/null +++ b/thinglinks-api/thinglinks-api-broker/src/main/java/com/mqttsnet/thinglinks/broker/api/domain/protocol/WebSocketEvent.java @@ -0,0 +1,26 @@ +package com.mqttsnet.thinglinks.broker.api.domain.protocol; + +/** + * ----------------------------------------------------------------------------- + * File Name: WebSocketEvent + * ----------------------------------------------------------------------------- + * Description: + * WebSocket事件 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/11 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/11 15:06 + */ +public class WebSocketEvent extends ProtocolEvent { + public WebSocketEvent(Object source, String message) { + super(source, message); + } +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteCacheOpenAnyService.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteCacheOpenAnyService.java new file mode 100644 index 00000000..e7d770e0 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteCacheOpenAnyService.java @@ -0,0 +1,52 @@ + + +package com.mqttsnet.thinglinks.link.api; + +import com.mqttsnet.thinglinks.common.core.constant.ServiceNameConstants; +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.link.api.factory.RemoteCacheOpenAnyFallbackFactory; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; + +/** + * 缓存开放服务 + * + * @author thinglinks + */ +@FeignClient(contextId = "remoteCacheOpenService", value = ServiceNameConstants.THINGLINKS_LINK, fallbackFactory = RemoteCacheOpenAnyFallbackFactory.class, path = "/dataOperation") +public interface RemoteCacheOpenAnyService { + + /** + * Refreshes the cache for all devices within a tenant. + * + * @return Response indicating the operation was successful. + */ + @GetMapping("/refreshAllDeviceCaches") + R refreshAllDeviceCaches(); + + /** + * Refreshes the cache for sub devices within a tenant. + * + * @return Response indicating the operation was successful. + */ + @GetMapping("/refreshAllDeviceInfoCaches") + R refreshAllDeviceInfoCaches(); + + /** + * Refreshes the cache for all products within a tenant. + * + * @return Response indicating the operation was successful. + */ + @GetMapping("/refreshAllProductCaches") + R refreshAllProductCaches(); + + /** + * Refreshes the cache for all product models within a tenant. + * + * @return Response indicating the operation was successful. + */ + @GetMapping("/refreshAllProductModelCaches") + R refreshAllProductModelCaches(); + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceActionService.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceActionService.java index b2387edc..d36a66a8 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceActionService.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/RemoteDeviceActionService.java @@ -5,7 +5,8 @@ import com.mqttsnet.thinglinks.link.api.domain.device.entity.DeviceAction; import com.mqttsnet.thinglinks.link.api.factory.RemoteDeviceActionFallbackFactory; import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; /** * 设备动作服务 @@ -21,6 +22,6 @@ public interface RemoteDeviceActionService { * @param mqttsDeviceAction * @return */ - @PostMapping("/device/action/add") + @PostMapping("/action") public R add(@RequestBody DeviceAction mqttsDeviceAction); } diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/device/DeviceCacheVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/device/DeviceCacheVO.java index 6d8f2a54..36f8b737 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/device/DeviceCacheVO.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/device/DeviceCacheVO.java @@ -2,7 +2,6 @@ import cn.hutool.core.map.MapUtil; import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductCacheVO; -import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.*; @@ -26,11 +25,152 @@ @Accessors(chain = true) @EqualsAndHashCode(callSuper = false) @ApiModel(value = "DeviceCacheVO", description = "设备档案缓存VO") -public class DeviceCacheVO extends Device implements Serializable { +public class DeviceCacheVO implements Serializable { private static final long serialVersionUID = 1L; private Map echoMap = MapUtil.newHashMap(); + + /** + * id + */ + @ApiModelProperty(value = "id") + private Long id; + + /** + * 客户端标识 + */ + @ApiModelProperty(value = "客户端标识") + private String clientId; + + /** + * 用户名 + */ + @ApiModelProperty(value = "用户名") + private String userName; + + /** + * 密码 + */ + @ApiModelProperty(value = "密码") + private String password; + + /** + * 应用ID + */ + @ApiModelProperty(value = "应用ID") + private String appId; + + /** + * 认证方式 + */ + @ApiModelProperty(value = "认证方式") + private String authMode; + + /** + * 设备标识 + */ + @ApiModelProperty(value = "设备标识") + private String deviceIdentification; + + /** + * 设备名称 + */ + @ApiModelProperty(value = "设备名称") + private String deviceName; + + /** + * 连接实例 + */ + @ApiModelProperty(value = "连接实例") + private String connector; + + /** + * 设备描述 + */ + @ApiModelProperty(value = "设备描述") + private String deviceDescription; + + /** + * 设备状态: 启用 || 禁用 + */ + @ApiModelProperty(value = "设备状态: 启用 || 禁用") + private String deviceStatus; + + /** + * 连接状态 : 在线:ONLINE || 离线:OFFLINE || 未连接:INIT + */ + @ApiModelProperty(value = "连接状态 : 在线:ONLINE || 离线:OFFLINE || 未连接:INIT,") + private String connectStatus; + + /** + * 是否遗言 + */ + @ApiModelProperty(value = "是否遗言") + private String isWill; + + /** + * 设备标签 + */ + @ApiModelProperty(value = "设备标签") + private String deviceTags; + + /** + * 产品标识 + */ + @ApiModelProperty(value = "产品标识") + private String productIdentification; + + + /** + * 协议类型 :mqtt || coap || modbus || http + */ + @ApiModelProperty(value = "协议类型 :mqtt || coap || modbus || http") + private String protocolType; + + /** + * 设备类型 + */ + @ApiModelProperty(value = "设备类型") + private String deviceType; + + /** + * 加密密钥 + */ + @ApiModelProperty(value = "加密密钥") + private String encryptKey; + /** + * 加密向量 + */ + @ApiModelProperty(value = "加密向量") + private String encryptVector; + /** + * 签名密钥 + */ + @ApiModelProperty(value = "签名密钥") + private String signKey; + /** + * 传输协议的加密方式:0-明文传输、1-SM4、2-AES + */ + @ApiModelProperty(value = "传输协议的加密方式:0-明文传输、1-SM4、2-AES ") + private String encryptMethod; + + /** + * 软件版本 + */ + @ApiModelProperty(value = "软件版本") + private String swVersion; + /** + * 固件版本 + */ + @ApiModelProperty(value = "固件版本") + private String fwVersion; + /** + * sdk版本 + */ + @ApiModelProperty(value = "sdk版本") + private String deviceSdkVersion; + /** * 设备产品基础信息 */ diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductCacheVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductCacheVO.java index 1349b55b..86826950 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductCacheVO.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/cache/product/ProductCacheVO.java @@ -1,12 +1,13 @@ package com.mqttsnet.thinglinks.link.api.domain.cache.product; import cn.hutool.core.map.MapUtil; -import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import lombok.*; import lombok.experimental.Accessors; import java.io.Serializable; +import java.time.LocalDateTime; import java.util.Map; /** @@ -22,12 +23,121 @@ @AllArgsConstructor @ToString(callSuper = true) @Accessors(chain = true) -@EqualsAndHashCode(callSuper = true) +@EqualsAndHashCode(callSuper = false) @ApiModel(value = "ProductCacheVO", description = "产品模型缓存VO") -public class ProductCacheVO extends Product implements Serializable { +public class ProductCacheVO implements Serializable { private static final long serialVersionUID = 1L; + /** + * id + */ + @ApiModelProperty(value = "id") + private Long id; + + /** + * 应用ID + */ + @ApiModelProperty(value = "应用ID") + private String appId; + + /** + * 产品模版标识 + */ + @ApiModelProperty(value = "产品模版标识") + private String templateIdentification; + + /** + * 产品名称:自定义,支持中文、英文大小写、数字、下划线和中划线 + */ + @ApiModelProperty(value = "产品名称:自定义,支持中文、英文大小写、数字、下划线和中划线") + private String productName; + + /** + * 产品标识 + */ + @ApiModelProperty(value = "产品标识") + private String productIdentification; + + /** + * 支持以下两种产品类型•COMMON:普通产品,需直连设备。 + * •GATEWAY:网关产品,可挂载子设备。 + */ + @ApiModelProperty(value = "支持以下两种产品类型•COMMON:普通产品,需直连设备。,•GATEWAY:网关产品,可挂载子设备。,") + private String productType; + + /** + * 厂商ID:支持英文大小写,数字,下划线和中划线 + */ + @ApiModelProperty(value = "厂商ID:支持英文大小写,数字,下划线和中划线") + private String manufacturerId; + + /** + * 厂商名称 :支持中文、英文大小写、数字、下划线和中划线 + */ + @ApiModelProperty(value = "厂商名称 :支持中文、英文大小写、数字、下划线和中划线") + private String manufacturerName; + + /** + * 产品型号,建议包含字母或数字来保证可扩展性。支持英文大小写、数字、下划线和中划线 + */ + @ApiModelProperty(value = "产品型号,建议包含字母或数字来保证可扩展性。支持英文大小写、数字、下划线和中划线,") + private String model; + + /** + * 数据格式,默认为JSON无需修改。 + */ + @ApiModelProperty(value = "数据格式,默认为JSON无需修改。") + private String dataFormat; + + /** + * 设备类型:支持英文大小写、数字、下划线和中划线 + */ + @ApiModelProperty(value = "设备类型:支持英文大小写、数字、下划线和中划线,") + private String deviceType; + + /** + * 设备接入平台的协议类型,默认为MQTT无需修改。 + */ + @ApiModelProperty(value = "设备接入平台的协议类型,默认为MQTT无需修改。, ") + private String protocolType; + + /** + * 状态(字典值:0启用 1停用) + */ + @ApiModelProperty(value = "状态(字典值:0启用 1停用)") + private String status; + + /** + * 产品描述 + */ + @ApiModelProperty(value = "产品描述") + private String remark; + + /** + * 创建者 + */ + @ApiModelProperty(value = "创建者") + private String createBy; + + /** + * 创建时间 + */ + @ApiModelProperty(value = "创建时间") + private LocalDateTime createTime; + + /** + * 更新者 + */ + @ApiModelProperty(value = "更新者") + private String updateBy; + + /** + * 更新时间 + */ + @ApiModelProperty(value = "更新时间") + private LocalDateTime updateTime; + private Map echoMap = MapUtil.newHashMap(); diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/empowerment/enumeration/EmpowermentStatusEnum.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/empowerment/enumeration/EmpowermentStatusEnum.java new file mode 100644 index 00000000..0319ef43 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/empowerment/enumeration/EmpowermentStatusEnum.java @@ -0,0 +1,63 @@ +package com.mqttsnet.thinglinks.link.api.domain.empowerment.enumeration; + +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.NoArgsConstructor; + +import java.util.Arrays; +import java.util.List; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 赋能状态类型 + * @packagename: com.mqttsnet.thinglinks.empowerment.enumeration + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-09-18 23:38 + **/ +@AllArgsConstructor +@NoArgsConstructor +@ApiModel(value = "EmpowermentStatus", description = "赋能状态类型") +public enum EmpowermentStatusEnum { + + /** + * 计划中 + */ + PLANNING(0, "计划中"), + + /** + * 执行中 + */ + IN_PROGRESS(1, "执行中"), + + /** + * 执行完成 + */ + COMPLETED(2, "执行完成"), + + ; + + private Integer value; + private String desc; + + /** + * 可选值 + */ + public static final List STATE_COLLECTION = Arrays.asList(PLANNING.value, IN_PROGRESS.value, COMPLETED.value); + + public Integer getValue() { + return value; + } + + public void setValue(Integer value) { + this.value = value; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/empowerment/enumeration/EmpowermentTypeEnum.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/empowerment/enumeration/EmpowermentTypeEnum.java new file mode 100644 index 00000000..93f03f21 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/empowerment/enumeration/EmpowermentTypeEnum.java @@ -0,0 +1,72 @@ +package com.mqttsnet.thinglinks.link.api.domain.empowerment.enumeration; + +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.NoArgsConstructor; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** + * @program: thinglinks-cloud-pro-datasource-column + * @description: 赋能类型 + * @packagename: com.mqttsnet.thinglinks.empowerment.enumeration + * @author: ShiHuan Sun + * @e-mainl: 13733918655@163.com + * @date: 2023-09-16 21:50 + **/ +@AllArgsConstructor +@NoArgsConstructor +@ApiModel(value = "EmpowermentTypeEnum", description = "赋能类型") +public enum EmpowermentTypeEnum { + + /** + * 未知 + */ + UNKNOWN(0, "未知"), + + /** + * 产品 + */ + PRODUCT(1, "产品"), + + /** + * 设备 + */ + DEVICE(2, "设备"), + + ; + + private Integer value; + private String desc; + + /** + * 可选值 + */ + public static final List TYPE_COLLECTION = Arrays.asList(UNKNOWN.value, PRODUCT.value, DEVICE.value); + + + public static EmpowermentTypeEnum valueOf(Integer value) { + return Arrays.stream(values()) + .filter(type -> type.getValue().equals(Optional.ofNullable(value).orElse(-1))) // 使用一个不存在的默认值,如-1 + .findFirst() + .orElse(UNKNOWN); // 或者您可以选择返回一个默认的枚举值,比如UNKNOWN + } + + public Integer getValue() { + return value; + } + + public void setValue(Integer value) { + this.value = value; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/empowerment/vo/result/EmpowermentRecordResultVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/empowerment/vo/result/EmpowermentRecordResultVO.java new file mode 100644 index 00000000..e93e0370 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/empowerment/vo/result/EmpowermentRecordResultVO.java @@ -0,0 +1,101 @@ +package com.mqttsnet.thinglinks.link.api.domain.empowerment.vo.result; + +import cn.hutool.core.map.MapUtil; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.time.LocalDateTime; +import java.util.Map; + +/** + *

+ * 表单查询方法返回值VO + * 赋能记录表 + *

+ * + * @author mqttsnet + * @date 2023-09-15 17:20:27 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode(callSuper = false) +@Builder +@ApiModel(value = "EmpowermentRecordResultVO", description = "赋能记录") +public class EmpowermentRecordResultVO implements Serializable { + + private static final long serialVersionUID = 1L; + + private Map echoMap = MapUtil.newHashMap(); + + @ApiModelProperty(value = "id") + private Long id; + + /** + * 应用ID + */ + @ApiModelProperty(value = "应用ID") + private String appId; + /** + * 赋能标识 + */ + @ApiModelProperty(value = "赋能标识") + private String empowermentIdentification; + /** + * 赋能类型 + */ + @ApiModelProperty(value = "赋能类型") + private Integer empowermentType; + /** + * 开始时间 + */ + @ApiModelProperty(value = "开始时间") + private LocalDateTime startTime; + /** + * 结束时间 + */ + @ApiModelProperty(value = "结束时间") + private LocalDateTime endTime; + /** + * 赋能结果 + */ + @ApiModelProperty(value = "赋能结果") + private String outcome; + /** + * 赋能反馈 + */ + @ApiModelProperty(value = "赋能反馈") + private String feedback; + /** + * 状态 + */ + @ApiModelProperty(value = "状态") + private Integer status; + /** + * 版本 + */ + @ApiModelProperty(value = "版本") + private String version; + /** + * 依赖关系 + */ + @ApiModelProperty(value = "依赖关系") + private String dependencies; + /** + * 描述 + */ + @ApiModelProperty(value = "描述") + private String remark; + /** + * 创建人组织 + */ + @ApiModelProperty(value = "创建人组织") + private Long createdOrgId; + + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductProperties.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductProperties.java index dcdda37a..678ac0ed 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductProperties.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/entity/ProductProperties.java @@ -36,10 +36,15 @@ public class ProductProperties extends BaseEntity implements Serializable { private Long id; /** - * 指示属性名称。 - */ - @ApiModelProperty(value="指示属性名称。") - private String name; + * 指示属性编码 + */ + @ApiModelProperty(value = "指示属性编码") + private String propertyCode; + /** + * 指示属性名称 + */ + @ApiModelProperty(value = "指示属性名称") + private String propertyName; /** * 服务ID diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/enumeration/ProtocolTypeEnum.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/enumeration/ProtocolTypeEnum.java new file mode 100644 index 00000000..859cd05d --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/enumeration/ProtocolTypeEnum.java @@ -0,0 +1,54 @@ +package com.mqttsnet.thinglinks.link.api.domain.product.enumeration; + +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.Optional; +import java.util.stream.Stream; + +/** + *

+ * 协议类型 + *

+ * + * @author shihuan sun + * @date 2023-04-14 + */ +@Getter +@AllArgsConstructor +@NoArgsConstructor +@ApiModel(value = "ProtocolTypeEnum", description = "协议类型") +public enum ProtocolTypeEnum { + + /** + * MQTT协议 + */ + MQTT("MQTT", "MQTT协议"), + + HTTP("HTTP", "HTTP协议"), + + TCP("TCP", "TCP协议"), + + WEBSOCKET("WEBSOCKET", "WEBSOCKET协议") + + ; + + private String value; + private String desc; + + public static Optional fromValue(String value) { + return Stream.of(ProtocolTypeEnum.values()) + .filter(e -> e.getValue().equals(value)) + .findFirst(); + } + + public void setValue(String value) { + this.value = value; + } + + public void setDesc(String desc) { + this.desc = desc; + } +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/model/ProductModel.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/model/ProductModel.java index 63ce2506..c7fbf8a1 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/model/ProductModel.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/model/ProductModel.java @@ -13,6 +13,7 @@ * @date 2021-12-23 */ @Data +@Deprecated public class ProductModel { private static final long serialVersionUID = 1L; private Long id; diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/model/Properties.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/model/Properties.java index 69dcfb97..a48239de 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/model/Properties.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/model/Properties.java @@ -22,7 +22,8 @@ public class Properties{ private Integer maxlength; private String method; private Integer min; - private String name; + private String propertyCode; + private String propertyName; private Integer required; private Integer step; private String unit; diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/model/Services.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/model/Services.java index 50a8d6c4..9e999763 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/model/Services.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/model/Services.java @@ -17,6 +17,7 @@ public class Services{ private static final long serialVersionUID = 1L; private Long productId; private String serviceId; + private String serviceCode; private String serviceName; private String description; private List commands; diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandParamVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandParamVO.java index 9d1db60b..097f55da 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandParamVO.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandParamVO.java @@ -32,6 +32,13 @@ public class ProductCommandParamVO implements Serializable { private static final long serialVersionUID = 1L; + /** + * id + */ + @ApiModelProperty(value = "id") + private Long id; + + /** * 服务ID */ diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandRequestParamVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandRequestParamVO.java index d62152d9..c3ce5431 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandRequestParamVO.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandRequestParamVO.java @@ -30,6 +30,13 @@ public class ProductCommandRequestParamVO implements Serializable { private static final long serialVersionUID = 1L; + /** + * id + */ + @ApiModelProperty(value = "id") + private Long id; + + /** * 服务ID diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandResponseParamVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandResponseParamVO.java index ab807ea3..383627ac 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandResponseParamVO.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductCommandResponseParamVO.java @@ -31,6 +31,13 @@ public class ProductCommandResponseParamVO implements Serializable { private static final long serialVersionUID = 1L; + /** + * id + */ + @ApiModelProperty(value = "id") + private Long id; + + /** * 命令ID */ diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductParamVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductParamVO.java new file mode 100644 index 00000000..e4be508f --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductParamVO.java @@ -0,0 +1,81 @@ +package com.mqttsnet.thinglinks.link.api.domain.product.vo.param; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.List; + +/** + *

+ * 表单保存方法VO + * 产品模型 + *

+ * + * @author mqttsnet + * @date 2023-03-14 19:39:59 + */ + +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString(callSuper = true) +@Accessors(chain = true) +@EqualsAndHashCode +@Builder +@ApiModel(value = "ProductParamVO", description = "产品模型参数VO") +public class ProductParamVO implements Serializable { + + /** + * id + */ + @ApiModelProperty(value = "id") + private Long id; + + + + @ApiModelProperty(value = "应用ID") + private String appId; + + @ApiModelProperty(value = "产品标识") + private String productIdentification; + + @ApiModelProperty(value = "模板ID") + private Long templateId; + + @ApiModelProperty(value = "产品名称") + private String productName; + + @ApiModelProperty(value = "产品类型") + private Integer productType; + + @ApiModelProperty(value = "厂商ID") + private String manufacturerId; + + @ApiModelProperty(value = "厂商名称") + private String manufacturerName; + + @ApiModelProperty(value = "产品型号") + private String model; + + @ApiModelProperty(value = "数据格式") + private String dataFormat; + + @ApiModelProperty(value = "设备类型") + private String deviceType; + + @ApiModelProperty(value = "协议类型") + private String protocolType; + + @ApiModelProperty(value = "产品版本") + private String productVersion; + + @ApiModelProperty(value = "产品描述") + private String remark; + + @ApiModelProperty(value = "产品模型服务") + private List services; + +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductPropertyParamVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductPropertyParamVO.java index 65b73052..fa29480a 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductPropertyParamVO.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductPropertyParamVO.java @@ -31,6 +31,13 @@ public class ProductPropertyParamVO implements Serializable { private static final long serialVersionUID = 1L; + /** + * id + */ + @ApiModelProperty(value = "id") + private Long id; + + /** * 服务ID */ diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductServiceParamVO.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductServiceParamVO.java index e511e2ed..e66c6c2b 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductServiceParamVO.java +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/domain/product/vo/param/ProductServiceParamVO.java @@ -33,10 +33,11 @@ public class ProductServiceParamVO implements Serializable { private static final long serialVersionUID = 1L; /** - * 产品ID + * 服务id */ - @ApiModelProperty(value = "产品ID") - private Long productId; + @ApiModelProperty(value = "服务id") + private Long id; + /** * 服务编码:支持英文大小写、数字、下划线和中划线 */ @@ -50,6 +51,19 @@ public class ProductServiceParamVO implements Serializable { @ApiModelProperty(value = "服务名称") @Size(max = 255, message = "服务名称长度不能超过{max}") private String serviceName; + + /** + * 产品模版标识 + */ + @ApiModelProperty(value = "产品模版标识") + private String templateIdentification; + + /** + * 产品标识 + */ + @ApiModelProperty(value = "产品标识") + private String productIdentification; + /** * 服务类型 */ diff --git a/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteCacheOpenAnyFallbackFactory.java b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteCacheOpenAnyFallbackFactory.java new file mode 100644 index 00000000..fdc46b50 --- /dev/null +++ b/thinglinks-api/thinglinks-api-link/src/main/java/com/mqttsnet/thinglinks/link/api/factory/RemoteCacheOpenAnyFallbackFactory.java @@ -0,0 +1,46 @@ + +package com.mqttsnet.thinglinks.link.api.factory; + +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.link.api.RemoteCacheOpenAnyService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.openfeign.FallbackFactory; +import org.springframework.stereotype.Component; + +/** + * 缓存开放服务降级处理 + * + * @author xiaonannet + */ +@Component +public class RemoteCacheOpenAnyFallbackFactory implements FallbackFactory { + private static final Logger log = LoggerFactory.getLogger(RemoteCacheOpenAnyFallbackFactory.class); + + @Override + public RemoteCacheOpenAnyService create(Throwable throwable) { + log.error("缓存开放服务调用失败:{}", throwable.getMessage()); + return new RemoteCacheOpenAnyService() { + + @Override + public R refreshAllDeviceCaches() { + return R.fail("刷新设备缓存失败" + throwable.getMessage()); + } + + @Override + public R refreshAllDeviceInfoCaches() { + return R.fail("刷新子设备信息缓存失败" + throwable.getMessage()); + } + + @Override + public R refreshAllProductCaches() { + return R.fail("刷新产品缓存失败" + throwable.getMessage()); + } + + @Override + public R refreshAllProductModelCaches() { + return R.fail("刷新产品模型缓存失败" + throwable.getMessage()); + } + }; + } +} diff --git a/thinglinks-api/thinglinks-api-link/src/main/resources/META-INF/spring.factories b/thinglinks-api/thinglinks-api-link/src/main/resources/META-INF/spring.factories index 1113b41e..461918f5 100644 --- a/thinglinks-api/thinglinks-api-link/src/main/resources/META-INF/spring.factories +++ b/thinglinks-api/thinglinks-api-link/src/main/resources/META-INF/spring.factories @@ -1,6 +1,7 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.mqttsnet.thinglinks.link.api.factory.RemoteDeviceFallbackFactory,\ - com.mqttsnet.thinglinks.link.api.factory.RemoteDeviceOpenAnyFallbackFactory, \ + com.mqttsnet.thinglinks.link.api.factory.RemoteCacheOpenAnyFallbackFactory, \ + com.mqttsnet.thinglinks.link.api.factory.RemoteDeviceOpenAnyFallbackFactory, \ com.mqttsnet.thinglinks.link.api.factory.RemoteDeviceActionFallbackFactory, \ com.mqttsnet.thinglinks.link.api.factory.RemoteDeviceDatasFallbackFactory, \ com.mqttsnet.thinglinks.link.api.factory.RemoteProtocolFallbackFactory,\ diff --git a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/RemoteTdEngineService.java b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/RemoteTdEngineService.java index 3f0b053e..65ad041f 100644 --- a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/RemoteTdEngineService.java +++ b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/RemoteTdEngineService.java @@ -11,9 +11,12 @@ import cn.hutool.json.JSONObject; import com.mqttsnet.thinglinks.common.core.constant.ServiceNameConstants; import com.mqttsnet.thinglinks.common.core.domain.R; -import com.mqttsnet.thinglinks.tdengine.api.domain.*; +import com.mqttsnet.thinglinks.tdengine.api.domain.SelectDto; +import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDescribeVO; +import com.mqttsnet.thinglinks.tdengine.api.domain.TagsSelectDao; import com.mqttsnet.thinglinks.tdengine.api.domain.model.SuperTableDTO; import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TagsSelectDTO; import com.mqttsnet.thinglinks.tdengine.api.factory.RemoteTdEngineFallbackFactory; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @@ -27,105 +30,17 @@ import java.util.List; import java.util.Map; -@FeignClient(contextId = "remoteTdEngineService", value = ServiceNameConstants.THINGLINKS_TDENGINE, fallbackFactory = RemoteTdEngineFallbackFactory.class) +@FeignClient(contextId = "remoteTdEngineService", value = ServiceNameConstants.THINGLINKS_TDENGINE, fallbackFactory = RemoteTdEngineFallbackFactory.class, path = "/dataOperation") public interface RemoteTdEngineService { - /** - * @param databaseName 数据库名称 - * @return R - * @MethodDescription 创建tdEngine数据库 - * @author thinglinks - * @Date 2021/12/31 11:05 - */ - @PostMapping("/dataOperation/createDb") - R createDataBase(@RequestParam("databaseName") String databaseName); - - /** - * @param superTableDto 创建超级表需要的入参的实体类 - * @return R - * @MethodDescription 创建超级表 - * @author thinglinks - * @Date 2021/12/27 11:05 - */ - @PostMapping("/dataOperation/createSTb") - R createSuperTable(@Validated @RequestBody SuperTableDto superTableDto); - - /** - * @param tableDto 创建超级表的子表需要的入参的实体类 - * @return R - * @MethodDescription 创建超级表的子表 - * @author thinglinks - * @Date 2021/12/27 11:06 - */ - @PostMapping("/dataOperation/createTb") - R createTable(@Validated @RequestBody TableDto tableDto); - - /** - * @param tableDto 插入数据需要的入参的实体类 - * @return R - * @MethodDescription 插入数据 - * @author thinglinks - * @Date 2022/1/10 14:44 - */ - @PostMapping("/dataOperation/insertData") - R insertData(@Validated @RequestBody TableDto tableDto); - - @PostMapping("/dataOperation/addColumnInStb") - R addColumnInStb(@RequestBody SuperTableDto superTableDto); - - /** - * @param selectDto 查询数据需要的入参的实体类 - * @return R - * @MethodDescription 根据时间戳查询数据 - * @author thinglinks - * @Date 2022/1/10 14:44 - */ - @PostMapping("/dataOperation/getDataByTimestamp") - R getDataByTimestamp(@Validated @RequestBody SelectDto selectDto); - - /** - * @param selectDto - * @return - * @MethodDescription 查询最新数据 - */ - @PostMapping("/dataOperation/getLastData") - R getLastData(@Validated @RequestBody SelectDto selectDto); - - /** - * 查询最新的数据带标签 - * - * @param tagsSelectDao - * @return - */ - @PostMapping("/dataOperation/getLastDataByTags") - public R>> getLastDataByTags(@Validated @RequestBody TagsSelectDao tagsSelectDao); - - /** - * 添加列字段 - * - * @param superTableDto - * @return - */ - @PostMapping("/dataOperation/addColumnInStb") - R addColumnForSuperTable(@RequestBody SuperTableDto superTableDto); - - /** - * 删除列字段 - * - * @param superTableDto - * @return - */ - @PostMapping("/dataOperation/dropColumnInStb") - R dropColumnForSuperTable(@RequestBody SuperTableDto superTableDto); - /** * 创建时序数据库 * * @param dataBaseName 数据库名称 * @return 执行结果 */ - @PostMapping("/dataOperation/createDatabase") - public R createDatabase(@RequestParam String dataBaseName); + @PostMapping("/createDatabase") + public R createDatabase(@RequestParam(name = "dataBaseName") String dataBaseName); /** * 创建超级表 @@ -133,8 +48,8 @@ public interface RemoteTdEngineService { * @param superTableName 超级表名称 * @return 执行结果 */ - @PostMapping("/dataOperation/createSuperTable") - public R createSuperTable(@RequestParam String superTableName); + @PostMapping("/createSuperTable") + public R createSuperTable(@RequestParam(name = "superTableName") String superTableName); /** * 创建超级表及字段 @@ -142,7 +57,7 @@ public interface RemoteTdEngineService { * @param superTableDTO 超级表信息 * @return 执行结果 */ - @PostMapping("/dataOperation/createSuperTableAndColumn") + @PostMapping("/createSuperTableAndColumn") public R createSuperTableAndColumn(@RequestBody SuperTableDTO superTableDTO); /** @@ -151,7 +66,7 @@ public interface RemoteTdEngineService { * @param object 超级表json信息 * @return 执行结果 */ - @PostMapping("/dataOperation/createSuperTableAndColumnTwo") + @PostMapping("/createSuperTableAndColumnTwo") public R createSuperTableAndColumnTwo(@RequestBody JSONObject object); /** @@ -160,7 +75,7 @@ public interface RemoteTdEngineService { * @param tableDTO 子表信息 * @return 执行结果 */ - @PostMapping("/dataOperation/createSubTable") + @PostMapping("/createSubTable") public R createSubTable(@RequestBody TableDTO tableDTO); /** @@ -169,7 +84,7 @@ public interface RemoteTdEngineService { * @param object 子表json信息 * @return 执行结果 */ - @PostMapping("/dataOperation/createSubTableTwo") + @PostMapping("/createSubTableTwo") public R createSubTableTwo(@RequestBody JSONObject object); /** @@ -178,8 +93,8 @@ public interface RemoteTdEngineService { * @param superTableName * @return */ - @PostMapping("/dataOperation/dropSuperTable") - public R dropSuperTable(@RequestParam String superTableName); + @PostMapping("/dropSuperTable") + public R dropSuperTable(@RequestParam(value = "superTableName") String superTableName); /** * 超级表新增字段 @@ -187,7 +102,7 @@ public interface RemoteTdEngineService { * @param superTableDTO 数据信息 * @return 执行结果 */ - @PostMapping("/dataOperation/alterSuperTableColumn") + @PostMapping("/alterSuperTableColumn") public R alterSuperTableColumn(@RequestBody SuperTableDTO superTableDTO); /** @@ -196,7 +111,7 @@ public interface RemoteTdEngineService { * @param superTableDTO 数据信息 * @return 执行结果 */ - @PostMapping("/dataOperation/dropSuperTableColumn") + @PostMapping("/dropSuperTableColumn") public R dropSuperTableColumn(@RequestBody SuperTableDTO superTableDTO); /** @@ -205,7 +120,7 @@ public interface RemoteTdEngineService { * @param superTableDTO 数据信息 * @return 执行结果 */ - @PostMapping("/dataOperation/alterSuperTableTag") + @PostMapping("/alterSuperTableTag") public R alterSuperTableTag(@RequestBody SuperTableDTO superTableDTO); /** @@ -214,7 +129,7 @@ public interface RemoteTdEngineService { * @param superTableDTO 数据信息 * @return 执行结果 */ - @PostMapping("/dataOperation/dropSuperTableTag") + @PostMapping("/dropSuperTableTag") public R dropSuperTableTag(@RequestBody SuperTableDTO superTableDTO); /** @@ -225,8 +140,8 @@ public interface RemoteTdEngineService { * @param newName * @return */ - @PostMapping("/dataOperation/alterSuperTableTagRename") - public R alterSuperTableTagRename(@RequestParam String superTableName, @RequestParam String oldName, @RequestParam String newName); + @PostMapping("/alterSuperTableTagRename") + public R alterSuperTableTagRename(@RequestParam(value = "superTableName") String superTableName, @RequestParam(value = "oldName") String oldName, @RequestParam(value = "newName") String newName); /** @@ -235,7 +150,7 @@ public interface RemoteTdEngineService { * @param tableName * @return */ - @GetMapping("/dataOperation/describeSuperOrSubTable") + @GetMapping("/describeSuperOrSubTable") public R> describeSuperOrSubTable(@RequestParam(value = "tableName") String tableName); /** @@ -244,7 +159,7 @@ public interface RemoteTdEngineService { * @param tableDTO 数据信息 * @return 执行结果 */ - @PostMapping("/dataOperation/insertTableData") + @PostMapping("/insertTableData") public R insertTableData(@RequestBody TableDTO tableDTO); @@ -258,10 +173,41 @@ public interface RemoteTdEngineService { * @return {@link R>>} The query result. */ @ApiOperation(value = "Query Data from a Regular Table Within a Time Range", notes = "Fetches data within the specified time range if both start and end times are provided; otherwise, retrieves the latest record.") - @GetMapping("/dataOperation/getDataInRangeOrLastRecord") + @GetMapping("/getDataInRangeOrLastRecord") public R>> getDataInRangeOrLastRecord( @ApiParam(value = "Name of the regular table", required = true) @RequestParam(value = "tableName") String tableName, @ApiParam(value = "Start time for the query", example = "1634572800000", required = false) @RequestParam(value = "startTime", required = false) Long startTime, @ApiParam(value = "End time for the query", example = "1634659200000", required = false) @RequestParam(value = "endTime", required = false) Long endTime); + + /** + * @param selectDto 查询数据需要的入参的实体类 + * @return R + * @MethodDescription 根据时间戳查询数据 + * @author thinglinks + * @Date 2022/1/10 14:44 + */ + @PostMapping("/getDataByTimestamp") + R getDataByTimestamp(@Validated @RequestBody SelectDto selectDto); + + /** + * @param selectDto + * @return + * @MethodDescription 查询最新数据 + */ + @PostMapping("/getLastData") + R getLastData(@Validated @RequestBody SelectDto selectDto); + + + /** + * 查询最新的数据带标签 + * + * @param tagsSelectDao + * @return + */ + @PostMapping("/getLastDataByTags") + public R>> getLastDataByTags(@Validated @RequestBody TagsSelectDTO tagsSelectDao); + + + } diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/constant/TdsConstants.java b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/constant/TdsConstants.java similarity index 90% rename from thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/constant/TdsConstants.java rename to thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/constant/TdsConstants.java index 03faed1b..9f93058c 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/constant/TdsConstants.java +++ b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/constant/TdsConstants.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.tdengine.common.constant; +package com.mqttsnet.thinglinks.tdengine.api.constant; /** * 全局基础常量 diff --git a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/TableDto.java b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/TableDto.java deleted file mode 100644 index 98d29862..00000000 --- a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/domain/TableDto.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.mqttsnet.thinglinks.tdengine.api.domain; - -import lombok.Data; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotEmpty; -import java.util.List; - -/** - * @ClassDescription: 创建超级表的子表需要的入参的实体类 - * @ClassName: TableDto - * @Author: thinglinks - * @Date: 2021-12-30 14:42:47 - * @Version 1.0 - */ -@Data -public class TableDto extends BaseEntity{ - - /** - * 超级表普通列字段的值 - * 值需要与创建超级表时普通列字段的数据类型对应上 - */ - private List schemaFieldValues; - - /** - * 超级表标签字段的值 - * 值需要与创建超级表时标签字段的数据类型对应上 - */ - private List tagsFieldValues; - - /** - * 表名称 - */ - @NotBlank(message = "invalid operation: tableName can not be empty") - private String tableName; -} diff --git a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/factory/RemoteTdEngineFallbackFactory.java b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/factory/RemoteTdEngineFallbackFactory.java index 13c7581a..8a4d487a 100644 --- a/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/factory/RemoteTdEngineFallbackFactory.java +++ b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/factory/RemoteTdEngineFallbackFactory.java @@ -3,9 +3,12 @@ import cn.hutool.json.JSONObject; import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.tdengine.api.RemoteTdEngineService; -import com.mqttsnet.thinglinks.tdengine.api.domain.*; +import com.mqttsnet.thinglinks.tdengine.api.domain.SelectDto; +import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDescribeVO; +import com.mqttsnet.thinglinks.tdengine.api.domain.TagsSelectDao; import com.mqttsnet.thinglinks.tdengine.api.domain.model.SuperTableDTO; import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TagsSelectDTO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.openfeign.FallbackFactory; @@ -31,68 +34,6 @@ public RemoteTdEngineService create(Throwable throwable) { log.error("TDengine服务调用失败:{}", throwable.getMessage()); return new RemoteTdEngineService() { - @Override - public R createDataBase(String databaseName) { - return R.fail("创建数据库失败:{}", throwable.getMessage()); - } - - @Override - public R createSuperTable(SuperTableDto superTableDto) { - return R.fail("创建超级表失败:{}", throwable.getMessage()); - } - - @Override - public R createTable(TableDto tableDto) { - return R.fail("创建表失败:{}", throwable.getMessage()); - } - - @Override - public R insertData(TableDto tableDto) { - return R.fail("插入数据失败:{}", throwable.getMessage()); - } - - @Override - public R addColumnInStb(SuperTableDto superTableDto) { - return R.fail("超级表增加列失败:{}", throwable.getMessage()); - } - - @Override - public R getDataByTimestamp(SelectDto selectDto) { - return R.fail("查询数据失败:{}", throwable.getMessage()); - } - - @Override - public R getLastData(SelectDto selectDto) { - return R.fail("查询最新数据失败:{}", throwable.getMessage()); - } - - @Override - public R getLastDataByTags(TagsSelectDao tagsSelectDao) { - return R.fail("查询最新数据失败:{}", throwable.getMessage()); - } - - /** - * 添加列字段 - * - * @param ·superTableDto - * @return - */ - @Override - public R addColumnForSuperTable(SuperTableDto superTableDto) { - return R.fail("添加列字段失败:{}", throwable.getMessage()); - } - - /** - * 删除列字段 - * - * @param superTableDto - * @return - */ - @Override - public R dropColumnForSuperTable(SuperTableDto superTableDto) { - return R.fail("删除列字段失败:{}", throwable.getMessage()); - } - @Override public R createDatabase(String dataBaseName) { return R.fail("创建数据库失败:{}", throwable.getMessage()); @@ -169,6 +110,22 @@ public R>> getDataInRangeOrLastRecord(String tableName, log.error("查询超级表、子表结构失败:{}", throwable.getMessage()); return R.fail(); } + + @Override + public R getDataByTimestamp(SelectDto selectDto) { + return R.fail("查询数据失败:{}", throwable.getMessage()); + } + + @Override + public R getLastData(SelectDto selectDto) { + return R.fail("查询最新数据失败:{}", throwable.getMessage()); + } + + @Override + public R>> getLastDataByTags(TagsSelectDTO tagsSelectDao) { + log.error("查询最新数据失败:{}", throwable.getMessage()); + return R.fail(); + } }; } } diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/utils/TdsUtils.java b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/utils/TdsUtils.java similarity index 99% rename from thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/utils/TdsUtils.java rename to thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/utils/TdsUtils.java index c47f7fae..df9786e4 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/utils/TdsUtils.java +++ b/thinglinks-api/thinglinks-api-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/api/utils/TdsUtils.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.tdengine.utils; +package com.mqttsnet.thinglinks.tdengine.api.utils; import cn.hutool.core.bean.BeanUtil; import cn.hutool.json.JSONObject; diff --git a/thinglinks-auth/src/main/java/com/mqttsnet/thinglinks/auth/ThingLinksAuthApplication.java b/thinglinks-auth/src/main/java/com/mqttsnet/thinglinks/auth/ThingLinksAuthApplication.java index d32fe1ee..9a5d2db0 100644 --- a/thinglinks-auth/src/main/java/com/mqttsnet/thinglinks/auth/ThingLinksAuthApplication.java +++ b/thinglinks-auth/src/main/java/com/mqttsnet/thinglinks/auth/ThingLinksAuthApplication.java @@ -1,28 +1,35 @@ package com.mqttsnet.thinglinks.auth; import com.mqttsnet.thinglinks.common.security.annotation.EnableRyFeignClients; +import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.CrossOrigin; +import java.net.InetAddress; + /** * 认证授权中心 - * + * * @author thinglinks */ +@Slf4j @EnableRyFeignClients //实现跨域注解 //origin="*"代表所有域名都可访问 //maxAge飞行前响应的缓存持续时间的最大年龄,简单来说就是Cookie的有效期 单位为秒 //若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失 -@CrossOrigin(origins = "*",maxAge = 3600) -@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class },scanBasePackages = {"com.mqttsnet.thinglinks"}) -public class ThingLinksAuthApplication -{ - public static void main(String[] args) - { - SpringApplication.run(ThingLinksAuthApplication.class, args); - System.out.println("(♥◠‿◠)ノ゙ 认证授权中心启动成功 ლ(´ڡ`ლ)゙ "); +@CrossOrigin(origins = "*", maxAge = 3600) +@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}, scanBasePackages = {"com.mqttsnet.thinglinks"}) +public class ThingLinksAuthApplication { + public static void main(String[] args) throws Exception { + ConfigurableApplicationContext application = SpringApplication.run(ThingLinksAuthApplication.class, args); + Environment env = application.getEnvironment(); + log.info("\n----------------------------------------------------------\n\t" + "应用 '{}' 启动成功! 访问连接:\n\t" + "Swagger文档: \t\thttp://{}:{}/swagger-ui.html\n\t" + + "数据库监控: \t\thttp://{}:{}/druid\n" + "----------------------------------------------------------", env.getProperty("spring.application.name"), + InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port", "8080"), "127.0.0.1", env.getProperty("server.port", "8080")); } } diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/CacheConstants.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/CacheConstants.java index 3de55f90..9131e8af 100644 --- a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/CacheConstants.java +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/CacheConstants.java @@ -14,39 +14,39 @@ public class CacheConstants { /** * 设备信息 cache key - * link-> device_record:deviceIdentification + * link-> def_device:deviceIdentification */ - public static final String DEVICE_RECORD_KEY = "device_record:"; + public static final String DEF_DEVICE = "def_device:"; /** * 全局产品信息 前缀 * link-> def_product:productIdentification */ - public static final String PRODUCT = "def_product"; + public static final String DEF_PRODUCT = "def_product:"; /** * 全局产品模型 前缀 * link-> def_product_model:productIdentification */ - public static final String PRODUCT_MODEL = "def_product_model"; + public static final String DEF_PRODUCT_MODEL = "def_product_model:"; /** * 全局产品模型超级表 前缀 * link-> def_product_model_super_table:productIdentification:serviceCode:deviceIdentification */ - public static final String PRODUCT_MODEL_SUPER_TABLE = "def_product_model_super_table"; + public static final String DEF_PRODUCT_MODEL_SUPER_TABLE = "def_product_model_super_table:"; /** * TDengine superTableFields cache key - * link-> tdengine_superTableFields:productIdentification:serviceCode:deviceIdentification + * link-> def_tdengine_superTableFields:productIdentification:serviceCode:deviceIdentification */ - public static final String TDENGINE_SUPERTABLEFILELDS = "tdengine_superTableFields:"; + public static final String DEF_TDENGINE_SUPERTABLEFILELDS = "def_tdengine_superTableFields:"; /** * 设备数据转换脚本 cache key - * link-> device_data_reported_agreement_script:deviceIdentification + * link-> DEF_DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT:deviceIdentification */ - public static final String DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT = "device_data_reported_agreement_script"; + public static final String DEF_DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT = "def_DEF_DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT:"; } diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/Constants.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/Constants.java index 224175ee..93e34f56 100644 --- a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/Constants.java +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/constant/Constants.java @@ -151,5 +151,17 @@ public class Constants { */ public static final String UNDERLINE = "_"; + /** + * 分隔符 + */ + public static final String SEPARATOR = ","; + + + /** + * 分号 + */ + public static final String SEMICOLON = ";"; + + } diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/exception/ArgumentException.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/exception/ArgumentException.java new file mode 100755 index 00000000..0f10c99d --- /dev/null +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/exception/ArgumentException.java @@ -0,0 +1,38 @@ +package com.mqttsnet.thinglinks.common.core.exception; + + +import com.mqttsnet.thinglinks.common.core.enums.ResultEnum; + +/** + * 业务参数异常 + * 用于在业务中,检测到非法参数时,进行抛出的异常。 + * + * @author mqttsnet + * @version 3.5.0 + */ +public class ArgumentException extends BaseUncheckedException { + + private static final long serialVersionUID = -3843907364558373817L; + + public ArgumentException(Throwable cause) { + super(cause); + } + + public ArgumentException(String message) { + super(ResultEnum.FAIL.getCode(), message); + } + + public ArgumentException(String message, Throwable cause) { + super(ResultEnum.FAIL.getCode(), message, cause); + } + + public ArgumentException(final String format, Object... args) { + super(ResultEnum.FAIL.getCode(), format, args); + } + + @Override + public String toString() { + return "ArgumentException [message=" + getMessage() + ", code=" + getCode() + "]"; + } + +} diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/exception/BaseCheckedException.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/exception/BaseCheckedException.java new file mode 100755 index 00000000..de9558a7 --- /dev/null +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/exception/BaseCheckedException.java @@ -0,0 +1,48 @@ +package com.mqttsnet.thinglinks.common.core.exception; + +import com.mqttsnet.thinglinks.common.core.exception.base.BaseException; + +/** + * 运行期异常基类 + * + * @author mqttsnet + * @version 1.0 + */ +public abstract class BaseCheckedException extends BaseException { + + private static final long serialVersionUID = 2706069899924648586L; + + /** + * 异常信息 + */ + private final String message; + + /** + * 具体异常码 + */ + private final int code; + + public BaseCheckedException(final int code, final String message) { + super(message); + this.code = code; + this.message = message; + } + + public BaseCheckedException(final int code, final String format, Object... args) { + super(String.format(format, args)); + this.code = code; + this.message = String.format(format, args); + } + + /** + * 获取 异常消息 + * + * @return 异常消息 + */ + @Override + public String getMessage() { + return message; + } + + +} diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/exception/BaseUncheckedException.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/exception/BaseUncheckedException.java new file mode 100755 index 00000000..cd97badc --- /dev/null +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/exception/BaseUncheckedException.java @@ -0,0 +1,63 @@ +package com.mqttsnet.thinglinks.common.core.exception; + +import cn.hutool.core.util.StrUtil; +import com.mqttsnet.thinglinks.common.core.utils.StrPool; +import lombok.Getter; + +/** + * 非运行期异常基类,所有自定义非运行时异常继承该类 + * + * @author mqttsnet + * @version 1.0 + * @see RuntimeException + */ +public class BaseUncheckedException extends Exception { + + private static final long serialVersionUID = -778887391066124051L; + + /** + * 异常信息 + */ + private String message; + + /** + * 具体异常码 + */ + @Getter + private int code; + + public BaseUncheckedException(Throwable cause) { + super(cause); + } + + public BaseUncheckedException(final int code, Throwable cause) { + super(cause); + this.code = code; + } + + + public BaseUncheckedException(final int code, final String message) { + super(message); + this.code = code; + this.message = message; + } + + public BaseUncheckedException(final int code, final String message, Throwable cause) { + super(cause); + this.code = code; + this.message = message; + } + + public BaseUncheckedException(final int code, final String format, Object... args) { + super(StrUtil.contains(format, StrPool.BRACE) ? StrUtil.format(format, args) : String.format(format, args)); + this.code = code; + this.message = StrUtil.contains(format, StrPool.BRACE) ? StrUtil.format(format, args) : String.format(format, args); + } + + + @Override + public String getMessage() { + return message; + } + +} diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/ArgumentAssert.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/ArgumentAssert.java new file mode 100755 index 00000000..8e031188 --- /dev/null +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/ArgumentAssert.java @@ -0,0 +1,1108 @@ +package com.mqttsnet.thinglinks.common.core.utils; + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.map.MapUtil; +import cn.hutool.core.util.ArrayUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.mqttsnet.thinglinks.common.core.exception.ArgumentException; + +import java.time.LocalDateTime; +import java.util.Collection; +import java.util.Map; +import java.util.function.Supplier; + +/** + * 断言
+ * 断言某些对象或值是否符合规定,否则抛出异常。经常用于做变量检查 + * + * @author Looly + */ +public class ArgumentAssert { + + /** + * 断言是否为真,如果为 {@code false} 抛出给定的异常
+ * + *
+     * Assert.isTrue(i > 0, ArgumentException::new);
+     * 
+ * + * @param 异常类型 + * @param expression 布尔值 + * @param supplier 指定断言不通过时抛出的异常 + * @throws X if expression is {@code false} + */ + public static void isTrue(boolean expression, Supplier supplier) throws X { + if (false == expression) { + throw supplier.get(); + } + } + + /** + * 断言是否为真,如果为 {@code false} 抛出 {@code ArgumentException} 异常
+ * + *
+     * Assert.isTrue(i > 0, "The value must be greater than zero");
+     * 
+ * + * @param expression 布尔值 + * @param errorMsgTemplate 错误抛出异常附带的消息模板,变量用{}代替 + * @param params 参数列表 + * @throws ArgumentException if expression is {@code false} + */ + public static void isTrue(boolean expression, String errorMsgTemplate, Object... params) throws ArgumentException { + isTrue(expression, () -> new ArgumentException(StrUtil.format(errorMsgTemplate, params))); + } + + /** + * 断言是否为真,如果为 {@code false} 抛出 {@code ArgumentException} 异常
+ * + *
+     * Assert.isTrue(i > 0, "The value must be greater than zero");
+     * 
+ * + * @param expression 布尔值 + * @throws ArgumentException if expression is {@code false} + */ + public static void isTrue(boolean expression) throws ArgumentException { + isTrue(expression, "[Assertion failed] - this expression must be true"); + } + + /** + * 断言是否为假,如果为 {@code true} 抛出指定类型异常
+ * 并使用指定的函数获取错误信息返回 + *
+     *  Assert.isFalse(i > 0, ()->{
+     *      // to query relation message
+     *      return new ArgumentException("relation message to return");
+     *  });
+     * 
+ * + * @param 异常类型 + * @param expression 布尔值 + * @param errorSupplier 指定断言不通过时抛出的异常 + * @throws X if expression is {@code false} + * @since 5.4.5 + */ + public static void isFalse(boolean expression, Supplier errorSupplier) throws X { + if (expression) { + throw errorSupplier.get(); + } + } + + /** + * 断言是否为假,如果为 {@code true} 抛出 {@code ArgumentException} 异常
+ * + *
+     * Assert.isFalse(i < 0, "The value must be greater than zero");
+     * 
+ * + * @param expression 布尔值 + * @param errorMsgTemplate 错误抛出异常附带的消息模板,变量用{}代替 + * @param params 参数列表 + * @throws ArgumentException if expression is {@code false} + */ + public static void isFalse(boolean expression, String errorMsgTemplate, Object... params) throws ArgumentException { + isFalse(expression, () -> new ArgumentException(StrUtil.format(errorMsgTemplate, params))); + } + + /** + * 断言是否为假,如果为 {@code true} 抛出 {@code ArgumentException} 异常
+ * + *
+     * Assert.isFalse(i < 0);
+     * 
+ * + * @param expression 布尔值 + * @throws ArgumentException if expression is {@code false} + */ + public static void isFalse(boolean expression) throws ArgumentException { + isFalse(expression, "[Assertion failed] - this expression must be false"); + } + + /** + * 断言对象是否为{@code null} ,如果不为{@code null} 抛出指定类型异常 + * 并使用指定的函数获取错误信息返回 + *
+     * Assert.isNull(value, ()->{
+     *      // to query relation message
+     *      return new ArgumentException("relation message to return");
+     *  });
+     * 
+ * + * @param 异常类型 + * @param object 被检查的对象 + * @param errorSupplier 错误抛出异常附带的消息生产接口 + * @throws X if the object is not {@code null} + * @since 5.4.5 + */ + public static void isNull(Object object, Supplier errorSupplier) throws X { + if (null != object) { + throw errorSupplier.get(); + } + } + + /** + * 断言对象是否为{@code null} ,如果不为{@code null} 抛出{@link ArgumentException} 异常 + * + *
+     * Assert.isNull(value, "The value must be null");
+     * 
+ * + * @param object 被检查的对象 + * @param errorMsgTemplate 消息模板,变量使用{}表示 + * @param params 参数列表 + * @throws ArgumentException if the object is not {@code null} + */ + public static void isNull(Object object, String errorMsgTemplate, Object... params) throws ArgumentException { + isNull(object, () -> new ArgumentException(StrUtil.format(errorMsgTemplate, params))); + } + + /** + * 断言对象是否为{@code null} ,如果不为{@code null} 抛出{@link ArgumentException} 异常 + * + *
+     * Assert.isNull(value);
+     * 
+ * + * @param object 被检查对象 + * @throws ArgumentException if the object is not {@code null} + */ + public static void isNull(Object object) throws ArgumentException { + isNull(object, "[Assertion failed] - the object argument must be null"); + } + + // ----------------------------------------------------------------------------------------------------------- Check not null + + /** + * 断言对象是否不为{@code null} ,如果为{@code null} 抛出指定类型异常 + * 并使用指定的函数获取错误信息返回 + *
+     * Assert.notNull(clazz, ()->{
+     *      // to query relation message
+     *      return new ArgumentException("relation message to return");
+     *  });
+     * 
+ * + * @param 被检查对象泛型类型 + * @param 异常类型 + * @param object 被检查对象 + * @param errorSupplier 错误抛出异常附带的消息生产接口 + * @return 被检查后的对象 t + * @throws X if the object is {@code null} + * @since 5.4.5 + */ + public static T notNull(T object, Supplier errorSupplier) throws X { + if (null == object) { + throw errorSupplier.get(); + } + return object; + } + + /** + * 断言对象是否不为{@code null} ,如果为{@code null} 抛出{@link ArgumentException} 异常 Assert that an object is not {@code null} . + * + *
+     * Assert.notNull(clazz, "The class must not be null");
+     * 
+ * + * @param 被检查对象泛型类型 + * @param object 被检查对象 + * @param errorMsgTemplate 错误消息模板,变量使用{}表示 + * @param params 参数 + * @return 被检查后的对象 t + * @throws ArgumentException if the object is {@code null} + */ + public static T notNull(T object, String errorMsgTemplate, Object... params) throws ArgumentException { + return notNull(object, () -> new ArgumentException(StrUtil.format(errorMsgTemplate, params))); + } + + /** + * 断言对象是否不为{@code null} ,如果为{@code null} 抛出{@link ArgumentException} 异常 + * + *
+     * Assert.notNull(clazz);
+     * 
+ * + * @param 被检查对象类型 + * @param object 被检查对象 + * @return 非空对象 t + * @throws ArgumentException if the object is {@code null} + */ + public static T notNull(T object) throws ArgumentException { + return notNull(object, "[Assertion failed] - this argument is required; it must not be null"); + } + + // ----------------------------------------------------------------------------------------------------------- Check empty + + /** + * 检查给定字符串是否为空,为空抛出自定义异常,并使用指定的函数获取错误信息返回。 + *
+     * Assert.notEmpty(name, ()->{
+     *      // to query relation message
+     *      return new ArgumentException("relation message to return");
+     *  });
+     * 
+ * + * @param 字符串类型 + * @param 异常类型 + * @param text 被检查字符串 + * @param errorSupplier 错误抛出异常附带的消息生产接口 + * @return 非空字符串 t + * @throws X 被检查字符串为空抛出此异常 + * @see StrUtil#isNotEmpty(CharSequence) StrUtil#isNotEmpty(CharSequence) + * @since 5.4.5 + */ + public static T notEmpty(T text, Supplier errorSupplier) throws X { + if (StrUtil.isEmpty(text)) { + throw errorSupplier.get(); + } + return text; + } + + /** + * 检查给定字符串是否为空,为空抛出 {@link ArgumentException} + * + *
+     * Assert.notEmpty(name, "Name must not be empty");
+     * 
+ * + * @param 字符串类型 + * @param text 被检查字符串 + * @param errorMsgTemplate 错误消息模板,变量使用{}表示 + * @param params 参数 + * @return 非空字符串 t + * @throws ArgumentException 被检查字符串为空 + * @see StrUtil#isNotEmpty(CharSequence) StrUtil#isNotEmpty(CharSequence) + */ + public static T notEmpty(T text, String errorMsgTemplate, Object... params) throws ArgumentException { + return notEmpty(text, () -> new ArgumentException(StrUtil.format(errorMsgTemplate, params))); + } + + /** + * 检查给定字符串是否为空,为空抛出 {@link ArgumentException} + * + *
+     * Assert.notEmpty(name);
+     * 
+ * + * @param 字符串类型 + * @param text 被检查字符串 + * @return 被检查的字符串 t + * @throws ArgumentException 被检查字符串为空 + * @see StrUtil#isNotEmpty(CharSequence) StrUtil#isNotEmpty(CharSequence) + */ + public static T notEmpty(T text) throws ArgumentException { + return notEmpty(text, "[Assertion failed] - this String argument must have length; it must not be null or empty"); + } + + /** + * 检查给定字符串是否为空白(null、空串或只包含空白符),为空抛出自定义异常。 + * 并使用指定的函数获取错误信息返回 + *
+     * Assert.notBlank(name, ()->{
+     *      // to query relation message
+     *      return new ArgumentException("relation message to return");
+     *  });
+     * 
+ * + * @param 字符串类型 + * @param 异常类型 + * @param text 被检查字符串 + * @param errorMsgSupplier 错误抛出异常附带的消息生产接口 + * @return 非空字符串 t + * @throws X 被检查字符串为空白 + * @see StrUtil#isNotBlank(CharSequence) StrUtil#isNotBlank(CharSequence) + */ + public static T notBlank(T text, Supplier errorMsgSupplier) throws X { + if (StrUtil.isBlank(text)) { + throw errorMsgSupplier.get(); + } + return text; + } + + /** + * 检查给定字符串是否为空白(null、空串或只包含空白符),为空抛出 {@link ArgumentException} + * + *
+     * Assert.notBlank(name, "Name must not be blank");
+     * 
+ * + * @param 字符串类型 + * @param text 被检查字符串 + * @param errorMsgTemplate 错误消息模板,变量使用{}表示 + * @param params 参数 + * @return 非空字符串 t + * @throws ArgumentException 被检查字符串为空白 + * @see StrUtil#isNotBlank(CharSequence) StrUtil#isNotBlank(CharSequence) + */ + public static T notBlank(T text, String errorMsgTemplate, Object... params) throws ArgumentException { + return notBlank(text, () -> new ArgumentException(StrUtil.format(errorMsgTemplate, params))); + } + + /** + * 检查给定字符串是否为空白(null、空串或只包含空白符),为空抛出 {@link ArgumentException} + * + *
+     * Assert.notBlank(name, "Name must not be blank");
+     * 
+ * + * @param 字符串类型 + * @param text 被检查字符串 + * @return 非空字符串 t + * @throws ArgumentException 被检查字符串为空白 + * @see StrUtil#isNotBlank(CharSequence) StrUtil#isNotBlank(CharSequence) + */ + public static T notBlank(T text) throws ArgumentException { + return notBlank(text, "[Assertion failed] - this String argument must have text; it must not be null, empty, or blank"); + } + + /** + * 断言给定字符串是否不被另一个字符串包含(即是否为子串) + * 并使用指定的函数获取错误信息返回 + *
+     * Assert.notContain(name, "rod", ()->{
+     *      // to query relation message
+     *      return new ArgumentException("relation message to return ");
+     *  });
+     * 
+ * + * @param 字符串类型 + * @param 异常类型 + * @param textToSearch 被搜索的字符串 + * @param substring 被检查的子串 + * @param errorSupplier 错误抛出异常附带的消息生产接口 + * @return 被检查的子串 t + * @throws X 非子串抛出异常 + * @see StrUtil#contains(CharSequence, CharSequence) StrUtil#contains(CharSequence, CharSequence) + * @since 5.4.5 + */ + public static T notContain(CharSequence textToSearch, T substring, Supplier errorSupplier) throws X { + if (StrUtil.contains(textToSearch, substring)) { + throw errorSupplier.get(); + } + return substring; + } + + /** + * 断言给定字符串是否不被另一个字符串包含(即是否为子串) + * + *
+     * Assert.notContain(name, "rod", "Name must not contain 'rod'");
+     * 
+ * + * @param textToSearch 被搜索的字符串 + * @param substring 被检查的子串 + * @param errorMsgTemplate 异常时的消息模板 + * @param params 参数列表 + * @return 被检查的子串 string + * @throws ArgumentException 非子串抛出异常 + */ + public static String notContain(String textToSearch, String substring, String errorMsgTemplate, Object... params) throws ArgumentException { + return notContain(textToSearch, substring, () -> new ArgumentException(StrUtil.format(errorMsgTemplate, params))); + } + + /** + * 断言给定字符串是否不被另一个字符串包含(即是否为子串) + * + *
+     * Assert.notContain(name, "rod", "Name must not contain 'rod'");
+     * 
+ * + * @param textToSearch 被搜索的字符串 + * @param substring 被检查的子串 + * @return 被检查的子串 string + * @throws ArgumentException 非子串抛出异常 + */ + public static String notContain(String textToSearch, String substring) throws ArgumentException { + return notContain(textToSearch, substring, "[Assertion failed] - this String argument must not contain the substring [{}]", substring); + } + + /** + * 断言给定值是否被另一个集合包含(即是否不为子串) + * + *
+     * Assert.notContain(names, "张三", "name's 中必须包含 '张三'");
+     * 
+ * + * @param collection 被搜索的集合 + * @param item 被检查的值 + * @return 被检查的值 string + * @throws ArgumentException 非子串抛出异常 + */ + public static T contain(Collection collection, T item) throws ArgumentException { + return contain(collection, item, "[断言失败] - 此集合中参数不得包含该值 [{}]", item); + } + + /** + * 断言给定值是否被另一个集合包含(即是否不为子串) + * + *
+     * Assert.notContain(names, "张三", "name's 中必须包含 '张三'");
+     * 
+ * + * @param collection 被搜索的集合 + * @param item 被检查的值 + * @param errorMsgTemplate 异常时的消息模板 + * @param params 参数列表 + * @return 被检查的值 string + * @throws ArgumentException 非子串抛出异常 + */ + public static T contain(Collection collection, T item, String errorMsgTemplate, Object... params) throws ArgumentException { + return contain(collection, item, () -> new ArgumentException(StrUtil.format(errorMsgTemplate, params))); + } + + /** + * 断言给定值是否被另一个集合包含(即是否不为子串) + * + *
+     * Assert.notContain(names, "张三", "name's 中必须包含 '张三'");
+     * 
+ * + * @param collection 被搜索的集合 + * @param item 被检查的值 + * @return 被检查的值 string + * @throws ArgumentException 非子串抛出异常 + */ + public static T contain(Collection collection, T item, Supplier errorSupplier) throws X { + if (!CollUtil.contains(collection, item)) { + throw errorSupplier.get(); + } + return item; + } + + /** + * 断言给定值是否不被另一个集合包含(即是否为子串) + * + *
+     * Assert.notContain(names, "张三", "name's 中不能包含 '张三'");
+     * 
+ * + * @param collection 被搜索的集合 + * @param item 被检查的值 + * @return 被检查的值 string + * @throws ArgumentException 非子串抛出异常 + */ + public static T notContain(Collection collection, T item) throws ArgumentException { + return notContain(collection, item, "[断言失败] - 此集合中参数不得包含该值 [{}]", item); + } + + /** + * 断言给定值是否不被另一个集合包含(即是否为子串) + * + *
+     * Assert.notContain(names, "张三", "name's 中不能包含 '张三'");
+     * 
+ * + * @param collection 被搜索的集合 + * @param item 被检查的值 + * @param errorMsgTemplate 异常时的消息模板 + * @param params 参数列表 + * @return 被检查的值 string + * @throws ArgumentException 非子串抛出异常 + */ + public static T notContain(Collection collection, T item, String errorMsgTemplate, Object... params) throws ArgumentException { + return notContain(collection, item, () -> new ArgumentException(StrUtil.format(errorMsgTemplate, params))); + } + + /** + * 断言给定值是否不被另一个集合包含(即是否为子串) + * + *
+     * Assert.notContain(names, "张三", "name's 中不能包含 '张三'");
+     * 
+ * + * @param collection 被搜索的集合 + * @param item 被检查的值 + * @return 被检查的值 string + * @throws ArgumentException 非子串抛出异常 + */ + public static T notContain(Collection collection, T item, Supplier errorSupplier) throws X { + if (CollUtil.contains(collection, item)) { + throw errorSupplier.get(); + } + return item; + } + + /** + * 断言给定数组是否包含元素,数组必须不为 {@code null} 且至少包含一个元素 + * 并使用指定的函数获取错误信息返回 + * + *
+     * Assert.notEmpty(array, ()->{
+     *      // to query relation message
+     *      return new ArgumentException("relation message to return");
+     *  });
+     * 
+ * + * @param 数组元素类型 + * @param 异常类型 + * @param array 被检查的数组 + * @param errorSupplier 错误抛出异常附带的消息生产接口 + * @return 被检查的数组 t [ ] + * @throws X if the object array is {@code null} or has no elements + * @see ArrayUtil#isNotEmpty(Object[]) ArrayUtil#isNotEmpty(Object[]) + * @since 5.4.5 + */ + public static T[] notEmpty(T[] array, Supplier errorSupplier) throws X { + if (ArrayUtil.isEmpty(array)) { + throw errorSupplier.get(); + } + return array; + } + + /** + * 断言给定数组是否包含元素,数组必须不为 {@code null} 且至少包含一个元素 + * + *
+     * Assert.notEmpty(array, "The array must have elements");
+     * 
+ * + * @param 数组元素类型 + * @param array 被检查的数组 + * @param errorMsgTemplate 异常时的消息模板 + * @param params 参数列表 + * @return 被检查的数组 t [ ] + * @throws ArgumentException if the object array is {@code null} or has no elements + */ + public static T[] notEmpty(T[] array, String errorMsgTemplate, Object... params) throws ArgumentException { + return notEmpty(array, () -> new ArgumentException(StrUtil.format(errorMsgTemplate, params))); + } + + /** + * 断言给定数组是否包含元素,数组必须不为 {@code null} 且至少包含一个元素 + * + *
+     * Assert.notEmpty(array, "The array must have elements");
+     * 
+ * + * @param 数组元素类型 + * @param array 被检查的数组 + * @return 被检查的数组 t [ ] + * @throws ArgumentException if the object array is {@code null} or has no elements + */ + public static T[] notEmpty(T[] array) throws ArgumentException { + return notEmpty(array, "[Assertion failed] - this array must not be empty: it must contain at least 1 element"); + } + + /** + * 断言给定数组是否不包含{@code null}元素,如果数组为空或 {@code null}将被认为不包含 + * 并使用指定的函数获取错误信息返回 + *
+     * Assert.noNullElements(array, ()->{
+     *      // to query relation message
+     *      return new ArgumentException("relation message to return ");
+     *  });
+     * 
+ * + * @param 数组元素类型 + * @param 异常类型 + * @param array 被检查的数组 + * @param errorSupplier 错误抛出异常附带的消息生产接口 + * @return 被检查的数组 t [ ] + * @throws X if the object array contains a {@code null} element + * @see ArrayUtil#hasNull(Object[]) ArrayUtil#hasNull(Object[]) + * @since 5.4.5 + */ + public static T[] noNullElements(T[] array, Supplier errorSupplier) throws X { + if (ArrayUtil.hasNull(array)) { + throw errorSupplier.get(); + } + return array; + } + + /** + * 断言给定数组是否不包含{@code null}元素,如果数组为空或 {@code null}将被认为不包含 + * + *
+     * Assert.noNullElements(array, "The array must have non-null elements");
+     * 
+ * + * @param 数组元素类型 + * @param array 被检查的数组 + * @param errorMsgTemplate 异常时的消息模板 + * @param params 参数列表 + * @return 被检查的数组 t [ ] + * @throws ArgumentException if the object array contains a {@code null} element + */ + public static T[] noNullElements(T[] array, String errorMsgTemplate, Object... params) throws ArgumentException { + return noNullElements(array, () -> new ArgumentException(StrUtil.format(errorMsgTemplate, params))); + } + + /** + * 断言给定数组是否不包含{@code null}元素,如果数组为空或 {@code null}将被认为不包含 + * + *
+     * Assert.noNullElements(array);
+     * 
+ * + * @param 数组元素类型 + * @param array 被检查的数组 + * @return 被检查的数组 t [ ] + * @throws ArgumentException if the object array contains a {@code null} element + */ + public static T[] noNullElements(T[] array) throws ArgumentException { + return noNullElements(array, "[Assertion failed] - this array must not contain any null elements"); + } + + /** + * 断言给定集合非空 + * 并使用指定的函数获取错误信息返回 + *
+     * Assert.notEmpty(collection, ()->{
+     *      // to query relation message
+     *      return new ArgumentException("relation message to return");
+     *  });
+     * 
+ * + * @param 集合元素类型 + * @param 集合类型 + * @param 异常类型 + * @param collection 被检查的集合 + * @param errorSupplier 错误抛出异常附带的消息生产接口 + * @return 非空集合 t + * @throws X if the collection is {@code null} or has no elements + * @see CollUtil#isNotEmpty(Iterable) CollUtil#isNotEmpty(Iterable) + * @since 5.4.5 + */ + public static , X extends Throwable> T notEmpty(T collection, Supplier errorSupplier) throws X { + if (CollUtil.isEmpty(collection)) { + throw errorSupplier.get(); + } + return collection; + } + + /** + * 断言给定集合非空 + * + *
+     * Assert.notEmpty(collection, "Collection must have elements");
+     * 
+ * + * @param 集合元素类型 + * @param 集合类型 + * @param collection 被检查的集合 + * @param errorMsgTemplate 异常时的消息模板 + * @param params 参数列表 + * @return 非空集合 t + * @throws ArgumentException if the collection is {@code null} or has no elements + */ + public static > T notEmpty(T collection, String errorMsgTemplate, Object... params) throws ArgumentException { + return notEmpty(collection, () -> new ArgumentException(StrUtil.format(errorMsgTemplate, params))); + } + + /** + * 断言给定集合非空 + * + *
+     * Assert.notEmpty(collection);
+     * 
+ * + * @param 集合元素类型 + * @param 集合类型 + * @param collection 被检查的集合 + * @return 被检查集合 t + * @throws ArgumentException if the collection is {@code null} or has no elements + */ + public static > T notEmpty(T collection) throws ArgumentException { + return notEmpty(collection, "[Assertion failed] - this collection must not be empty: it must contain at least 1 element"); + } + + /** + * 断言给定Map非空 + * 并使用指定的函数获取错误信息返回 + *
+     * Assert.notEmpty(map, ()->{
+     *      // to query relation message
+     *      return new ArgumentException("relation message to return");
+     *  });
+     * 
+ * + * @param Key类型 + * @param Value类型 + * @param Map类型 + * @param 异常类型 + * @param map 被检查的Map + * @param errorSupplier 错误抛出异常附带的消息生产接口 + * @return 被检查的Map t + * @throws X if the map is {@code null} or has no entries + * @see MapUtil#isNotEmpty(Map) MapUtil#isNotEmpty(Map) + * @since 5.4.5 + */ + public static , X extends Throwable> T notEmpty(T map, Supplier errorSupplier) throws X { + if (MapUtil.isEmpty(map)) { + throw errorSupplier.get(); + } + return map; + } + + /** + * 断言给定Map非空 + * + *
+     * Assert.notEmpty(map, "Map must have entries");
+     * 
+ * + * @param Key类型 + * @param Value类型 + * @param Map类型 + * @param map 被检查的Map + * @param errorMsgTemplate 异常时的消息模板 + * @param params 参数列表 + * @return 被检查的Map t + * @throws ArgumentException if the map is {@code null} or has no entries + */ + public static > T notEmpty(T map, String errorMsgTemplate, Object... params) throws ArgumentException { + return notEmpty(map, () -> new ArgumentException(StrUtil.format(errorMsgTemplate, params))); + } + + /** + * 断言给定Map非空 + * + *
+     * Assert.notEmpty(map, "Map must have entries");
+     * 
+ * + * @param Key类型 + * @param Value类型 + * @param Map类型 + * @param map 被检查的Map + * @return 被检查的Map t + * @throws ArgumentException if the map is {@code null} or has no entries + */ + public static > T notEmpty(T map) throws ArgumentException { + return notEmpty(map, "[Assertion failed] - this map must not be empty; it must contain at least one entry"); + } + + /** + * 断言给定对象是否是给定类的实例 + * + *
+     * Assert.instanceOf(Foo.class, foo);
+     * 
+ * + * @param 被检查对象泛型类型 + * @param type 被检查对象匹配的类型 + * @param obj 被检查对象 + * @return 被检查的对象 t + * @throws ArgumentException if the object is not an instance of clazz + * @see Class#isInstance(Object) Class#isInstance(Object) + */ + public static T isInstanceOf(Class type, T obj) throws ArgumentException { + return isInstanceOf(type, obj, "Object [{}] is not instanceof [{}]", obj, type); + } + + /** + * 断言给定对象是否是给定类的实例 + * + *
+     * Assert.instanceOf(Foo.class, foo);
+     * 
+ * + * @param 被检查对象泛型类型 + * @param type 被检查对象匹配的类型 + * @param obj 被检查对象 + * @param errorMsgTemplate 异常时的消息模板 + * @param params 参数列表 + * @return 被检查对象 t + * @throws ArgumentException if the object is not an instance of clazz + * @see Class#isInstance(Object) Class#isInstance(Object) + */ + public static T isInstanceOf(Class type, T obj, String errorMsgTemplate, Object... params) throws ArgumentException { + notNull(type, "Type to check against must not be null"); + if (false == type.isInstance(obj)) { + throw new ArgumentException(StrUtil.format(errorMsgTemplate, params)); + } + return obj; + } + + /** + * 断言 {@code superType.isAssignableFrom(subType)} 是否为 {@code true}. + * + *
+     * Assert.isAssignable(Number.class, myClass);
+     * 
+ * + * @param superType 需要检查的父类或接口 + * @param subType 需要检查的子类 + * @throws ArgumentException 如果子类非继承父类,抛出此异常 + */ + public static void isAssignable(Class superType, Class subType) throws ArgumentException { + isAssignable(superType, subType, "{} is not assignable to {})", subType, superType); + } + + /** + * 断言 {@code superType.isAssignableFrom(subType)} 是否为 {@code true}. + * + *
+     * Assert.isAssignable(Number.class, myClass);
+     * 
+ * + * @param superType 需要检查的父类或接口 + * @param subType 需要检查的子类 + * @param errorMsgTemplate 异常时的消息模板 + * @param params 参数列表 + * @throws ArgumentException 如果子类非继承父类,抛出此异常 + */ + public static void isAssignable(Class superType, Class subType, String errorMsgTemplate, Object... params) throws ArgumentException { + notNull(superType, "Type to check against must not be null"); + if (subType == null || !superType.isAssignableFrom(subType)) { + throw new ArgumentException(StrUtil.format(errorMsgTemplate, params)); + } + } + + /** + * 检查boolean表达式,当检查结果为false时抛出 {@code IllegalStateException}。 + * 并使用指定的函数获取错误信息返回 + *
+     * Assert.state(id == null, ()->{
+     *      // to query relation message
+     *      return "relation message to return ";
+     *  });
+     * 
+ * + * @param expression boolean 表达式 + * @param errorMsgSupplier 错误抛出异常附带的消息生产接口 + * @throws IllegalStateException 表达式为 {@code false} 抛出此异常 + */ + public static void state(boolean expression, Supplier errorMsgSupplier) throws IllegalStateException { + if (false == expression) { + throw new IllegalStateException(errorMsgSupplier.get()); + } + } + + /** + * 检查boolean表达式,当检查结果为false时抛出 {@code IllegalStateException}。 + * + *
+     * Assert.state(id == null, "The id property must not already be initialized");
+     * 
+ * + * @param expression boolean 表达式 + * @param errorMsgTemplate 异常时的消息模板 + * @param params 参数列表 + * @throws IllegalStateException 表达式为 {@code false} 抛出此异常 + */ + public static void state(boolean expression, String errorMsgTemplate, Object... params) throws IllegalStateException { + if (false == expression) { + throw new IllegalStateException(StrUtil.format(errorMsgTemplate, params)); + } + } + + /** + * 检查boolean表达式,当检查结果为false时抛出 {@code IllegalStateException}。 + * + *
+     * Assert.state(id == null);
+     * 
+ * + * @param expression boolean 表达式 + * @throws IllegalStateException 表达式为 {@code false} 抛出此异常 + */ + public static void state(boolean expression) throws IllegalStateException { + state(expression, "[Assertion failed] - this state invariant must be true"); + } + + /** + * 检查下标(数组、集合、字符串)是否符合要求,下标必须满足: + * + *
+     * 0 ≤ index < size
+     * 
+ * + * @param index 下标 + * @param size 长度 + * @return 检查后的下标 int + * @throws ArgumentException 如果size < 0 抛出此异常 + * @throws IndexOutOfBoundsException 如果index < 0或者 index ≥ size 抛出此异常 + * @since 4.1.9 + */ + public static int checkIndex(int index, int size) throws ArgumentException, IndexOutOfBoundsException { + return checkIndex(index, size, "[Assertion failed]"); + } + + /** + * 检查下标(数组、集合、字符串)是否符合要求,下标必须满足: + * + *
+     * 0 ≤ index < size
+     * 
+ * + * @param index 下标 + * @param size 长度 + * @param errorMsgTemplate 异常时的消息模板 + * @param params 参数列表 + * @return 检查后的下标 int + * @throws ArgumentException 如果size < 0 抛出此异常 + * @throws IndexOutOfBoundsException 如果index < 0或者 index ≥ size 抛出此异常 + * @since 4.1.9 + */ + public static int checkIndex(int index, int size, String errorMsgTemplate, Object... params) throws ArgumentException, IndexOutOfBoundsException { + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException(badIndexMsg(index, size, errorMsgTemplate, params)); + } + return index; + } + + /** + * 检查值是否在指定范围内 + * + * @param value 值 + * @param min 最小值(包含) + * @param max 最大值(包含) + * @return 检查后的长度值 int + * @since 4.1.10 + */ + public static int checkBetween(int value, int min, int max) throws ArgumentException { + if (value < min || value > max) { + throw new ArgumentException(StrUtil.format("Length must be between {} and {}.", min, max)); + } + return value; + } + + /** + * 检查日志是否大于指定值 + * + * @param value 值 + * @param min 最小值(包含) + * @return 检查后的长度值 int + * @since 4.1.10 + */ + public static LocalDateTime checkGt(LocalDateTime value, LocalDateTime min, String... msg) throws ArgumentException { + if (value.isBefore(min)) { + String message = null; + if (ArrayUtil.isNotEmpty(msg)) { + message = msg[0]; + } else { + message = StrUtil.format("{} 必须大于 {} .", value, min); + } + throw new ArgumentException(message); + } + return value; + } + + /** + * 检查日志是否小于指定值 + * + * @param value 值 + * @param max 最大值(包含) + * @return 检查后的长度值 int + * @since 4.1.10 + */ + public static LocalDateTime checkLt(LocalDateTime value, LocalDateTime max, String... msg) throws ArgumentException { + if (value.isAfter(max)) { + String message = null; + if (ArrayUtil.isNotEmpty(msg)) { + message = msg[0]; + } else { + message = StrUtil.format("{} 必须小于 {} .", value, max); + } + throw new ArgumentException(message); + } + return value; + } + + + /** + * 检查值是否在指定范围内 + * + * @param value 值 + * @param min 最小值(包含) + * @param max 最大值(包含) + * @return 检查后的长度值 long + * @since 4.1.10 + */ + public static long checkBetween(long value, long min, long max) throws ArgumentException { + if (value < min || value > max) { + throw new ArgumentException(StrUtil.format("Length must be between {} and {}.", min, max)); + } + return value; + } + + /** + * 检查值是否在指定范围内 + * + * @param value 值 + * @param min 最小值(包含) + * @param max 最大值(包含) + * @return 检查后的长度值 double + * @since 4.1.10 + */ + public static double checkBetween(double value, double min, double max) throws ArgumentException { + if (value < min || value > max) { + throw new ArgumentException(StrUtil.format("Length must be between {} and {}.", min, max)); + } + return value; + } + + /** + * 检查值是否在指定范围内 + * + * @param value 值 + * @param min 最小值(包含) + * @param max 最大值(包含) + * @return 检查后的长度值 number + * @since 4.1.10 + */ + public static Number checkBetween(Number value, Number min, Number max) throws ArgumentException { + notNull(value); + notNull(min); + notNull(max); + double valueDouble = value.doubleValue(); + double minDouble = min.doubleValue(); + double maxDouble = max.doubleValue(); + if (valueDouble < minDouble || valueDouble > maxDouble) { + throw new ArgumentException(StrUtil.format("Length must be between {} and {}.", min, max)); + } + return value; + } + + /** + * 断言2个字符串是否相等,如果不等用指定错误码抛出异常 + * + * @param expected 预期的值 + * @param actual 需要比较的字符串expected + * @param errorMsgTemplate 错误抛出异常附带的消息模板,变量用{}代替 + * @param params 参数列表 + * @throws ArgumentException if expression is {@code false} + */ + public static void equals(Object expected, Object actual, String errorMsgTemplate, Object... params) throws ArgumentException { + equals(expected, actual, () -> new ArgumentException(StrUtil.format(errorMsgTemplate, params))); + } + + /** + * 断言2个字符串是否相等,如果 不相等 抛出给定的异常 + * + * @param expected 预期的值 + * @param actual 需要比较的字符串 + * @param supplier 指定断言不通过时抛出的异常 + * @throws X if expression is {@code false} + */ + public static void equals(Object expected, Object actual, Supplier supplier) throws X { + if (!ObjectUtil.equals(expected, actual)) { + throw supplier.get(); + } + } + + // -------------------------------------------------------------------------------------------------------------------------------------------- Private method start + + /** + * 错误的下标时显示的消息 + * + * @param index 下标 + * @param size 长度 + * @param desc 异常时的消息模板 + * @param params 参数列表 + * @return 消息 + */ + private static String badIndexMsg(int index, int size, String desc, Object... params) throws ArgumentException { + if (index < 0) { + return StrUtil.format("{} ({}) must not be negative", StrUtil.format(desc, params), index); + } else if (size < 0) { + throw new ArgumentException("negative size: " + size); + } else { // index >= size + return StrUtil.format("{} ({}) must be less than size ({})", StrUtil.format(desc, params), index, size); + } + } + // -------------------------------------------------------------------------------------------------------------------------------------------- Private method end +} diff --git a/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/StrPool.java b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/StrPool.java new file mode 100755 index 00000000..7d4fd9a7 --- /dev/null +++ b/thinglinks-common/thinglinks-common-core/src/main/java/com/mqttsnet/thinglinks/common/core/utils/StrPool.java @@ -0,0 +1,141 @@ +package com.mqttsnet.thinglinks.common.core.utils; + +import cn.hutool.core.util.RandomUtil; + +/** + * 常用字符串 + * + * @author mqttsnet + * @date 2019/07/25 + */ +public interface StrPool { + String AMPERSAND = "&"; + String AND = "and"; + String AT = "@"; + String ASTERISK = "*"; + String STAR = "*"; + String BACK_SLASH = "\\"; + String COLON = ":"; + String COMMA = ","; + String DASH = "-"; + String DOLLAR = "$"; + String DOT = "."; + String DOTDOT = ".."; + String DOT_CLASS = ".class"; + String DOT_JAVA = ".java"; + String DOT_XML = ".xml"; + String EMPTY = ""; + String EQUALS = "="; + String FALSE = "false"; + String SLASH = "/"; + String HASH = "#"; + String HAT = "^"; + String LEFT_BRACE = "{"; + String BRACE = "{}"; + String LEFT_BRACKET = "("; + char LEFT_BRACKET_CHAR = '('; + String LEFT_CHEV = "<"; + String NEWLINE = "\n"; + String N = "n"; + String NO = "no"; + String NULL = "null"; + String OFF = "off"; + String ON = "on"; + String PERCENT = "%"; + String PIPE = "|"; + String PLUS = "+"; + String QUESTION_MARK = "?"; + String EXCLAMATION_MARK = "!"; + String QUOTE = "\""; + String RETURN = "\r"; + String TAB = "\t"; + String RIGHT_BRACE = "}"; + String RIGHT_BRACKET = ")"; + String RIGHT_CHEV = ">"; + String SEMICOLON = ";"; + String SINGLE_QUOTE = "'"; + String BACKTICK = "`"; + String SPACE = " "; + String TILDA = "~"; + String LEFT_SQ_BRACKET = "["; + String RIGHT_SQ_BRACKET = "]"; + String TRUE = "true"; + String UNDERSCORE = "_"; + String UTF_8 = "UTF-8"; + String GBK = "GBK"; + String US_ASCII = "US-ASCII"; + String ISO_8859_1 = "ISO-8859-1"; + String Y = "y"; + String YES = "yes"; + String ONE = "1"; + String ZERO = "0"; + String DOLLAR_LEFT_BRACE = "${"; + String HASH_LEFT_BRACE = "#{"; + String CRLF = "\r\n"; + String HTML_NBSP = " "; + String HTML_AMP = "&"; + String HTML_QUOTE = """; + String HTML_LT = "<"; + String HTML_GT = ">"; + String STRING_TYPE_NAME = "java.lang.String"; + String LONG_TYPE_NAME = "java.lang.Long"; + String BYTE_TYPE_NAME = "java.lang.Byte"; + String CHARACTER_TYPE_NAME = "java.lang.Character"; + String INTEGER_TYPE_NAME = "java.lang.Integer"; + String SHORT_TYPE_NAME = "java.lang.Short"; + String DOUBLE_TYPE_NAME = "java.lang.Double"; + String FLOAT_TYPE_NAME = "java.lang.Float"; + String BOOLEAN_TYPE_NAME = "java.lang.Boolean"; + String SET_TYPE_NAME = "java.util.Set"; + String LIST_TYPE_NAME = "java.util.List"; + String COLLECTION_TYPE_NAME = "java.util.Collection"; + String DATE_TYPE_NAME = "java.util.Date"; + String LOCAL_DATE_TIME_TYPE_NAME = "java.time.LocalDateTime"; + String LOCAL_DATE_TYPE_NAME = "java.time.LocalDate"; + String LOCAL_TIME_TYPE_NAME = "java.time.LocalTime"; + String JAVA_TEMP_DIR = "java.io.tmpdir"; + + String ARRAY = "Array"; + String INTEGER = "Integer"; + String FLOAT = "Float"; + String DATETIME = "DateTime"; + String DATE = "Date"; + String TIME = "Time"; + String BOOLEAN = "Boolean"; + + + String HTTPS_PREFIX = "https://"; + String HTTP_PREFIX = "http://"; + String HTTPS = "https"; + String HTTP = "http"; + /** + * 编码 + */ + String UTF8 = "UTF-8"; + /** + * JSON 资源 + */ + String CONTENT_TYPE = "application/json; charset=utf-8"; + + /** + * 用于随机选的字符 + */ + String BASE_UPPER_CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + /** + * 用于随机选的字符和数字 + */ + String BASE_ALL_CHAR_NUMBER = BASE_UPPER_CHAR + RandomUtil.BASE_CHAR + RandomUtil.BASE_NUMBER; + + + String TEST_TOKEN = "Bearer test"; + String DEV = "dev"; + String TEST = "test"; + String PROD = "prod"; + + /** + * 默认的父id + */ + Long DEF_PARENT_ID = 0L; + + String UNKNOW = "unknown"; +} diff --git a/thinglinks-gateway/src/main/java/com/mqttsnet/thinglinks/gateway/ThingLinksGatewayApplication.java b/thinglinks-gateway/src/main/java/com/mqttsnet/thinglinks/gateway/ThingLinksGatewayApplication.java index dea65a24..ff21a8ba 100644 --- a/thinglinks-gateway/src/main/java/com/mqttsnet/thinglinks/gateway/ThingLinksGatewayApplication.java +++ b/thinglinks-gateway/src/main/java/com/mqttsnet/thinglinks/gateway/ThingLinksGatewayApplication.java @@ -1,26 +1,33 @@ package com.mqttsnet.thinglinks.gateway; +import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.CrossOrigin; +import java.net.InetAddress; + /** * 网关启动程序 - * + * * @author thinglinks */ +@Slf4j //实现跨域注解 //origin="*"代表所有域名都可访问 //maxAge飞行前响应的缓存持续时间的最大年龄,简单来说就是Cookie的有效期 单位为秒 //若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失 -@CrossOrigin(origins = "*",maxAge = 3600) -@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class },scanBasePackages = {"com.mqttsnet.thinglinks"}) -public class ThingLinksGatewayApplication -{ - public static void main(String[] args) - { - SpringApplication.run(ThingLinksGatewayApplication.class, args); - System.out.println("(♥◠‿◠)ノ゙ ThingLinks网关启动成功 ლ(´ڡ`ლ)゙ "); +@CrossOrigin(origins = "*", maxAge = 3600) +@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}, scanBasePackages = {"com.mqttsnet.thinglinks"}) +public class ThingLinksGatewayApplication { + public static void main(String[] args) throws Exception { + ConfigurableApplicationContext application = SpringApplication.run(ThingLinksGatewayApplication.class, args); + Environment env = application.getEnvironment(); + log.info("\n----------------------------------------------------------\n\t" + "应用 '{}' 启动成功! 访问连接:\n\t" + "Swagger文档: \t\thttp://{}:{}/swagger-ui.html\n\t" + + "数据库监控: \t\thttp://{}:{}/druid\n" + "----------------------------------------------------------", env.getProperty("spring.application.name"), + InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port", "8080"), "127.0.0.1", env.getProperty("server.port", "8080")); } } diff --git a/thinglinks-modules/thinglinks-modules-broker/pom.xml b/thinglinks-modules/thinglinks-modules-broker/pom.xml index 27ee1299..1dd7ac77 100644 --- a/thinglinks-modules/thinglinks-modules-broker/pom.xml +++ b/thinglinks-modules/thinglinks-modules-broker/pom.xml @@ -27,12 +27,24 @@ spring-cloud-starter-alibaba-nacos-config + + + com.alibaba.cloud + spring-cloud-starter-alibaba-sentinel + + org.springframework.boot spring-boot-starter-actuator + + + mysql + mysql-connector-java + + com.mqttsnet @@ -47,6 +59,13 @@ ${thinglinks.version} + + + com.mqttsnet + thinglinks-common-log + ${thinglinks.version} + + com.mqttsnet @@ -54,10 +73,11 @@ ${thinglinks.version} - + + com.mqttsnet - thinglinks-common-log + thinglinks-common-rocketmq ${thinglinks.version} @@ -74,33 +94,29 @@ thinglinks-common-protocol ${thinglinks.version} - - - - com.mqttsnet - thinglinks-api-link - ${thinglinks.version} - - org.springframework.boot spring-boot-starter-websocket + + com.mqttsnet - thinglinks-api-broker + thinglinks-api-link ${thinglinks.version} + com.mqttsnet - thinglinks-modules-link + thinglinks-api-broker ${thinglinks.version} + com.mqttsnet - thinglinks-modules-tdengine + thinglinks-api-tdengine ${thinglinks.version} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/ThingLinksBrokerApplication.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/ThingLinksBrokerApplication.java index a9ae0cf3..66ea0ebe 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/ThingLinksBrokerApplication.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/ThingLinksBrokerApplication.java @@ -2,15 +2,21 @@ import com.mqttsnet.thinglinks.common.security.annotation.EnableRyFeignClients; import com.mqttsnet.thinglinks.common.swagger.annotation.EnableCustomSwagger2; +import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.CrossOrigin; +import java.net.InetAddress; + /** * Broker * * @author thinglinks */ +@Slf4j @EnableCustomSwagger2 @EnableRyFeignClients //实现跨域注解 @@ -20,8 +26,11 @@ @CrossOrigin(origins = "*", maxAge = 3600) @SpringBootApplication(scanBasePackages = {"com.mqttsnet.thinglinks"}) public class ThingLinksBrokerApplication { - public static void main(String[] args) { - SpringApplication.run(ThingLinksBrokerApplication.class, args); - System.out.println("(♥◠‿◠)ノ゙ Broker模块启动成功 ლ(´ڡ`ლ)゙ "); + public static void main(String[] args) throws Exception { + ConfigurableApplicationContext application = SpringApplication.run(ThingLinksBrokerApplication.class, args); + Environment env = application.getEnvironment(); + log.info("\n----------------------------------------------------------\n\t" + "应用 '{}' 启动成功! 访问连接:\n\t" + "Swagger文档: \t\thttp://{}:{}/swagger-ui.html\n\t" + + "数据库监控: \t\thttp://{}:{}/druid\n" + "----------------------------------------------------------", env.getProperty("spring.application.name"), + InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port", "8080"), "127.0.0.1", env.getProperty("server.port", "8080")); } } diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/common/asyncthread/BrokerAsyncConfig.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/common/asyncthread/BrokerAsyncConfig.java index 30a9848d..3be52f61 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/common/asyncthread/BrokerAsyncConfig.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/common/asyncthread/BrokerAsyncConfig.java @@ -70,6 +70,7 @@ public Executor brokerAsync() { return executor; } + /** * MQTT设备消息消费异步线程池配置 */ @@ -90,5 +91,65 @@ public Executor brokerAsyncMqttMsg() { return executor; } + /** + * HTTP设备消息消费异步线程池配置 + */ + @Bean("brokerAsync-httpMsg") + public Executor mqsAsyncHttpMsg() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(corePoolSize);//核心线程数 + executor.setMaxPoolSize(maxPoolSize);//最大线程数 cpu核数/(1-0.8)//cup核数*2//cup核数+1 + //传参正值使用无界LinkedBlockingQueue + //其他传参使用不缓存SynchronousQueue + executor.setQueueCapacity(queueCapacity);//队列长度(超过队列长度无法存储,则开启最大线程数) + executor.setKeepAliveSeconds(keepAliveTime);//空闲线程最大存活时间 默认60s + executor.setThreadNamePrefix(threadNamePrefix + "brokerAsync-httpMsg");//线程名前缀 + executor.setRejectedExecutionHandler(rejectHandle);//自定义任务丢失处理策略 该策略输出由scheduling-1打印 + executor.setWaitForTasksToCompleteOnShutdown(true); + executor.setAwaitTerminationSeconds(keepAliveTime); + executor.initialize(); + return executor; + } + + /** + * webSocket设备消息消费异步线程池配置 + */ + @Bean("brokerAsync-webSocketMsg") + public Executor brokerAsyncWebSocketMsg() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(corePoolSize);//核心线程数 + executor.setMaxPoolSize(maxPoolSize);//最大线程数 cpu核数/(1-0.8)//cup核数*2//cup核数+1 + //传参正值使用无界LinkedBlockingQueue + //其他传参使用不缓存SynchronousQueue + executor.setQueueCapacity(queueCapacity);//队列长度(超过队列长度无法存储,则开启最大线程数) + executor.setKeepAliveSeconds(keepAliveTime);//空闲线程最大存活时间 默认60s + executor.setThreadNamePrefix(threadNamePrefix + "brokerAsync-webSocketMsg");//线程名前缀 + executor.setRejectedExecutionHandler(rejectHandle);//自定义任务丢失处理策略 该策略输出由scheduling-1打印 + executor.setWaitForTasksToCompleteOnShutdown(true); + executor.setAwaitTerminationSeconds(keepAliveTime); + executor.initialize(); + return executor; + } + + /** + * TCP设备消息消费异步线程池配置 + */ + @Bean("brokerAsync-tcpMsg") + public Executor brokerAsyncTcpMsg() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(corePoolSize);//核心线程数 + executor.setMaxPoolSize(maxPoolSize);//最大线程数 cpu核数/(1-0.8)//cup核数*2//cup核数+1 + //传参正值使用无界LinkedBlockingQueue + //其他传参使用不缓存SynchronousQueue + executor.setQueueCapacity(queueCapacity);//队列长度(超过队列长度无法存储,则开启最大线程数) + executor.setKeepAliveSeconds(keepAliveTime);//空闲线程最大存活时间 默认60s + executor.setThreadNamePrefix(threadNamePrefix + "brokerAsync-tcpMsg");//线程名前缀 + executor.setRejectedExecutionHandler(rejectHandle);//自定义任务丢失处理策略 该策略输出由scheduling-1打印 + executor.setWaitForTasksToCompleteOnShutdown(true); + executor.setAwaitTerminationSeconds(keepAliveTime); + executor.initialize(); + return executor; + } + } diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaProducerService.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/consumer/kafka/KafkaProducerService.java similarity index 96% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaProducerService.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/consumer/kafka/KafkaProducerService.java index efb1fe4d..1c7133d0 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaProducerService.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/consumer/kafka/KafkaProducerService.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.broker.mqs.handler.kafka; +package com.mqttsnet.thinglinks.broker.mqs.consumer.kafka; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaSendResultHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/consumer/kafka/KafkaSendResultHandler.java similarity index 94% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaSendResultHandler.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/consumer/kafka/KafkaSendResultHandler.java index ee0d2df1..2024b749 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/KafkaSendResultHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/consumer/kafka/KafkaSendResultHandler.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.broker.mqs.handler.kafka; +package com.mqttsnet.thinglinks.broker.mqs.consumer.kafka; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.clients.producer.ProducerRecord; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MqttMessageKafkaConsumerHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/consumer/kafka/MqttMessageKafkaConsumerHandler.java similarity index 52% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MqttMessageKafkaConsumerHandler.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/consumer/kafka/MqttMessageKafkaConsumerHandler.java index 0c922a14..4c2f37af 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MqttMessageKafkaConsumerHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/consumer/kafka/MqttMessageKafkaConsumerHandler.java @@ -1,15 +1,11 @@ -package com.mqttsnet.thinglinks.broker.mqs.handler.kafka; +package com.mqttsnet.thinglinks.broker.mqs.consumer.kafka; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; -import com.mqttsnet.thinglinks.broker.mqs.event.publisher.MqttEventPublisher; +import com.mqttsnet.thinglinks.broker.mqs.protocol.ProtocolHandlerFactory; +import com.mqttsnet.thinglinks.broker.mqs.protocol.handler.ProtocolHandler; import com.mqttsnet.thinglinks.common.core.mqs.ConsumerTopicConstant; -import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; +import com.mqttsnet.thinglinks.link.api.domain.product.enumeration.ProtocolTypeEnum; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.annotation.KafkaHandler; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.kafka.support.Acknowledgment; @@ -19,9 +15,8 @@ import java.util.Optional; /** - * @program: thinglinks + * @program: thinglinks-cloud-pro-datasource-column * @description: Mqtt Message kafka监听消息 - * @packagename: com.mqttsnet.thinglinks.kafka * @author: ShiHuan Sun * @e-mainl: 13733918655@163.com * @date: 2023-06-18 11:46 @@ -30,11 +25,11 @@ @Component public class MqttMessageKafkaConsumerHandler { - @Autowired - private MqttEventPublisher eventPublisher; + private final ProtocolHandlerFactory protocolHandlerFactory; - @Autowired - private CacheDataHelper cacheDataHelper; + public MqttMessageKafkaConsumerHandler(ProtocolHandlerFactory protocolHandlerFactory) { + this.protocolHandlerFactory = protocolHandlerFactory; + } /** * 监听kafka消息(批量) @@ -84,45 +79,13 @@ public void handleBatchMessages(List> records, Acknowledgme private void processMessage(String message) { log.info("ThingLinks物联网平台数据消费-->Received message={}", message); try { - JSONObject thinglinksMessage = JSON.parseObject(String.valueOf(message)); - String eventStr = Optional.ofNullable(thinglinksMessage.getString("event")) - .orElse(""); - Long tenantId = Optional.ofNullable(thinglinksMessage.getString("tenantId")) - .filter(StringUtils::isNotBlank) - .map(Long::valueOf) - .orElse(null); - if (StringUtils.isEmpty(eventStr) || tenantId == null) { - log.warn("event or tenantId cannot be empty {}", eventStr); - return; + ProtocolHandler handler = protocolHandlerFactory.getHandler(ProtocolTypeEnum.MQTT); + if (handler != null) { + handler.processMessage(message); + } else { + log.error("未找到对应的协议处理器: " + ProtocolTypeEnum.MQTT); + throw new IllegalStateException("未找到对应的协议处理器: " + ProtocolTypeEnum.MQTT); } - Optional optionalEvent = MqttEventEnum.getMqttEventEnum(thinglinksMessage.get("event").toString()); - optionalEvent.ifPresent(event -> { - switch (event) { - case CONNECT: - eventPublisher.publishMqttConnectEvent(MqttEventEnum.CONNECT, thinglinksMessage.toJSONString()); - break; - case CLOSE: - eventPublisher.publishMqttCloseEvent(MqttEventEnum.CLOSE, thinglinksMessage.toJSONString()); - break; - case DISCONNECT: - eventPublisher.publishMqttDisconnectEvent(MqttEventEnum.DISCONNECT, thinglinksMessage.toJSONString()); - break; - case PUBLISH: - eventPublisher.publishMqttPublishEvent(MqttEventEnum.PUBLISH, thinglinksMessage.toJSONString()); - break; - case SUBSCRIBE: - eventPublisher.publishMqttSubscribeEvent(MqttEventEnum.SUBSCRIBE, thinglinksMessage.toJSONString()); - break; - case UNSUBSCRIBE: - eventPublisher.publishMqttUnsubscribeEvent(MqttEventEnum.UNSUBSCRIBE, thinglinksMessage.toJSONString()); - break; - case PING: - eventPublisher.publishMqttPingEvent(MqttEventEnum.PING, thinglinksMessage.toJSONString()); - break; - default: - break; - } - }); } catch (Exception e) { log.error("ThingLinks物联网平台数据消费-->消费失败,失败原因:{}", e.getMessage()); } diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MyKafkaListenerErrorHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/consumer/kafka/MyKafkaListenerErrorHandler.java similarity index 95% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MyKafkaListenerErrorHandler.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/consumer/kafka/MyKafkaListenerErrorHandler.java index efb1801f..8e3ec1cd 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/handler/kafka/MyKafkaListenerErrorHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/consumer/kafka/MyKafkaListenerErrorHandler.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.broker.mqs.handler.kafka; +package com.mqttsnet.thinglinks.broker.mqs.consumer.kafka; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.clients.consumer.Consumer; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/consumer/rocketmq/MqttMessageRocketmqConsumerHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/consumer/rocketmq/MqttMessageRocketmqConsumerHandler.java new file mode 100644 index 00000000..34e49fb0 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/consumer/rocketmq/MqttMessageRocketmqConsumerHandler.java @@ -0,0 +1,82 @@ +package com.mqttsnet.thinglinks.broker.mqs.consumer.rocketmq; + + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.event.publisher.MqttEventPublisher; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.rocketmq.spring.core.RocketMQListener; +import org.springframework.scheduling.annotation.Async; + +import javax.annotation.Resource; +import java.util.Optional; + +/** + * @Description: Mqtt Message Rocketmq模式 消费者 + * @ClassName: MqttMessageRocketmqConsumerHandler + * @Date: 2023/04/28$ 16:11$ + * @author: ShiHuan Sun + */ +@Slf4j +//@Component +//@RocketMQMessageListener(consumerGroup = ConsumerGroupConstant.THINGLINKS_GROUP, topic = ConsumerTopicConstant.Mqtt.THINGLINKS_MQS_MQTT_MSG, messageModel = MessageModel.CLUSTERING) +public class MqttMessageRocketmqConsumerHandler implements RocketMQListener { + + @Resource + private MqttEventPublisher eventPublisher; + + @Async("mqsAsync-mqttMsg") + @Override + public void onMessage(Object message) { + if (null == message) { + log.warn("message cannot be empty {}", message); + return; + } + log.info("ThingLinks物联网平台数据消费-->Received message={}", message); + try { + JSONObject thinglinksMessage = JSON.parseObject(String.valueOf(message)); + String eventStr = Optional.ofNullable(thinglinksMessage.getString("event")) + .orElse(""); + Long tenantId = Optional.ofNullable(thinglinksMessage.getString("tenantId")) + .filter(StringUtils::isNotBlank) + .map(Long::valueOf) + .orElse(null); + if (StringUtils.isEmpty(eventStr) || tenantId == null) { + log.warn("event or tenantId cannot be empty {}", eventStr); + return; + } + Optional optionalEvent = MqttEventEnum.getMqttEventEnum(thinglinksMessage.get("event").toString()); + optionalEvent.ifPresent(event -> { + switch (event) { + case CONNECT: + eventPublisher.publishMqttConnectEvent(MqttEventEnum.CONNECT, thinglinksMessage.toJSONString()); + break; + case CLOSE: + eventPublisher.publishMqttCloseEvent(MqttEventEnum.CLOSE, thinglinksMessage.toJSONString()); + break; + case DISCONNECT: + eventPublisher.publishMqttDisconnectEvent(MqttEventEnum.DISCONNECT, thinglinksMessage.toJSONString()); + break; + case PUBLISH: + eventPublisher.publishMqttPublishEvent(MqttEventEnum.PUBLISH, thinglinksMessage.toJSONString()); + break; + case SUBSCRIBE: + eventPublisher.publishMqttSubscribeEvent(MqttEventEnum.SUBSCRIBE, thinglinksMessage.toJSONString()); + break; + case UNSUBSCRIBE: + eventPublisher.publishMqttUnsubscribeEvent(MqttEventEnum.UNSUBSCRIBE, thinglinksMessage.toJSONString()); + break; + case PING: + eventPublisher.publishMqttPingEvent(MqttEventEnum.PING, thinglinksMessage.toJSONString()); + break; + default: + break; + } + }); + } catch (Exception e) { + log.error("ThingLinks物联网平台数据消费-->消费失败,失败原因:{}", e.getMessage()); + } + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttCloseEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttCloseEvent.java similarity index 93% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttCloseEvent.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttCloseEvent.java index d303e952..29f2617f 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttCloseEvent.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttCloseEvent.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.broker.mqs.event; +package com.mqttsnet.thinglinks.broker.mqs.mqtt.event; import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; import org.springframework.context.ApplicationEvent; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttConnectEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttConnectEvent.java similarity index 93% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttConnectEvent.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttConnectEvent.java index 093d600a..f9f95ef6 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttConnectEvent.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttConnectEvent.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.broker.mqs.event; +package com.mqttsnet.thinglinks.broker.mqs.mqtt.event; import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; import org.springframework.context.ApplicationEvent; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttDisconnectEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttDisconnectEvent.java similarity index 93% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttDisconnectEvent.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttDisconnectEvent.java index d50b6283..eca40b7f 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttDisconnectEvent.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttDisconnectEvent.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.broker.mqs.event; +package com.mqttsnet.thinglinks.broker.mqs.mqtt.event; import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; import org.springframework.context.ApplicationEvent; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPingEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttPingEvent.java similarity index 93% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPingEvent.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttPingEvent.java index cc31e446..1a857b99 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPingEvent.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttPingEvent.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.broker.mqs.event; +package com.mqttsnet.thinglinks.broker.mqs.mqtt.event; import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; import org.springframework.context.ApplicationEvent; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPublishEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttPublishEvent.java similarity index 93% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPublishEvent.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttPublishEvent.java index 19bdf4e1..6fb41cb0 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttPublishEvent.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttPublishEvent.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.broker.mqs.event; +package com.mqttsnet.thinglinks.broker.mqs.mqtt.event; import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; import org.springframework.context.ApplicationEvent; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttSubscribeEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttSubscribeEvent.java similarity index 93% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttSubscribeEvent.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttSubscribeEvent.java index 6b24374d..0e1e0d46 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttSubscribeEvent.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttSubscribeEvent.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.broker.mqs.event; +package com.mqttsnet.thinglinks.broker.mqs.mqtt.event; import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; import org.springframework.context.ApplicationEvent; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttUnsubscribeEvent.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttUnsubscribeEvent.java similarity index 93% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttUnsubscribeEvent.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttUnsubscribeEvent.java index 31051bef..6c527573 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/MqttUnsubscribeEvent.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/MqttUnsubscribeEvent.java @@ -1,4 +1,4 @@ -package com.mqttsnet.thinglinks.broker.mqs.event; +package com.mqttsnet.thinglinks.broker.mqs.mqtt.event; import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; import org.springframework.context.ApplicationEvent; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttCloseEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttCloseEventListener.java similarity index 95% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttCloseEventListener.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttCloseEventListener.java index 18a956a3..41cad454 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttCloseEventListener.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttCloseEventListener.java @@ -1,7 +1,7 @@ -package com.mqttsnet.thinglinks.broker.mqs.event.listener; +package com.mqttsnet.thinglinks.broker.mqs.mqtt.event.listener; import com.google.gson.Gson; -import com.mqttsnet.thinglinks.broker.mqs.event.MqttCloseEvent; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.event.MqttCloseEvent; import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventActionService; import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatusEnum; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttConnectEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttConnectEventListener.java similarity index 95% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttConnectEventListener.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttConnectEventListener.java index 4c17644b..cb32e9e8 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttConnectEventListener.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttConnectEventListener.java @@ -1,7 +1,7 @@ -package com.mqttsnet.thinglinks.broker.mqs.event.listener; +package com.mqttsnet.thinglinks.broker.mqs.mqtt.event.listener; import com.google.gson.Gson; -import com.mqttsnet.thinglinks.broker.mqs.event.MqttConnectEvent; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.event.MqttConnectEvent; import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventActionService; import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatusEnum; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttDisconnectEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttDisconnectEventListener.java similarity index 95% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttDisconnectEventListener.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttDisconnectEventListener.java index 6849df7d..9a82b1ae 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttDisconnectEventListener.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttDisconnectEventListener.java @@ -1,7 +1,7 @@ -package com.mqttsnet.thinglinks.broker.mqs.event.listener; +package com.mqttsnet.thinglinks.broker.mqs.mqtt.event.listener; import com.google.gson.Gson; -import com.mqttsnet.thinglinks.broker.mqs.event.MqttDisconnectEvent; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.event.MqttDisconnectEvent; import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventActionService; import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.common.core.enums.DeviceConnectStatusEnum; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPingEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttPingEventListener.java similarity index 85% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPingEventListener.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttPingEventListener.java index b79dc140..9de399cd 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPingEventListener.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttPingEventListener.java @@ -1,6 +1,6 @@ -package com.mqttsnet.thinglinks.broker.mqs.event.listener; +package com.mqttsnet.thinglinks.broker.mqs.mqtt.event.listener; -import com.mqttsnet.thinglinks.broker.mqs.event.MqttPingEvent; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.event.MqttPingEvent; import lombok.extern.slf4j.Slf4j; import org.springframework.context.event.EventListener; import org.springframework.scheduling.annotation.Async; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPublishEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttPublishEventListener.java similarity index 93% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPublishEventListener.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttPublishEventListener.java index 117a6a71..d38af9bb 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttPublishEventListener.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttPublishEventListener.java @@ -1,9 +1,9 @@ -package com.mqttsnet.thinglinks.broker.mqs.event.listener; +package com.mqttsnet.thinglinks.broker.mqs.mqtt.event.listener; import cn.hutool.json.JSONUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; -import com.mqttsnet.thinglinks.broker.mqs.event.MqttPublishEvent; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.event.MqttPublishEvent; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.event.MqttMessageEvent; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttSubscribeEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttSubscribeEventListener.java similarity index 90% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttSubscribeEventListener.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttSubscribeEventListener.java index 2d8e4a37..ba264c4f 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttSubscribeEventListener.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttSubscribeEventListener.java @@ -1,6 +1,6 @@ -package com.mqttsnet.thinglinks.broker.mqs.event.listener; +package com.mqttsnet.thinglinks.broker.mqs.mqtt.event.listener; -import com.mqttsnet.thinglinks.broker.mqs.event.MqttSubscribeEvent; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.event.MqttSubscribeEvent; import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventActionService; import com.mqttsnet.thinglinks.link.api.domain.device.enumeration.DeviceActionTypeEnum; import lombok.extern.slf4j.Slf4j; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttUnsubscribeEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttUnsubscribeEventListener.java similarity index 90% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttUnsubscribeEventListener.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttUnsubscribeEventListener.java index 6c9958e9..58528bce 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/listener/MqttUnsubscribeEventListener.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/listener/MqttUnsubscribeEventListener.java @@ -1,6 +1,6 @@ -package com.mqttsnet.thinglinks.broker.mqs.event.listener; +package com.mqttsnet.thinglinks.broker.mqs.mqtt.event.listener; -import com.mqttsnet.thinglinks.broker.mqs.event.MqttUnsubscribeEvent; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.event.MqttUnsubscribeEvent; import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventActionService; import com.mqttsnet.thinglinks.link.api.domain.device.enumeration.DeviceActionTypeEnum; import lombok.extern.slf4j.Slf4j; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/publisher/MqttEventPublisher.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/publisher/MqttEventPublisher.java similarity index 95% rename from thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/publisher/MqttEventPublisher.java rename to thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/publisher/MqttEventPublisher.java index fb1dafea..5e3f0fe3 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/event/publisher/MqttEventPublisher.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/event/publisher/MqttEventPublisher.java @@ -1,7 +1,7 @@ -package com.mqttsnet.thinglinks.broker.mqs.event.publisher; +package com.mqttsnet.thinglinks.broker.mqs.mqtt.event.publisher; import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; -import com.mqttsnet.thinglinks.broker.mqs.event.*; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.event.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/AddSubDeviceHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/AddSubDeviceHandler.java index d5bd07f2..62abe392 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/AddSubDeviceHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/AddSubDeviceHandler.java @@ -8,11 +8,11 @@ import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.common.redis.service.RedisService; import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoAddSubDeviceParam; import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; -import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -32,11 +32,11 @@ public class AddSubDeviceHandler extends AbstractMessageHandler implements Topic private static final ObjectMapper objectMapper = new ObjectMapper(); - public AddSubDeviceHandler(CacheDataHelper cacheDataHelper, + public AddSubDeviceHandler(RedisService redisService, RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + super(redisService, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } /** diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/CommandResponseHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/CommandResponseHandler.java index 8d414c63..440d2188 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/CommandResponseHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/CommandResponseHandler.java @@ -5,10 +5,9 @@ import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventCommandService; +import com.mqttsnet.thinglinks.common.redis.service.RedisService; import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; -import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; -import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -26,11 +25,11 @@ @Slf4j @Service public class CommandResponseHandler extends AbstractMessageHandler implements TopicHandler { - public CommandResponseHandler(CacheDataHelper cacheDataHelper, + public CommandResponseHandler(RedisService redisService, RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + super(redisService, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } @Autowired diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeleteSubDeviceHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeleteSubDeviceHandler.java index 64489e9a..421111ec 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeleteSubDeviceHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeleteSubDeviceHandler.java @@ -8,11 +8,11 @@ import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.common.redis.service.RedisService; import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoDeleteSubDeviceParam; import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; -import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -32,11 +32,11 @@ public class DeleteSubDeviceHandler extends AbstractMessageHandler implements To private static final ObjectMapper objectMapper = new ObjectMapper(); - public DeleteSubDeviceHandler(CacheDataHelper cacheDataHelper, + public DeleteSubDeviceHandler(RedisService redisService, RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + super(redisService, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } /** diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeviceDatasHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeviceDatasHandler.java index a91e78a1..ab429d5b 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeviceDatasHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/DeviceDatasHandler.java @@ -13,6 +13,7 @@ import com.mqttsnet.thinglinks.common.core.utils.DateUtils; import com.mqttsnet.thinglinks.common.core.utils.StringUtils; import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; +import com.mqttsnet.thinglinks.common.redis.service.RedisService; import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductModelCacheVO; @@ -22,13 +23,12 @@ import com.mqttsnet.thinglinks.link.api.domain.product.vo.result.ProductResultVO; import com.mqttsnet.thinglinks.link.api.domain.product.vo.result.ProductServiceResultVO; import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoDeviceDataReportParam; -import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; import com.mqttsnet.thinglinks.tdengine.api.RemoteTdEngineService; import com.mqttsnet.thinglinks.tdengine.api.domain.Fields; import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDescribeVO; import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; -import com.mqttsnet.thinglinks.tdengine.common.constant.TdsConstants; -import com.mqttsnet.thinglinks.tdengine.utils.TdsUtils; +import com.mqttsnet.thinglinks.tdengine.api.constant.TdsConstants; +import com.mqttsnet.thinglinks.tdengine.api.utils.TdsUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -48,11 +48,11 @@ @Service public class DeviceDatasHandler extends AbstractMessageHandler implements TopicHandler { - public DeviceDatasHandler(CacheDataHelper cacheDataHelper, + public DeviceDatasHandler(RedisService redisService, RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + super(redisService, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } @Resource diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/OtaCommandResponseHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/OtaCommandResponseHandler.java index 5c3ee2ca..5cc73d20 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/OtaCommandResponseHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/OtaCommandResponseHandler.java @@ -5,9 +5,9 @@ import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; import com.mqttsnet.thinglinks.broker.mqs.mqtt.service.MqttEventOtaCommandResponseService; +import com.mqttsnet.thinglinks.common.redis.service.RedisService; import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; -import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -25,11 +25,11 @@ @Slf4j @Service public class OtaCommandResponseHandler extends AbstractMessageHandler implements TopicHandler { - public OtaCommandResponseHandler(CacheDataHelper cacheDataHelper, + public OtaCommandResponseHandler(RedisService redisService, RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + super(redisService, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } @Autowired diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/QueryDeviceHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/QueryDeviceHandler.java index 5277b405..944be02d 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/QueryDeviceHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/QueryDeviceHandler.java @@ -8,11 +8,11 @@ import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.common.redis.service.RedisService; import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoQueryDeviceParam; import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoQueryDeviceResultVO; -import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -32,11 +32,11 @@ public class QueryDeviceHandler extends AbstractMessageHandler implements TopicH private static final ObjectMapper objectMapper = new ObjectMapper(); - public QueryDeviceHandler(CacheDataHelper cacheDataHelper, + public QueryDeviceHandler(RedisService redisService, RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + super(redisService, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } /** diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/SecretKeyHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/SecretKeyHandler.java index 5583c4d5..f87eb36b 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/SecretKeyHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/SecretKeyHandler.java @@ -5,10 +5,9 @@ import com.mqttsnet.basic.protocol.factory.ProtocolMessageAdapter; import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; +import com.mqttsnet.thinglinks.common.redis.service.RedisService; import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; -import com.mqttsnet.thinglinks.link.api.RemoteDeviceService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; -import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -28,11 +27,11 @@ public class SecretKeyHandler extends AbstractMessageHandler implements TopicHan private static final ObjectMapper objectMapper = new ObjectMapper(); - public SecretKeyHandler(CacheDataHelper cacheDataHelper, + public SecretKeyHandler(RedisService redisService, RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + super(redisService, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } /** diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/UpdateSubDeviceHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/UpdateSubDeviceHandler.java index de008715..eb019e07 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/UpdateSubDeviceHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/UpdateSubDeviceHandler.java @@ -8,11 +8,11 @@ import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.mqs.mqtt.handler.factory.AbstractMessageHandler; import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.common.redis.service.RedisService; import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoUpdateSubDeviceStatusParam; import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; -import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -32,11 +32,11 @@ public class UpdateSubDeviceHandler extends AbstractMessageHandler implements To private static final ObjectMapper objectMapper = new ObjectMapper(); - public UpdateSubDeviceHandler(CacheDataHelper cacheDataHelper, + public UpdateSubDeviceHandler(RedisService redisService, RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, ProtocolMessageAdapter protocolMessageAdapter) { - super(cacheDataHelper, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); + super(redisService, remoteDeviceOpenAnyService, remoteMqttBrokerOpenApi, protocolMessageAdapter); } /** diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/AbstractMessageHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/AbstractMessageHandler.java index a50aad38..e421b21e 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/AbstractMessageHandler.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/handler/factory/AbstractMessageHandler.java @@ -4,15 +4,20 @@ import com.mqttsnet.basic.protocol.factory.ProtocolMessageAdapter; import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.broker.api.domain.vo.PublishMessageRequestVO; +import com.mqttsnet.thinglinks.common.core.constant.CacheConstants; import com.mqttsnet.thinglinks.common.core.utils.SnowflakeIdUtil; +import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; +import com.mqttsnet.thinglinks.common.redis.service.RedisService; import com.mqttsnet.thinglinks.link.api.RemoteDeviceOpenAnyService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductModelCacheVO; -import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; +import com.mqttsnet.thinglinks.link.api.domain.device.entity.Device; import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDescribeVO; import lombok.extern.slf4j.Slf4j; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; /** * @program: thinglinks @@ -25,36 +30,84 @@ @Slf4j public abstract class AbstractMessageHandler { - protected final CacheDataHelper cacheDataHelper; + protected final RedisService redisService; protected final RemoteDeviceOpenAnyService remoteDeviceOpenAnyService; protected final RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi; protected final ProtocolMessageAdapter protocolMessageAdapter; - public AbstractMessageHandler(CacheDataHelper cacheDataHelper, + public AbstractMessageHandler(RedisService redisService, RemoteDeviceOpenAnyService remoteDeviceOpenAnyService, RemoteMqttBrokerOpenApi remoteMqttBrokerOpenApi, ProtocolMessageAdapter protocolMessageAdapter) { - this.cacheDataHelper = cacheDataHelper; + this.redisService = redisService; this.remoteDeviceOpenAnyService = remoteDeviceOpenAnyService; this.remoteMqttBrokerOpenApi = remoteMqttBrokerOpenApi; this.protocolMessageAdapter = protocolMessageAdapter; } protected DeviceCacheVO getDeviceCacheVO(String deviceIdentification) { - return cacheDataHelper.getDeviceCacheVO(deviceIdentification); + if (deviceIdentification == null) { + log.warn("Device identification is null"); + return null; + } + Device deviceCacheObject = redisService.getCacheObject(CacheConstants.DEF_DEVICE + deviceIdentification); + return BeanPlusUtil.toBeanIgnoreError(deviceCacheObject, DeviceCacheVO.class); } protected ProductModelCacheVO getProductModelCacheVO(String productIdentification) { - return cacheDataHelper.getProductModelCacheVO(productIdentification); + if (productIdentification == null) { + log.warn("Product identification is null"); + return null; + } + + ProductModelCacheVO objectCacheResult = redisService.getCacheObject(CacheConstants.DEF_PRODUCT_MODEL + productIdentification); + return BeanPlusUtil.toBeanIgnoreError(objectCacheResult, ProductModelCacheVO.class); } protected List getProductModelSuperTableCacheVO(String productIdentification, String serviceCode, String deviceIdentification) { - return cacheDataHelper.getProductModelSuperTableCacheVO(productIdentification, serviceCode, deviceIdentification); + // 构造缓存键 + String cacheKey = CacheConstants.DEF_PRODUCT_MODEL_SUPER_TABLE + productIdentification + ":" + serviceCode + ":" + deviceIdentification; + + // 尝试从缓存获取数据 + List cacheList; + try { + cacheList = redisService.getCacheList(cacheKey); + } catch (Exception e) { + log.error("Error fetching from cache for key: {}", cacheKey, e); + return Collections.emptyList(); + } + + // 检查缓存结果是否为空 + if (cacheList == null || cacheList.isEmpty()) { + log.warn("The product model super table is not in the cache for key: {}", cacheKey); + return Collections.emptyList(); + } + + // 尝试将缓存结果转换为预期类型的列表 + try { + // 这里假设所有缓存的对象都已经是SuperTableDescribeVO类型的实例 + // 为了安全起见,我们进行一次类型检查 + @SuppressWarnings("unchecked") + List result = (List) cacheList.stream() + .filter(SuperTableDescribeVO.class::isInstance) + .map(SuperTableDescribeVO.class::cast) + .collect(Collectors.toList()); + + if (result.isEmpty()) { + log.warn("The product model super table cache list is empty for key: {}", cacheKey); + } + return result; + } catch (ClassCastException e) { + log.error("Unexpected type in cached list for key: {}", cacheKey, e); + return Collections.emptyList(); + } } protected void setProductModelSuperTableCacheVO(String productIdentification, String serviceCode, String deviceIdentification, List superTableDescribeOpt) { - cacheDataHelper.setProductModelSuperTableCacheVO(productIdentification, serviceCode, deviceIdentification, superTableDescribeOpt); + String cacheKey = CacheConstants.DEF_PRODUCT_MODEL_SUPER_TABLE + productIdentification + ":" + serviceCode + ":" + deviceIdentification; + redisService.delete(cacheKey); + redisService.setCacheObject(cacheKey, superTableDescribeOpt); } protected void sendMessage(String topic, String qos, String message, String tenantId) { diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventActionService.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventActionService.java index fabcd7b7..bdb63d03 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventActionService.java +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/mqtt/service/MqttEventActionService.java @@ -43,12 +43,14 @@ public void saveMqttEventAction(String eventMessage, DeviceActionTypeEnum action map = gson.fromJson(eventMessage, map.getClass()); String clientId = String.valueOf(map.get("clientId")); + log.info("Save MQTT event action: clientId={}, actionType={}, describable={}", clientId, actionType, describable); + // save device action DeviceAction deviceAction = new DeviceAction() .setDeviceIdentification(clientId) .setActionType(actionType.getAction()) .setStatus(ResultEnum.SUCCESS.getMessage()) - .setMessage(describable); + .setMessage(eventMessage); R deviceActionR = remoteDeviceActionService.add(deviceAction); if (ResultEnum.SUCCESS.getCode() != deviceActionR.getCode()) { diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/ProtocolHandlerFactory.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/ProtocolHandlerFactory.java new file mode 100644 index 00000000..80df8dda --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/ProtocolHandlerFactory.java @@ -0,0 +1,63 @@ +package com.mqttsnet.thinglinks.broker.mqs.protocol; + +import com.mqttsnet.thinglinks.broker.mqs.protocol.handler.*; +import com.mqttsnet.thinglinks.link.api.domain.product.enumeration.ProtocolTypeEnum; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * ----------------------------------------------------------------------------- + * File Name: ProtocolHandlerFactory + * ----------------------------------------------------------------------------- + * Description: + * 协议处理工厂 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/11 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email + * @date 2024/3/11 16:26 + */ +@Slf4j +@Component +public class ProtocolHandlerFactory { + private final MqttHandler mqttHandler; + private final WebSocketHandler webSocketHandler; + private final HttpHandler httpHandler; + private final TcpHandler tcpHandler; + + @Autowired + public ProtocolHandlerFactory( + MqttHandler mqttHandler, + WebSocketHandler webSocketHandler, + HttpHandler httpHandler, + TcpHandler tcpHandler) { + this.mqttHandler = mqttHandler; + this.webSocketHandler = webSocketHandler; + this.httpHandler = httpHandler; + this.tcpHandler = tcpHandler; + } + + public ProtocolHandler getHandler(ProtocolTypeEnum type) { + switch (type) { + case MQTT: + return mqttHandler; + case WEBSOCKET: + return webSocketHandler; + case HTTP: + return httpHandler; + case TCP: + return tcpHandler; + default: + log.error("Unknown protocol type: {}", type); + throw new IllegalStateException("Unknown protocol type: " + type); + } + } +} \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/listener/HttpEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/listener/HttpEventListener.java new file mode 100644 index 00000000..4e640593 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/listener/HttpEventListener.java @@ -0,0 +1,46 @@ +package com.mqttsnet.thinglinks.broker.mqs.protocol.event.listener; + +import com.mqttsnet.thinglinks.broker.api.domain.protocol.HttpEvent; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.event.EventListener; +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.Retryable; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +/** + * ----------------------------------------------------------------------------- + * File Name: HttpEventListener + * ----------------------------------------------------------------------------- + * Description: + * HTTP事件监听器 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/11 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@136.com + * @date 2024/3/11 15:50 + */ +@Component +@Slf4j +public class HttpEventListener { + + /** + * 发布HTTP事件 + * + * @param event 事件消息 + */ + @EventListener + @Async("mqsAsync") + @Retryable(value = {Exception.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000)) + public void handleHttpEvent(HttpEvent event) { + log.info("处理HTTP事件: 消息={}", event.getMessage()); + // TODO 实现HTTP事件的处理逻辑 + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/listener/MqttEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/listener/MqttEventListener.java new file mode 100644 index 00000000..0055086c --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/listener/MqttEventListener.java @@ -0,0 +1,102 @@ +package com.mqttsnet.thinglinks.broker.mqs.protocol.event.listener; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.mqttsnet.thinglinks.broker.api.domain.enumeration.MqttEventEnum; +import com.mqttsnet.thinglinks.broker.api.domain.protocol.MqttEvent; +import com.mqttsnet.thinglinks.broker.mqs.mqtt.event.publisher.MqttEventPublisher; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.EventListener; +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.Retryable; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import java.util.Optional; + +/** + * ----------------------------------------------------------------------------- + * File Name: MqttEventListener + * ----------------------------------------------------------------------------- + * Description: + * MQTT事件监听器 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/11 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/11 15:47 + */ + +@Component +@Slf4j +public class MqttEventListener { + + + @Autowired + private MqttEventPublisher eventPublisher; + + /** + * 发布MQTT事件 + * + * @param event 事件消息 + */ + @EventListener + @Async("brokerAsync-mqttMsg") + @Retryable(value = {Exception.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000)) + public void handleMqttEvent(MqttEvent event) { + log.info("处理MQTT事件: 消息={}", event.getMessage()); + try { + JSONObject thinglinksMessage = JSON.parseObject(String.valueOf(event.getMessage())); + String eventStr = Optional.ofNullable(thinglinksMessage.getString("event")) + .orElse(""); + Long tenantId = Optional.ofNullable(thinglinksMessage.getString("tenantId")) + .filter(StringUtils::isNotBlank) + .map(Long::valueOf) + .orElse(null); + if (StringUtils.isEmpty(eventStr) || tenantId == null) { + log.warn("event or tenantId cannot be empty {}", eventStr); + return; + } + Optional optionalEvent = MqttEventEnum.getMqttEventEnum(thinglinksMessage.get("event").toString()); + optionalEvent.ifPresent(eventEnum -> { + switch (eventEnum) { + case CONNECT: + eventPublisher.publishMqttConnectEvent(MqttEventEnum.CONNECT, thinglinksMessage.toJSONString()); + break; + case CLOSE: + eventPublisher.publishMqttCloseEvent(MqttEventEnum.CLOSE, thinglinksMessage.toJSONString()); + break; + case DISCONNECT: + eventPublisher.publishMqttDisconnectEvent(MqttEventEnum.DISCONNECT, thinglinksMessage.toJSONString()); + break; + case PUBLISH: + eventPublisher.publishMqttPublishEvent(MqttEventEnum.PUBLISH, thinglinksMessage.toJSONString()); + break; + case SUBSCRIBE: + eventPublisher.publishMqttSubscribeEvent(MqttEventEnum.SUBSCRIBE, thinglinksMessage.toJSONString()); + break; + case UNSUBSCRIBE: + eventPublisher.publishMqttUnsubscribeEvent(MqttEventEnum.UNSUBSCRIBE, thinglinksMessage.toJSONString()); + break; + case PING: + eventPublisher.publishMqttPingEvent(MqttEventEnum.PING, thinglinksMessage.toJSONString()); + break; + default: + break; + } + }); + } catch (Exception e) { + log.error("处理MQTT事件-->处理失败,失败原因:{}", e.getMessage()); + } + } + +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/listener/TcpEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/listener/TcpEventListener.java new file mode 100644 index 00000000..af5578de --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/listener/TcpEventListener.java @@ -0,0 +1,46 @@ +package com.mqttsnet.thinglinks.broker.mqs.protocol.event.listener; + +import com.mqttsnet.thinglinks.broker.api.domain.protocol.TcpEvent; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.event.EventListener; +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.Retryable; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +/** + * ----------------------------------------------------------------------------- + * File Name: TcpEventListener + * ----------------------------------------------------------------------------- + * Description: + * TCP事件监听器 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/11 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/11 15:55 + */ +@Component +@Slf4j +public class TcpEventListener { + + /** + * 发布TCP事件 + * + * @param event 事件消息 + */ + @EventListener + @Async("mqsAsync") + @Retryable(value = {Exception.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000)) + public void handleTcpEvent(TcpEvent event) { + log.info("处理TCP事件: 消息={}", event.getMessage()); + // TODO 实现TCP事件的处理逻辑 + } +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/listener/WebSocketEventListener.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/listener/WebSocketEventListener.java new file mode 100644 index 00000000..f6c3da43 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/listener/WebSocketEventListener.java @@ -0,0 +1,47 @@ +package com.mqttsnet.thinglinks.broker.mqs.protocol.event.listener; + +import com.mqttsnet.thinglinks.broker.api.domain.protocol.WebSocketEvent; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.event.EventListener; +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.Retryable; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +/** + * ----------------------------------------------------------------------------- + * File Name: WebSocketEventListener + * ----------------------------------------------------------------------------- + * Description: + * WebSocket事件监听器 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/11 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/11 15:57 + */ +@Component +@Slf4j +public class WebSocketEventListener { + + /** + * 发布WebSocket事件 + * + * @param event 事件消息 + */ + @EventListener + @Async("mqsAsync") + @Retryable(value = {Exception.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000)) + public void handleWebSocketEvent(WebSocketEvent event) { + log.info("处理WebSocket事件: 消息={}", event.getMessage()); + // TODO 实现WebSocket事件的处理逻辑 + } + +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/publisher/ProtocolMessageEventPublisher.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/publisher/ProtocolMessageEventPublisher.java new file mode 100644 index 00000000..3fbfbbd8 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/event/publisher/ProtocolMessageEventPublisher.java @@ -0,0 +1,68 @@ +package com.mqttsnet.thinglinks.broker.mqs.protocol.event.publisher; + +import com.mqttsnet.thinglinks.broker.api.domain.protocol.HttpEvent; +import com.mqttsnet.thinglinks.broker.api.domain.protocol.MqttEvent; +import com.mqttsnet.thinglinks.broker.api.domain.protocol.TcpEvent; +import com.mqttsnet.thinglinks.broker.api.domain.protocol.WebSocketEvent; +import com.mqttsnet.thinglinks.link.api.domain.product.enumeration.ProtocolTypeEnum; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Component; + +/** + * ----------------------------------------------------------------------------- + * File Name: ProtocolMessageEventPublisher + * ----------------------------------------------------------------------------- + * Description: + * 协议消息事件发布器 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/11 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/11 15:00 + */ +@Component +@Slf4j +public class ProtocolMessageEventPublisher { + + @Autowired + private ApplicationEventPublisher eventPublisher; + + /** + * 根据协议类型发布对应的事件 + * + * @param protocolType 协议类型 + * @param message 消息内容 + */ + public void publishEvent(ProtocolTypeEnum protocolType, String message) { + log.info("发布{}事件, 消息内容: {}", protocolType.getDesc(), message); + + switch (protocolType) { + case MQTT: + eventPublisher.publishEvent(new MqttEvent(this, message)); + break; + case HTTP: + eventPublisher.publishEvent(new HttpEvent(this, message)); + break; + case TCP: + eventPublisher.publishEvent(new TcpEvent(this, message)); + break; + case WEBSOCKET: + eventPublisher.publishEvent(new WebSocketEvent(this, message)); + break; + // ...为其他协议添加case语句... + default: + log.error("未知的协议类型: {}", protocolType); + break; + } + } + +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/HttpHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/HttpHandler.java new file mode 100644 index 00000000..0fc1b1bb --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/HttpHandler.java @@ -0,0 +1,53 @@ +package com.mqttsnet.thinglinks.broker.mqs.protocol.handler; + +import com.mqttsnet.thinglinks.broker.mqs.protocol.event.publisher.ProtocolMessageEventPublisher; +import com.mqttsnet.thinglinks.link.api.domain.product.enumeration.ProtocolTypeEnum; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * ----------------------------------------------------------------------------- + * File Name: HttpHandler + * ----------------------------------------------------------------------------- + * Description: + * HTTP协议处理器 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/11 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/11 17:09 + */ +@Component +@Slf4j +public class HttpHandler implements ProtocolHandler { + + @Autowired + private ProtocolMessageEventPublisher eventPublisher; + + @Override + public void processMessage(String message) { + // HTTP协议特定的预处理逻辑 + log.info("处理HTTP协议消息: {}", message); + eventPublisher.publishEvent(getProtocolTypeEnum(), message); + } + + + /** + * 获取协议类型枚举 + * + * @return 协议类型 + */ + @Override + public ProtocolTypeEnum getProtocolTypeEnum() { + return ProtocolTypeEnum.HTTP; + } + +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/MqttHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/MqttHandler.java new file mode 100644 index 00000000..72f624f0 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/MqttHandler.java @@ -0,0 +1,53 @@ +package com.mqttsnet.thinglinks.broker.mqs.protocol.handler; + +import com.mqttsnet.thinglinks.broker.mqs.protocol.event.publisher.ProtocolMessageEventPublisher; +import com.mqttsnet.thinglinks.link.api.domain.product.enumeration.ProtocolTypeEnum; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * ----------------------------------------------------------------------------- + * File Name: MqttHandler + * ----------------------------------------------------------------------------- + * Description: + * MQTT协议处理器 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/11 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/11 14:57 + */ +@Component +@Slf4j +public class MqttHandler implements ProtocolHandler { + + @Autowired + private ProtocolMessageEventPublisher eventPublisher; + + @Override + public void processMessage(String message) { + // MQTT协议特定的预处理逻辑 + log.info("处理MQTT协议消息: {}", message); + eventPublisher.publishEvent(getProtocolTypeEnum(), message); + } + + + /** + * 获取协议类型枚举 + * + * @return 协议类型 + */ + @Override + public ProtocolTypeEnum getProtocolTypeEnum() { + return ProtocolTypeEnum.MQTT; + } + +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/ProtocolHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/ProtocolHandler.java new file mode 100644 index 00000000..a50e7ce0 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/ProtocolHandler.java @@ -0,0 +1,41 @@ +package com.mqttsnet.thinglinks.broker.mqs.protocol.handler; + + +import com.mqttsnet.thinglinks.link.api.domain.product.enumeration.ProtocolTypeEnum; + +/** + * ----------------------------------------------------------------------------- + * File Name: ProtocolHandler + * ----------------------------------------------------------------------------- + * Description: + * 协议接口 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/11 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 1373398655@163.com + * @date 2024/3/11 14:55 + */ +public interface ProtocolHandler { + + /** + * 处理特定协议的消息 + * + * @param message 消息内容 + */ + void processMessage(String message); + + /** + * 获取协议类型枚举 + * + * @return 协议类型 + */ + ProtocolTypeEnum getProtocolTypeEnum(); + +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/TcpHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/TcpHandler.java new file mode 100644 index 00000000..65082601 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/TcpHandler.java @@ -0,0 +1,53 @@ +package com.mqttsnet.thinglinks.broker.mqs.protocol.handler; + +import com.mqttsnet.thinglinks.broker.mqs.protocol.event.publisher.ProtocolMessageEventPublisher; +import com.mqttsnet.thinglinks.link.api.domain.product.enumeration.ProtocolTypeEnum; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * ----------------------------------------------------------------------------- + * File Name: TcpHandler + * ----------------------------------------------------------------------------- + * Description: + * TCP协议处理器 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/11 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/11 17:11 + */ +@Component +@Slf4j +public class TcpHandler implements ProtocolHandler { + + @Autowired + private ProtocolMessageEventPublisher eventPublisher; + + @Override + public void processMessage(String message) { + // TCP协议特定的预处理逻辑 + log.info("处理TCP协议消息: {}", message); + eventPublisher.publishEvent(getProtocolTypeEnum(), message); + } + + + /** + * 获取协议类型枚举 + * + * @return 协议类型 + */ + @Override + public ProtocolTypeEnum getProtocolTypeEnum() { + return ProtocolTypeEnum.TCP; + } + +} \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/WebSocketHandler.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/WebSocketHandler.java new file mode 100644 index 00000000..70a79f35 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/mqs/protocol/handler/WebSocketHandler.java @@ -0,0 +1,53 @@ +package com.mqttsnet.thinglinks.broker.mqs.protocol.handler; + +import com.mqttsnet.thinglinks.broker.mqs.protocol.event.publisher.ProtocolMessageEventPublisher; +import com.mqttsnet.thinglinks.link.api.domain.product.enumeration.ProtocolTypeEnum; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * ----------------------------------------------------------------------------- + * File Name: WebSocketHandler + * ----------------------------------------------------------------------------- + * Description: + * WebSocket协议处理器 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/11 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/11 17:12 + */ +@Component +@Slf4j +public class WebSocketHandler implements ProtocolHandler { + + @Autowired + private ProtocolMessageEventPublisher eventPublisher; + + @Override + public void processMessage(String message) { + // WEBSOCKET协议特定的预处理逻辑 + log.info("处理WEBSOCKET协议消息: {}", message); + eventPublisher.publishEvent(getProtocolTypeEnum(), message); + } + + + /** + * 获取协议类型枚举 + * + * @return 协议类型 + */ + @Override + public ProtocolTypeEnum getProtocolTypeEnum() { + return ProtocolTypeEnum.WEBSOCKET; + } + +} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/websocket/LoggingWSServer.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/websocket/LoggingWSServer.java deleted file mode 100644 index a1e39f33..00000000 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/websocket/LoggingWSServer.java +++ /dev/null @@ -1,146 +0,0 @@ -package com.mqttsnet.thinglinks.broker.websocket; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Date; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.regex.Pattern; -import javax.websocket.*; -import javax.websocket.server.ServerEndpoint; - -import com.mqttsnet.thinglinks.common.core.utils.ErrorUtil; -import com.mqttsnet.thinglinks.common.core.utils.StringUtils; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.task.AsyncTaskExecutor; -import org.springframework.stereotype.Component; - -/** - * WebSocket获取实时日志并输出到Web页面 - */ -@Slf4j -@Component -@ServerEndpoint(value = "/websocket/logging", configurator = MyEndpointConfigure.class) -public class LoggingWSServer { - - @Autowired - AsyncTaskExecutor asyncTaskExecutor; - - /** - * 连接集合 - */ - private static Map sessionMap = new ConcurrentHashMap<>(16); - private static Map lengthMap = new ConcurrentHashMap<>(16); - - /** - * 匹配日期开头加换行,2019-08-12 14:15:04 - */ - private Pattern datePattern = Pattern.compile("[\\d+][\\d+][\\d+][\\d+]-[\\d+][\\d+]-[\\d+][\\d+] [\\d+][\\d+]:[\\d+][\\d+]:[\\d+][\\d+]"); - - - /** - * 连接建立成功调用的方法 - */ - @OnOpen - public void onOpen(Session session) { - //添加到集合中 - sessionMap.put(session.getId(), session); - lengthMap.put(session.getId(), 1);//默认从第一行开始 - - //获取日志信息 - asyncTaskExecutor.submit(() -> { - boolean first = true; - BufferedReader reader = null; - FileReader fileReader = null; - while (sessionMap.get(session.getId()) != null) { - try { - //日志文件,获取最新的如 thinglinks-broker.2022-07-12.log - fileReader = new FileReader(System.getProperty("user.dir") + "/logs/thinglinks-broker/all" + "." + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + - ".log"); - //字符流 - reader = new BufferedReader(fileReader); - Object[] lines = reader.lines().toArray(); - - //只取从上次之后产生的日志 - Object[] copyOfRange = Arrays.copyOfRange(lines, lengthMap.get(session.getId()), lines.length); - - //对日志进行着色,更加美观 PS:注意,这里要根据日志生成规则来操作 - for (int i = 0; i < copyOfRange.length; i++) { - String line = String.valueOf(copyOfRange[i]); - copyOfRange[i] = line; - } - - //存储最新一行开始 - lengthMap.replace(session.getId(), lines.length); - - //第一次如果太大,截取最新的200行就够了,避免传输的数据太大 - if (first && copyOfRange.length > 200) { - copyOfRange = Arrays.copyOfRange(copyOfRange, copyOfRange.length - 200, copyOfRange.length); - first = false; - } - - String result = StringUtils.join(copyOfRange, "
"); - - //发送 - send(session, result); - - //休眠一秒 - Thread.sleep(1000); - } catch (Exception e) { - //输出到日志文件中 - log.error(ErrorUtil.errorInfoToString(e)); - } - } - try { - reader.close(); - fileReader.close(); - } catch (IOException e) { - //输出到日志文件中 - log.error(ErrorUtil.errorInfoToString(e)); - } - }); - } - - /** - * 连接关闭调用的方法 - */ - @OnClose - public void onClose(Session session) { - //从集合中删除 - sessionMap.remove(session.getId()); - lengthMap.remove(session.getId()); - } - - /** - * 发生错误时调用 - */ - @OnError - public void onError(Session session, Throwable error) { - //输出到日志文件中 - log.error(ErrorUtil.errorInfoToString(error)); - } - - /** - * 服务器接收到客户端消息时调用的方法 - */ - @OnMessage - public void onMessage(String message, Session session) { - - } - - /** - * 封装一个send方法,发送消息到前端 - */ - private void send(Session session, String message) { - try { - session.getBasicRemote().sendText(message); - } catch (Exception e) { - //输出到日志文件中 - log.error(ErrorUtil.errorInfoToString(e)); - } - } -} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/websocket/MyEndpointConfigure.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/websocket/MyEndpointConfigure.java deleted file mode 100644 index c304a45b..00000000 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/websocket/MyEndpointConfigure.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.mqttsnet.thinglinks.broker.websocket; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; - -import javax.websocket.server.ServerEndpointConfig; - -/** - * 解决注入其他类的问题,详情参考这篇帖子:webSocket无法注入其他类:https://blog.csdn.net/tornadojava/article/details/78781474 - */ -public class MyEndpointConfigure extends ServerEndpointConfig.Configurator implements ApplicationContextAware { - - private static volatile BeanFactory context; - - @Override - public T getEndpointInstance(Class clazz){ - return context.getBean(clazz); - } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - MyEndpointConfigure.context = applicationContext; - } -} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/websocket/WebSocketConfig.java b/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/websocket/WebSocketConfig.java deleted file mode 100644 index 77e14df4..00000000 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/java/com/mqttsnet/thinglinks/broker/websocket/WebSocketConfig.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.mqttsnet.thinglinks.broker.websocket; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.socket.server.standard.ServerEndpointExporter; - -/** - * WebSocket配置 - */ -@Configuration -public class WebSocketConfig { - - - /** - * 用途:扫描并注册所有携带@ServerEndpoint注解的实例。 @ServerEndpoint("/websocket") - * PS:如果使用外部容器 则无需提供ServerEndpointExporter。 - */ - @Bean - public ServerEndpointExporter serverEndpointExporter() { - return new ServerEndpointExporter(); - } - - /** - * 支持注入其他类 - */ - @Bean - public MyEndpointConfigure newMyEndpointConfigure() { - return new MyEndpointConfigure(); - } -} diff --git a/thinglinks-modules/thinglinks-modules-broker/src/main/resources/bootstrap.yml b/thinglinks-modules/thinglinks-modules-broker/src/main/resources/bootstrap.yml index 52a6e1d4..91424fcc 100644 --- a/thinglinks-modules/thinglinks-modules-broker/src/main/resources/bootstrap.yml +++ b/thinglinks-modules/thinglinks-modules-broker/src/main/resources/bootstrap.yml @@ -1,5 +1,5 @@ # Spring -spring: +spring: application: # 应用名称 name: @project.artifactId@ @@ -35,5 +35,7 @@ spring: refresh: true - dataId: kafka.yml refresh: false + - dataId: rocketmq.yml + refresh: false username: @nacos.username@ password: @nacos.password@ \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-file/src/main/java/com/mqttsnet/thinglinks/file/ThingLinksFileApplication.java b/thinglinks-modules/thinglinks-modules-file/src/main/java/com/mqttsnet/thinglinks/file/ThingLinksFileApplication.java index eec92994..6e4eb7c5 100644 --- a/thinglinks-modules/thinglinks-modules-file/src/main/java/com/mqttsnet/thinglinks/file/ThingLinksFileApplication.java +++ b/thinglinks-modules/thinglinks-modules-file/src/main/java/com/mqttsnet/thinglinks/file/ThingLinksFileApplication.java @@ -1,28 +1,35 @@ package com.mqttsnet.thinglinks.file; import com.mqttsnet.thinglinks.common.swagger.annotation.EnableCustomSwagger2; +import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.CrossOrigin; +import java.net.InetAddress; + /** * 文件服务 - * + * * @author thinglinks */ +@Slf4j @EnableCustomSwagger2 //实现跨域注解 //origin="*"代表所有域名都可访问 //maxAge飞行前响应的缓存持续时间的最大年龄,简单来说就是Cookie的有效期 单位为秒 //若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失 -@CrossOrigin(origins = "*",maxAge = 3600) -@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class },scanBasePackages = {"com.mqttsnet.thinglinks"}) -public class ThingLinksFileApplication -{ - public static void main(String[] args) - { - SpringApplication.run(ThingLinksFileApplication.class, args); - System.out.println("(♥◠‿◠)ノ゙ 文件服务模块启动成功 ლ(´ڡ`ლ)゙ "); +@CrossOrigin(origins = "*", maxAge = 3600) +@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}, scanBasePackages = {"com.mqttsnet.thinglinks"}) +public class ThingLinksFileApplication { + public static void main(String[] args) throws Exception { + ConfigurableApplicationContext application = SpringApplication.run(ThingLinksFileApplication.class, args); + Environment env = application.getEnvironment(); + log.info("\n----------------------------------------------------------\n\t" + "应用 '{}' 启动成功! 访问连接:\n\t" + "Swagger文档: \t\thttp://{}:{}/swagger-ui.html\n\t" + + "数据库监控: \t\thttp://{}:{}/druid\n" + "----------------------------------------------------------", env.getProperty("spring.application.name"), + InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port", "8080"), "127.0.0.1", env.getProperty("server.port", "8080")); } } diff --git a/thinglinks-modules/thinglinks-modules-gen/src/main/java/com/mqttsnet/thinglinks/gen/ThingLinksGenApplication.java b/thinglinks-modules/thinglinks-modules-gen/src/main/java/com/mqttsnet/thinglinks/gen/ThingLinksGenApplication.java index dde45ab8..5cecdf7f 100644 --- a/thinglinks-modules/thinglinks-modules-gen/src/main/java/com/mqttsnet/thinglinks/gen/ThingLinksGenApplication.java +++ b/thinglinks-modules/thinglinks-modules-gen/src/main/java/com/mqttsnet/thinglinks/gen/ThingLinksGenApplication.java @@ -3,15 +3,21 @@ import com.mqttsnet.thinglinks.common.security.annotation.EnableCustomConfig; import com.mqttsnet.thinglinks.common.security.annotation.EnableRyFeignClients; import com.mqttsnet.thinglinks.common.swagger.annotation.EnableCustomSwagger2; +import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.CrossOrigin; +import java.net.InetAddress; + /** * 代码生成 - * + * * @author thinglinks */ +@Slf4j @EnableCustomConfig @EnableCustomSwagger2 @EnableRyFeignClients @@ -19,13 +25,14 @@ //origin="*"代表所有域名都可访问 //maxAge飞行前响应的缓存持续时间的最大年龄,简单来说就是Cookie的有效期 单位为秒 //若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失 -@CrossOrigin(origins = "*",maxAge = 3600) +@CrossOrigin(origins = "*", maxAge = 3600) @SpringBootApplication(scanBasePackages = {"com.mqttsnet.thinglinks"}) -public class ThingLinksGenApplication -{ - public static void main(String[] args) - { - SpringApplication.run(ThingLinksGenApplication.class, args); - System.out.println("(♥◠‿◠)ノ゙ 代码生成模块启动成功 ლ(´ڡ`ლ)゙ "); +public class ThingLinksGenApplication { + public static void main(String[] args) throws Exception { + ConfigurableApplicationContext application = SpringApplication.run(ThingLinksGenApplication.class, args); + Environment env = application.getEnvironment(); + log.info("\n----------------------------------------------------------\n\t" + "应用 '{}' 启动成功! 访问连接:\n\t" + "Swagger文档: \t\thttp://{}:{}/swagger-ui.html\n\t" + + "数据库监控: \t\thttp://{}:{}/druid\n" + "----------------------------------------------------------", env.getProperty("spring.application.name"), + InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port", "8080"), "127.0.0.1", env.getProperty("server.port", "8080")); } } diff --git a/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/ThingLinksJobApplication.java b/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/ThingLinksJobApplication.java index 9f82235f..b8394619 100644 --- a/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/ThingLinksJobApplication.java +++ b/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/ThingLinksJobApplication.java @@ -3,16 +3,21 @@ import com.mqttsnet.thinglinks.common.security.annotation.EnableCustomConfig; import com.mqttsnet.thinglinks.common.security.annotation.EnableRyFeignClients; import com.mqttsnet.thinglinks.common.swagger.annotation.EnableCustomSwagger2; +import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.CrossOrigin; +import java.net.InetAddress; + /** * 定时任务 - * + * * @author thinglinks */ +@Slf4j @EnableCustomConfig @EnableCustomSwagger2 @EnableRyFeignClients @@ -20,13 +25,14 @@ //origin="*"代表所有域名都可访问 //maxAge飞行前响应的缓存持续时间的最大年龄,简单来说就是Cookie的有效期 单位为秒 //若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失 -@CrossOrigin(origins = "*",maxAge = 3600) +@CrossOrigin(origins = "*", maxAge = 3600) @SpringBootApplication(scanBasePackages = {"com.mqttsnet.thinglinks"}) -public class ThingLinksJobApplication -{ - public static void main(String[] args) - { - SpringApplication.run(ThingLinksJobApplication.class, args); - System.out.println("(♥◠‿◠)ノ゙ 定时任务模块启动成功 ლ(´ڡ`ლ)゙ "); +public class ThingLinksJobApplication { + public static void main(String[] args) throws Exception { + ConfigurableApplicationContext application = SpringApplication.run(ThingLinksJobApplication.class, args); + Environment env = application.getEnvironment(); + log.info("\n----------------------------------------------------------\n\t" + "应用 '{}' 启动成功! 访问连接:\n\t" + "Swagger文档: \t\thttp://{}:{}/swagger-ui.html\n\t" + + "数据库监控: \t\thttp://{}:{}/druid\n" + "----------------------------------------------------------", env.getProperty("spring.application.name"), + InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port", "8080"), "127.0.0.1", env.getProperty("server.port", "8080")); } } diff --git a/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/DeviceInfoTask.java b/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/CacheDeviceInfoTask.java similarity index 55% rename from thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/DeviceInfoTask.java rename to thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/CacheDeviceInfoTask.java index 429bb3bc..182ecc34 100644 --- a/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/DeviceInfoTask.java +++ b/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/CacheDeviceInfoTask.java @@ -1,35 +1,33 @@ package com.mqttsnet.thinglinks.job.task.link; -import com.mqttsnet.thinglinks.common.core.utils.StringUtils; -import com.mqttsnet.thinglinks.link.api.RemoteDeviceInfoService; +import com.mqttsnet.thinglinks.link.api.RemoteCacheOpenAnyService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.time.StopWatch; import org.springframework.stereotype.Component; import javax.annotation.Resource; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; /** * @program: thinglinks - * @description: 子设备管理管理定时任务 + * @description: 子设备管理缓存刷新定时任务 * @packagename: com.mqttsnet.thinglinks.job.task.link * @author: ShiHuan Sun * @e-mainl: 13733918655@163.com * @date: 2022-07-11 15:08 **/ -@Component("linkDeviceInfoTask") +@Component("cacheDeviceInfoTask") @Slf4j -public class DeviceInfoTask { +public class CacheDeviceInfoTask { @Resource - private RemoteDeviceInfoService remoteDeviceInfoService; + private RemoteCacheOpenAnyService remoteCacheOpenAnyService; /** - * 刷新子设备数据模型定时任务 + * Refreshes the cache for specific device information models. + * This is a scheduled task. + * + * @param params Comma-separated device IDs to refresh. */ public void refreshDeviceInfoDataModel(String params) { StopWatch watch = new StopWatch(); @@ -37,8 +35,7 @@ public void refreshDeviceInfoDataModel(String params) { if (log.isInfoEnabled()) { log.info("刷新子设备数据模型定时任务开始,参数:{}", params); } - List collect = StringUtils.isNotEmpty(params)?Arrays.stream(params.split(",")).map(Long::valueOf).collect(Collectors.toList()):new ArrayList<>(); - remoteDeviceInfoService.refreshDeviceInfoDataModel(collect.toArray(new Long[0])); + remoteCacheOpenAnyService.refreshAllDeviceInfoCaches(); watch.stop(); if (log.isInfoEnabled()) { log.info("刷新子设备数据模型定时任务结束,耗时(millisecond):{}", watch.getTime()); diff --git a/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/CacheDeviceTask.java b/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/CacheDeviceTask.java new file mode 100644 index 00000000..ab0a61d6 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/CacheDeviceTask.java @@ -0,0 +1,51 @@ +package com.mqttsnet.thinglinks.job.task.link; + +import com.mqttsnet.thinglinks.link.api.RemoteCacheOpenAnyService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.time.StopWatch; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; + +/** + * ----------------------------------------------------------------------------- + * File Name: CacheDeviceTask + * ----------------------------------------------------------------------------- + * Description: + * 刷新设备缓存定时任务 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/24 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/24 15:14 + */ +@Component("cacheDeviceTask") +@Slf4j +public class CacheDeviceTask { + + @Resource + private RemoteCacheOpenAnyService remoteCacheOpenAnyService; + + /** + * Refreshes the cache for all devices within a tenant. + * This is a scheduled task. + */ + public void refreshAllDeviceCaches(String params) { + StopWatch watch = new StopWatch(); + watch.start(); + log.info("Starting to refresh all device caches."); + + remoteCacheOpenAnyService.refreshAllDeviceCaches(); + + watch.stop(); + log.info("Finished refreshing all device caches. Duration (milliseconds): {}", watch.getTime()); + } + +} diff --git a/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/CacheProductModelTask.java b/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/CacheProductModelTask.java new file mode 100644 index 00000000..94ca089c --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/CacheProductModelTask.java @@ -0,0 +1,51 @@ +package com.mqttsnet.thinglinks.job.task.link; + +import com.mqttsnet.thinglinks.link.api.RemoteCacheOpenAnyService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.time.StopWatch; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; + +/** + * ----------------------------------------------------------------------------- + * File Name: CacheProductModelTask + * ----------------------------------------------------------------------------- + * Description: + * 刷新产品模型定时任务 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/24 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/24 15:17 + */ +@Component("cacheProductModelTask") +@Slf4j +public class CacheProductModelTask { + @Resource + private RemoteCacheOpenAnyService remoteCacheOpenAnyService; + + + /** + * Refreshes the cache for all product models within a tenant. + * This is a scheduled task. + */ + public void refreshAllProductModelCaches(String params) { + StopWatch watch = new StopWatch(); + watch.start(); + log.info("Starting to refresh all product model caches."); + + remoteCacheOpenAnyService.refreshAllProductModelCaches(); + + watch.stop(); + log.info("Finished refreshing all product model caches. Duration (milliseconds): {}", watch.getTime()); + } + +} diff --git a/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/CacheProductTask.java b/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/CacheProductTask.java new file mode 100644 index 00000000..4cb90c63 --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-job/src/main/java/com/mqttsnet/thinglinks/job/task/link/CacheProductTask.java @@ -0,0 +1,51 @@ +package com.mqttsnet.thinglinks.job.task.link; + +import com.mqttsnet.thinglinks.link.api.RemoteCacheOpenAnyService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.time.StopWatch; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; + +/** + * ----------------------------------------------------------------------------- + * File Name: CacheProductTask + * ----------------------------------------------------------------------------- + * Description: + * 刷新产品缓存定时任务 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/24 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/24 15:16 + */ +@Component("cacheProductTask") +@Slf4j +public class CacheProductTask { + @Resource + private RemoteCacheOpenAnyService remoteCacheOpenAnyService; + + /** + * Refreshes the cache for all products within a tenant. + * This is a scheduled task. + */ + public void refreshAllProductCaches(String params) { + StopWatch watch = new StopWatch(); + watch.start(); + log.info("Starting to refresh all product caches."); + + remoteCacheOpenAnyService.refreshAllProductCaches(); + + watch.stop(); + log.info("Finished refreshing all product caches. Duration (milliseconds): {}", watch.getTime()); + } + + +} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/CacheSuperAbstract.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/CacheSuperAbstract.java index dab89ff7..08d0ffa4 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/CacheSuperAbstract.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/CacheSuperAbstract.java @@ -7,5 +7,5 @@ public abstract class CacheSuperAbstract { public static int PAGE_SIZE = 5000; - public static final Long THIRTY_MINUTES = 30L; + public static final Long THIRTY_MINUTES = 60L; } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/helper/CacheDataHelper.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/helper/CacheDataHelper.java index 1cafe62f..ea4a564c 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/helper/CacheDataHelper.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/helper/CacheDataHelper.java @@ -48,7 +48,7 @@ public DeviceCacheVO getDeviceCacheVO(String deviceIdentification) { log.warn("Device identification is null"); return null; } - Device deviceCacheObject = redisService.getCacheObject(CacheConstants.DEVICE_RECORD_KEY + deviceIdentification); + Device deviceCacheObject = redisService.getCacheObject(CacheConstants.DEF_DEVICE + deviceIdentification); return BeanPlusUtil.toBeanIgnoreError(deviceCacheObject, DeviceCacheVO.class); } @@ -58,13 +58,13 @@ public ProductModelCacheVO getProductModelCacheVO(String productIdentification) return null; } - ProductModelCacheVO objectCacheResult = redisService.getCacheObject(CacheConstants.DEVICE_RECORD_KEY + productIdentification); + ProductModelCacheVO objectCacheResult = redisService.getCacheObject(CacheConstants.DEF_PRODUCT_MODEL + productIdentification); return BeanPlusUtil.toBeanIgnoreError(objectCacheResult, ProductModelCacheVO.class); } public List getProductModelSuperTableCacheVO(String productIdentification, String serviceCode, String deviceIdentification) { // 构造缓存键 - String cacheKey = CacheConstants.PRODUCT_MODEL_SUPER_TABLE + productIdentification + ":" + serviceCode + ":" + deviceIdentification; + String cacheKey = CacheConstants.DEF_PRODUCT_MODEL_SUPER_TABLE + productIdentification + ":" + serviceCode + ":" + deviceIdentification; // 尝试从缓存获取数据 List cacheList; @@ -104,7 +104,13 @@ public List getProductModelSuperTableCacheVO(String produc public void setProductModelSuperTableCacheVO(String productIdentification, String serviceCode, String deviceIdentification, List superTableDescribeOpt) { - String cacheKey = CacheConstants.PRODUCT_MODEL_SUPER_TABLE + productIdentification + ":" + serviceCode + ":" + deviceIdentification; + String cacheKey = CacheConstants.DEF_PRODUCT_MODEL_SUPER_TABLE + productIdentification + ":" + serviceCode + ":" + deviceIdentification; + redisService.delete(cacheKey); + redisService.setCacheObject(cacheKey, superTableDescribeOpt); + } + + public void setProductModelSuperTableCacheVO(String productIdentification, String serviceCode, List superTableDescribeOpt) { + String cacheKey = CacheConstants.DEF_PRODUCT_MODEL_SUPER_TABLE + productIdentification + ":" + serviceCode; redisService.delete(cacheKey); redisService.setCacheObject(cacheKey, superTableDescribeOpt); } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java index 3d361e25..12300f22 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/DeviceCacheService.java @@ -1,8 +1,8 @@ package com.mqttsnet.thinglinks.link.common.cache.service; import cn.hutool.core.bean.BeanUtil; -import cn.hutool.core.collection.CollUtil; import com.github.pagehelper.PageHelper; +import com.mqttsnet.thinglinks.common.core.constant.CacheConstants; import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; import com.mqttsnet.thinglinks.common.redis.service.RedisService; import com.mqttsnet.thinglinks.link.api.domain.cache.device.DeviceCacheVO; @@ -21,8 +21,6 @@ import java.util.stream.IntStream; - - @Service @RequiredArgsConstructor @Slf4j @@ -39,9 +37,8 @@ public void refreshDeviceCacheForTenant() { int totalDataCount = deviceService.findDeviceTotal().intValue(); int totalPages = (int) Math.ceil((double) totalDataCount / PAGE_SIZE); List deviceList = IntStream.range(0, totalPages).mapToObj(currentPage -> { - PageHelper.startPage(currentPage+1, PAGE_SIZE); - List pageDevices = deviceService.findDevices(); - return pageDevices; + PageHelper.startPage(currentPage + 1, PAGE_SIZE); + return deviceService.findDevices(); }) .flatMap(Collection::stream) .collect(Collectors.toList()); @@ -91,9 +88,9 @@ private DeviceCacheVO transformToDeviceCacheVO(Device device) { * @param deviceCacheVO DeviceCacheVO object to be cached. */ private void cacheDeviceBasedOnIdentification(DeviceCacheVO deviceCacheVO) { - String deviceIdentKey = deviceCacheVO.getDeviceIdentification(); - redisService.delete(deviceIdentKey); - redisService.setCacheObject(deviceIdentKey, deviceCacheVO, THIRTY_MINUTES, TimeUnit.MINUTES); + String cacheKey = CacheConstants.DEF_DEVICE + deviceCacheVO.getDeviceIdentification(); + redisService.delete(cacheKey); + redisService.setCacheObject(cacheKey, deviceCacheVO, THIRTY_MINUTES, TimeUnit.MINUTES); } /** @@ -102,9 +99,9 @@ private void cacheDeviceBasedOnIdentification(DeviceCacheVO deviceCacheVO) { * @param deviceCacheVO DeviceCacheVO object to be cached. */ private void cacheDeviceBasedOnClientId(DeviceCacheVO deviceCacheVO) { - String clientId = deviceCacheVO.getClientId(); - redisService.delete(clientId); - redisService.setCacheObject(clientId, deviceCacheVO, THIRTY_MINUTES, TimeUnit.MINUTES); + String cacheKey = CacheConstants.DEF_DEVICE + deviceCacheVO.getClientId(); + redisService.delete(cacheKey); + redisService.setCacheObject(cacheKey, deviceCacheVO, THIRTY_MINUTES, TimeUnit.MINUTES); } } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/ProductCacheService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/ProductCacheService.java index 53172624..fd55311f 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/ProductCacheService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/ProductCacheService.java @@ -1,6 +1,7 @@ package com.mqttsnet.thinglinks.link.common.cache.service; +import com.mqttsnet.thinglinks.common.core.constant.CacheConstants; import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; import com.mqttsnet.thinglinks.common.redis.service.RedisService; import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductCacheVO; @@ -13,7 +14,6 @@ import java.util.Collection; import java.util.Collections; - import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @@ -48,7 +48,6 @@ public class ProductCacheService extends CacheSuperAbstract { /** * Refreshes the product cache for a specific tenant. - * */ public void refreshProductCacheForTenant() { int totalDataCount = productService.findProductTotal().intValue(); @@ -81,7 +80,7 @@ private List fetchProductPageContent(int currentPage) { * * @param productList List of products to be cached. */ - private void cacheProductsForTenant( List productList) { + private void cacheProductsForTenant(List productList) { productList.stream() .map(this::transformToProductCacheVO) .forEach(this::cacheProduct); @@ -90,10 +89,10 @@ private void cacheProductsForTenant( List productList) { /** * Transforms a product object into a ProductCacheVO object. * - * @param product Product object to be transformed. + * @param product Product object to be transformed. * @return Transformed ProductCacheVO object. */ - private ProductCacheVO transformToProductCacheVO( Product product) { + private ProductCacheVO transformToProductCacheVO(Product product) { return BeanPlusUtil.toBeanIgnoreError(product, ProductCacheVO.class); } @@ -103,9 +102,9 @@ private ProductCacheVO transformToProductCacheVO( Product product) { * @param productCacheVO ProductCacheVO object to be cached. */ private void cacheProduct(ProductCacheVO productCacheVO) { - String cacheKey = productCacheVO.getProductIdentification(); + String cacheKey = CacheConstants.DEF_PRODUCT +productCacheVO.getProductIdentification(); redisService.delete(cacheKey); - redisService.setCacheObject(cacheKey, productCacheVO,THIRTY_MINUTES, TimeUnit.MINUTES); + redisService.setCacheObject( cacheKey, productCacheVO, THIRTY_MINUTES, TimeUnit.MINUTES); } } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/ProductModelCacheService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/ProductModelCacheService.java index 5bc4354e..43f81562 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/ProductModelCacheService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/cache/service/ProductModelCacheService.java @@ -1,21 +1,21 @@ package com.mqttsnet.thinglinks.link.common.cache.service; +import com.mqttsnet.thinglinks.common.core.constant.CacheConstants; import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; import com.mqttsnet.thinglinks.common.redis.service.RedisService; import com.mqttsnet.thinglinks.link.api.domain.cache.product.ProductModelCacheVO; import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; +import com.mqttsnet.thinglinks.link.api.domain.product.vo.param.ProductParamVO; import com.mqttsnet.thinglinks.link.common.cache.CacheSuperAbstract; import com.mqttsnet.thinglinks.link.service.product.ProductService; - import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.apache.ibatis.cache.CacheKey; import org.springframework.stereotype.Service; import java.util.Collection; import java.util.Collections; import java.util.List; -import java.util.Optional; +import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -48,12 +48,10 @@ public class ProductModelCacheService extends CacheSuperAbstract { /** * Refreshes the product model cache for a specific tenant. - * */ public void refreshProductModelCache() { int totalDataCount = productService.findProductTotal().intValue(); int totalPages = (int) Math.ceil((double) totalDataCount / PAGE_SIZE); - List productList = IntStream.range(0, totalPages) .mapToObj(this::fetchProductPageContent) .flatMap(Collection::stream) @@ -71,7 +69,9 @@ public void refreshProductModelCache() { * @return List of products from the specified page. */ private List fetchProductPageContent(int currentPage) { - return null; + int offset = currentPage * PAGE_SIZE; + List products = productService.findProductsByPage(offset, PAGE_SIZE); + return products != null ? products : Collections.emptyList(); } /** @@ -79,7 +79,7 @@ private List fetchProductPageContent(int currentPage) { * * @param productList List of products to be cached as product models. */ - private void cacheProductModelsForTenant( List productList) { + private void cacheProductModelsForTenant(List productList) { productList.stream() .map(this::transformToProductModelCacheVO) .forEach(this::cacheProductModel); @@ -88,11 +88,12 @@ private void cacheProductModelsForTenant( List productList) { /** * Transforms a product object into a ProductModelCacheVO object. * - * @param product Product object to be transformed. + * @param product Product object to be transformed. * @return Transformed ProductModelCacheVO object. */ - private ProductModelCacheVO transformToProductModelCacheVO( Product product) { - return null; + private ProductModelCacheVO transformToProductModelCacheVO(Product product) { + ProductParamVO productParamVO = productService.selectFullProductByProductIdentification(product.getProductIdentification()); + return BeanPlusUtil.toBeanIgnoreError(productParamVO, ProductModelCacheVO.class); } /** @@ -101,7 +102,9 @@ private ProductModelCacheVO transformToProductModelCacheVO( Product product) { * @param productModelCacheVO ProductModelCacheVO object to be cached. */ private void cacheProductModel(ProductModelCacheVO productModelCacheVO) { - + String cacheKey = CacheConstants.DEF_PRODUCT_MODEL + productModelCacheVO.getProductIdentification(); + redisService.delete(cacheKey); + redisService.setCacheObject(cacheKey, productModelCacheVO, THIRTY_MINUTES, TimeUnit.MINUTES); } } \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/init/InitDataBase.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/init/InitDataBase.java deleted file mode 100644 index 661fb6af..00000000 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/init/InitDataBase.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.mqttsnet.thinglinks.link.common.init; - -import com.mqttsnet.thinglinks.link.service.product.ProductService; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.time.StopWatch; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; - -/** - * @Description: 初始化基础数据 - * @Author: ShiHuan SUN - * @E-mail: 13733918655@163.com - * @Website: http://thinglinks.mqttsnet.com - * @CreateDate: 2022/3/28$ 16:12$ - * @UpdateUser: ShiHuan SUN - * @UpdateDate: 2022/3/28$ 16:12$ - * @UpdateRemark: 修改内容 - * @Version: V1.0 - */ -@Component -@Slf4j -@RefreshScope -public class InitDataBase { - private static InitDataBase InitDataBase; - - @Autowired - private ProductService productService; - - @PostConstruct - public void init() throws Exception { - InitDataBase = this; - InitDataBase.productService=this.productService; - StopWatch watch = new StopWatch(); - watch.start(); - //初始化产品模型数据 - this.productService.createSuperTableDataModel(null,true); - watch.stop(); - log.info("初始化基础数据成功 ! Time Elapsed (millisecond): {}",watch.getTime()); - } - -} diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/listener/RedisKeyExpirationListener.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/listener/RedisKeyExpirationListener.java index 0653d283..6cde8cd5 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/listener/RedisKeyExpirationListener.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/common/listener/RedisKeyExpirationListener.java @@ -51,9 +51,9 @@ public void onMessage(Message message, byte[] pattern) { resultLock = redisService.checkLock(expiredKey, uuid, 1000L); if (resultLock) { log.info("获取分布式锁成功-key:{},value:{}", expiredKey, uuid); - if (expiredKey.contains(CacheConstants.DEVICE_RECORD_KEY)){ + if (expiredKey.contains(CacheConstants.DEF_DEVICE)){ log.info("设备信息缓存失效{}",expiredKey); - deviceService.cacheInvalidation(expiredKey.replace(CacheConstants.DEVICE_RECORD_KEY, "")); + deviceService.cacheInvalidation(expiredKey.replace(CacheConstants.DEF_DEVICE, "")); } }else { log.info("获取分布式锁失败-key:{},value:{}", expiredKey, uuid); diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/cache/CacheOpenAnyController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/cache/CacheOpenAnyController.java new file mode 100644 index 00000000..8cd1dbfd --- /dev/null +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/cache/CacheOpenAnyController.java @@ -0,0 +1,100 @@ +package com.mqttsnet.thinglinks.link.controller.cache; + +import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.link.common.cache.service.DeviceCacheService; +import com.mqttsnet.thinglinks.link.common.cache.service.ProductCacheService; +import com.mqttsnet.thinglinks.link.common.cache.service.ProductModelCacheService; +import com.mqttsnet.thinglinks.link.service.device.DeviceInfoService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; + +/** + * ----------------------------------------------------------------------------- + * File Name: CacheOpenAnyController + * ----------------------------------------------------------------------------- + * Description: + * 缓存开放接口 + * ----------------------------------------------------------------------------- + * + * @author xiaonannet + * @version 1.0 + * ----------------------------------------------------------------------------- + * Revision History: + * Date Author Version Description + * -------- -------- ------- -------------------- + * 2024/3/24 xiaonannet 1.0 Initial creation + * ----------------------------------------------------------------------------- + * @email 13733918655@163.com + * @date 2024/3/24 02:00 + */ +@RestController +@RequestMapping("/cache/open/any") +@Slf4j +public class CacheOpenAnyController implements Serializable { + private static final long serialVersionUID = 1L; + + @Autowired + private DeviceCacheService deviceCacheService; + @Autowired + private ProductCacheService productCacheService; + @Autowired + private ProductModelCacheService productModelCacheService; + @Autowired + private DeviceInfoService deviceInfoService; + + /** + * Refreshes the cache for all devices within a tenant. + * + * @return Response indicating the operation was successful. + */ + @GetMapping("/refreshAllDeviceCaches") + public R refreshAllDeviceCaches() { + log.info("Starting to refresh all device caches."); + deviceCacheService.refreshDeviceCacheForTenant(); + return R.ok(); + } + + /** + * Refreshes the cache for sub devices within a tenant. + * + * @return Response indicating the operation was successful. + */ + @GetMapping("/refreshAllDeviceInfoCaches") + public R refreshAllDeviceInfoCaches() { + log.info("Starting to refresh all device info caches."); + deviceInfoService.refreshDeviceInfoDataModel(new ArrayList<>()); + return R.ok(); + } + + /** + * Refreshes the cache for all products within a tenant. + * + * @return Response indicating the operation was successful. + */ + @GetMapping("/refreshAllProductCaches") + public R refreshAllProductCaches() { + log.info("Starting to refresh all product caches."); + productCacheService.refreshProductCacheForTenant(); + return R.ok(); + } + + /** + * Refreshes the cache for all product models within a tenant. + * + * @return Response indicating the operation was successful. + */ + @GetMapping("/refreshAllProductModelCaches") + public R refreshAllProductModelCaches() { + log.info("Starting to refresh all product model caches."); + productModelCacheService.refreshProductModelCache(); + return R.ok(); + } +} \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceActionController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceActionController.java index b4693890..08e56f14 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceActionController.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceActionController.java @@ -67,8 +67,6 @@ public AjaxResult getInfo(@PathVariable("id") Long id) /** * 新增设备动作数据 */ - @PreAuthorize(hasPermi = "link:action:add") - @Log(title = "设备动作数据", businessType = BusinessType.INSERT) @PostMapping public AjaxResult add(@RequestBody DeviceAction deviceAction) { diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceController.java index cfe3b7cf..a9398ca1 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceController.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceController.java @@ -22,7 +22,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; @@ -45,6 +44,7 @@ public class DeviceController extends BaseController { @Autowired private ProductService productService; + /** * 查询设备管理列表 */ diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceInfoController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceInfoController.java index 313eba3d..a5f24c02 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceInfoController.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/device/DeviceInfoController.java @@ -16,7 +16,6 @@ import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.IOException; -import java.util.Arrays; import java.util.List; import java.util.Map; @@ -109,17 +108,5 @@ public AjaxResult getDeviceInfoShadow(@RequestBody Map params) { return AjaxResult.success(deviceInfoService.getDeviceInfoShadow(ids.toString(), startTime.toString(), endTime.toString())); } - /** - * 刷新子设备数据模型 - * - * @param ids - * @return - */ - @PreAuthorize(hasPermi = "link:deviceInfo:initialize") - @GetMapping("/refreshDeviceInfoDataModel/{ids}") - public AjaxResult refreshDeviceInfoDataModel(@PathVariable("ids") Long[] ids) { - return toAjax(deviceInfoService.refreshDeviceInfoDataModel(Arrays.asList(ids))); - } - } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradeTasksController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradeTasksController.java index 53972a0f..dac24e08 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradeTasksController.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradeTasksController.java @@ -1,6 +1,7 @@ package com.mqttsnet.thinglinks.link.controller.ota; import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.common.core.exception.ArgumentException; import com.mqttsnet.thinglinks.common.core.web.controller.BaseController; import com.mqttsnet.thinglinks.link.api.domain.ota.vo.result.OtaUpgradeTasksResultVO; import com.mqttsnet.thinglinks.link.api.domain.ota.vo.save.OtaUpgradeTasksSaveVO; @@ -17,6 +18,7 @@ import javax.validation.Valid; import java.time.LocalDateTime; import java.util.List; + @Validated @RestController @RequestMapping("/otaUpgradeTasks") @@ -47,22 +49,40 @@ public R changeTaskStatus( @ApiParam(value = "任务ID", required = true) @PathVariable("id") Long id, @ApiParam(value = "新任务状态(0:待处理,1:进行中,2:已完成,3:已取消)", required = true, allowableValues = "0,1,2,3") @RequestParam("status") Integer status) { log.info("更改任务状态 id:{}, 状态:{}", id, status); - return R.ok(otaUpgradeTasksService.changeTaskStatus(id, status)); + try { + return R.ok(otaUpgradeTasksService.changeTaskStatus(id, status)); + } catch (Exception e) { + return R.fail(e.getMessage()); + } } @ApiOperation(value = "删除OTA升级任务", httpMethod = "DELETE", notes = "通过其ID删除OTA升级任务") @DeleteMapping("/deleteOtaUpgradeTask/{id}") public R deleteOtaUpgradeTask(@ApiParam(value = "OTA升级任务ID", required = true) @PathVariable("id") Long id) { log.info("删除OTA升级任务 id: {}", id); - return R.ok(otaUpgradeTasksService.deleteOtaUpgradeTask(id)); + try { + return R.ok(otaUpgradeTasksService.deleteOtaUpgradeTask(id)); + } catch (Exception e) { + return R.fail(e.getMessage()); + } } @ApiOperation(value = "批量删除OTA升级任务", httpMethod = "DELETE", notes = "通过它们的ID批量删除OTA升级任务") @DeleteMapping("/deleteOtaUpgradeTasks") public R deleteOtaUpgradeTasks(@ApiParam(value = "OTA升级任务ID", required = true) @RequestBody List ids) { log.info("批量删除OTA升级任务 ids: {}", ids); - boolean allDeleted = ids.stream().distinct().allMatch(id -> otaUpgradeTasksService.deleteOtaUpgradeTask(id)); - return R.ok(allDeleted); + try { + boolean allDeleted = ids.stream().distinct().allMatch(id -> { + try { + return otaUpgradeTasksService.deleteOtaUpgradeTask(id); + } catch (ArgumentException e) { + throw new RuntimeException(e); + } + }); + return R.ok(allDeleted); + } catch (Exception e) { + return R.fail(e.getMessage()); + } } /** @@ -74,8 +94,13 @@ public R deleteOtaUpgradeTasks(@ApiParam(value = "OTA升级任务ID", r @ApiOperation(value = "获取OTA升级任务详情", httpMethod = "GET", notes = "通过ID检索OTA升级任务的详细信息。") @GetMapping("/details/{id}") public R getUpgradeTaskDetails(@ApiParam(value = "OTA升级任务的唯一标识符。", required = true) @PathVariable Long id) { - return R.ok(otaUpgradeTasksService.getUpgradeTaskDetails(id)); + try { + return R.ok(otaUpgradeTasksService.getUpgradeTaskDetails(id)); + } catch (ArgumentException e) { + return R.fail(e.getMessage()); + } } + /** * 根据开始时间及结束时间执行ota升级任务,包括相关升级包信息。 * diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradesController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradesController.java index 857b4c3b..ba26f31f 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradesController.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/ota/OtaUpgradesController.java @@ -1,6 +1,7 @@ package com.mqttsnet.thinglinks.link.controller.ota; import com.mqttsnet.thinglinks.common.core.domain.R; +import com.mqttsnet.thinglinks.common.core.exception.ArgumentException; import com.mqttsnet.thinglinks.common.core.web.controller.BaseController; import com.mqttsnet.thinglinks.link.api.domain.ota.vo.save.OtaUpgradesSaveVO; import com.mqttsnet.thinglinks.link.api.domain.ota.vo.update.OtaUpgradesUpdateVO; @@ -15,6 +16,7 @@ import javax.annotation.Resource; import javax.validation.Valid; import java.util.List; + @Validated @RestController @RequestMapping("/otaUpgrades") @@ -50,28 +52,45 @@ public R updateOtaUpgradeStatus( @ApiParam(value = "新状态值(1:启用,-1:禁用)", required = true) @RequestParam("status") Integer status) { // 记录信息 log.info("更新OTA升级状态 id:{}, 状态:{}", id, status); - // 返回更新状态的成功响应 - return R.ok(otaUpgradesService.updateOtaUpgradeStatus(id, status)); + try { + // 返回更新状态的成功响应 + return R.ok(otaUpgradesService.updateOtaUpgradeStatus(id, status)); + } catch (ArgumentException e) { + // 返回更新状态的失败响应 + return R.fail(e.getMessage()); + } + } @ApiOperation(value = "删除OTA升级包", httpMethod = "DELETE", notes = "通过其ID删除一个OTA升级包") @DeleteMapping("/deleteOtaUpgrade/{id}") public R deleteOtaUpgrade(@ApiParam(value = "OTA升级包ID", required = true) @PathVariable("id") Long id) { - // 记录信息 log.info("删除OTA升级包 id: {}", id); - // 返回删除操作的成功响应 - return R.ok(otaUpgradesService.deleteOtaUpgrade(id)); + try { + // 返回删除操作的成功响应 + return R.ok(otaUpgradesService.deleteOtaUpgrade(id)); + } catch (ArgumentException e) { + // 返回删除操作的失败响应 + return R.fail(e.getMessage()); + } } @ApiOperation(value = "批量删除OTA升级包", httpMethod = "DELETE", notes = "通过它们的ID批量删除OTA升级包") @DeleteMapping("/deleteOtaUpgrades") public R deleteOtaUpgrades(@ApiParam(value = "OTA升级包ID", required = true) @RequestBody List ids) { - // 记录信息 log.info("批量删除OTA升级包 ids: {}", ids); - // 检查是否所有ID对应的OTA升级包都已被删除 - boolean allDeleted = ids.stream().distinct().allMatch(id -> otaUpgradesService.deleteOtaUpgrade(id)); - // 返回批量删除操作的成功响应 - return R.ok(allDeleted); + try { + boolean allDeleted = ids.stream().distinct().allMatch(id -> { + try { + return otaUpgradesService.deleteOtaUpgrade(id); + } catch (ArgumentException e) { + throw new RuntimeException(e); + } + }); + return R.ok(allDeleted); + } catch (Exception e) { + return R.fail(e.getMessage()); + } } } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/product/ProductController.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/product/ProductController.java index 1090f7c6..80d69cf3 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/product/ProductController.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/controller/product/ProductController.java @@ -16,6 +16,7 @@ import com.mqttsnet.thinglinks.link.api.domain.product.model.ProductModel; import com.mqttsnet.thinglinks.link.service.product.ProductService; import com.mqttsnet.thinglinks.system.api.RemoteFileService; +import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -191,27 +192,6 @@ public AjaxResult validationFindOneByProductName(@PathVariable("productName") St return AjaxResult.error("产品名称已存在"); } - /** - * 初始化数据模型 - * - * @param productIds 产品ID集合 - * @param initializeOrNot 是否初始化 - * @return - * @throws Exception - */ -// @NoRepeatSubmit - @PreAuthorize(hasPermi = "link:product:initialize") - @Log(title = "产品管理", businessType = BusinessType.OTHER) - @GetMapping(value = "/initializeDataModel/{productIds}/{initializeOrNot}") - public AjaxResult initializeDataModel(@PathVariable("productIds") Long[] productIds, @PathVariable("initializeOrNot") Boolean initializeOrNot) { - try { - return AjaxResult.success(productService.createSuperTableDataModel(productIds, initializeOrNot)); - } catch (Exception e) { - log.error(e.getMessage()); - } - return AjaxResult.error("产品数据异常,请联系管理员"); - } - /** * 快捷生成产品模型json数据 * @@ -248,4 +228,19 @@ public R selectAllProductByStatus(@PathVariable(value = "status") String stat public R selectProductByProductIdentificationList(@RequestBody List productIdentificationList) { return R.ok(productService.selectProductByProductIdentificationList(productIdentificationList)); } + + +// @PreAuthorize(hasPermi = "link:product:empowerment") + @ApiOperation(value = "产品赋能", httpMethod = "GET", notes = "产品赋能") + @Log(title = "产品管理", businessType = BusinessType.OTHER) + @GetMapping(value = "/productEmpowerment/{productIds}") + public AjaxResult productEmpowerment(@PathVariable("productIds") Long[] productIds) { + try { + return AjaxResult.success(productService.productEmpowerment(productIds)); + } catch (Exception e) { + log.error(e.getMessage()); + } + return AjaxResult.error("产品赋能异常,请联系管理员"); + } + } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductCommandsMapper.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductCommandsMapper.java index 7525594b..6e366a6d 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductCommandsMapper.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductCommandsMapper.java @@ -119,4 +119,6 @@ public interface ProductCommandsMapper { int deleteProductCommandsByIds(Long[] ids); List selectProductCommandsByIdList(@Param("commandIdList") List commandIdList); + + List selectProductCommandsByServiceIdList(@Param("serviceIdList") List serviceIdList); } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductCommandsRequestsMapper.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductCommandsRequestsMapper.java index 1dbbea28..ba3b8173 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductCommandsRequestsMapper.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductCommandsRequestsMapper.java @@ -116,4 +116,7 @@ public interface ProductCommandsRequestsMapper { * @return 结果 */ int deleteProductCommandsRequestsByIds(Long[] ids); + + List selectProductCommandsRequestsByCommandIdList(@Param("commandIdList") List commandIdList); + } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductCommandsResponseMapper.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductCommandsResponseMapper.java index b580fdce..e5fd8a1b 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductCommandsResponseMapper.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductCommandsResponseMapper.java @@ -1,12 +1,11 @@ package com.mqttsnet.thinglinks.link.mapper.product; import com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductCommandsResponse; - -import java.util.List; - import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; +import java.util.List; + /** * @Description: java类作用描述 * @Author: ShiHuan Sun @@ -117,4 +116,6 @@ public interface ProductCommandsResponseMapper { * @return 结果 */ int deleteProductCommandsResponseByIds(Long[] ids); + + List selectProductCommandsResponseByCommandIdList(@Param("commandIdList") List commandIdList); } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductMapper.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductMapper.java index 16b29572..0c0c18a5 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductMapper.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductMapper.java @@ -4,7 +4,6 @@ import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; -import java.util.Collection; import java.util.List; /** @@ -148,5 +147,10 @@ public interface ProductMapper { List findAllByIdInAndStatus(@Param("ids") List ids, @Param("status") String status); List selectAllProductByStatus(@Param("status") String status); + List selectProductByProductIdentificationList(@Param("productIdentificationList") List productIdentificationList); + + Long findProductTotal(); + + List findProductsByPage(@Param("offset") int offset, @Param("pageSize") int pageSize); } \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductPropertiesMapper.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductPropertiesMapper.java index 81d4171e..6df17052 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductPropertiesMapper.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/mapper/product/ProductPropertiesMapper.java @@ -122,4 +122,7 @@ public interface ProductPropertiesMapper { int deleteProductPropertiesByIds(Long[] ids); List selectPropertiesByPropertiesIdList(@Param("propertiesIdList") List propertiesIdList); + + + List selectPropertiesByServiceIdList(@Param("serviceIdList") List serviceIdList); } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceActionServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceActionServiceImpl.java index e181f6a3..60ab0b54 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceActionServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceActionServiceImpl.java @@ -231,7 +231,7 @@ public void refreshDeviceCache(JSONObject thinglinksMessage) { Device device = deviceService.findOneByClientId(String.valueOf(map.get("clientId"))); if (null != device){ //缓存设备信息 - redisService.setCacheObject(CacheConstants.DEVICE_RECORD_KEY+device.getClientId(),device,60L+ Long.parseLong(DateUtils.getRandom(1)), TimeUnit.SECONDS); + redisService.setCacheObject(CacheConstants.DEF_DEVICE+device.getClientId(),device,60L+ Long.parseLong(DateUtils.getRandom(1)), TimeUnit.SECONDS); } } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceDatasServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceDatasServiceImpl.java index 235268fe..c03caa82 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceDatasServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceDatasServiceImpl.java @@ -40,7 +40,7 @@ import com.mqttsnet.thinglinks.tdengine.api.RemoteTdEngineService; import com.mqttsnet.thinglinks.tdengine.api.domain.Fields; import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDto; -import com.mqttsnet.thinglinks.tdengine.api.domain.TableDto; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -267,9 +267,9 @@ public String processingTopoAddTopic(String deviceIdentification, String body) t StringBuilder shadowTableNameBuilder = new StringBuilder(); // 新增设备管理成功后,创建TD普通表 List allByProductIdAndStatus = productServicesService.findAllByProductIdentificationIdAndStatus(product.getProductIdentification(), Constants.ENABLE); - TableDto tableDto; + TableDTO tableDto; for (ProductServices productServices : allByProductIdAndStatus) { - tableDto = new TableDto(); + tableDto = new TableDTO(); tableDto.setDataBaseName(dataBaseName); //超级表命名规则 : 产品类型_产品标识_服务名称 String superTableName = TdUtils.getSuperTableName(product.getProductType(), product.getProductIdentification(), productServices.getServiceName()); @@ -282,7 +282,7 @@ public String processingTopoAddTopic(String deviceIdentification, String body) t fields.setFieldValue(device.getDeviceIdentification()); tagsFieldValues.add(fields); tableDto.setTagsFieldValues(tagsFieldValues); - final R ctResult = remoteTdEngineService.createTable(tableDto); + final R ctResult = remoteTdEngineService.createSubTable(tableDto); if (ctResult.getCode() == ResultEnum.SUCCESS.getCode()) { shadowTableNameBuilder.append(tableDto.getTableName()).append(","); log.info("Create SuperTable Success: " + ctResult.getMsg()); @@ -427,12 +427,12 @@ public void processingDatasTopic(String deviceIdentification, String body) throw for (Map item : items) { final Object deviceId = item.get("deviceId"); Device device = null; - if (Boolean.TRUE.equals(redisService.hasKey(CacheConstants.DEVICE_RECORD_KEY + deviceIdentification))) { - device = redisService.getCacheObject(CacheConstants.DEVICE_RECORD_KEY + deviceIdentification); + if (Boolean.TRUE.equals(redisService.hasKey(CacheConstants.DEF_DEVICE + deviceIdentification))) { + device = redisService.getCacheObject(CacheConstants.DEF_DEVICE + deviceIdentification); } else { device = deviceService.findOneByDeviceIdentification(deviceIdentification); if (StringUtils.isNotNull(device)) { - redisService.setCacheObject(CacheConstants.DEVICE_RECORD_KEY + deviceIdentification, device); + redisService.setCacheObject(CacheConstants.DEF_DEVICE + deviceIdentification, device); } else { log.error("The side device reports data processing, but the device does not exist,DeviceIdentification:{},Body:{}", deviceIdentification, body); continue; @@ -472,7 +472,7 @@ public void processingDatasTopic(String deviceIdentification, String body) throw //子表命名规则 : 产品类型_产品标识_服务名称_设备标识(设备唯一标识) String tableName = superTableName + "_" + deviceId.toString(); //从redis根据超级表名称取出超级表表结构信息 - final Object cacheObject = redisService.getCacheObject(CacheConstants.TDENGINE_SUPERTABLEFILELDS + superTableName); + final Object cacheObject = redisService.getCacheObject(CacheConstants.DEF_TDENGINE_SUPERTABLEFILELDS + superTableName); ObjectMapper objectMapper = new ObjectMapper(); SuperTableDto superTableDto = objectMapper.convertValue(cacheObject, SuperTableDto.class); //获取超级表的表结构信息 @@ -534,14 +534,14 @@ public void processingDatasTopic(String deviceIdentification, String body) throw continue; } //设置插入所需参数 - TableDto tableDto = new TableDto(); + TableDTO tableDto = new TableDTO(); tableDto.setDataBaseName(superTableDto.getDataBaseName()); tableDto.setSuperTableName(superTableDto.getSuperTableName()); tableDto.setTableName(tableName); tableDto.setSchemaFieldValues(schemaFieldsStream); tableDto.setTagsFieldValues(tagsFieldsStream); //调用插入方法插入数据 TODO 需要改为mq异步处理 - final R insertResult = this.remoteTdEngineService.insertData(tableDto); + final R insertResult = this.remoteTdEngineService.insertTableData(tableDto); if (insertResult.getCode() == ResultEnum.SUCCESS.getCode()) { log.info("DeviceIdentification: {}, Insert data result: {}", deviceIdentification, ResultEnum.SUCCESS.getMessage()); } else { @@ -568,8 +568,8 @@ public void processingTopoCommandResponseTopic(String deviceIdentification, Stri * 根据设备找到所属产品 产品的服务及属性 转换出系统能识别的json 找到这个产品的协议内容即Java代码 */ public String convertToBody(String deviceIdentification, String body) { - if (Boolean.TRUE.equals(redisService.hasKey(CacheConstants.DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + ProtocolType.MQTT.getValue() + deviceIdentification))) { - String protocolContent = redisService.get(CacheConstants.DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + ProtocolType.MQTT.getValue() + deviceIdentification); + if (Boolean.TRUE.equals(redisService.hasKey(CacheConstants.DEF_DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + ProtocolType.MQTT.getValue() + deviceIdentification))) { + String protocolContent = redisService.get(CacheConstants.DEF_DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + ProtocolType.MQTT.getValue() + deviceIdentification); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); PrintWriter out = new PrintWriter(buffer, true); byte[] classBytes = DynamicLoaderEngine.compile(protocolContent, out, null);//传入要执行的代码 diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java index 30ac15ec..fdfda12d 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceInfoServiceImpl.java @@ -41,7 +41,7 @@ import com.mqttsnet.thinglinks.tdengine.api.RemoteTdEngineService; import com.mqttsnet.thinglinks.tdengine.api.domain.Fields; import com.mqttsnet.thinglinks.tdengine.api.domain.SelectDto; -import com.mqttsnet.thinglinks.tdengine.api.domain.TableDto; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -364,9 +364,9 @@ public Boolean refreshDeviceInfoDataModel(Collection idCollection) { StringBuilder shadowTableNameBuilder = new StringBuilder(); // 新增设备管理成功后,创建TD普通表 List allByProductIdAndStatus = productServicesService.findAllByProductIdentificationIdAndStatus(product.getProductIdentification(), Constants.ENABLE); - TableDto tableDto; + TableDTO tableDto; for (ProductServices productServices : allByProductIdAndStatus) { - tableDto = new TableDto(); + tableDto = new TableDTO(); tableDto.setDataBaseName(dataBaseName); //超级表命名规则 : 产品类型_产品标识_服务名称 String superTableName = TdUtils.getSuperTableName(product.getProductType(), product.getProductIdentification(), productServices.getServiceName()); @@ -379,7 +379,7 @@ public Boolean refreshDeviceInfoDataModel(Collection idCollection) { fields.setFieldValue(device.getDeviceIdentification()); tagsFieldValues.add(fields); tableDto.setTagsFieldValues(tagsFieldValues); - final R ctResult = remoteTdEngineService.createTable(tableDto); + final R ctResult = remoteTdEngineService.createSubTable(tableDto); if (ctResult.getCode() == ResultEnum.SUCCESS.getCode()) { shadowTableNameBuilder.append(tableDto.getTableName()).append(","); log.info("Create SuperTable Success: " + ctResult.getMsg()); diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java index c2c801ea..054479ec 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/device/impl/DeviceServiceImpl.java @@ -1,8 +1,6 @@ package com.mqttsnet.thinglinks.link.service.device.impl; import cn.hutool.core.bean.BeanUtil; -import cn.hutool.core.bean.copier.CopyOptions; -import cn.hutool.core.text.CharSequenceUtil; import com.mqttsnet.thinglinks.broker.api.RemoteMqttBrokerOpenApi; import com.mqttsnet.thinglinks.common.core.constant.CacheConstants; import com.mqttsnet.thinglinks.common.core.constant.Constants; @@ -12,7 +10,6 @@ import com.mqttsnet.thinglinks.common.core.enums.DeviceType; import com.mqttsnet.thinglinks.common.core.enums.ResultEnum; import com.mqttsnet.thinglinks.common.core.utils.DateUtils; -import com.mqttsnet.thinglinks.common.core.utils.SnowflakeIdUtil; import com.mqttsnet.thinglinks.common.core.utils.StringUtils; import com.mqttsnet.thinglinks.common.core.utils.tdengine.TdUtils; import com.mqttsnet.thinglinks.common.redis.service.RedisService; @@ -22,11 +19,10 @@ import com.mqttsnet.thinglinks.link.api.domain.device.entity.DeviceTopic; import com.mqttsnet.thinglinks.link.api.domain.device.enumeration.MqttProtocolTopoStatusEnum; import com.mqttsnet.thinglinks.link.api.domain.device.model.DeviceParams; -import com.mqttsnet.thinglinks.link.api.domain.deviceInfo.model.DeviceInfoParams; import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; import com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductServices; -import com.mqttsnet.thinglinks.link.api.domain.vo.param.*; -import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoAddDeviceResultVO; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoDeviceDataReportParam; +import com.mqttsnet.thinglinks.link.api.domain.vo.param.TopoQueryDeviceParam; import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoDeviceOperationResultVO; import com.mqttsnet.thinglinks.link.api.domain.vo.result.TopoQueryDeviceResultVO; import com.mqttsnet.thinglinks.link.mapper.device.DeviceMapper; @@ -38,9 +34,7 @@ import com.mqttsnet.thinglinks.system.api.domain.SysUser; import com.mqttsnet.thinglinks.system.api.model.LoginUser; import com.mqttsnet.thinglinks.tdengine.api.RemoteTdEngineService; -import com.mqttsnet.thinglinks.tdengine.api.domain.Fields; import com.mqttsnet.thinglinks.tdengine.api.domain.SelectDto; -import com.mqttsnet.thinglinks.tdengine.api.domain.TableDto; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -171,6 +165,7 @@ public int batchInsert(List list) { @Override public int updateConnectStatusByClientId(String updatedConnectStatus, String clientId) { + log.info("更新设备连接状态为: {} , clientId: {}", updatedConnectStatus, clientId); return deviceMapper.updateConnectStatusByClientId(updatedConnectStatus, clientId); } @@ -240,23 +235,52 @@ public int insertDevice(DeviceParams deviceParams) throws Exception { //基础TOPIC集合 Map topicMap = new HashMap<>(); if (DeviceType.GATEWAY.getValue().equals(device.getDeviceType())) { - topicMap.put("/v1/devices/" + device.getDeviceIdentification() + "/topo/add", "边设备添加子设备"); - topicMap.put("/v1/devices/" + device.getDeviceIdentification() + "/topo/addResponse", "物联网平台返回的添加子设备的响应"); - topicMap.put("/v1/devices/" + device.getDeviceIdentification() + "/topo/delete", "边设备删除子设备"); - topicMap.put("/v1/devices/" + device.getDeviceIdentification() + "/topo/deleteResponse", "物联网平台返回的删除子设备的响应"); - topicMap.put("/v1/devices/" + device.getDeviceIdentification() + "/topo/update", "边设备更新子设备状态"); - topicMap.put("/v1/devices/" + device.getDeviceIdentification() + "/topo/updateResponse", "物联网平台返回的更新子设备状态的响应"); - topicMap.put("/v1/devices/" + device.getDeviceIdentification() + "/datas", "边设备上报数据"); - topicMap.put("/v1/devices/" + device.getDeviceIdentification() + "/command", "物联网平台给设备或边设备下发命令"); - topicMap.put("/v1/devices/" + device.getDeviceIdentification() + "/commandResponse", "边设备返回给物联网平台的命令响应"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/add", "边设备添加子设备"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/addResponse", "物联网平台返回的添加子设备的响应"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/delete", "边设备删除子设备"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/deleteResponse", "物联网平台返回的删除子设备的响应"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/update", "边设备更新子设备状态"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/updateResponse", "物联网平台返回的更新子设备状态的响应"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/datas", "边设备上报数据"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/command", "物联网平台给设备或边设备下发命令"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/commandResponse", "边设备返回给物联网平台的命令响应"); + + // 添加OTA更新命令和响应 + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/otaCommand", "物联网平台给网关设备下发OTA远程升级命令"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/otaCommandResponse", "网关设备返回给物联网平台的OTA远程升级命令响应"); + + // 添加OTA拉取命令和响应 + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/otaPull", "网关设备拉取物联网平台的最新软固件信息"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/otaPullResponse", "物联网平台响应软固件信息给设备"); + + // 添加OTA上报命令和响应 + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/otaReport", "网关设备向物联网平台上报软固件版本"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/otaReportResponse", "物联网平台接收到上报软固件信息响应"); + + // 添加OTA读取命令和响应 + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/otaRead", "物联网平台读取设备软固件版本"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/otaReadResponse", "网关设备回复物联网平台读取设备固件版本指令"); + } else if (DeviceType.COMMON.getValue().equals(device.getDeviceType())) { - topicMap.put("/v1/devices/" + device.getDeviceIdentification() + "/datas", "边设备上报数据"); - topicMap.put("/v1/devices/" + device.getDeviceIdentification() + "/command", "物联网平台给设备或边设备下发命令"); - topicMap.put("/v1/devices/" + device.getDeviceIdentification() + "/commandResponse", "边设备返回给物联网平台的命令响应"); - Boolean commonDeviceTDSubtable = this.createCommonDeviceTDSubtable(device); - if (!commonDeviceTDSubtable) { - throw new Exception("创建普通设备TD子表失败"); - } + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/datas", "普通设备上报数据"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/command", "物联网平台给普通设备下发命令"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/commandResponse", "普通设备返回给物联网平台的命令响应"); + // 添加OTA更新命令和响应 + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/otaCommand", "物联网平台给普通设备下发OTA远程升级命令"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/otaCommandResponse", "普通设备返回给物联网平台的OTA远程升级命令响应"); + + // 添加OTA拉取命令和响应 + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/otaPull", "普通设备拉取物联网平台的最新软固件信息"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/otaPullResponse", "物联网平台响应软固件信息给普通设备"); + + // 添加OTA上报命令和响应 + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/otaReport", "普通设备向物联网平台上报软固件版本"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/otaReportResponse", "物联网平台接收到上报软固件信息响应"); + + // 添加OTA读取命令和响应 + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/otaRead", "物联网平台读取设备软固件版本"); + topicMap.put("/" + device.getDeviceSdkVersion() + "/devices/" + device.getDeviceIdentification() + "/topo/otaReadResponse", "普通设备回复物联网平台读取设备固件版本指令"); + } //设备基础Topic数据存储 for (Map.Entry entry : topicMap.entrySet()) { @@ -264,13 +288,13 @@ public int insertDevice(DeviceParams deviceParams) throws Exception { deviceTopic.setDeviceIdentification(device.getDeviceIdentification()); deviceTopic.setType(DeviceTopicEnum.BASIS.getKey()); deviceTopic.setTopic(entry.getKey()); - if (entry.getKey().startsWith("/v1/devices/") && entry.getKey().endsWith("datas")) { + if (entry.getKey().startsWith("/" + device.getDeviceSdkVersion() + "/devices/") && entry.getKey().endsWith("datas")) { deviceTopic.setPublisher("边设备"); deviceTopic.setSubscriber("物联网平台"); - } else if (entry.getKey().startsWith("/v1/devices/") && entry.getKey().endsWith("commandResponse")) { + } else if (entry.getKey().startsWith("/" + device.getDeviceSdkVersion() + "/devices/") && entry.getKey().endsWith("commandResponse")) { deviceTopic.setPublisher("边设备"); deviceTopic.setSubscriber("物联网平台"); - } else if (entry.getKey().startsWith("/v1/devices/") && (entry.getKey().endsWith("Response") || entry.getKey().endsWith("command"))) { + } else if (entry.getKey().startsWith("/" + device.getDeviceSdkVersion() + "/devices/") && (entry.getKey().endsWith("Response") || entry.getKey().endsWith("command"))) { deviceTopic.setPublisher("物联网平台"); deviceTopic.setSubscriber("边设备"); } else { @@ -368,7 +392,7 @@ public Boolean cacheInvalidation(String clientId) { //设备信息缓存失效 删除缓存 更新数据库设备状态 if (StringUtils.isNotNull(oneByClientId)) { //删除缓存 - redisService.delete(CacheConstants.DEVICE_RECORD_KEY + oneByClientId.getDeviceIdentification()); + redisService.delete(CacheConstants.DEF_DEVICE + oneByClientId.getDeviceIdentification()); //更新数据库设备状态 Device device = new Device(); device.setId(oneByClientId.getId()); @@ -421,7 +445,7 @@ public Device clientAuthentication(String clientIdentifier, String username, Str final Device device = this.findOneByClientIdAndUserNameAndPasswordAndDeviceStatusAndProtocolType(clientIdentifier, username, password, deviceStatus, protocolType); if (Optional.ofNullable(device).isPresent()) { //缓存设备信息 - redisService.setCacheObject(CacheConstants.DEVICE_RECORD_KEY + device.getDeviceIdentification(), device, 60L + Long.parseLong(DateUtils.getRandom(1)), TimeUnit.SECONDS); + redisService.setCacheObject(CacheConstants.DEF_DEVICE + device.getDeviceIdentification(), device, 60L + Long.parseLong(DateUtils.getRandom(1)), TimeUnit.SECONDS); //更改设备在线状态为在线 this.updateConnectStatusByClientId(DeviceConnectStatusEnum.ONLINE.getValue(), clientIdentifier); return device; @@ -520,43 +544,6 @@ public Map>> getDeviceShadow(String ids, String return map; } - /** - * 创建普通设备TD子表 - * - * @param device - * @return - */ - public Boolean createCommonDeviceTDSubtable(Device device) { - final Product product = productService.findOneByProductIdentificationAndProtocolType(device.getProductIdentification(), device.getProtocolType()); - if (StringUtils.isNull(product)) { - log.error("刷新子设备数据模型失败,子设备产品不存在"); - return false; - } - List allByProductIdAndStatus = productServicesService.findAllByProductIdentificationIdAndStatus(product.getProductIdentification(), Constants.ENABLE); - TableDto tableDto; - for (ProductServices productServices : allByProductIdAndStatus) { - tableDto = new TableDto(); - tableDto.setDataBaseName(dataBaseName); - //超级表命名规则 : 产品类型_产品标识_服务名称 - String superTableName = TdUtils.getSuperTableName(product.getProductType(), product.getProductIdentification(), productServices.getServiceName()); - tableDto.setSuperTableName(superTableName); - //子表命名规则 : 产品类型_产品标识_服务名称_设备标识(设备唯一标识) - tableDto.setTableName(TdUtils.getSubTableName(superTableName, device.getDeviceIdentification())); - //Tag的处理 - List tagsFieldValues = new ArrayList<>(); - Fields fields = new Fields(); - fields.setFieldValue(device.getDeviceIdentification()); - tagsFieldValues.add(fields); - tableDto.setTagsFieldValues(tagsFieldValues); - final R ctResult = remoteTdEngineService.createTable(tableDto); - if (ctResult.getCode() == ResultEnum.SUCCESS.getCode()) { - log.info("Create SuperTable Success: " + ctResult.getMsg()); - } else { - log.error("Create SuperTable Exception: " + ctResult.getMsg()); - } - } - return true; - } public List selectDeviceByDeviceIdentificationList(List deviceIdentificationList) { return deviceMapper.selectDeviceByDeviceIdentificationList(deviceIdentificationList); @@ -608,7 +595,6 @@ public TopoQueryDeviceResultVO queryDeviceByHttp(TopoQueryDeviceParam topoQueryD } - /** * Queries device information based on provided parameters. * @@ -653,6 +639,7 @@ private TopoQueryDeviceResultVO queryDeviceInfo(TopoQueryDeviceParam topoQueryDe .setStatusDesc("Query completed"); return topoQueryDeviceResultVO; } + @Override public Long findDeviceTotal() { return deviceMapper.findDeviceTotal(); diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradeTasksService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradeTasksService.java index 12ed9fe2..fecd46e6 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradeTasksService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradeTasksService.java @@ -1,5 +1,6 @@ package com.mqttsnet.thinglinks.link.service.ota; +import com.mqttsnet.thinglinks.common.core.exception.ArgumentException; import com.mqttsnet.thinglinks.link.api.domain.ota.vo.result.OtaUpgradeTasksResultVO; import com.mqttsnet.thinglinks.link.api.domain.ota.vo.save.OtaUpgradeTasksSaveVO; import com.mqttsnet.thinglinks.link.api.domain.ota.vo.update.OtaUpgradeTasksUpdateVO; @@ -32,7 +33,7 @@ public interface OtaUpgradeTasksService { * @param status 状态 * @return {@link Boolean} 返回结果 */ - boolean changeTaskStatus(Long id, Integer status); + boolean changeTaskStatus(Long id, Integer status) throws ArgumentException; /** * Delete OTA Upgrade Task @@ -40,7 +41,7 @@ public interface OtaUpgradeTasksService { * @param id 主键 * @return {@link Boolean} 返回结果 */ - boolean deleteOtaUpgradeTask(Long id); + boolean deleteOtaUpgradeTask(Long id) throws ArgumentException; /** * Get OTA Upgrade Task Details @@ -48,7 +49,7 @@ public interface OtaUpgradeTasksService { * @param id 主键 * @return {@link OtaUpgradeTasksResultVO} 返回结果 */ - OtaUpgradeTasksResultVO getUpgradeTaskDetails(Long id); + OtaUpgradeTasksResultVO getUpgradeTaskDetails(Long id) throws ArgumentException; /** * Perform ota upgrade tasks based on the start time and end time, including upgrade package information. diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradesService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradesService.java index 0f6e1843..7f6fa9b0 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradesService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/OtaUpgradesService.java @@ -1,5 +1,6 @@ package com.mqttsnet.thinglinks.link.service.ota; +import com.mqttsnet.thinglinks.common.core.exception.ArgumentException; import com.mqttsnet.thinglinks.link.api.domain.ota.vo.save.OtaUpgradesSaveVO; import com.mqttsnet.thinglinks.link.api.domain.ota.vo.update.OtaUpgradesUpdateVO; @@ -27,7 +28,7 @@ public interface OtaUpgradesService { * @param status 状态 * @return {@link Boolean} 返回结果 */ - Boolean updateOtaUpgradeStatus(Long id, Integer status); + Boolean updateOtaUpgradeStatus(Long id, Integer status) throws ArgumentException; - Boolean deleteOtaUpgrade(Long id); + Boolean deleteOtaUpgrade(Long id) throws ArgumentException; } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradeTasksServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradeTasksServiceImpl.java index adaed3c6..f4e60a33 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradeTasksServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradeTasksServiceImpl.java @@ -1,5 +1,6 @@ package com.mqttsnet.thinglinks.link.service.ota.impl; +import com.mqttsnet.thinglinks.common.core.exception.ArgumentException; import com.mqttsnet.thinglinks.common.core.exception.ServiceException; import com.mqttsnet.thinglinks.common.core.utils.ArgumentAssert; import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; @@ -83,7 +84,7 @@ public OtaUpgradeTasksUpdateVO updateUpgradeTask(OtaUpgradeTasksUpdateVO updateV } @Override - public boolean changeTaskStatus(Long id, Integer status) { + public boolean changeTaskStatus(Long id, Integer status) throws ArgumentException { ArgumentAssert.notNull(id, "Package ID cannot be null"); ArgumentAssert.notNull(status, "Status cannot be null"); @@ -101,7 +102,7 @@ public boolean changeTaskStatus(Long id, Integer status) { } @Override - public boolean deleteOtaUpgradeTask(Long id) { + public boolean deleteOtaUpgradeTask(Long id) throws ArgumentException { ArgumentAssert.notNull(id, "Task ID cannot be null"); OtaUpgradeTasks task = otaUpgradeTasksMapper.selectOtaUpgradeTaskById(id); @@ -115,7 +116,7 @@ public boolean deleteOtaUpgradeTask(Long id) { } @Override - public OtaUpgradeTasksResultVO getUpgradeTaskDetails(Long id) { + public OtaUpgradeTasksResultVO getUpgradeTaskDetails(Long id) throws ArgumentException { ArgumentAssert.notNull(id, "Task ID cannot be null"); OtaUpgradeTasks otaUpgradeTask = otaUpgradeTasksMapper.selectOtaUpgradeTaskById(id); diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradesServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradesServiceImpl.java index 9dd15ac1..e700e962 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradesServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/ota/impl/OtaUpgradesServiceImpl.java @@ -1,5 +1,6 @@ package com.mqttsnet.thinglinks.link.service.ota.impl; +import com.mqttsnet.thinglinks.common.core.exception.ArgumentException; import com.mqttsnet.thinglinks.common.core.exception.ServiceException; import com.mqttsnet.thinglinks.common.core.utils.ArgumentAssert; import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; @@ -75,7 +76,7 @@ public OtaUpgradesUpdateVO updateUpgradePackage(OtaUpgradesUpdateVO updateVO) { } @Override - public Boolean updateOtaUpgradeStatus(Long id, Integer status) { + public Boolean updateOtaUpgradeStatus(Long id, Integer status) throws ArgumentException { ArgumentAssert.notNull(id, "Package ID cannot be null"); ArgumentAssert.notNull(status, "Status cannot be null"); @@ -99,7 +100,7 @@ public Boolean updateOtaUpgradeStatus(Long id, Integer status) { * @throws ServiceException if the OTA upgrade package does not exist or is in use */ @Override - public Boolean deleteOtaUpgrade(Long id) { + public Boolean deleteOtaUpgrade(Long id) throws ArgumentException { ArgumentAssert.notNull(id, "Package ID cannot be null"); OtaUpgrades otaUpgrade = otaUpgradesMapper.selectOtaUpgradeById(id); diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductCommandsRequestsService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductCommandsRequestsService.java index 282826ab..8f001a39 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductCommandsRequestsService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductCommandsRequestsService.java @@ -3,6 +3,7 @@ import java.util.List; import com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductCommandsRequests; +import org.apache.ibatis.annotations.Param; /** * @Description: java类作用描述 @@ -80,4 +81,6 @@ public interface ProductCommandsRequestsService { */ int deleteProductCommandsRequestsByIds(Long[] ids); + List selectProductCommandsRequestsByCommandIdList(@Param("commandIdList") List commandIdList); + } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductCommandsResponseService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductCommandsResponseService.java index 48515312..5db19265 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductCommandsResponseService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductCommandsResponseService.java @@ -3,6 +3,7 @@ import java.util.List; import com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductCommandsResponse; +import org.apache.ibatis.annotations.Param; /** * @Description: java类作用描述 @@ -80,4 +81,6 @@ public interface ProductCommandsResponseService { */ int deleteProductCommandsResponseByIds(Long[] ids); + List selectProductCommandsResponseByCommandIdList(@Param("commandIdList") List commandIdList); + } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductCommandsService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductCommandsService.java index b92dfcda..2a024f1a 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductCommandsService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductCommandsService.java @@ -1,9 +1,9 @@ package com.mqttsnet.thinglinks.link.service.product; -import java.util.List; - import com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductCommands; +import java.util.List; + /** * @Description: java类作用描述 * @Author: ShiHuan Sun @@ -80,6 +80,7 @@ public interface ProductCommandsService { List selectProductCommandsByIdList(List commandIdList); + List selectProductCommandsByServiceIdList(List serviceIdList); } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductPropertiesService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductPropertiesService.java index 0c8889b6..dfb191ba 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductPropertiesService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductPropertiesService.java @@ -1,9 +1,8 @@ package com.mqttsnet.thinglinks.link.service.product; -import java.util.List; - import com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductProperties; -import org.springframework.web.bind.annotation.RequestParam; + +import java.util.List; /** * @Description: java类作用描述 @@ -84,5 +83,7 @@ public interface ProductPropertiesService { */ int deleteProductPropertiesByIds(Long[] ids); - List selectPropertiesByPropertiesIdList( List propertiesIdList); + List selectPropertiesByPropertiesIdList(List propertiesIdList); + + List selectPropertiesByServiceIdList(List serviceIdList); } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductService.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductService.java index bea78d2c..2bb17fbb 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductService.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/ProductService.java @@ -1,15 +1,14 @@ package com.mqttsnet.thinglinks.link.service.product; -import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.mqttsnet.thinglinks.common.core.web.domain.AjaxResult; import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; import com.mqttsnet.thinglinks.link.api.domain.product.model.ProductModel; +import com.mqttsnet.thinglinks.link.api.domain.product.vo.param.ProductParamVO; import com.mqttsnet.thinglinks.link.api.domain.product.vo.result.ProductResultVO; import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDto; import org.springframework.web.multipart.MultipartFile; -import java.util.Collection; import java.util.List; /** @@ -65,10 +64,10 @@ public interface ProductService { /** * 解析产品模型数据 * - * @param content 产品模型数据 - * @param appId 应用ID + * @param content 产品模型数据 + * @param appId 应用ID * @param templateIdentification 产品模型模板标识 - * @param status 状态(字典值:启用 停用) + * @param status 状态(字典值:启用 停用) * @return 解析结果 * @throws Exception */ @@ -148,29 +147,8 @@ public interface ProductService { Product findOneByManufacturerIdAndModelAndDeviceType(String manufacturerId, String model, String deviceType); - /** - * 根据产品模型创建超级表 - * - * @param product - * @param services - * @return - * @throws Exception - */ - AjaxResult createSuperTable(Product product, JSONArray services) throws Exception; - - List findAllByStatus(String status); - /** - * 初始化生成超级表模型 - * - * @param productIds 产品ID集合 productIds==null 初始化所有产品:productIds!=null 初始化指定产品 - * @param InitializeOrNot 是否初始化 - * @return - * @throws Exception - */ - List createSuperTableDataModel(Long[] productIds, Boolean InitializeOrNot); - Product findOneByManufacturerIdAndModelAndProtocolTypeAndStatus(String manufacturerId, String model, String protocolType, String status); @@ -198,5 +176,21 @@ public interface ProductService { Long findProductTotal(); List findProductsByPage(int offset, int pageSize); + + /** + * 查询产品管理 带服务、属性、命令 + * + * @param productIdentification 产品标识 + * @return 产品管理 + */ + ProductParamVO selectFullProductByProductIdentification(String productIdentification); + + /** + * 产品赋能 + * + * @param productIds 产品ID集合 + * @return 赋能结果 + */ + String productEmpowerment(Long[] productIds); } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductCommandsRequestsServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductCommandsRequestsServiceImpl.java index ce3d4245..d025875e 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductCommandsRequestsServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductCommandsRequestsServiceImpl.java @@ -137,4 +137,9 @@ public int deleteProductCommandsRequestsByIds(Long[] ids) { return productCommandsRequestsMapper.deleteProductCommandsRequestsByIds(ids); } + @Override + public List selectProductCommandsRequestsByCommandIdList(List commandIdList) { + return productCommandsRequestsMapper.selectProductCommandsRequestsByCommandIdList(commandIdList); + } + } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductCommandsResponseServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductCommandsResponseServiceImpl.java index 78fe77ef..277a5549 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductCommandsResponseServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductCommandsResponseServiceImpl.java @@ -137,4 +137,9 @@ public int deleteProductCommandsResponseByIds(Long[] ids) { return productCommandsResponseMapper.deleteProductCommandsResponseByIds(ids); } + @Override + public List selectProductCommandsResponseByCommandIdList(List commandIdList) { + return productCommandsResponseMapper.selectProductCommandsResponseByCommandIdList(commandIdList); + } + } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductCommandsServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductCommandsServiceImpl.java index 358541b3..0beaedd1 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductCommandsServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductCommandsServiceImpl.java @@ -140,4 +140,9 @@ public int deleteProductCommandsByIds(Long[] ids) { public List selectProductCommandsByIdList(List commandIdList){ return productCommandsMapper.selectProductCommandsByIdList(commandIdList); } + + @Override + public List selectProductCommandsByServiceIdList(List serviceIdList) { + return productCommandsMapper.selectProductCommandsByServiceIdList(serviceIdList); + } } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductPropertiesServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductPropertiesServiceImpl.java index 90012c99..58d6c0f8 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductPropertiesServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductPropertiesServiceImpl.java @@ -149,4 +149,9 @@ public List selectPropertiesByPropertiesIdList(List pro { return productPropertiesMapper.selectPropertiesByPropertiesIdList(propertiesIdList); } + + @Override + public List selectPropertiesByServiceIdList(List serviceIdList) { + return productPropertiesMapper.selectPropertiesByServiceIdList(serviceIdList); + } } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServiceImpl.java index 4b44f868..4796b41e 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/product/impl/ProductServiceImpl.java @@ -1,11 +1,12 @@ package com.mqttsnet.thinglinks.link.service.product.impl; -import com.alibaba.fastjson.JSON; +import cn.hutool.json.JSONUtil; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.jayway.jsonpath.JsonPath; -import com.mqttsnet.thinglinks.common.core.constant.CacheConstants; import com.mqttsnet.thinglinks.common.core.constant.Constants; import com.mqttsnet.thinglinks.common.core.domain.R; import com.mqttsnet.thinglinks.common.core.enums.DataTypeEnum; @@ -13,30 +14,39 @@ import com.mqttsnet.thinglinks.common.core.text.CharsetKit; import com.mqttsnet.thinglinks.common.core.text.UUID; import com.mqttsnet.thinglinks.common.core.utils.StringUtils; +import com.mqttsnet.thinglinks.common.core.utils.bean.BeanPlusUtil; import com.mqttsnet.thinglinks.common.core.utils.bean.BeanUtils; import com.mqttsnet.thinglinks.common.core.web.domain.AjaxResult; import com.mqttsnet.thinglinks.common.redis.service.RedisService; import com.mqttsnet.thinglinks.common.security.service.TokenService; +import com.mqttsnet.thinglinks.link.api.domain.empowerment.enumeration.EmpowermentStatusEnum; +import com.mqttsnet.thinglinks.link.api.domain.empowerment.vo.result.EmpowermentRecordResultVO; import com.mqttsnet.thinglinks.link.api.domain.product.entity.Product; +import com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductCommands; import com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductProperties; import com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductServices; +import com.mqttsnet.thinglinks.link.api.domain.product.enumeration.ProductTypeEnum; import com.mqttsnet.thinglinks.link.api.domain.product.model.ProductModel; import com.mqttsnet.thinglinks.link.api.domain.product.model.Properties; import com.mqttsnet.thinglinks.link.api.domain.product.model.Services; +import com.mqttsnet.thinglinks.link.api.domain.product.vo.param.*; +import com.mqttsnet.thinglinks.link.api.domain.product.vo.result.ProductResultVO; +import com.mqttsnet.thinglinks.link.common.cache.helper.CacheDataHelper; import com.mqttsnet.thinglinks.link.mapper.product.ProductMapper; -import com.mqttsnet.thinglinks.link.service.product.ProductPropertiesService; -import com.mqttsnet.thinglinks.link.service.product.ProductService; -import com.mqttsnet.thinglinks.link.service.product.ProductServicesService; +import com.mqttsnet.thinglinks.link.service.product.*; import com.mqttsnet.thinglinks.system.api.domain.SysUser; import com.mqttsnet.thinglinks.system.api.model.LoginUser; import com.mqttsnet.thinglinks.tdengine.api.RemoteTdEngineService; +import com.mqttsnet.thinglinks.tdengine.api.constant.TdsConstants; import com.mqttsnet.thinglinks.tdengine.api.domain.Fields; -import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDto; +import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDescribeVO; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.FieldsVO; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.SuperTableDTO; +import com.mqttsnet.thinglinks.tdengine.api.utils.TdsUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; @@ -48,7 +58,10 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.time.Duration; +import java.time.LocalDateTime; import java.util.*; +import java.util.stream.Collectors; /** * @Description: 产品模型业务层 @@ -75,11 +88,24 @@ public class ProductServiceImpl implements ProductService { private ProductServicesService productServicesService; @Autowired private ProductPropertiesService productPropertiesService; + + @Autowired + private ProductCommandsService productCommandsService; + + @Autowired + private ProductCommandsRequestsService productCommandsRequestsService; + + @Autowired + private ProductCommandsResponseService productCommandsResponseService; + @Resource private RemoteTdEngineService remoteTdEngineService; @Autowired private RedisService redisService; + @Autowired + private CacheDataHelper cacheDataHelper; + /** * 数据库名称 */ @@ -318,10 +344,11 @@ public AjaxResult productJsonDataAnalysis(JSONObject content, String appId, Stri productProperties.setServiceId(productServices.getId()); productProperties.setCreateBy(sysUser.getUserName()); final int batchInsert = productPropertiesService.insertSelective(productProperties); + if (batchInsert == 0) { + log.error("Property capability Data storage fails"); + } } } - //解析入库成功创建TD超级表及子表 - this.createSuperTable(product, services); } catch (Exception e) { log.error(e.getMessage()); return AjaxResult.error("操作失败"); @@ -329,94 +356,6 @@ public AjaxResult productJsonDataAnalysis(JSONObject content, String appId, Stri return AjaxResult.success("操作成功"); } - /** - * 根据产品模型创建超级表 - * - * @param product - * @param services - * @return - * @throws Exception - */ - @Override - @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) - public AjaxResult createSuperTable(Product product, JSONArray services) throws Exception { - //构建超级表入参对象 - SuperTableDto superTableDto = new SuperTableDto(); - try { - loop: - for (int i = 0; i < services.size(); i++) { - JSONObject service = services.getJSONObject(i); - //超级表名称命名规则:产品类型_产品标识_服务名称 - String superTableName = product.getProductType() + "_" + product.getProductIdentification() + "_" + service.getString("serviceId"); - //设置数据库名称和超级表名称 - superTableDto.setDataBaseName(dataBaseName); - superTableDto.setSuperTableName(superTableName); - //构建超级表的表结构字段列表 - JSONArray properties = service.getJSONArray("properties"); - //如果服务下属性值为空,没必要为该服务创建超级表,跳过该循环,进入下个服务 - if (properties.isEmpty()) { - continue; - } - //构建超级表的表结构字段列表 - List schemaFields = new ArrayList<>(); - //超级表第一个字段数据类型必须为时间戳,默认Ts为当前系统时间 - Fields tsColumn = new Fields(); - tsColumn.setFieldName("ts"); - tsColumn.setDataType(DataTypeEnum.TIMESTAMP); - schemaFields.add(tsColumn); - //超级表第二个字段为事件发生时间数据类型必须为时间戳 - Fields eventTimeColumn = new Fields(); - eventTimeColumn.setFieldName("event_time"); - eventTimeColumn.setDataType(DataTypeEnum.TIMESTAMP); - schemaFields.add(eventTimeColumn); - //根据属性对象列表循环构建超级表表结构 - for (int j = 0; j < properties.size(); j++) { - JSONObject propertie = properties.getJSONObject(j); - //获取字段名称 - String filedName = (String) propertie.get("name"); - //获取该属性数据类型 - String datatype = (String) propertie.get("datatype"); - //获取该属性的数据大小 - Integer size = (Integer) propertie.get("maxlength"); - //添加超级表表结构字段 - Fields fields = new Fields(filedName, datatype, size); - schemaFields.add(fields); - } - //构建超级表标签字段列表 - //根据业务逻辑,将超级表的标签字段定为 - // 1:设备标识:deviceIdentification - List tagsFields = new ArrayList<>(); - Fields tags = new Fields(); - tags.setFieldName("device_identification"); - tags.setDataType(DataTypeEnum.BINARY); - tags.setSize(64); - tagsFields.add(tags); - - //设置超级表表结构列表 - superTableDto.setSchemaFields(schemaFields); - //设置超级表标签字段列表 - superTableDto.setTagsFields(tagsFields); - R cstResult = remoteTdEngineService.createSuperTable(superTableDto); - //创建超级表报错,打印报错信息,并跳过该循环,继续为下个服务创建表 - if (cstResult.getCode() != ResultEnum.SUCCESS.getCode()) { - log.error("Create SuperTable Exception: " + cstResult.getMsg()); - continue loop; - } - log.info("Create SuperTable Result: {}", cstResult.getCode()); - //将之前存在redis里的同样的名称的超级表的表结构信息删除 - if (redisService.hasKey(CacheConstants.TDENGINE_SUPERTABLEFILELDS + superTableName)) { - redisService.deleteObject(CacheConstants.TDENGINE_SUPERTABLEFILELDS + superTableName); - } - //在redis里存入新的超级表对的表结构信息 - redisService.setCacheObject(CacheConstants.TDENGINE_SUPERTABLEFILELDS + superTableName, superTableDto); - log.info("缓存超级表数据模型:{}", JSON.toJSONString(superTableDto)); - } - } catch (Exception e) { - log.error(e.getMessage()); - } - return AjaxResult.success("操作成功"); - } - /** * 查询产品管理 * @@ -439,6 +378,7 @@ public Product selectByProductIdentification(String productIdentification) { * @param id 产品管理主键 * @return 产品管理 */ + @Deprecated @Override public ProductModel selectFullProductById(Long id) { Product product = selectProductById(id); @@ -561,113 +501,6 @@ public List findAllByStatus(String status) { return productMapper.findAllByStatus(status); } - - /** - * 初始化生成超级表模型 - * - * @param productIds 产品ID集合 productIds==null 初始化所有产品:productIds!=null 初始化指定产品 - * @param InitializeOrNot 是否初始化 - * @return - * @throws Exception - */ - @Async - @Override - public List createSuperTableDataModel(Long[] productIds, Boolean InitializeOrNot) { - List superTableDtoList = new ArrayList<>(); - List productList; - if (null == productIds) { - productList = productMapper.findAllByStatus(Constants.ENABLE); - } else { - productList = productMapper.findAllByIdInAndStatus(Arrays.asList(productIds), Constants.ENABLE); - } - if (productList.isEmpty()) { - return superTableDtoList; - } - SuperTableDto superTableDto; - loop: - for (Product product : productList) { - List allByProductIdAndStatus = productServicesService.findAllByProductIdentificationIdAndStatus(product.getProductIdentification(), Constants.ENABLE); - if (StringUtils.isEmpty(allByProductIdAndStatus)) { - continue; - } - for (ProductServices productServices : allByProductIdAndStatus) { - superTableDto = new SuperTableDto(); - if (StringUtils.isNull(productServices)) { - continue loop; - } - //超级表名称命名规则:产品类型_产品标识_服务名称 - String superTableName = product.getProductType() + "_" + product.getProductIdentification() + "_" + productServices.getServiceName(); - //设置数据库名称和超级表名称 - superTableDto.setDataBaseName(dataBaseName); - superTableDto.setSuperTableName(superTableName); - //构建超级表的表结构字段列表 - List allByServiceId = productPropertiesService.findAllByServiceId(productServices.getId()); - //如果服务下属性值为空,没必要为该服务创建超级表,跳过该循环,进入下个服务 - if (StringUtils.isNull(allByServiceId)) { - continue loop; - } - //构建超级表的表结构字段列表 - List schemaFields = new ArrayList<>(); - //超级表第一个字段数据类型必须为时间戳,默认Ts为当前系统时间 - Fields tsColumn = new Fields(); - tsColumn.setFieldName("ts"); - tsColumn.setDataType(DataTypeEnum.TIMESTAMP); - schemaFields.add(tsColumn); - //超级表第二个字段为事件发生时间数据类型必须为时间戳 - Fields eventTimeColumn = new Fields(); - eventTimeColumn.setFieldName("event_time"); - eventTimeColumn.setDataType(DataTypeEnum.TIMESTAMP); - schemaFields.add(eventTimeColumn); - //根据属性对象列表循环构建超级表表结构 - for (ProductProperties productProperties : allByServiceId) { - //获取字段名称 - String filedName = productProperties.getName(); - //获取该属性数据类型 - String datatype = productProperties.getDatatype(); - //获取该属性的数据大小 - Integer size = productProperties.getMaxlength(); - //添加超级表表结构字段 - Fields fields = new Fields(filedName, datatype, size); - schemaFields.add(fields); - } - //构建超级表标签字段列表 - //根据业务逻辑,将超级表的标签字段定为 - // 1:设备标识:deviceIdentification - List tagsFields = new ArrayList<>(); - Fields tags = new Fields(); - tags.setFieldName("device_identification"); - tags.setDataType(DataTypeEnum.BINARY); - tags.setSize(64); - tagsFields.add(tags); - - //设置超级表表结构列表 - superTableDto.setSchemaFields(schemaFields); - //设置超级表标签字段列表 - superTableDto.setTagsFields(tagsFields); - //将之前存在redis里的同样的名称的超级表的表结构信息删除 - if (redisService.hasKey(CacheConstants.TDENGINE_SUPERTABLEFILELDS + superTableName)) { - redisService.deleteObject(CacheConstants.TDENGINE_SUPERTABLEFILELDS + superTableName); - } - //在redis里存入新的超级表对的表结构信息 - redisService.setCacheObject(CacheConstants.TDENGINE_SUPERTABLEFILELDS + superTableName, superTableDto); - log.info("缓存超级表数据模型:{}", JSON.toJSONString(superTableDto)); - superTableDtoList.add(superTableDto); - if (Boolean.TRUE.equals(InitializeOrNot)) { - //推送RocketMq消息初始化超级表 TODO 改为API调用 - /*MQMessage mqMessage = new MQMessage(); - mqMessage.setTopic(ConsumerTopicConstant.PRODUCTSUPERTABLE_CREATEORUPDATE); - final JSONObject jsonObject = new JSONObject(); - jsonObject.put("type", "create"); - jsonObject.put("msg", JSON.toJSONString(superTableDto)); - mqMessage.setMessage(jsonObject.toJSONString()); - - rocketMQTemplate.convertAndSend(mqMessage.getTopic(), mqMessage.getMessage());*/ - } - } - } - return superTableDtoList; - } - @Override public Product findOneByManufacturerIdAndModelAndProtocolTypeAndStatus(String manufacturerId, String model, String protocolType, String status) { return productMapper.findOneByManufacturerIdAndModelAndProtocolTypeAndStatus(manufacturerId, model, protocolType, status); @@ -703,5 +536,313 @@ public List selectAllProductByStatus(String status) { public List selectProductByProductIdentificationList(List productIdentificationList) { return productMapper.selectProductByProductIdentificationList(productIdentificationList); } + + @Override + public ProductResultVO findOneByProductIdentification(String productIdentification) { + return BeanPlusUtil.toBeanIgnoreError(productMapper.selectByProductIdentification(productIdentification), ProductResultVO.class); + } + + @Override + public Long findProductTotal() { + return productMapper.findProductTotal(); + } + + @Override + public List findProductsByPage(int offset, int pageSize) { + return productMapper.findProductsByPage(offset, pageSize); + } + + /** + * 查询产品管理 带服务、属性、命令 + * + * @param productIdentification 产品标识 + * @return + */ + @Override + public ProductParamVO selectFullProductByProductIdentification(String productIdentification) { + return Optional.ofNullable(this.findOneByProductIdentification(productIdentification)) + .map(product -> { + ProductParamVO productDetails = BeanPlusUtil.toBeanIgnoreError(product, ProductParamVO.class); + ProductServices find = new ProductServices(); + find.setProductIdentification(product.getProductIdentification()); + find.setStatus(Constants.ENABLE); + List productServicesList = productServicesService.selectProductServicesList(find); + + List serviceIds = productServicesList.stream() + .map(ProductServices::getId) + .collect(Collectors.toList()); + + List productCommandList = Optional.ofNullable( + productCommandsService.selectProductCommandsByServiceIdList(serviceIds)) + .orElse(Collections.emptyList()); + + List productPropertiesList = Optional.ofNullable( + productPropertiesService.selectPropertiesByServiceIdList(serviceIds)) + .orElse(Collections.emptyList()); + + List services = productServicesList.stream() + .map(ps -> { + ProductServiceParamVO service = BeanPlusUtil.toBeanIgnoreError(ps, ProductServiceParamVO.class); + + List commands = Optional.ofNullable(productCommandList) + .orElse(Collections.emptyList()) + .stream() + .filter(command -> command.getServiceId().equals(ps.getId())) + .map(command -> { + ProductCommandParamVO commandParamVO = BeanPlusUtil.toBeanIgnoreError(command, ProductCommandParamVO.class); + + // Simplifying the stream operations and request/response mapping + List filteredRequests = Optional.ofNullable( + productCommandsRequestsService.selectProductCommandsRequestsByCommandIdList(Arrays.asList(command.getId()))) + .orElse(Collections.emptyList()) + .stream() + .map(request -> BeanPlusUtil.toBeanIgnoreError(request, ProductCommandRequestParamVO.class)) + .collect(Collectors.toList()); + + commandParamVO.setRequests(filteredRequests); + + List filteredResponses = Optional.ofNullable( + productCommandsResponseService.selectProductCommandsResponseByCommandIdList(Arrays.asList(command.getId()))) + .orElse(Collections.emptyList()) + .stream() + .map(response -> BeanPlusUtil.toBeanIgnoreError(response, ProductCommandResponseParamVO.class)) + .collect(Collectors.toList()); + + commandParamVO.setResponses(filteredResponses); + + return commandParamVO; + }) + .collect(Collectors.toList()); + service.setCommands(commands); + + List properties = Optional.ofNullable(productPropertiesList) + .orElse(Collections.emptyList()) + .stream() + .filter(property -> property.getServiceId().equals(ps.getId())) + .map(pp -> BeanPlusUtil.toBeanIgnoreError(pp, ProductPropertyParamVO.class)) + .collect(Collectors.toList()); + service.setProperties(properties); + + return service; + }) + .collect(Collectors.toList()); + + productDetails.setServices(services); + return productDetails; + }) + .orElse(new ProductParamVO()); // Return an empty ProductParamVO object if the initial product is null + } + + @Override + public String productEmpowerment(Long[] productIds) { + List productList; + if (null == productIds) { + productList = productMapper.findAllByStatus(Constants.ENABLE); + } else { + productList = productMapper.findAllByIdInAndStatus(Arrays.asList(productIds), Constants.ENABLE); + } + if (productList.isEmpty()) { + return "No product data"; + } + List empowermentRecordResultVOS = new ArrayList<>(); + + productList.forEach(product -> { + log.info("Processing product with identification: {}", product.getProductIdentification()); + EmpowermentRecordResultVO record = new EmpowermentRecordResultVO(); + LocalDateTime startTime = LocalDateTime.now(); + record.setStartTime(startTime); + List feedbackList = new ArrayList<>(); + + String productIdentification = ""; + String productName = ""; + String productVersion = ""; + + Optional productOpt = Optional.ofNullable(this.selectFullProductByProductIdentification(product.getProductIdentification())); + if (productOpt.isPresent()) { + ProductParamVO productParamVO = productOpt.get(); + ProductTypeEnum productTypeEnum = ProductTypeEnum.valueOf(productParamVO.getProductType()); + record.setAppId(productParamVO.getAppId()); + record.setEmpowermentIdentification(productParamVO.getProductIdentification()); + record.setVersion(productParamVO.getProductVersion()); + productIdentification = productParamVO.getProductIdentification(); + productName = productParamVO.getProductName(); + productVersion = productParamVO.getProductVersion(); + + productParamVO.getServices().forEach(service -> { + String superTableName = TdsUtils.superTableName(String.valueOf(productTypeEnum.getDesc()), productParamVO.getProductIdentification(), service.getServiceCode()); + R> superTableDescribeVOListR = remoteTdEngineService.describeSuperOrSubTable(superTableName); + + List existingFields = Optional.ofNullable(superTableDescribeVOListR.getData()).orElse(Collections.emptyList()); + + if (existingFields.isEmpty()) { + String feedback = createNewSuperTableStructure(service, superTableName); + feedbackList.add(feedback); + } else { + String feedback = updateSuperTableStructure(service, superTableName, existingFields); + feedbackList.add(feedback); + } + + //save to redis + Optional> superTableDescribeOpt = Optional.ofNullable( + remoteTdEngineService.describeSuperOrSubTable(superTableName).getData() + ); + if (superTableDescribeOpt.isPresent() && !superTableDescribeOpt.get().isEmpty()) { + cacheDataHelper.setProductModelSuperTableCacheVO(productParamVO.getProductIdentification(), service.getServiceCode(), superTableDescribeOpt.get()); + } + + }); + + log.info("Product processed: {}", product.getProductIdentification()); + } else { + log.warn("Product not found for product ID: {}", product.getProductIdentification()); + } + + LocalDateTime endTime = LocalDateTime.now(); + record.setEndTime(endTime); + + List> feedbacks = feedbackList.stream() + .map(feedback -> { + Map map = new HashMap<>(); + // Using epoch time in milliseconds as the timestamp + map.put("timestamp", System.currentTimeMillis()); + map.put("message", feedback); + return map; + }) + .collect(Collectors.toList()); + + ObjectMapper mapper = new ObjectMapper(); + + String jsonFeedback = ""; + try { + jsonFeedback = mapper.writeValueAsString(feedbacks); + } catch (JsonProcessingException e) { + log.error("Error converting feedback to JSON. Using default empty value.", e); + } + + record.setFeedback(jsonFeedback); + + + record.setStatus(EmpowermentStatusEnum.COMPLETED.getValue()); + + Duration duration = Duration.between(startTime, endTime); + record.setOutcome(String.format("Processed product with identification: %s, name: %s, version: %s. Total time taken: %s seconds.", + productIdentification, productName, productVersion, duration.getSeconds())); + + + log.info("Empowerment record: {}", record); + empowermentRecordResultVOS.add(record); + }); + + // TODO save empowerment records to database + log.info("Empowerment records: {}, count: {}", empowermentRecordResultVOS, empowermentRecordResultVOS.size()); + return "Empowerment process completed. Total records: " + empowermentRecordResultVOS.size(); + + } + + + private String createNewSuperTableStructure(ProductServiceParamVO service, String superTableName) { + StringBuilder feedback = new StringBuilder("Creating new super table: ").append(superTableName).append(". "); + + SuperTableDTO superTableDTO = new SuperTableDTO(); + superTableDTO.setSuperTableName(superTableName); + + List schemaFields = new ArrayList<>(Arrays.asList( + new FieldsVO(TdsConstants.TS, DataTypeEnum.TIMESTAMP.getDataType(), null), + new FieldsVO(TdsConstants.EVENT_TIME, DataTypeEnum.TIMESTAMP.getDataType(), null) + )); + + service.getProperties().forEach(property -> { + String fieldName = property.getPropertyCode(); + Integer size = Optional.ofNullable(property.getMaxlength()).map(Integer::parseInt).orElse(null); + schemaFields.add(new FieldsVO(fieldName, DataTypeEnum.valueOfByDataType(property.getDatatype()).getDataType(), size)); + }); + + List tagsFields = Collections.singletonList(new FieldsVO(TdsConstants.DEVICE_IDENTIFICATION, DataTypeEnum.BINARY.getDataType(), 64)); + + superTableDTO.setSchemaFields(FieldsVO.toFieldsList(schemaFields)); + superTableDTO.setTagsFields(FieldsVO.toFieldsList(tagsFields)); + + log.info("catch superTableDTO:{}", JSONUtil.toJsonStr(superTableDTO)); + R superTableAndColumn = remoteTdEngineService.createSuperTableAndColumn(superTableDTO); + if (ResultEnum.SUCCESS.getCode() != superTableAndColumn.getCode()) { + feedback.append("Creation of field(s) failed with message: ").append(superTableAndColumn.getMsg()).append(Constants.SEMICOLON); + } else { + feedback.append("Successfully created fields: ").append(FieldsVO.toFieldsList(schemaFields).stream().map(Fields::getFieldName).collect(Collectors.joining(Constants.SEPARATOR))).append(Constants.SEMICOLON); + } + return feedback.toString(); + } + + private String updateSuperTableStructure(ProductServiceParamVO service, String superTableName, List existingFields) { + StringBuilder feedback = new StringBuilder("Updating super table: ").append(superTableName).append(". "); + SuperTableDTO superTableDTO = new SuperTableDTO(); + superTableDTO.setDataBaseName(""); + superTableDTO.setSuperTableName(superTableName); + + List existingFieldNames = existingFields.stream() + .filter(describeVO -> !Objects.equals(TdsConstants.TAG, describeVO.getNote())) + .map(SuperTableDescribeVO::getField) + .collect(Collectors.toList()); + + service.getProperties().forEach(property -> { + String fieldName = property.getPropertyCode(); + DataTypeEnum dataTypeEnum = DataTypeEnum.valueOfByDataType(property.getDatatype()); + Integer size = Optional.ofNullable(property.getMaxlength()) + .map(Integer::parseInt) + .orElse(null); + + Optional matchedFieldOpt = existingFields.stream() + .filter(f -> Objects.equals(f.getField(), fieldName)) + .findFirst(); + + boolean isTypeMatch = matchedFieldOpt.map(field -> DataTypeEnum.valueOfByDataType(field.getType())) + .map(fieldTypeEnum -> dataTypeEnum.isTypeEqual(fieldTypeEnum.getDataType())) + .orElse(false); + + boolean isSizeMatch = matchedFieldOpt.map(SuperTableDescribeVO::getLength) + .map(length -> Objects.equals(length, size)) + .orElse(false); + + // Check if type or size mismatch + if (matchedFieldOpt.isPresent() && (!isTypeMatch || !isSizeMatch)) { + // Delete the existing field first if type or size doesn't match + superTableDTO.setFields(FieldsVO.toFields(new FieldsVO(fieldName, null, null))); + remoteTdEngineService.dropSuperTableColumn(superTableDTO); + } + + // Check if field is absent or type or size mismatch + if (!matchedFieldOpt.isPresent() || !isTypeMatch || !isSizeMatch) { + // Add or alter field if not matched or not matching in type or size + FieldsVO fieldsVO = new FieldsVO(fieldName, dataTypeEnum.getDataType(), size); + superTableDTO.setFields(FieldsVO.toFields(fieldsVO)); + R alterSuperTableColumn = remoteTdEngineService.alterSuperTableColumn(superTableDTO); + if (ResultEnum.SUCCESS.getCode() != alterSuperTableColumn.getCode()) { + feedback.append("Alteration of field(s) failed with message: ").append(alterSuperTableColumn.getMsg()).append(Constants.SEMICOLON); + } else { + feedback.append("Successfully altered fields: ").append(fieldName).append(Constants.SEMICOLON); + } + } + }); + + + // Check for fields that should be deleted + existingFieldNames.stream() + .filter(existingFieldName -> !Arrays.asList(TdsConstants.TS, TdsConstants.EVENT_TIME).contains(existingFieldName)) + .filter(existingFieldName -> service.getProperties().stream().noneMatch(p -> Objects.equals(p.getPropertyCode(), existingFieldName))) + .forEach(existingFieldName -> { + FieldsVO fieldsVO = new FieldsVO(); + fieldsVO.setFieldName(existingFieldName); + superTableDTO.setFields(FieldsVO.toFields(fieldsVO)); + R alterSuperTableColumn = remoteTdEngineService.dropSuperTableColumn(superTableDTO); + if (ResultEnum.SUCCESS.getCode() != alterSuperTableColumn.getCode()) { + feedback.append("Deletion of field: ").append(existingFieldName).append(" failed with message: ").append(alterSuperTableColumn.getMsg()).append(Constants.SEMICOLON); + } else { + feedback.append("Successfully deleted field: ").append(existingFieldName).append(Constants.SEMICOLON); + } + }); + + return feedback.toString(); + } + + } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/protocol/impl/ProtocolServiceImpl.java b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/protocol/impl/ProtocolServiceImpl.java index ee3fd85a..b8020db6 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/protocol/impl/ProtocolServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-link/src/main/java/com/mqttsnet/thinglinks/link/service/protocol/impl/ProtocolServiceImpl.java @@ -171,7 +171,7 @@ public int enable(Long[] ids) { List deviceList = deviceService.findAllByProductIdentification(protocol.getProductIdentification()); String content = StringEscapeUtils.unescapeHtml4(protocol.getContent()); for (Device device : deviceList) { - redisService.set(CacheConstants.DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + device.getProtocolType() + device.getDeviceIdentification(), content); + redisService.set(CacheConstants.DEF_DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + device.getProtocolType() + device.getDeviceIdentification(), content); } protocolMapper.updateStatusById(Constants.ENABLE, protocol.getId()); } @@ -190,7 +190,7 @@ public int disable(Long[] ids) { for (Protocol protocol : protocolList) { List deviceList = deviceService.findAllByProductIdentification(protocol.getProductIdentification()); for (Device device : deviceList) { - redisService.delete(CacheConstants.DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + protocol.getProtocolType() + device.getDeviceIdentification()); + redisService.delete(CacheConstants.DEF_DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + protocol.getProtocolType() + device.getDeviceIdentification()); } protocolMapper.updateStatusById(Constants.DISABLE, protocol.getId()); } @@ -218,7 +218,7 @@ public int protocolScriptCacheRefresh() { for (Protocol protocol : protocolList) { List deviceList = deviceService.findAllByProductIdentification(protocol.getProductIdentification()); for (Device device : deviceList) { - redisService.delete(CacheConstants.DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + protocol.getProtocolType() + device.getDeviceIdentification()); + redisService.delete(CacheConstants.DEF_DEVICE_DATA_REPORTED_AGREEMENT_SCRIPT + protocol.getProtocolType() + device.getDeviceIdentification()); } protocolMapper.updateStatusById(Constants.DISABLE, protocol.getId()); } diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductCommandsMapper.xml b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductCommandsMapper.xml index 1eee2395..a6f53b59 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductCommandsMapper.xml +++ b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductCommandsMapper.xml @@ -528,7 +528,7 @@ from product_commands - + and id in #{item} @@ -536,4 +536,20 @@ + + + diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductCommandsRequestsMapper.xml b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductCommandsRequestsMapper.xml index 6a84d13c..ae4689d9 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductCommandsRequestsMapper.xml +++ b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductCommandsRequestsMapper.xml @@ -963,4 +963,20 @@ #{id} + + + diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductCommandsResponseMapper.xml b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductCommandsResponseMapper.xml index 3a64fb92..de8d89c4 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductCommandsResponseMapper.xml +++ b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductCommandsResponseMapper.xml @@ -60,17 +60,17 @@ useGeneratedKeys="true"> insert into product_commands_response (commands_id, service_id, datatype, - enumlist, `max`, maxlength, - `min`, parameter_description, `parameter_name`, - required, step, unit, - create_by, create_time, update_by, - update_time) + enumlist, `max`, maxlength, + `min`, parameter_description, `parameter_name`, + required, step, unit, + create_by, create_time, update_by, + update_time) values (#{commandsId,jdbcType=BIGINT}, #{serviceId,jdbcType=BIGINT}, #{datatype,jdbcType=VARCHAR}, - #{enumlist,jdbcType=VARCHAR}, #{max,jdbcType=VARCHAR}, #{maxlength,jdbcType=VARCHAR}, - #{min,jdbcType=VARCHAR}, #{parameterDescription,jdbcType=VARCHAR}, #{parameterName,jdbcType=VARCHAR}, - #{required,jdbcType=VARCHAR}, #{step,jdbcType=VARCHAR}, #{unit,jdbcType=VARCHAR}, - #{createBy,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{updateBy,jdbcType=VARCHAR}, - #{updateTime,jdbcType=TIMESTAMP}) + #{enumlist,jdbcType=VARCHAR}, #{max,jdbcType=VARCHAR}, #{maxlength,jdbcType=VARCHAR}, + #{min,jdbcType=VARCHAR}, #{parameterDescription,jdbcType=VARCHAR}, #{parameterName,jdbcType=VARCHAR}, + #{required,jdbcType=VARCHAR}, #{step,jdbcType=VARCHAR}, #{unit,jdbcType=VARCHAR}, + #{createBy,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{updateBy,jdbcType=VARCHAR}, + #{updateTime,jdbcType=TIMESTAMP}) update product_commands_response - set commands_id = #{commandsId,jdbcType=BIGINT}, - service_id = #{serviceId,jdbcType=BIGINT}, - datatype = #{datatype,jdbcType=VARCHAR}, - enumlist = #{enumlist,jdbcType=VARCHAR}, - `max` = #{max,jdbcType=VARCHAR}, - maxlength = #{maxlength,jdbcType=VARCHAR}, - `min` = #{min,jdbcType=VARCHAR}, - parameter_description = #{parameterDescription,jdbcType=VARCHAR}, - `parameter_name` = #{parameterName,jdbcType=VARCHAR}, - required = #{required,jdbcType=VARCHAR}, - step = #{step,jdbcType=VARCHAR}, - unit = #{unit,jdbcType=VARCHAR}, - create_by = #{createBy,jdbcType=VARCHAR}, - create_time = #{createTime,jdbcType=TIMESTAMP}, - update_by = #{updateBy,jdbcType=VARCHAR}, - update_time = #{updateTime,jdbcType=TIMESTAMP} + set commands_id = #{commandsId,jdbcType=BIGINT}, + service_id = #{serviceId,jdbcType=BIGINT}, + datatype = #{datatype,jdbcType=VARCHAR}, + enumlist = #{enumlist,jdbcType=VARCHAR}, + `max` = #{max,jdbcType=VARCHAR}, + maxlength = #{maxlength,jdbcType=VARCHAR}, + `min` = #{min,jdbcType=VARCHAR}, + parameter_description = #{parameterDescription,jdbcType=VARCHAR}, + `parameter_name` = #{parameterName,jdbcType=VARCHAR}, + required = #{required,jdbcType=VARCHAR}, + step = #{step,jdbcType=VARCHAR}, + unit = #{unit,jdbcType=VARCHAR}, + create_by = #{createBy,jdbcType=VARCHAR}, + create_time = #{createTime,jdbcType=TIMESTAMP}, + update_by = #{updateBy,jdbcType=VARCHAR}, + update_time = #{updateTime,jdbcType=TIMESTAMP} where id = #{id,jdbcType=BIGINT} @@ -472,17 +472,17 @@ insert into product_commands_response (commands_id, service_id, datatype, enumlist, `max`, maxlength, `min`, parameter_description, - `parameter_name`, required, step, unit, create_by, create_time, update_by, update_time) + `parameter_name`, required, step, unit, create_by, create_time, update_by, update_time) values (#{item.commandsId,jdbcType=BIGINT}, #{item.serviceId,jdbcType=BIGINT}, #{item.datatype,jdbcType=VARCHAR}, - #{item.enumlist,jdbcType=VARCHAR}, #{item.max,jdbcType=VARCHAR}, #{item.maxlength,jdbcType=VARCHAR}, - #{item.min,jdbcType=VARCHAR}, #{item.parameterDescription,jdbcType=VARCHAR}, - #{item.parameterName,jdbcType=VARCHAR}, - #{item.required,jdbcType=VARCHAR}, #{item.step,jdbcType=VARCHAR}, #{item.unit,jdbcType=VARCHAR}, - #{item.createBy,jdbcType=VARCHAR}, #{item.createTime,jdbcType=TIMESTAMP}, - #{item.updateBy,jdbcType=VARCHAR}, - #{item.updateTime,jdbcType=TIMESTAMP}) + #{item.enumlist,jdbcType=VARCHAR}, #{item.max,jdbcType=VARCHAR}, #{item.maxlength,jdbcType=VARCHAR}, + #{item.min,jdbcType=VARCHAR}, #{item.parameterDescription,jdbcType=VARCHAR}, + #{item.parameterName,jdbcType=VARCHAR}, + #{item.required,jdbcType=VARCHAR}, #{item.step,jdbcType=VARCHAR}, #{item.unit,jdbcType=VARCHAR}, + #{item.createBy,jdbcType=VARCHAR}, #{item.createTime,jdbcType=TIMESTAMP}, + #{item.updateBy,jdbcType=VARCHAR}, + #{item.updateTime,jdbcType=TIMESTAMP}) id = #{id,jdbcType=BIGINT}, - commands_id = #{commandsId,jdbcType=BIGINT}, - service_id = #{serviceId,jdbcType=BIGINT}, - datatype = #{datatype,jdbcType=VARCHAR}, - enumlist = #{enumlist,jdbcType=VARCHAR}, - `max` = #{max,jdbcType=VARCHAR}, - maxlength = #{maxlength,jdbcType=VARCHAR}, - `min` = #{min,jdbcType=VARCHAR}, + commands_id = #{commandsId,jdbcType=BIGINT}, + service_id = #{serviceId,jdbcType=BIGINT}, + datatype = #{datatype,jdbcType=VARCHAR}, + enumlist = #{enumlist,jdbcType=VARCHAR}, + `max` = #{max,jdbcType=VARCHAR}, + maxlength = #{maxlength,jdbcType=VARCHAR}, + `min` = #{min,jdbcType=VARCHAR}, parameter_description = #{parameterDescription,jdbcType=VARCHAR}, - `parameter_name` = #{parameterName,jdbcType=VARCHAR}, - required = #{required,jdbcType=VARCHAR}, - step = #{step,jdbcType=VARCHAR}, - unit = #{unit,jdbcType=VARCHAR}, - create_by = #{createBy,jdbcType=VARCHAR}, - create_time = #{createTime,jdbcType=TIMESTAMP}, - update_by = #{updateBy,jdbcType=VARCHAR}, - update_time = #{updateTime,jdbcType=TIMESTAMP}, + `parameter_name` = #{parameterName,jdbcType=VARCHAR}, + required = #{required,jdbcType=VARCHAR}, + step = #{step,jdbcType=VARCHAR}, + unit = #{unit,jdbcType=VARCHAR}, + create_by = #{createBy,jdbcType=VARCHAR}, + create_time = #{createTime,jdbcType=TIMESTAMP}, + update_by = #{updateBy,jdbcType=VARCHAR}, + update_time = #{updateTime,jdbcType=TIMESTAMP}, + + diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductMapper.xml b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductMapper.xml index 6f1613ef..d5ba7fd0 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductMapper.xml +++ b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductMapper.xml @@ -1126,17 +1126,31 @@ + + + + + \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductPropertiesMapper.xml b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductPropertiesMapper.xml index 35a3f062..c26b7369 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductPropertiesMapper.xml +++ b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductPropertiesMapper.xml @@ -5,7 +5,8 @@ - + + @@ -25,7 +26,8 @@ id, - `name`, + property_code, + property_name, service_id, datatype, description, @@ -59,18 +61,19 @@ parameterType="com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductProperties" useGeneratedKeys="true"> - insert into product_properties (`name`, service_id, - datatype, description, enumlist, - `max`, maxlength, `method`, - `min`, required, step, - unit, create_by, create_time, - update_by, update_time) - values (#{name,jdbcType=VARCHAR}, #{serviceId,jdbcType=BIGINT}, - #{datatype,jdbcType=VARCHAR}, #{description,jdbcType=VARCHAR}, #{enumlist,jdbcType=VARCHAR}, - #{max,jdbcType=VARCHAR}, #{maxlength,jdbcType=BIGINT}, #{method,jdbcType=VARCHAR}, - #{min,jdbcType=VARCHAR}, #{required,jdbcType=BIGINT}, #{step,jdbcType=BIGINT}, - #{unit,jdbcType=VARCHAR}, #{createBy,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, - #{updateBy,jdbcType=VARCHAR}, #{updateTime,jdbcType=TIMESTAMP}) + insert into product_properties ( property_code, + property_name, service_id, + datatype, description, enumlist, + `max`, maxlength, `method`, + `min`, required, step, + unit, create_by, create_time, + update_by, update_time) + values (#{propertyCode},#{propertyName}, #{serviceId,jdbcType=BIGINT}, + #{datatype,jdbcType=VARCHAR}, #{description,jdbcType=VARCHAR}, #{enumlist,jdbcType=VARCHAR}, + #{max,jdbcType=VARCHAR}, #{maxlength,jdbcType=BIGINT}, #{method,jdbcType=VARCHAR}, + #{min,jdbcType=VARCHAR}, #{required,jdbcType=BIGINT}, #{step,jdbcType=BIGINT}, + #{unit,jdbcType=VARCHAR}, #{createBy,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, + #{updateBy,jdbcType=VARCHAR}, #{updateTime,jdbcType=TIMESTAMP}) insert into product_properties - - `name`, + + property_code, + + + property_name, service_id, @@ -128,8 +134,11 @@ - - #{name,jdbcType=VARCHAR}, + + #{propertyCode,jdbcType=VARCHAR}, + + + #{propertyName,jdbcType=VARCHAR}, #{serviceId,jdbcType=BIGINT}, @@ -183,8 +192,11 @@ update product_properties - - `name` = #{name,jdbcType=VARCHAR}, + + property_code = #{propertyCode,jdbcType=VARCHAR}, + + + property_name = #{propertyName,jdbcType=VARCHAR}, service_id = #{serviceId,jdbcType=BIGINT}, @@ -238,31 +250,38 @@ parameterType="com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductProperties"> update product_properties - set `name` = #{name,jdbcType=VARCHAR}, - service_id = #{serviceId,jdbcType=BIGINT}, - datatype = #{datatype,jdbcType=VARCHAR}, - description = #{description,jdbcType=VARCHAR}, - enumlist = #{enumlist,jdbcType=VARCHAR}, - `max` = #{max,jdbcType=VARCHAR}, - maxlength = #{maxlength,jdbcType=BIGINT}, - `method` = #{method,jdbcType=VARCHAR}, - `min` = #{min,jdbcType=VARCHAR}, - required = #{required,jdbcType=BIGINT}, - step = #{step,jdbcType=BIGINT}, - unit = #{unit,jdbcType=VARCHAR}, - create_by = #{createBy,jdbcType=VARCHAR}, - create_time = #{createTime,jdbcType=TIMESTAMP}, - update_by = #{updateBy,jdbcType=VARCHAR}, - update_time = #{updateTime,jdbcType=TIMESTAMP} + set + property_code = #{propertyCode,jdbcType=VARCHAR}, + property_name = #{propertyName,jdbcType=VARCHAR}, + service_id = #{serviceId,jdbcType=BIGINT}, + datatype = #{datatype,jdbcType=VARCHAR}, + description = #{description,jdbcType=VARCHAR}, + enumlist = #{enumlist,jdbcType=VARCHAR}, + `max` = #{max,jdbcType=VARCHAR}, + maxlength = #{maxlength,jdbcType=BIGINT}, + `method` = #{method,jdbcType=VARCHAR}, + `min` = #{min,jdbcType=VARCHAR}, + required = #{required,jdbcType=BIGINT}, + step = #{step,jdbcType=BIGINT}, + unit = #{unit,jdbcType=VARCHAR}, + create_by = #{createBy,jdbcType=VARCHAR}, + create_time = #{createTime,jdbcType=TIMESTAMP}, + update_by = #{updateBy,jdbcType=VARCHAR}, + update_time = #{updateTime,jdbcType=TIMESTAMP} where id = #{id,jdbcType=BIGINT} update product_properties - + + + when id = #{item.id,jdbcType=BIGINT} then #{item.propertyCode,jdbcType=VARCHAR} + + + - when id = #{item.id,jdbcType=BIGINT} then #{item.name,jdbcType=VARCHAR} + when id = #{item.id,jdbcType=BIGINT} then #{item.propertyName,jdbcType=VARCHAR} @@ -350,10 +369,17 @@ update product_properties - + - - when id = #{item.id,jdbcType=BIGINT} then #{item.name,jdbcType=VARCHAR} + + when id = #{item.id,jdbcType=BIGINT} then #{item.propertyCode,jdbcType=VARCHAR} + + + + + + + when id = #{item.id,jdbcType=BIGINT} then #{item.propertyName,jdbcType=VARCHAR} @@ -471,16 +497,17 @@ insert into product_properties - (`name`, service_id, datatype, description, enumlist, `max`, maxlength, - `method`, `min`, required, step, unit, create_by, create_time, update_by, update_time) + (property_code, property_name, service_id, datatype, description, enumlist, `max`, maxlength, `method`, `min`, + required, step, unit, create_by, create_time, update_by, update_time) values - (#{item.name,jdbcType=VARCHAR}, #{item.serviceId,jdbcType=BIGINT}, - #{item.datatype,jdbcType=VARCHAR}, #{item.description,jdbcType=VARCHAR}, #{item.enumlist,jdbcType=VARCHAR}, - #{item.max,jdbcType=VARCHAR}, #{item.maxlength,jdbcType=BIGINT}, #{item.method,jdbcType=VARCHAR}, - #{item.min,jdbcType=VARCHAR}, #{item.required,jdbcType=BIGINT}, #{item.step,jdbcType=BIGINT}, - #{item.unit,jdbcType=VARCHAR}, #{item.createBy,jdbcType=VARCHAR}, #{item.createTime,jdbcType=TIMESTAMP}, - #{item.updateBy,jdbcType=VARCHAR}, #{item.updateTime,jdbcType=TIMESTAMP}) + (#{item.propertyCode,jdbcType=VARCHAR}, #{item.propertyName,jdbcType=VARCHAR}, + #{item.serviceId,jdbcType=BIGINT}, + #{item.datatype,jdbcType=VARCHAR}, #{item.description,jdbcType=VARCHAR}, #{item.enumlist,jdbcType=VARCHAR}, + #{item.max,jdbcType=VARCHAR}, #{item.maxlength,jdbcType=BIGINT}, #{item.method,jdbcType=VARCHAR}, + #{item.min,jdbcType=VARCHAR}, #{item.required,jdbcType=BIGINT}, #{item.step,jdbcType=BIGINT}, + #{item.unit,jdbcType=VARCHAR}, #{item.createBy,jdbcType=VARCHAR}, #{item.createTime,jdbcType=TIMESTAMP}, + #{item.updateBy,jdbcType=VARCHAR}, #{item.updateTime,jdbcType=TIMESTAMP}) id, - `name`, + property_code, + property_name, service_id, datatype, description, @@ -514,7 +542,8 @@ #{id,jdbcType=BIGINT}, - #{name,jdbcType=VARCHAR}, + #{propertyCode,jdbcType=VARCHAR}, + #{propertyName,jdbcType=VARCHAR}, #{serviceId,jdbcType=BIGINT}, #{datatype,jdbcType=VARCHAR}, #{description,jdbcType=VARCHAR}, @@ -536,21 +565,22 @@ id = #{id,jdbcType=BIGINT}, - `name` = #{name,jdbcType=VARCHAR}, - service_id = #{serviceId,jdbcType=BIGINT}, - datatype = #{datatype,jdbcType=VARCHAR}, + property_code = #{propertyCode,jdbcType=VARCHAR}, + property_name = #{propertyName,jdbcType=VARCHAR}, + service_id = #{serviceId,jdbcType=BIGINT}, + datatype = #{datatype,jdbcType=VARCHAR}, description = #{description,jdbcType=VARCHAR}, - enumlist = #{enumlist,jdbcType=VARCHAR}, - `max` = #{max,jdbcType=VARCHAR}, - maxlength = #{maxlength,jdbcType=BIGINT}, - `method` = #{method,jdbcType=VARCHAR}, - `min` = #{min,jdbcType=VARCHAR}, - required = #{required,jdbcType=BIGINT}, - step = #{step,jdbcType=BIGINT}, - unit = #{unit,jdbcType=VARCHAR}, - create_by = #{createBy,jdbcType=VARCHAR}, + enumlist = #{enumlist,jdbcType=VARCHAR}, + `max` = #{max,jdbcType=VARCHAR}, + maxlength = #{maxlength,jdbcType=BIGINT}, + `method` = #{method,jdbcType=VARCHAR}, + `min` = #{min,jdbcType=VARCHAR}, + required = #{required,jdbcType=BIGINT}, + step = #{step,jdbcType=BIGINT}, + unit = #{unit,jdbcType=VARCHAR}, + create_by = #{createBy,jdbcType=VARCHAR}, create_time = #{createTime,jdbcType=TIMESTAMP}, - update_by = #{updateBy,jdbcType=VARCHAR}, + update_by = #{updateBy,jdbcType=VARCHAR}, update_time = #{updateTime,jdbcType=TIMESTAMP}, @@ -563,8 +593,11 @@ id, - - `name`, + + property_code, + + + property_name, service_id, @@ -617,8 +650,11 @@ #{id,jdbcType=BIGINT}, - - #{name,jdbcType=VARCHAR}, + + #{propertyCode,jdbcType=VARCHAR}, + + + #{propertyName,jdbcType=VARCHAR}, #{serviceId,jdbcType=BIGINT}, @@ -671,8 +707,11 @@ id = #{id,jdbcType=BIGINT}, - - `name` = #{name,jdbcType=VARCHAR}, + + property_code = #{propertyCode,jdbcType=VARCHAR}, + + + property_name = #{propertyName,jdbcType=VARCHAR}, service_id = #{serviceId,jdbcType=BIGINT}, @@ -736,7 +775,8 @@ select id, - `name`, + property_code, + property_name, service_id, datatype, description, @@ -760,8 +800,11 @@ resultMap="BaseResultMap"> - - and name like concat('%', #{name}, '%') + + and property_code = #{propertyCode} + + + and property_name = #{propertyName} and service_id = #{serviceId} @@ -809,8 +852,11 @@ useGeneratedKeys="true" keyProperty="id"> insert into product_properties - - name, + + property_code, + + + property_name, service_id, @@ -859,8 +905,11 @@ - - #{name}, + + #{propertyCode}, + + + #{propertyName}, #{serviceId}, @@ -914,8 +963,11 @@ parameterType="com.mqttsnet.thinglinks.link.api.domain.product.entity.ProductProperties"> update product_properties - - name = #{name}, + + property_code = #{propertyCode}, + + + property_name = #{propertyName}, service_id = #{serviceId}, @@ -976,11 +1028,11 @@ + + diff --git a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductServicesMapper.xml b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductServicesMapper.xml index c442fdd0..9a5896c5 100644 --- a/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductServicesMapper.xml +++ b/thinglinks-modules/thinglinks-modules-link/src/main/resources/mapper/link/product/ProductServicesMapper.xml @@ -739,7 +739,7 @@ from product_services - + and id in #{item} diff --git a/thinglinks-modules/thinglinks-modules-protocolAnalysis/src/main/java/com/mqttsnet/thinglinks/protocolAnalysis/ThingLinksProtocolAnalysisApplication.java b/thinglinks-modules/thinglinks-modules-protocolAnalysis/src/main/java/com/mqttsnet/thinglinks/protocolAnalysis/ThingLinksProtocolAnalysisApplication.java index 1d9917a6..7e79096d 100644 --- a/thinglinks-modules/thinglinks-modules-protocolAnalysis/src/main/java/com/mqttsnet/thinglinks/protocolAnalysis/ThingLinksProtocolAnalysisApplication.java +++ b/thinglinks-modules/thinglinks-modules-protocolAnalysis/src/main/java/com/mqttsnet/thinglinks/protocolAnalysis/ThingLinksProtocolAnalysisApplication.java @@ -3,11 +3,17 @@ import com.mqttsnet.thinglinks.common.security.annotation.EnableCustomConfig; import com.mqttsnet.thinglinks.common.security.annotation.EnableRyFeignClients; import com.mqttsnet.thinglinks.common.swagger.annotation.EnableCustomSwagger2; +import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.CrossOrigin; +import java.net.InetAddress; + +@Slf4j @EnableCustomConfig @EnableCustomSwagger2 @EnableRyFeignClients @@ -15,12 +21,15 @@ //origin="*"代表所有域名都可访问 //maxAge飞行前响应的缓存持续时间的最大年龄,简单来说就是Cookie的有效期 单位为秒 //若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失 -@CrossOrigin(origins = "*",maxAge = 3600) -@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class },scanBasePackages = {"com.mqttsnet.thinglinks"}) +@CrossOrigin(origins = "*", maxAge = 3600) +@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}, scanBasePackages = {"com.mqttsnet.thinglinks"}) public class ThingLinksProtocolAnalysisApplication { - public static void main(String[] args) { - SpringApplication.run(ThingLinksProtocolAnalysisApplication.class, args); - System.out.println("(♥◠‿◠)ノ゙ ProtocolAnalysis服务启动成功 ლ(´ڡ`ლ)゙ "); + public static void main(String[] args) throws Exception { + ConfigurableApplicationContext application = SpringApplication.run(ThingLinksProtocolAnalysisApplication.class, args); + Environment env = application.getEnvironment(); + log.info("\n----------------------------------------------------------\n\t" + "应用 '{}' 启动成功! 访问连接:\n\t" + "Swagger文档: \t\thttp://{}:{}/swagger-ui.html\n\t" + + "数据库监控: \t\thttp://{}:{}/druid\n" + "----------------------------------------------------------", env.getProperty("spring.application.name"), + InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port", "8080"), "127.0.0.1", env.getProperty("server.port", "8080")); } } \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/ThingLinksRuleApplication.java b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/ThingLinksRuleApplication.java index c25b53e2..52b5e153 100644 --- a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/ThingLinksRuleApplication.java +++ b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/ThingLinksRuleApplication.java @@ -3,15 +3,21 @@ import com.mqttsnet.thinglinks.common.security.annotation.EnableCustomConfig; import com.mqttsnet.thinglinks.common.security.annotation.EnableRyFeignClients; import com.mqttsnet.thinglinks.common.swagger.annotation.EnableCustomSwagger2; +import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.CrossOrigin; +import java.net.InetAddress; + /** * Rule * * @author thinglinks */ +@Slf4j @EnableCustomConfig @EnableCustomSwagger2 @EnableRyFeignClients @@ -22,8 +28,11 @@ @CrossOrigin(origins = "*", maxAge = 3600) @SpringBootApplication(scanBasePackages = {"com.mqttsnet.thinglinks"}) public class ThingLinksRuleApplication { - public static void main(String[] args) { - SpringApplication.run(ThingLinksRuleApplication.class, args); - System.out.println("(♥◠‿◠)ノ゙ Rule模块启动成功 ლ(´ڡ`ლ)゙ "); + public static void main(String[] args) throws Exception { + ConfigurableApplicationContext application = SpringApplication.run(ThingLinksRuleApplication.class, args); + Environment env = application.getEnvironment(); + log.info("\n----------------------------------------------------------\n\t" + "应用 '{}' 启动成功! 访问连接:\n\t" + "Swagger文档: \t\thttp://{}:{}/swagger-ui.html\n\t" + + "数据库监控: \t\thttp://{}:{}/druid\n" + "----------------------------------------------------------", env.getProperty("spring.application.name"), + InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port", "8080"), "127.0.0.1", env.getProperty("server.port", "8080")); } } diff --git a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/common/consumer/rocketmq/RuleTriggerMessageRocketmqConsumer.java b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/common/consumer/rocketmq/RuleTriggerMessageRocketmqConsumer.java index 2be09743..5b4b19e1 100644 --- a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/common/consumer/rocketmq/RuleTriggerMessageRocketmqConsumer.java +++ b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/common/consumer/rocketmq/RuleTriggerMessageRocketmqConsumer.java @@ -39,6 +39,12 @@ public void onMessage(Object message) { JSONObject json = JSONObject.parseObject(String.valueOf(message)); Boolean flag = ruleDeviceLinkageService.checkRuleConditions(json.getString("msg")); log.info("规则匹配结果:{}", flag); + + // 触发器规则匹配成功,执行动作 + if (flag) { + //TODO 触发器规则匹配成功,执行动作 业务逻辑 自行补充 +// ruleDeviceLinkageService.executeRuleAction(json.getString("msg")); + } } catch (Exception e) { log.error("规则引擎-触发器规则数据消费-->消费失败,失败原因:{}", e.getMessage()); } diff --git a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/controller/RuleController.java b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/controller/RuleController.java index 2075bfa2..9c81c890 100644 --- a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/controller/RuleController.java +++ b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/controller/RuleController.java @@ -25,6 +25,7 @@ import com.mqttsnet.thinglinks.rule.service.RuleService; import com.mqttsnet.thinglinks.tdengine.api.RemoteTdEngineService; import com.mqttsnet.thinglinks.tdengine.api.domain.TagsSelectDao; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TagsSelectDTO; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -147,7 +148,7 @@ public R checkRuleConditions(@PathVariable("ruleIdentification") String ruleI // 获取该产品下的所有设备数据 Map> maps = extractedDeviceData(conditions); // 属性名称 - String productPropertiesName = propertiesData.getName(); + String productPropertiesName = propertiesData.getPropertyName(); // 属性类型 String productPropertiesType = propertiesData.getDatatype(); // 比较模式 @@ -232,7 +233,7 @@ private Map> extractedDeviceData(RuleConditions cond String superName = product.getProductType() + "_" + conditions.getProductIdentification() + "_" + productServices.getServiceName(); // 查询最新的设备记录 - TagsSelectDao tagsSelectDao = new TagsSelectDao(); + TagsSelectDTO tagsSelectDao = new TagsSelectDTO(); tagsSelectDao.setDataBaseName("thinglinks"); tagsSelectDao.setStableName(superName); R lastDataByTags = remoteTdEngineService.getLastDataByTags(tagsSelectDao); diff --git a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/service/impl/RuleDeviceLinkageServiceImpl.java b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/service/impl/RuleDeviceLinkageServiceImpl.java index 8263258b..6458d22b 100644 --- a/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/service/impl/RuleDeviceLinkageServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-rule/src/main/java/com/mqttsnet/thinglinks/rule/service/impl/RuleDeviceLinkageServiceImpl.java @@ -22,7 +22,7 @@ import com.mqttsnet.thinglinks.rule.service.RuleDeviceLinkageService; import com.mqttsnet.thinglinks.rule.service.RuleService; import com.mqttsnet.thinglinks.tdengine.api.RemoteTdEngineService; -import com.mqttsnet.thinglinks.tdengine.api.domain.TagsSelectDao; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TagsSelectDTO; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.rocketmq.spring.core.RocketMQTemplate; @@ -137,7 +137,7 @@ public Boolean checkRuleConditions(String ruleIdentification) { log.info("maps:{}", maps.toString()); // 属性名称 - String productPropertiesName = propertiesData.getName(); + String productPropertiesName = propertiesData.getPropertyName(); // 属性类型 String productPropertiesType = propertiesData.getDatatype(); // 比较模式 @@ -258,11 +258,11 @@ private Map> extractedDeviceData(RuleConditions cond String superName = product.getProductType() + "_" + conditions.getProductIdentification() + "_" + productServices.getServiceName(); // 查询最新的设备记录 - TagsSelectDao tagsSelectDao = new TagsSelectDao(); - tagsSelectDao.setDataBaseName("thinglinks"); - tagsSelectDao.setStableName(superName); - tagsSelectDao.setTagsName("device_identification"); - R>> lastDataByTags = remoteTdEngineService.getLastDataByTags(tagsSelectDao); + TagsSelectDTO tagsSelectDTO = new TagsSelectDTO(); + tagsSelectDTO.setDataBaseName("thinglinks"); + tagsSelectDTO.setStableName(superName); + tagsSelectDTO.setTagsName("device_identification"); + R>> lastDataByTags = remoteTdEngineService.getLastDataByTags(tagsSelectDTO); if (lastDataByTags != null && lastDataByTags.getData() != null) { maps = lastDataByTags.getData(); } diff --git a/thinglinks-modules/thinglinks-modules-system/src/main/java/com/mqttsnet/thinglinks/system/ThingLinksSystemApplication.java b/thinglinks-modules/thinglinks-modules-system/src/main/java/com/mqttsnet/thinglinks/system/ThingLinksSystemApplication.java index 67cf8949..4efd53f8 100644 --- a/thinglinks-modules/thinglinks-modules-system/src/main/java/com/mqttsnet/thinglinks/system/ThingLinksSystemApplication.java +++ b/thinglinks-modules/thinglinks-modules-system/src/main/java/com/mqttsnet/thinglinks/system/ThingLinksSystemApplication.java @@ -3,16 +3,21 @@ import com.mqttsnet.thinglinks.common.security.annotation.EnableCustomConfig; import com.mqttsnet.thinglinks.common.security.annotation.EnableRyFeignClients; import com.mqttsnet.thinglinks.common.swagger.annotation.EnableCustomSwagger2; +import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.CrossOrigin; +import java.net.InetAddress; + /** * 系统模块 - * + * * @author thinglinks */ +@Slf4j @EnableCustomConfig @EnableCustomSwagger2 @EnableRyFeignClients @@ -20,13 +25,14 @@ //origin="*"代表所有域名都可访问 //maxAge飞行前响应的缓存持续时间的最大年龄,简单来说就是Cookie的有效期 单位为秒 //若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失 -@CrossOrigin(origins = "*",maxAge = 3600) +@CrossOrigin(origins = "*", maxAge = 3600) @SpringBootApplication(scanBasePackages = {"com.mqttsnet.thinglinks"}) -public class ThingLinksSystemApplication -{ - public static void main(String[] args) - { - SpringApplication.run(ThingLinksSystemApplication.class, args); - System.out.println("(♥◠‿◠)ノ゙ 系统模块启动成功 ლ(´ڡ`ლ)゙ "); +public class ThingLinksSystemApplication { + public static void main(String[] args) throws Exception { + ConfigurableApplicationContext application = SpringApplication.run(ThingLinksSystemApplication.class, args); + Environment env = application.getEnvironment(); + log.info("\n----------------------------------------------------------\n\t" + "应用 '{}' 启动成功! 访问连接:\n\t" + "Swagger文档: \t\thttp://{}:{}/swagger-ui.html\n\t" + + "数据库监控: \t\thttp://{}:{}/druid\n" + "----------------------------------------------------------", env.getProperty("spring.application.name"), + InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port", "8080"), "127.0.0.1", env.getProperty("server.port", "8080")); } } diff --git a/thinglinks-modules/thinglinks-modules-tdengine/pom.xml b/thinglinks-modules/thinglinks-modules-tdengine/pom.xml index 2c871a90..f531b162 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/pom.xml +++ b/thinglinks-modules/thinglinks-modules-tdengine/pom.xml @@ -11,7 +11,7 @@ 4.0.0 thinglinks-modules-tdengine ${project.artifactId} - thinglinks-modules-tdengine 时序数据库模块 + thinglinks-modules-tdengine 时序数据库模块 @@ -79,13 +79,6 @@ ${thinglinks.version} - - - com.mqttsnet - thinglinks-common-rocketmq - ${thinglinks.version} - - com.mqttsnet @@ -134,110 +127,110 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/ThingLinksTdengineApplication.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/ThingLinksTdengineApplication.java index 9ae780ca..51568102 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/ThingLinksTdengineApplication.java +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/ThingLinksTdengineApplication.java @@ -1,14 +1,18 @@ package com.mqttsnet.thinglinks.tdengine; -import com.alibaba.fastjson.JSONObject; import com.mqttsnet.thinglinks.common.security.annotation.EnableCustomConfig; import com.mqttsnet.thinglinks.common.security.annotation.EnableRyFeignClients; import com.mqttsnet.thinglinks.common.swagger.annotation.EnableCustomSwagger2; +import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Import; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.CrossOrigin; +import java.net.InetAddress; + +@Slf4j @EnableCustomConfig @EnableCustomSwagger2 @EnableRyFeignClients @@ -16,12 +20,15 @@ //origin="*"代表所有域名都可访问 //maxAge飞行前响应的缓存持续时间的最大年龄,简单来说就是Cookie的有效期 单位为秒 //若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失 -@CrossOrigin(origins = "*",maxAge = 3600) +@CrossOrigin(origins = "*", maxAge = 3600) @SpringBootApplication(scanBasePackages = {"com.mqttsnet.thinglinks"}) public class ThingLinksTdengineApplication { - public static void main(String[] args) { - SpringApplication.run(ThingLinksTdengineApplication.class, args); - System.out.println("(♥◠‿◠)ノ゙ TDengine服务启动成功 ლ(´ڡ`ლ)゙ "); + public static void main(String[] args) throws Exception { + ConfigurableApplicationContext application = SpringApplication.run(ThingLinksTdengineApplication.class, args); + Environment env = application.getEnvironment(); + log.info("\n----------------------------------------------------------\n\t" + "应用 '{}' 启动成功! 访问连接:\n\t" + "Swagger文档: \t\thttp://{}:{}/swagger-ui.html\n\t" + + "数据库监控: \t\thttp://{}:{}/druid\n" + "----------------------------------------------------------", env.getProperty("spring.application.name"), + InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port", "8080"), "127.0.0.1", env.getProperty("server.port", "8080")); } } \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/consumer/rocketmq/ProductCreateSuperTableMessageRocketmqConsumer.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/consumer/rocketmq/ProductCreateSuperTableMessageRocketmqConsumer.java deleted file mode 100644 index 26306011..00000000 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/consumer/rocketmq/ProductCreateSuperTableMessageRocketmqConsumer.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.mqttsnet.thinglinks.tdengine.common.consumer.rocketmq; - -import com.alibaba.fastjson.JSONObject; -import com.mqttsnet.thinglinks.common.core.mqs.ConsumerGroupConstant; -import com.mqttsnet.thinglinks.common.core.mqs.ConsumerTopicConstant; -import com.mqttsnet.thinglinks.common.core.utils.StringUtils; -import com.mqttsnet.thinglinks.tdengine.service.ProductSuperTableCreateOrUpdateService; -import lombok.extern.slf4j.Slf4j; -import org.apache.rocketmq.spring.annotation.MessageModel; -import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; -import org.apache.rocketmq.spring.core.RocketMQListener; -import org.springframework.beans.factory.annotation.Autowired; - -/** - * @Description: TDengine超级表创键修改动作监听(Rocketmq模式) - * @Author: ShiHuan Sun - * @E-mail: 13733918655@163.com - * @Website: http://thinglinks.mqttsnet.com - * @CreateDate: 2021/11/22$ 16:11$ - * @UpdateUser: ShiHuan Sun - * @UpdateDate: 2021/11/22$ 16:11$ - * @UpdateRemark: 修改内容 - * @Version: 1.0 - */ -@Slf4j -//@Component -@RocketMQMessageListener(consumerGroup = ConsumerGroupConstant.THINGLINKS_GROUP, topic = ConsumerTopicConstant.Tdengine.PRODUCTSUPERTABLE_CREATEORUPDATE, messageModel = MessageModel.CLUSTERING) -public class ProductCreateSuperTableMessageRocketmqConsumer implements RocketMQListener { - - @Autowired - private ProductSuperTableCreateOrUpdateService productSuperTableCreateOrUpdateService; - - /** - * 超级表创建及修改处理 - * - * @param message - */ - @Override - public void onMessage(Object message) { - if (StringUtils.isNull(message)) { - log.error("消息为空,不处理"); - return; - } - JSONObject stableMessage = JSONObject.parseObject(String.valueOf(message)); - log.info("TDengine消费{}超级表消息:{}", stableMessage.get("type"), stableMessage.get("msg")); - if ("create".equals(stableMessage.get("type"))) { - try { - productSuperTableCreateOrUpdateService.createProductSuperTable(String.valueOf(stableMessage.get("msg"))); - } catch (Exception e) { - log.error(e.getMessage()); - } - } else if ("update".equals(stableMessage.get("type"))) { - productSuperTableCreateOrUpdateService.updateProductSuperTable(String.valueOf(stableMessage.get("msg"))); - } - - } -} diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/init/InitDataBase.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/init/InitDataBase.java deleted file mode 100644 index afa7f1fa..00000000 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/common/init/InitDataBase.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.mqttsnet.thinglinks.tdengine.common.init; - -import com.mqttsnet.thinglinks.tdengine.service.TdEngineService; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.time.StopWatch; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; - -/** - * @Description: 初始化数据库 - * @Author: ShiHuan SUN - * @E-mail: 13733918655@163.com - * @Website: http://thinglinks.mqttsnet.com - * @CreateDate: 2022/3/28$ 16:12$ - * @UpdateUser: ShiHuan SUN - * @UpdateDate: 2022/3/28$ 16:12$ - * @UpdateRemark: 修改内容 - * @Version: V1.0 - */ -@Component -@Slf4j -@RefreshScope -public class InitDataBase { - private static InitDataBase InitDataBase; - - @Autowired - private TdEngineService tdEngineService; - - /** - * 数据库名称 - */ - @Value("${spring.datasource.dynamic.datasource.master.dbName}") - private String dataBaseName = "thinglinks"; - - @PostConstruct - public void init() throws Exception { - InitDataBase = this; - InitDataBase.tdEngineService=this.tdEngineService; - StopWatch watch = new StopWatch(); - watch.start(); - //创建数据库 - this.tdEngineService.createDateBase(dataBaseName); - watch.stop(); - log.info("初始化数据库:{} 成功 ! Time Elapsed (millisecond): {}",dataBaseName,watch.getTime()); - } - -} diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/controller/TdEngineController.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/controller/TdEngineController.java index 729b43ea..54696ff8 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/controller/TdEngineController.java +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/controller/TdEngineController.java @@ -3,19 +3,19 @@ import cn.hutool.core.util.StrUtil; import cn.hutool.json.JSONObject; import com.mqttsnet.thinglinks.common.core.domain.R; -import com.mqttsnet.thinglinks.common.core.enums.DataTypeEnum; import com.mqttsnet.thinglinks.common.core.utils.StringUtils; -import com.mqttsnet.thinglinks.tdengine.api.domain.*; +import com.mqttsnet.thinglinks.tdengine.api.constant.TdsConstants; +import com.mqttsnet.thinglinks.tdengine.api.domain.SelectDto; +import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDescribeVO; +import com.mqttsnet.thinglinks.tdengine.api.domain.TagsSelectDao; import com.mqttsnet.thinglinks.tdengine.api.domain.model.SuperTableDTO; import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; -import com.mqttsnet.thinglinks.tdengine.api.domain.visual.SelectVisualDto; -import com.mqttsnet.thinglinks.tdengine.common.constant.TdsConstants; +import com.mqttsnet.thinglinks.tdengine.api.domain.model.TagsSelectDTO; +import com.mqttsnet.thinglinks.tdengine.api.utils.TdsUtils; import com.mqttsnet.thinglinks.tdengine.service.TdEngineService; -import com.mqttsnet.thinglinks.tdengine.utils.TdsUtils; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.UncategorizedSQLException; import org.springframework.validation.annotation.Validated; @@ -32,6 +32,7 @@ * @Version 1.0 */ +@Slf4j @RestController @RequestMapping("/dataOperation") public class TdEngineController { @@ -39,343 +40,25 @@ public class TdEngineController { @Autowired private TdEngineService tdEngineService; - private static final Logger log = LoggerFactory.getLogger(TdEngineController.class); /** - * @param dataBaseName 数据库名称 - * @return R - * @MethodDescription 创建tdEngine数据库 - * @author thinglinks - * @Date 2021/12/27 16:26 - */ - @PostMapping("/createDb") - public R createDataBase(@RequestBody() String dataBaseName) { - try { - //调用创建数据库方法 - this.tdEngineService.createDateBase(dataBaseName); - log.info("successful operation: created database '" + dataBaseName + "' success"); - return R.ok(); - } catch (UncategorizedSQLException e) { - String message = e.getCause().getMessage(); - try { - message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) { - } - log.error(message); - return R.fail(message); - } catch (Exception e) { - log.error(e.getMessage()); - return R.fail(e.getMessage()); - } - } - - /** - * @param superTableDto 创建超级表需要的入参的实体类 - * @return R - * @MethodDescription 创建超级表 - * @author thinglinks - * @Date 2021/12/27 16:26 - */ - @PostMapping("/createSTb") - public R createSuperTable(@Validated @RequestBody SuperTableDto superTableDto) { - //从入参对象获取列字段(超级表结构)对象集合 - List schemaFields = superTableDto.getSchemaFields(); - //从入参对象获取标签字段对象集合 - List tagsFields = superTableDto.getTagsFields(); - //从入参获取数据库名称 - String dataBaseName = superTableDto.getDataBaseName(); - //从入参获取超级表名称 - String superTableName = superTableDto.getSuperTableName(); - //获取列字段对象集合的第一个对象的字段数据类型 - DataTypeEnum dataType = schemaFields.get(0).getDataType(); - //如果该数据类型不是时间戳,打印和返回报错信息 - if (dataType == null || !"timestamp".equals(dataType.getDataType())) { - log.error("invalid operation: first column must be timestamp"); - return R.fail("invalid operation: the first column must be timestamp"); - } - - try { - //将列字段对象集合和标签字段对象集合转码为字段Vo类对象集合 - List schemaFieldsVoList = FieldsVo.fieldsTranscoding(schemaFields); - List tagsFieldsVoList = FieldsVo.fieldsTranscoding(tagsFields); - //创建超级表 - this.tdEngineService.createSuperTable(schemaFieldsVoList, tagsFieldsVoList, dataBaseName, superTableName); - log.info("successful operation: created superTable '" + superTableName + "' success"); - return R.ok(); - } catch (UncategorizedSQLException e) { - String message = e.getCause().getMessage(); - try { - message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) { - } - log.error(message); - return R.fail(message); - } catch (Exception e) { - log.error(e.getMessage()); - return R.fail(e.getMessage()); - } - } - - /** - * 添加列字段 + * 创建时序数据库 * - * @param superTableDto - * @return - */ - @PostMapping("/addColumnInStb") - public R addColumnForSuperTable(@RequestBody SuperTableDto superTableDto) { - - String superTableName = superTableDto.getSuperTableName(); - if (StringUtils.isBlank(superTableName)) { - return R.fail("invalid operation: superTableName can not be empty"); - } - - Fields fields = superTableDto.getFields(); - if (fields == null) { - return R.fail("invalid operation: fields can not be empty"); - } - - try { - FieldsVo fieldsVo = FieldsVo.fieldsTranscoding(fields); - this.tdEngineService.addColumnForSuperTable(superTableName, fieldsVo); - log.info("successful operation: add column for superTable '" + superTableName + "' success"); - return R.ok(); - } catch (UncategorizedSQLException e) { - String message = e.getCause().getMessage(); - try { - message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) { - } - log.error(message); - return R.fail(message); - } catch (Exception e) { - log.error(e.getMessage()); - return R.fail(e.getMessage()); - } - } - - /** - * 删除列字段 - * - * @param superTableDto - * @return - */ - @PostMapping("/dropColumnInStb") - public R dropColumnForSuperTable(@RequestBody SuperTableDto superTableDto) { - - String superTableName = superTableDto.getSuperTableName(); - if (StringUtils.isBlank(superTableName)) { - return R.fail("invalid operation: superTableName can not be empty"); - } - - Fields fields = superTableDto.getFields(); - if (fields == null) { - return R.fail("invalid operation: fields can not be empty"); - } - - try { - FieldsVo fieldsVo = FieldsVo.fieldsTranscoding(fields); - this.tdEngineService.addColumnForSuperTable(superTableName, fieldsVo); - log.info("successful operation: drop column for superTable '" + superTableName + "' success"); - return R.ok(); - } catch (UncategorizedSQLException e) { - String message = e.getCause().getMessage(); - try { - message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) { - } - log.error(message); - return R.fail(message); - } catch (Exception e) { - log.error(e.getMessage()); - return R.fail(e.getMessage()); - } - } - - /** - * @param tableDto 创建超级表的子表需要的入参的实体类 - * @return R - * @MethodDescription 创建超级表的子表 - * @author thinglinks - * @Date 2021/12/30 14:15 - */ - @PostMapping("/createTb") - public R createTable(@Validated @RequestBody TableDto tableDto) { - try { - this.tdEngineService.createTable(tableDto); - log.info("successful operation: create table success"); - return R.ok("successful operation: create table success"); - } catch (Exception e) { - String message = e.getCause().getMessage(); - try { - message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) { - log.error(ex.getMessage()); - } - log.error(message); - return R.fail(message); - } - } - - /** - * @param tableDto 插入数据需要的入参的实体类 - * @return R - * @MethodDescription 插入数据 - * @author thinglinks - * @Date 2022/1/10 14:43 - */ - @PostMapping("/insertData") - public R insertData(@Validated @RequestBody TableDto tableDto) { - try { - List tagsFieldValues = tableDto.getTagsFieldValues(); - for (Fields fields : tagsFieldValues) { - if (StringUtils.isBlank(fields.getFieldName()) || fields.getFieldValue() == null) { - log.error("invalid operation: fieldName or fieldValue can not be empty"); - return R.fail("invalid operation: fieldName or fieldValue can not be empty"); - } - } - this.tdEngineService.insertData(tableDto); - log.info("successful operation: insert data success"); - return R.ok(); - } catch (UncategorizedSQLException e) { - String message = e.getCause().getMessage(); - try { - message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) { - } - log.error(message); - return R.fail(message); - } catch (Exception e) { - log.error(e.getMessage()); - return R.fail(e.getMessage()); - } - } - - /** - * @param selectDto 查询数据需要的入参的实体类 - * @return R - * @MethodDescription 根据时间戳查询数据 - * @author thinglinks - * @Date 2022/1/10 14:44 - */ - @PostMapping("/getDataByTimestamp") - public R getDataByTimestamp(@Validated @RequestBody SelectDto selectDto) { - try { - return R.ok(this.tdEngineService.selectByTimesTamp(selectDto)); - } catch (UncategorizedSQLException e) { - String message = e.getCause().getMessage(); - try { - message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) { - } - log.error(message); - return R.fail(message); - } catch (Exception e) { - log.error(e.getMessage()); - return R.fail(e.getMessage()); - } - } - - @PostMapping("/getCountByTimestamp") - public R getCountByTimestamp(@Validated @RequestBody SelectDto selectDto) { - try { - return R.ok(this.tdEngineService.getCountByTimesTamp(selectDto)); - } catch (UncategorizedSQLException e) { - String message = e.getCause().getMessage(); - try { - message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) { - } - log.error(message); - return R.fail(message); - } catch (Exception e) { - log.error(e.getMessage()); - return R.fail(e.getMessage()); - } - } - - - /** - * @param selectDto - * @return R - * @MethodDescription 查询最新数据 - */ - @PostMapping("/getLastData") - public R getLastData(@Validated @RequestBody SelectDto selectDto) { - try { - return R.ok(this.tdEngineService.getLastData(selectDto)); - } catch (UncategorizedSQLException e) { - String message = e.getCause().getMessage(); - try { - message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) { - } - log.error(message); - return R.fail(message); - } catch (Exception e) { - log.error(e.getMessage()); - return R.fail(e.getMessage()); - } - } - - - /** - * @param selectVisualDto - * @return R - * @MethodDescription 可视化数据 返回格式,时间,数值列 - * 历史数据 SELECT voltage ,ts FROM test.meters where ts between '2017-07-14 02:40:00.000' and '2017-07-14 02:40:00.001' LIMIT [topnums] - * ts > now - 24h; - * 实时数据 select col from table LIMIT [topnums] - * 聚合数据 select [avg/max/sum/count..](col) from table where ts between '2017-07-14 02:40:00.000' and '2017-07-14 02:40:00.001' group by col LIMIT [topnums] - */ - @PostMapping("/getVisualizeData") - public R getVisualizeData(@Validated @RequestBody SelectVisualDto selectVisualDto) { - try { - if (selectVisualDto.getType() == 0) {//查询历史 - return R.ok(this.tdEngineService.getHistoryData(selectVisualDto)); - } else if (selectVisualDto.getType() == 1) {//查询实时 - return R.ok(this.tdEngineService.getRealtimeData(selectVisualDto)); - } else {//查询聚合 - return R.ok(this.tdEngineService.getAggregateData(selectVisualDto)); - } - } catch (UncategorizedSQLException e) { - String message = e.getCause().getMessage(); - try { - message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) { - } - log.error(message); - return R.fail(message); - } catch (Exception e) { - log.error(e.getMessage()); - return R.fail(e.getMessage()); - } - } - - /** - * @param tagsSelectDao - * @return R - * @MethodDescription 根据超级表查询包含Tags的最新数据集合 + * @param dataBaseName 数据库名称 + * @return 执行结果 */ - @PostMapping("/getLastDataByTags") - public R>> getLastDataByTags(@Validated @RequestBody TagsSelectDao tagsSelectDao) { + @ApiOperation(value = "创建时序数据库", notes = "创建时序数据库") + @PostMapping("/createDatabase") + public R createDatabase(@RequestParam String dataBaseName) { try { - return R.ok(this.tdEngineService.getLastDataByTags(tagsSelectDao)); - } catch (UncategorizedSQLException e) { - String message = e.getCause().getMessage(); - try { - message = message.substring(message.lastIndexOf("invalid operation")); - } catch (Exception ex) { - } - log.error(message); - return R.fail(message); + tdEngineService.createDatabase(dataBaseName); } catch (Exception e) { - log.error(e.getMessage()); + log.error("创建时序数据库失败{}", e.getMessage()); return R.fail(e.getMessage()); } + return R.ok(); } - /** * 创建超级表 * @@ -492,7 +175,7 @@ public R createSubTableTwo(@RequestBody JSONObject object) { */ @ApiOperation(value = "删除超级表", notes = "删除超级表") @PostMapping("/dropSuperTable") - public R dropSuperTable(@RequestParam String superTableName) { + public R dropSuperTable(@RequestParam(value = "superTableName") String superTableName) { try { tdEngineService.dropSuperTable(TdsConstants.DATA_BASE, superTableName); } catch (Exception e) { @@ -596,7 +279,7 @@ public R dropSuperTableTag(@RequestBody SuperTableDTO superTableDTO) { */ @ApiOperation(value = "修改标签名称", notes = "修改标签名称") @PostMapping("/alterSuperTableTagRename") - public R alterSuperTableTagRename(@RequestParam String superTableName, @RequestParam String oldName, @RequestParam String newName) { + public R alterSuperTableTagRename(@RequestParam(value = "superTableName") String superTableName, @RequestParam(value = "oldName") String oldName, @RequestParam(value = "newName") String newName) { try { tdEngineService.alterSuperTableTagRename(TdsConstants.DATA_BASE, superTableName, oldName, newName); } catch (Exception e) { @@ -665,7 +348,7 @@ public R>> getDataInRangeOrLastRecord( @ApiParam(value = "Start time for the query", example = "1634572800000", required = false) @RequestParam(value = "startTime", required = false) Long startTime, @ApiParam(value = "End time for the query", example = "1634659200000", required = false) @RequestParam(value = "endTime", required = false) Long endTime) { try { - if (StrUtil.isBlank(tableName)) { + if (StringUtils.isEmpty(tableName)) { return R.fail("Table name cannot be empty"); } List> dataInRangeOrLastRecord = tdEngineService.getDataInRangeOrLastRecord(TdsConstants.DATA_BASE, tableName, startTime, endTime); @@ -676,4 +359,76 @@ public R>> getDataInRangeOrLastRecord( } } + /** + * @param selectDto 查询数据需要的入参的实体类 + * @return R + * @MethodDescription 根据时间戳查询数据 + * @author thinglinks + * @Date 2022/1/10 14:44 + */ + @PostMapping("/getDataByTimestamp") + public R getDataByTimestamp(@Validated @RequestBody SelectDto selectDto) { + try { + return R.ok(this.tdEngineService.selectByTimesTamp(selectDto)); + } catch (UncategorizedSQLException e) { + String message = e.getCause().getMessage(); + try { + message = message.substring(message.lastIndexOf("invalid operation")); + } catch (Exception ex) { + } + log.error(message); + return R.fail(message); + } catch (Exception e) { + log.error(e.getMessage()); + return R.fail(e.getMessage()); + } + } + + /** + * @param selectDto + * @return R + * @MethodDescription 查询最新数据 + */ + @PostMapping("/getLastData") + public R getLastData(@Validated @RequestBody SelectDto selectDto) { + try { + return R.ok(this.tdEngineService.getLastData(selectDto)); + } catch (UncategorizedSQLException e) { + String message = e.getCause().getMessage(); + try { + message = message.substring(message.lastIndexOf("invalid operation")); + } catch (Exception ex) { + } + log.error(message); + return R.fail(message); + } catch (Exception e) { + log.error(e.getMessage()); + return R.fail(e.getMessage()); + } + } + + /** + * @param tagsSelectDao + * @return R + * @MethodDescription 根据超级表查询包含Tags的最新数据集合 + */ + @PostMapping("/getLastDataByTags") + public R>> getLastDataByTags(@Validated @RequestBody TagsSelectDTO tagsSelectDao) { + try { + return R.ok(this.tdEngineService.getLastDataByTags(tagsSelectDao)); + } catch (UncategorizedSQLException e) { + String message = e.getCause().getMessage(); + try { + message = message.substring(message.lastIndexOf("invalid operation")); + } catch (Exception ex) { + } + log.error(message); + return R.fail(message); + } catch (Exception e) { + log.error(e.getMessage()); + return R.fail(e.getMessage()); + } + } + + } diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/mapper/ProductSuperTableCreateOrUpdateMapper.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/mapper/ProductSuperTableCreateOrUpdateMapper.java deleted file mode 100644 index f3deaa71..00000000 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/mapper/ProductSuperTableCreateOrUpdateMapper.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.mqttsnet.thinglinks.tdengine.mapper; - -import org.apache.ibatis.annotations.Mapper; - -/** - * @Description: 超级表创建及修改持久层接口 - * @Author: ShiHuan Sun - * @E-mail: 13733918655@163.com - * @Website: http://thinglinks.mqttsnet.com - * @CreateDate: 2021/12/26$ 22:17$ - * @UpdateUser: ShiHuan Sun - * @UpdateDate: 2021/12/26$ 22:17$ - * @UpdateRemark: 修改内容 - * @Version: 1.0 - */ -@Mapper -public interface ProductSuperTableCreateOrUpdateMapper { - - void dropDB(); - - void createDB(); - - void createSuperTable(); -} diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/mapper/TdEngineMapper.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/mapper/TdEngineMapper.java index 0da599c3..fe6d9fd9 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/mapper/TdEngineMapper.java +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/mapper/TdEngineMapper.java @@ -1,10 +1,11 @@ package com.mqttsnet.thinglinks.tdengine.mapper; -import com.mqttsnet.thinglinks.tdengine.api.domain.*; +import com.mqttsnet.thinglinks.tdengine.api.domain.Fields; +import com.mqttsnet.thinglinks.tdengine.api.domain.SelectDto; +import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDescribeVO; import com.mqttsnet.thinglinks.tdengine.api.domain.model.SuperTableDTO; import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; import com.mqttsnet.thinglinks.tdengine.api.domain.model.TagsSelectDTO; -import com.mqttsnet.thinglinks.tdengine.api.domain.visual.SelectVisualDto; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @@ -21,51 +22,13 @@ @Mapper public interface TdEngineMapper { - void createDatabase(@Param("dataBaseName") String dataBaseName); - - void createSuperTable(@Param("schemaFields") List schemaFields, - @Param("tagsFields") List tagsFields, - @Param("dataBaseName") String dataBaseName, - @Param("superTableName") String superTableName); - - void createTable(TableDto tableDto); - - void insertData(TableDto tableDto); - - List> selectByTimestamp(SelectDto selectDto); - - void addColumnForSuperTable(@Param("superTableName") String superTableName, - @Param("fieldsVo") FieldsVo fieldsVo); - - void dropColumnForSuperTable(@Param("superTableName") String superTableName, - @Param("fieldsVo") FieldsVo fieldsVo); - - void addTagForSuperTable(@Param("superTableName") String superTableName, - @Param("fieldsVo") FieldsVo fieldsVo); - - void dropTagForSuperTable(@Param("superTableName") String superTableName, - @Param("fieldsVo") FieldsVo fieldsVo); - - Map getCountByTimestamp(SelectDto selectDto); /** - * 检查表是否存在 + * 创建数据库 + * * @param dataBaseName - * @param tableName 可以为超级表名或普通表名 - * @return */ - Integer checkTableExists(@Param("dataBaseName") String dataBaseName, @Param("tableName")String tableName); - - List> getLastData(SelectDto selectDto); - - List> getHistoryData(SelectVisualDto selectVisualDto); - - List> getRealtimeData(SelectVisualDto selectVisualDto); - - List> getAggregateData(SelectVisualDto selectVisualDto); - - List> getLastDataByTags(TagsSelectDao tagsSelectDao); - + void createDatabase(@Param("dataBaseName") String dataBaseName); /** * 创建超级表 @@ -184,4 +147,9 @@ List> getDataInRangeOrLastRecord( @Param("tableName") String tableName, @Param("startTime") Long startTime, @Param("endTime") Long endTime); + + List> selectByTimestamp(SelectDto selectDto); + + + List> getLastData(SelectDto selectDto); } diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/ProductSuperTableCreateOrUpdateService.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/ProductSuperTableCreateOrUpdateService.java deleted file mode 100644 index 3c1fdcee..00000000 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/ProductSuperTableCreateOrUpdateService.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.mqttsnet.thinglinks.tdengine.service; - -/** - * @Description: java类作用描述 - * @Author: ShiHuan Sun - * @E-mail: 13733918655@163.com - * @Website: http://thinglinks.mqttsnet.com - * @CreateDate: 2021/12/26$ 21:51$ - * @UpdateUser: ShiHuan Sun - * @UpdateDate: 2021/12/26$ 21:51$ - * @UpdateRemark: 修改内容 - * @Version: 1.0 - */ -public interface ProductSuperTableCreateOrUpdateService { - - /** - * @Author: ShiHuan Sun - * @E-mail: 13733918655@163.com - * @Description: 创建超级表 - * @CreateDate: 2021/12/26 22:05 - * @Version: V1.0 - * @Param: - * msg 产品模型信息 - * @return - */ - - void createProductSuperTable(String msg) throws Exception; - - /** - * @Author: ShiHuan Sun - * @E-mail: 13733918655@163.com - * @Description: 修改超级表 - * @CreateDate: 2021/12/26 22:05 - * @Version: V1.0 - * @Param: - * msg 产品模型信息 - * @return - */ - void updateProductSuperTable(String msg); -} diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/TdEngineService.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/TdEngineService.java index 67c79287..36b82d05 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/TdEngineService.java +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/TdEngineService.java @@ -1,11 +1,12 @@ package com.mqttsnet.thinglinks.tdengine.service; -import com.mqttsnet.thinglinks.tdengine.api.domain.*; +import com.mqttsnet.thinglinks.tdengine.api.domain.Fields; +import com.mqttsnet.thinglinks.tdengine.api.domain.SelectDto; +import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDescribeVO; import com.mqttsnet.thinglinks.tdengine.api.domain.model.SuperTableDTO; import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; import com.mqttsnet.thinglinks.tdengine.api.domain.model.TagsSelectDTO; -import com.mqttsnet.thinglinks.tdengine.api.domain.visual.SelectVisualDto; import org.apache.ibatis.annotations.Param; import java.util.List; @@ -19,33 +20,14 @@ * @Version 1.0 */ public interface TdEngineService { - void createDateBase(String dataBaseName) throws Exception; - - void createSuperTable(List schemaFields, List tagsFields, String dataBaseName, String superTableName) throws Exception; - - void createTable(TableDto tableDto) throws Exception; - - void insertData(TableDto tableDto) throws Exception; - - List> selectByTimesTamp(SelectDto selectDto) throws Exception; - - void addColumnForSuperTable(String superTableName, FieldsVo fieldsVo) throws Exception; - - void dropColumnForSuperTable(String superTableName, FieldsVo fieldsVo) throws Exception; - - Long getCountByTimesTamp(SelectDto selectDto) throws Exception; - - void initSTableFrame(String msg) throws Exception; - - List> getLastData(SelectDto selectDto) throws Exception; - - Map> getLastDataByTags(TagsSelectDao tagsSelectDao); - - List> getHistoryData(SelectVisualDto selectVisualDto); - - List> getRealtimeData(SelectVisualDto selectVisualDto); + /** + * 创建数据库 + * + * @param dataBaseName + */ + default void createDatabase(@Param("dataBaseName") String dataBaseName) { - List> getAggregateData(SelectVisualDto selectVisualDto); + } /** * 创建超级表 @@ -188,4 +170,14 @@ default Map> getLastDataByTags(TagsSelectDTO tagsSel default List> getDataInRangeOrLastRecord(String dataBaseName, String tableName, Long startTime, Long endTime) { return null; } + + + default List> selectByTimesTamp(SelectDto selectDto) throws Exception { + return null; + } + + default List> getLastData(SelectDto selectDto) throws Exception { + return null; + } + } diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/impl/ProductSuperTableCreateOrUpdateServiceImpl.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/impl/ProductSuperTableCreateOrUpdateServiceImpl.java deleted file mode 100644 index 0f50b293..00000000 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/impl/ProductSuperTableCreateOrUpdateServiceImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.mqttsnet.thinglinks.tdengine.service.impl; - -import com.mqttsnet.thinglinks.tdengine.api.domain.ProductSuperTableModel; -import com.mqttsnet.thinglinks.tdengine.mapper.ProductSuperTableCreateOrUpdateMapper; -import com.mqttsnet.thinglinks.tdengine.service.ProductSuperTableCreateOrUpdateService; -import com.mqttsnet.thinglinks.tdengine.service.TdEngineService; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.sql.Timestamp; - -/** - * @Description: java类作用描述 - * @Author: ShiHuan Sun - * @E-mail: 13733918655@163.com - * @Website: http://thinglinks.mqttsnet.com - * @CreateDate: 2021/12/26$ 21:51$ - * @UpdateUser: ShiHuan Sun - * @UpdateDate: 2021/12/26$ 21:51$ - * @UpdateRemark: 修改内容 - * @Version: 1.0 - */ -@Service -@Slf4j -public class ProductSuperTableCreateOrUpdateServiceImpl implements ProductSuperTableCreateOrUpdateService { - - @Autowired - private ProductSuperTableCreateOrUpdateMapper productSuperTableCreateOrUpdateMapper; - @Autowired - private TdEngineService tdEngineService; - - - @Override - public void createProductSuperTable(String msg) throws Exception { - //TODO 创建超级表逻辑处理 - tdEngineService.initSTableFrame(msg); - } - - - @Override - public void updateProductSuperTable(String msg) { - - } -} diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/impl/TdEngineServiceImpl.java b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/impl/TdEngineServiceImpl.java index 896f485b..c76ccc0f 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/impl/TdEngineServiceImpl.java +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/java/com/mqttsnet/thinglinks/tdengine/service/impl/TdEngineServiceImpl.java @@ -1,14 +1,11 @@ package com.mqttsnet.thinglinks.tdengine.service.impl; -import com.alibaba.fastjson.JSONObject; -import com.baomidou.dynamic.datasource.annotation.DS; -import com.mqttsnet.thinglinks.common.core.enums.DataTypeEnum; -import com.mqttsnet.thinglinks.common.redis.service.RedisService; -import com.mqttsnet.thinglinks.tdengine.api.domain.*; +import com.mqttsnet.thinglinks.tdengine.api.domain.Fields; +import com.mqttsnet.thinglinks.tdengine.api.domain.SelectDto; +import com.mqttsnet.thinglinks.tdengine.api.domain.SuperTableDescribeVO; import com.mqttsnet.thinglinks.tdengine.api.domain.model.SuperTableDTO; import com.mqttsnet.thinglinks.tdengine.api.domain.model.TableDTO; import com.mqttsnet.thinglinks.tdengine.api.domain.model.TagsSelectDTO; -import com.mqttsnet.thinglinks.tdengine.api.domain.visual.SelectVisualDto; import com.mqttsnet.thinglinks.tdengine.mapper.TdEngineMapper; import com.mqttsnet.thinglinks.tdengine.service.TdEngineService; import lombok.extern.slf4j.Slf4j; @@ -34,228 +31,76 @@ public class TdEngineServiceImpl implements TdEngineService { @Autowired - private TdEngineMapper tdEngineMapper; - @Autowired - private RedisService redisService; - - @Override - public void createDateBase(String dataBaseName) throws Exception { - this.tdEngineMapper.createDatabase(dataBaseName); - } - - @Override - public void createSuperTable(List schemaFields, List tagsFields, String dataBaseName, String superTableName) throws Exception { - this.tdEngineMapper.createSuperTable(schemaFields, tagsFields, dataBaseName, superTableName); - } - - @Override - public void createTable(TableDto tableDto) throws Exception { - this.tdEngineMapper.createTable(tableDto); - } - - @Override - public void insertData(TableDto tableDto) throws Exception { - this.tdEngineMapper.insertData(tableDto); - } - - @Override - public List> selectByTimesTamp(SelectDto selectDto) throws Exception { - List> maps = this.tdEngineMapper.selectByTimestamp(selectDto); - for (Map map : maps) { - Map filterMap = map.entrySet() - .stream() - .filter(entry -> entry.getValue() != null) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - } - return maps; - } - - @Override - public void addColumnForSuperTable(String superTableName, FieldsVo fieldsVo) throws Exception { - this.tdEngineMapper.addColumnForSuperTable(superTableName, fieldsVo); - } - - - @Override - public void dropColumnForSuperTable(String superTableName, FieldsVo fieldsVo) throws Exception { - this.tdEngineMapper.dropColumnForSuperTable(superTableName, fieldsVo); - } - - @Override - public Long getCountByTimesTamp(SelectDto selectDto) throws Exception { - Map countMap = this.tdEngineMapper.getCountByTimestamp(selectDto); - if (countMap == null) { - return 0L; - } - Long count = countMap.get("count"); - return count; - } - - /** - * 检查数据库表是否存在 - * - * @param dataBaseName 数据库名 - * @param tableName tableName 可以为超级表名或普通表名 - * @return - */ - public boolean checkTableExists(String dataBaseName, String tableName) throws Exception { - try { - Integer count = tdEngineMapper.checkTableExists(dataBaseName, tableName); - return count == 1; - } catch (Exception e) { - log.warn("{},{} 数据库表不存在", dataBaseName, tableName); - return false; - } - } - - @Override - public void initSTableFrame(String msg) throws Exception { - final SuperTableDto superTableDto = JSONObject.toJavaObject(JSONObject.parseObject(msg), SuperTableDto.class); - //从入参对象获取列字段(超级表结构)对象集合 - List schemaFields = superTableDto.getSchemaFields(); - //从入参对象获取标签字段对象集合 - List tagsFields = superTableDto.getTagsFields(); - //从入参获取数据库名称 - String dataBaseName = superTableDto.getDataBaseName(); - //从入参获取超级表名称 - String superTableName = superTableDto.getSuperTableName(); - final boolean tableExists = this.checkTableExists(dataBaseName, superTableName); - if (tableExists) { - log.info("超级表{}已存在", superTableName); - return; - } - //获取列字段对象集合的第一个对象的字段数据类型 - DataTypeEnum dataType = schemaFields.get(0).getDataType(); - //如果该数据类型不是时间戳,打印和返回报错信息 - if (dataType == null || !"timestamp".equals(dataType.getDataType())) { - log.error("invalid operation: first column must be timestamp"); - return; - } - //将列字段对象集合和标签字段对象集合转码为字段Vo类对象集合 - List schemaFieldsVoList = FieldsVo.fieldsTranscoding(schemaFields); - List tagsFieldsVoList = FieldsVo.fieldsTranscoding(tagsFields); - //创建超级表 - this.createSuperTable(schemaFieldsVoList, tagsFieldsVoList, dataBaseName, superTableName); - log.info("create {} super table success", superTableName); - } - - /** - * @param selectDto - * @return - */ - @Override - public List> getLastData(SelectDto selectDto) throws Exception { - List> maps = this.tdEngineMapper.getLastData(selectDto); -// for (Map map : maps) { -// Map filterMap = map.entrySet() -// .stream() -// .filter(entry -> entry.getValue() != null) -// .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); -// } - return maps; - } + private TdEngineMapper tdengineMapper; - /** - * @param tagsSelectDao - * @return - */ @Override - public Map> getLastDataByTags(TagsSelectDao tagsSelectDao) { - List> maps = this.tdEngineMapper.getLastDataByTags(tagsSelectDao); - Map> objectHashMap = new HashMap<>(); - for (Map map : maps) { -// Map filterMap = map.entrySet() -// .stream() -// .filter(entry -> entry.getValue() != null) -// .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - objectHashMap.put(map.get("last("+tagsSelectDao.getTagsName()+")").toString(), map); - } - return objectHashMap; - } - - - @Override - public List> getHistoryData(SelectVisualDto selectVisualDto) { - List> maps = this.tdEngineMapper.getHistoryData(selectVisualDto); - return maps; - } - - @Override - public List> getRealtimeData(SelectVisualDto selectVisualDto) { - List> maps = this.tdEngineMapper.getRealtimeData(selectVisualDto); - return maps; - } - - @Override - public List> getAggregateData(SelectVisualDto selectVisualDto) { - List> maps = this.tdEngineMapper.getAggregateData(selectVisualDto); - return maps; + public void createDatabase(String dataBaseName) { + tdengineMapper.createDatabase(dataBaseName); } @Override public void createSuperTable(String dataBaseName, String superTableName) { - tdEngineMapper.createSuperTable(dataBaseName, superTableName); + tdengineMapper.createSuperTable(dataBaseName, superTableName); } @Override public void createSuperTableAndColumn(SuperTableDTO superTableDTO) { - tdEngineMapper.createSuperTableAndColumn(superTableDTO); + tdengineMapper.createSuperTableAndColumn(superTableDTO); } @Override public void createSubTable(TableDTO tableDTO) { - tdEngineMapper.createSubTable(tableDTO); + tdengineMapper.createSubTable(tableDTO); } @Override public void dropSuperTable(String dataBaseName, String superTableName) { - tdEngineMapper.dropSuperTable(dataBaseName, superTableName); + tdengineMapper.dropSuperTable(dataBaseName, superTableName); } @Override public void alterSuperTableColumn(String dataBaseName, String superTableName, Fields fields) { - tdEngineMapper.alterSuperTableColumn(dataBaseName, superTableName, fields); + tdengineMapper.alterSuperTableColumn(dataBaseName, superTableName, fields); } @Override public void dropSuperTableColumn(String dataBaseName, String superTableName, Fields fields) { - tdEngineMapper.dropSuperTableColumn(dataBaseName, superTableName, fields); + tdengineMapper.dropSuperTableColumn(dataBaseName, superTableName, fields); } @Override public List describeSuperOrSubTable(String dataBaseName, String tableName) { - List superTableDescribeVOS = new ArrayList<>(); try { - superTableDescribeVOS = tdEngineMapper.describeSuperOrSubTable(dataBaseName, tableName); + return tdengineMapper.describeSuperOrSubTable(dataBaseName, tableName); } catch (Exception e) { - log.warn("describeSuperTable error:{}", e.getMessage()); + log.warn("Error describing super or sub table. Database: {}, Table: {}, Error: {}", dataBaseName, tableName, e.getMessage()); + return Collections.emptyList(); } - return superTableDescribeVOS; } @Override public void alterSuperTableTag(String dataBaseName, String superTableName, Fields fields) { - tdEngineMapper.alterSuperTableTag(dataBaseName, superTableName, fields); + tdengineMapper.alterSuperTableTag(dataBaseName, superTableName, fields); } @Override public void dropSuperTableTag(String dataBaseName, String superTableName, Fields fields) { - tdEngineMapper.dropSuperTableTag(dataBaseName, superTableName, fields); + tdengineMapper.dropSuperTableTag(dataBaseName, superTableName, fields); } @Override public void alterSuperTableTagRename(String dataBaseName, String superTableName, String oldName, String newName) { - tdEngineMapper.alterSuperTableTagRename(dataBaseName, superTableName, oldName, newName); + tdengineMapper.alterSuperTableTagRename(dataBaseName, superTableName, oldName, newName); } @Override public void insertTableData(TableDTO tableDTO) { - tdEngineMapper.insertTableData(tableDTO); + tdengineMapper.insertTableData(tableDTO); } @Override public Map> getLastDataByTags(TagsSelectDTO tagsSelectDTO) { - List> maps = tdEngineMapper.getLastDataByTags(tagsSelectDTO); + List> maps = tdengineMapper.getLastDataByTags(tagsSelectDTO); Map> objectHashMap = new HashMap<>(); for (Map map : maps) { @@ -269,7 +114,38 @@ public Map> getLastDataByTags(TagsSelectDTO tagsSele @Override public List> getDataInRangeOrLastRecord(String dataBaseName, String tableName, Long startTime, Long endTime) { - return tdEngineMapper.getDataInRangeOrLastRecord(dataBaseName, tableName, startTime, endTime); + return tdengineMapper.getDataInRangeOrLastRecord(dataBaseName, tableName, startTime, endTime); } + + @Override + public List> selectByTimesTamp(SelectDto selectDto) throws Exception { + List> maps = tdengineMapper.selectByTimestamp(selectDto); + for (Map map : maps) { + Map filterMap = map.entrySet() + .stream() + .filter(entry -> entry.getValue() != null) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } + return maps; + } + + + /** + * @param selectDto + * @return + */ + @Override + public List> getLastData(SelectDto selectDto) throws Exception { + List> maps = this.tdengineMapper.getLastData(selectDto); +// for (Map map : maps) { +// Map filterMap = map.entrySet() +// .stream() +// .filter(entry -> entry.getValue() != null) +// .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); +// } + return maps; + } + + } diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/bootstrap.yml b/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/bootstrap.yml index d375112f..36c3e718 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/bootstrap.yml +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/bootstrap.yml @@ -1,5 +1,5 @@ # Spring -spring: +spring: application: # 应用名称 name: @project.artifactId@ @@ -31,7 +31,5 @@ spring: refresh: true - dataId: redis.yml refresh: false - - dataId: rocketmq.yml - refresh: false username: @nacos.username@ password: @nacos.password@ \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/mapper/ProductSuperTableCreateOrUpdateMapper.xml b/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/mapper/ProductSuperTableCreateOrUpdateMapper.xml deleted file mode 100644 index 58e0ca65..00000000 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/mapper/ProductSuperTableCreateOrUpdateMapper.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - drop - database if exists thinglinks - - - - create - database if not exists thinglinks - - - - create table if not exists thinglinks.${superTableName}( - - - #{key} #{value} - - - ) - tags( - - #{key} #{value} - - ) - - \ No newline at end of file diff --git a/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/mapper/TdEngineMapper.xml b/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/mapper/TdEngineMapper.xml index 6b2dbc7e..a367d9d0 100644 --- a/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/mapper/TdEngineMapper.xml +++ b/thinglinks-modules/thinglinks-modules-tdengine/src/main/resources/mapper/TdEngineMapper.xml @@ -1,312 +1,15 @@ - - - create database if not exists #{dataBaseName} - - - - create stable if not exists #{dataBaseName}.#{superTableName} - - - ${item.fieldName} - - - - - timestamp - - - tinyint - - - smallint - - - int - - - bigint - - - float - - - double - - - binary - - - nchar - - - bool - - - json - - - - - (#{item.size}) - - - tags - - - - ${item.fieldName} - - - - - timestamp - - - tinyint - - - smallint - - - int - - - bigint - - - float - - - double - - - binary - - - nchar - - - bool - - - json - - - - - (#{item.size}) - - - - - - create table - if not exists #{dataBaseName}.#{tableName} - using #{dataBaseName}.#{superTableName} - tags - - '${item.fieldValue}' - - - - - insert into #{dataBaseName}.#{tableName} - - ${item.fieldName} - - using #{dataBaseName}.#{superTableName} - tags - - '${item.fieldValue}' - - values - - #{item.fieldValue} - - - - - - - ALTER - STABLE - #{superTableName} - ADD - COLUMN - - ${fieldsVo.fieldName} - - - - - timestamp - - - tinyint - - - smallint - - - int - - - bigint - - - float - - - double - - - binary - - - nchar - - - bool - - - json - - - - - ( - #{fieldsVo.size} - ) - - - - ALTER - STABLE - #{superTableName} - DROP - COLUMN - - ${fieldsVo.fieldName} - - - - - ALTER - STABLE - #{superTableName} - ADD - TAG - - ${fieldsVo.fieldName} - - - - - timestamp - - - tinyint - - - smallint - - - int - - - bigint - - - float - - - double - - - binary - - - nchar - - - bool - - - json - - - - - ( - #{fieldsVo.size} - ) - - - - - ALTER - STABLE - #{superTableName} - DROP - TAG - - ${fieldsVo.fieldName} - + + create + database if not exists + #{dataBaseName} - - - - - - - - - - - - - - - + create table if not exists #{dataBaseName}.#{superTableName} @@ -491,7 +194,8 @@ - @@ -524,4 +228,20 @@ + + + + + diff --git a/thinglinks-ui/src/api/link/deviceInfo.js b/thinglinks-ui/src/api/link/deviceInfo.js index e510954d..34d2f428 100644 --- a/thinglinks-ui/src/api/link/deviceInfo.js +++ b/thinglinks-ui/src/api/link/deviceInfo.js @@ -51,10 +51,3 @@ export function getDeviceInfoShadow(data) { data: data }) } -// 初始化子设备影子数据 -export function refreshDeviceInfoDataModel(id) { - return request({ - url: '/link/deviceInfo/refreshDeviceInfoDataModel/' + id, - method: 'get' - }) -} diff --git a/thinglinks-ui/src/api/link/product/product.js b/thinglinks-ui/src/api/link/product/product.js index 3555544d..5de078ae 100644 --- a/thinglinks-ui/src/api/link/product/product.js +++ b/thinglinks-ui/src/api/link/product/product.js @@ -61,13 +61,12 @@ export function generateProductJson(data) { } /** - * 初始化数据模型 + * 产品赋能 * @param productIds 产品ID集合 - * @param initializeOrNot 是否初始化 */ -export function initializeDataModel(productIds, initializeOrNot) { +export function productEmpowerment(productIds) { return request({ - url: '/link/product/initializeDataModel/' + productIds + "/" + initializeOrNot, + url: '/link/product/productEmpowerment/' + productIds, method: 'get' }) } diff --git a/thinglinks-ui/src/views/link/deviceInfo/index.vue b/thinglinks-ui/src/views/link/deviceInfo/index.vue index f44111aa..1d405a0c 100644 --- a/thinglinks-ui/src/views/link/deviceInfo/index.vue +++ b/thinglinks-ui/src/views/link/deviceInfo/index.vue @@ -69,12 +69,6 @@ v-hasPermi="['link:deviceInfo:remove']">删除 - - - 设备初始化 - - 导出 @@ -126,13 +120,6 @@ - - - - - - @@ -334,21 +321,6 @@ setDecive(did) { this.form.did = did }, - //初始化数据模型 - initializeTheDataModel(row) { - const ids = row.id || this.ids; - this.$modal - .confirm('是否初始化"' + ids + '"的数据项?') - .then(function() { - console.log(ids); - return refreshDeviceInfoDataModel(ids); - }) - .then(() => { - this.getList() - this.$modal.msgSuccess("初始化成功"); - }) - .catch(() => {}); - }, // 高级搜索切换显示隐藏 advancedSearch_toggle() { this.advancedSearch = !this.advancedSearch; diff --git a/thinglinks-ui/src/views/link/product/index.vue b/thinglinks-ui/src/views/link/product/index.vue index da9e68bd..bda76bc0 100644 --- a/thinglinks-ui/src/views/link/product/index.vue +++ b/thinglinks-ui/src/views/link/product/index.vue @@ -62,8 +62,8 @@ - 产品初始化 + @click="productEmpowerment"> + 产品赋能 @@ -105,9 +105,9 @@ @click="handleDelete(scope.row)"> - + + @click="productEmpowerment(scope.row)"> @@ -690,19 +690,33 @@
- + - + -
+
+ + + + + + + + + + +
@@ -1051,7 +1065,8 @@ } ], required: [{ required: true, message: "是否必须不能为空", trigger: "blur" },], - name: [{ required: true, message: "指示属性名称不能为空", trigger: "blur" }], + propertyCode: [{ required: true, message: "指示属性编码不能为空", trigger: "blur" }], + propertyName: [{ required: true, message: "指示属性名称不能为空", trigger: "blur" }], method: [{ required: true, message: "指示访问模式不能为空", trigger: " change" }], }, }, @@ -1069,18 +1084,17 @@ watch: { }, methods: { - //初始化数据模型 - initializeTheDataModel(row) { + //产品赋能 + productEmpowerment(row) { const ids = row.id || this.ids; - const initializeOrNot = true this.$modal - .confirm('是否初始化"' + ids + '"的数据项?') + .confirm('是否赋能"' + ids + '"的数据项?') .then(function () { - return initializeDataModel(ids, initializeOrNot); + return productEmpowerment(ids); }) .then(() => { this.getList() - this.$modal.msgSuccess("初始化成功"); + this.$modal.msgSuccess("赋能成功"); }) .catch(() => { }); }, diff --git a/thinglinks-ui/src/views/link/product/properties/index.vue b/thinglinks-ui/src/views/link/product/properties/index.vue index 3f90365f..85fc319b 100644 --- a/thinglinks-ui/src/views/link/product/properties/index.vue +++ b/thinglinks-ui/src/views/link/product/properties/index.vue @@ -1,8 +1,11 @@ diff --git a/thinglinks-ui/src/views/link/device/index.vue b/thinglinks-ui/src/views/link/device/index.vue index 9718e5c7..fa8d3328 100644 --- a/thinglinks-ui/src/views/link/device/index.vue +++ b/thinglinks-ui/src/views/link/device/index.vue @@ -2,13 +2,13 @@
- +

{{ onlineCount }}/ {{ offlineCount }}/ {{ initCount }}/ + >/ {{ initCount }}/ {{ total }}

@@ -40,10 +40,10 @@ 二次开发: 下载Demo 开发文档开发文档

@@ -207,16 +207,19 @@ size="mini" type="primary" @click="handleQuery" - >搜索搜索 + 重置重置 + 高级搜索高级搜索 + @@ -230,7 +233,7 @@ size="mini" type="primary" @click="handleAdd" - >新增 + >新增 @@ -242,7 +245,7 @@ size="mini" type="danger" @click="handleDelete" - >删除 + >删除 @@ -254,7 +257,7 @@ size="mini" type="danger" @click="handleDisconnect" - >断开连接 + >断开连接 @@ -265,7 +268,7 @@ size="mini" type="warning" @click="handleExport" - >导出 + >导出 - - + +
**************** {{ - deviceList[scope.$index].password - }} + deviceList[scope.$index].password + }} @@ -449,7 +452,7 @@ - + @@ -489,13 +492,20 @@ - - + + placeholder="请选择所属产品" + > + + @@ -543,11 +553,19 @@ - - + + + + @@ -569,14 +587,14 @@ - + - - - - + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -645,11 +712,11 @@ @@ -659,21 +726,20 @@ '; + + function stringToUTF8Array(str) { + var data = []; + var i=0, l = str.length; + for (i=0; i> 6)); + data.push(0x80 | (char & 0x3f)); + } else if (char < 0xd800 || char >= 0xe000) { + data.push(0xe0 | (char >> 12)); + data.push(0x80 | ((char>>6) & 0x3f)); + data.push(0x80 | (char & 0x3f)); + } else { + i++; + char = 0x10000 + (((char & 0x3ff)<<10) | (str.charAt(i) & 0x3ff)); + data.push(0xf0 | (char >>18)); + data.push(0x80 | ((char>>12) & 0x3f)); + data.push(0x80 | ((char>>6) & 0x3f)); + data.push(0x80 | (char & 0x3f)); + } + } + return data; + } + + + var definition = { + show: function(options) { + var value = options.value; + var onCancel = options.cancel; + var onComplete = options.complete; + var type = "_buffer" + if ($("script[data-template-name='"+type+"']").length === 0) { + $(template).appendTo("#red-ui-editor-node-configs"); + } + RED.view.state(RED.state.EDITING); + var bufferStringEditor = []; + var bufferBinValue; + + var panels; + + var trayOptions = { + title: options.title, + focusElement: options.focusElement, + width: "inherit", + buttons: [ + { + id: "node-dialog-cancel", + text: RED._("common.label.cancel"), + click: function() { + if (onCancel) { onCancel(); } + RED.tray.close(); + } + }, + { + id: "node-dialog-ok", + text: RED._("common.label.done"), + class: "primary", + click: function() { + bufferStringEditor.saveView(); + if (onComplete) { onComplete(JSON.stringify(bufferBinValue),null,bufferStringEditor); } + RED.tray.close(); + } + } + ], + resize: function(dimensions) { + var height = $("#dialog-form").height(); + if (panels) { + panels.resize(height); + } + }, + open: function(tray) { + var dialogForm = RED.editor.buildEditForm(tray.find('.red-ui-tray-body'),'dialog-form',type,'editor'); + bufferStringEditor = RED.editor.createEditor({ + id: 'red-ui-editor-type-buffer-str', + value: value||"", + stateId: RED.editor.generateViewStateId("buffer", options, ""), + focus: true, + mode:"ace/mode/text" + }); + + bufferBinEditor = RED.editor.createEditor({ + id: 'red-ui-editor-type-buffer-bin', + value: "", + stateId: false, + focus: false, + mode:"ace/mode/text", + readOnly: true + }); + + var changeTimer; + var buildBuffer = function(data) { + var valid = true; + var isString = typeof data === 'string'; + var binBuffer = []; + if (isString) { + bufferBinValue = stringToUTF8Array(data); + } else { + bufferBinValue = data; + } + var i=0,l=bufferBinValue.length; + var c = 0; + for(i=0;i 255)) { + valid = false; + break; + } + if (i>0) { + if (i%8 === 0) { + if (i%16 === 0) { + binBuffer.push("\n"); + } else { + binBuffer.push(" "); + } + } else { + binBuffer.push(" "); + } + } + binBuffer.push((d<16?"0":"")+d.toString(16).toUpperCase()); + } + if (valid) { + $("#red-ui-editor-type-buffer-type-string").toggle(isString); + $("#red-ui-editor-type-buffer-type-array").toggle(!isString); + bufferBinEditor.setValue(binBuffer.join(""),1); + } + return valid; + } + var bufferStringUpdate = function() { + var value = bufferStringEditor.getValue(); + var isValidArray = false; + if (/^[\s]*\[[\s\S]*\][\s]*$/.test(value)) { + isValidArray = true; + try { + var data = JSON.parse(value); + isValidArray = buildBuffer(data); + } catch(err) { + isValidArray = false; + } + } + if (!isValidArray) { + buildBuffer(value); + } + + } + bufferStringEditor.getSession().on('change', function() { + clearTimeout(changeTimer); + changeTimer = setTimeout(bufferStringUpdate,200); + }); + + bufferStringUpdate(); + + dialogForm.i18n(); + + panels = RED.panels.create({ + id:"red-ui-editor-type-buffer-panels", + resize: function(p1Height,p2Height) { + var p1 = $("#red-ui-editor-type-buffer-panel-str"); + p1Height -= $(p1.children()[0]).outerHeight(true); + var editorRow = $(p1.children()[1]); + p1Height -= (parseInt(editorRow.css("marginTop"))+parseInt(editorRow.css("marginBottom"))); + $("#red-ui-editor-type-buffer-str").css("height",(p1Height-5)+"px"); + bufferStringEditor.resize(); + + var p2 = $("#red-ui-editor-type-buffer-panel-bin"); + editorRow = $(p2.children()[0]); + p2Height -= (parseInt(editorRow.css("marginTop"))+parseInt(editorRow.css("marginBottom"))); + $("#red-ui-editor-type-buffer-bin").css("height",(p2Height-5)+"px"); + bufferBinEditor.resize(); + } + }); + + $(".red-ui-editor-type-buffer-type").on("click", function(e) { + e.preventDefault(); + RED.sidebar.help.set(RED._("bufferEditor.modeDesc")); + }) + + + }, + close: function() { + if (options.onclose) { + options.onclose(); + } + bufferStringEditor.destroy(); + bufferBinEditor.destroy(); + }, + show: function() {} + } + RED.tray.show(trayOptions); + } + } + RED.editor.registerTypeEditor("_buffer", definition); + +})(); +;/** + * Copyright JS Foundation and other contributors, http://js.foundation + * + * 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. + **/ + +/** + * @namespace RED.editor.codeEditor + */ + RED.editor.codeEditor = (function() { + + const MONACO = "monaco"; + const ACE = "ace"; + const defaultEditor = MONACO; + const DEFAULT_SETTINGS = { lib: defaultEditor, options: {} }; + var selectedCodeEditor = null; + var initialised = false; + + function init() { + var codeEditorSettings = RED.editor.codeEditor.settings; + var editorChoice = codeEditorSettings.lib === MONACO ? MONACO : ACE; + try { + var browser = RED.utils.getBrowserInfo(); + selectedCodeEditor = RED.editor.codeEditor[editorChoice]; + //fall back to default code editor if there are any issues + if (!selectedCodeEditor || (editorChoice === MONACO && (browser.ie || !window.monaco))) { + selectedCodeEditor = RED.editor.codeEditor[defaultEditor]; + } + initialised = selectedCodeEditor.init(); + } catch (error) { + selectedCodeEditor = null; + console.warn("Problem initialising '" + editorChoice + "' code editor", error); + } + if(!initialised) { + selectedCodeEditor = RED.editor.codeEditor[defaultEditor]; + initialised = selectedCodeEditor.init(); + } + + $('

').appendTo('#red-ui-editor'); + $("#red-ui-image-drop-target").hide(); + } + + function create(options) { + //TODO: (quandry - for consideration) + // Below, I had to create a hidden element if options.id || options.element is not in the DOM + // I have seen 1 node calling `this.editor = RED.editor.createEditor()` with an + // invalid (non existing html element selector) (e.g. node-red-contrib-components does this) + // This causes monaco to throw an error when attempting to hook up its events to the dom & the rest of the 'oneditperapre' + // code is thus skipped. + // In ACE mode, creating an ACE editor (with an invalid ID) allows the editor to be created (but obviously there is no UI) + // Because one (or more) contrib nodes have left this bad code in place, how would we handle this? + // For compatibility, I have decided to create a hidden element so that at least an editor is created & errors do not occur. + // IMO, we should warn and exit as it is a coding error by the contrib author. + + if (!options) { + console.warn("createEditor() options are missing"); + options = {}; + } + + var editor = null; + if (this.editor.type === MONACO) { + // compatibility (see above note) + if (!options.element && !options.id) { + options.id = 'node-backwards-compatability-dummy-editor'; + } + options.element = options.element || $("#" + options.id)[0]; + if (!options.element) { + console.warn("createEditor() options.element or options.id is not valid", options); + $("#dialog-form").append('