From 8520e19309e9a4cd475291249ec9dfb662d63016 Mon Sep 17 00:00:00 2001 From: Iamasoldier <1272745473@qq.com> Date: Tue, 17 Jun 2025 09:39:52 +0800 Subject: [PATCH 01/10] =?UTF-8?q?feat:=E6=96=B0=E5=A2=9E=E8=AE=BE=E5=A4=87?= =?UTF-8?q?=E7=A6=BB=E7=BA=BF=E5=BC=82=E5=B8=B8=E9=80=BB=E8=BE=91=E5=A4=84?= =?UTF-8?q?=E7=90=86=EF=BC=8C=E5=90=8C=E6=97=B6=E6=96=B0=E5=A2=9E=E4=B8=8B?= =?UTF-8?q?=E5=8F=91=E8=AE=BE=E5=A4=87=E8=BF=94=E5=9B=9E=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E6=89=93=E5=8D=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../listener/OrderStatusChangeListener.java | 2 +- .../src/main/frontend/config/proxy.ts | 28 +++++++++---------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/zlt-business/order-center/src/main/java/com/central/order/listener/OrderStatusChangeListener.java b/zlt-business/order-center/src/main/java/com/central/order/listener/OrderStatusChangeListener.java index 17c8cb50..19fef809 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/listener/OrderStatusChangeListener.java +++ b/zlt-business/order-center/src/main/java/com/central/order/listener/OrderStatusChangeListener.java @@ -257,7 +257,7 @@ public class OrderStatusChangeListener { if (sysUser.getOpenId() != null) { - String tip = "订单退款完成"; + String tip = "检测到订单数据异常触发退款"; String orderName = tourism.getTourismName(); String pageUrl = "pages/task/task"; wxMiniSubscribeService.sendServiceProcessMsg( diff --git a/zlt-web/react-web/src/main/frontend/config/proxy.ts b/zlt-web/react-web/src/main/frontend/config/proxy.ts index 28ffaeca..61b5280f 100644 --- a/zlt-web/react-web/src/main/frontend/config/proxy.ts +++ b/zlt-web/react-web/src/main/frontend/config/proxy.ts @@ -9,23 +9,23 @@ export default { dev: { '/api-uaa/': { - // target: 'http://119.45.169.13:9900', - target: 'http://127.0.0.1:9900', + target: 'http://119.45.169.13:9900', + // target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-user/': { - // target: 'http://119.45.169.13:9900', - target: 'http://127.0.0.1:9900', + target: 'http://119.45.169.13:9900', + // target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-log/': { - // target: 'http://119.45.169.13:9900', - target: 'http://127.0.0.1:9900', + target: 'http://119.45.169.13:9900', + // target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-search/': { - // target: 'http://119.45.169.13:9900', - target: 'http://127.0.0.1:9900', + target: 'http://119.45.169.13:9900', + // target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-generator/': { @@ -34,18 +34,18 @@ changeOrigin: true, }, '/api-file/': { - // target: 'http://119.45.169.13:9900', - target: 'http://127.0.0.1:9900', + target: 'http://119.45.169.13:9900', + // target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-order/': { - // target: 'http://119.45.169.13:9900', - target: 'http://127.0.0.1:9900', + target: 'http://119.45.169.13:9900', + // target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-device/': { - // target: 'http://119.45.169.13:9900', - target: 'http://127.0.0.1:9900', + target: 'http://119.45.169.13:9900', + // target: 'http://127.0.0.1:9900', changeOrigin: true, }, }, From 1d92ed07495d669cee4ae4afaf332be4dc6ba866 Mon Sep 17 00:00:00 2001 From: Iamasoldier <1272745473@qq.com> Date: Tue, 17 Jun 2025 10:00:04 +0800 Subject: [PATCH 02/10] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E7=99=BB?= =?UTF-8?q?=E5=BD=95=E5=90=8E=E5=B7=A6=E4=BE=A7=E8=8F=9C=E5=8D=95=E4=B8=8D?= =?UTF-8?q?=E6=98=BE=E7=A4=BA=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../react-web/src/main/frontend/src/app.tsx | 79 ++++++++++--------- .../src/components/RightContent/index.tsx | 4 + .../main/frontend/src/locales/zh-CN/menu.ts | 2 +- .../main/frontend/src/models/useMessage.ts | 10 ++- .../src/main/frontend/src/pages/Welcome.less | 33 +++++--- .../src/main/frontend/src/pages/Welcome.tsx | 22 +++--- .../frontend/src/pages/user/Login/index.tsx | 54 +++++++++---- .../frontend/src/services/login/typings.d.ts | 2 + .../main/frontend/src/services/message/api.ts | 2 +- 9 files changed, 133 insertions(+), 75 deletions(-) diff --git a/zlt-web/react-web/src/main/frontend/src/app.tsx b/zlt-web/react-web/src/main/frontend/src/app.tsx index da9d7335..3ff85bc5 100644 --- a/zlt-web/react-web/src/main/frontend/src/app.tsx +++ b/zlt-web/react-web/src/main/frontend/src/app.tsx @@ -95,50 +95,56 @@ export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) = userId: initialState?.currentUser?.userId, }, request: async () => { - // initialState.currentUser 中包含了所有用户信息 - const menuData = await fetchMenuData(); + try { + // initialState.currentUser 中包含了所有用户信息 + const menuData = await fetchMenuData(); - const mapIcon = (css: string | undefined) => { - switch (css) { - case 'layui-icon-set': - return ; - case 'layui-icon-friends': - return ; - case 'layui-icon-user': - return ; - case 'layui-icon-menu-fill': - return ; - default: - return ; - } - }; + const mapIcon = (css: string | undefined) => { + switch (css) { + case 'layui-icon-set': + return ; + case 'layui-icon-friends': + return ; + case 'layui-icon-user': + return ; + case 'layui-icon-menu-fill': + return ; + default: + return ; + } + }; - const mapMenu = (value: API.Menu[]): MenuDataItem[] => { - return value.map((item) => { - return { - key: item.id + '', - name: item.name, - locale: false, - path: - item.path?.endsWith('.html') || item.path?.startsWith('http') - ? item.path - : undefined, - icon: mapIcon(item.css), - children: item.subMenus && mapMenu(item.subMenus), - }; - }); - }; - const menus = mapMenu(menuData); - return [ - { key: 'welcome', name: ' 首页', path: '/welcome', icon: }, - ...menus, - ]; + const mapMenu = (value: API.Menu[]): MenuDataItem[] => { + return value.map((item) => { + return { + key: item.id + '', + name: item.name, + locale: false, + path: + item.path?.endsWith('.html') || item.path?.startsWith('http') + ? item.path + : undefined, + icon: mapIcon(item.css), + children: item.subMenus && mapMenu(item.subMenus), + }; + }); + }; + const menus = mapMenu(menuData); + return [ + { key: 'welcome', name: '首页', path: '/welcome', icon: }, + ...menus, + ]; + } catch (error) { + console.error('获取菜单数据失败:', error); + return []; + } }, }, headerContentRender: () => { return ( + {/* 注释掉相关链接下拉菜单 + */} ); }, diff --git a/zlt-web/react-web/src/main/frontend/src/components/RightContent/index.tsx b/zlt-web/react-web/src/main/frontend/src/components/RightContent/index.tsx index b3aaa2f1..66e2a0ed 100644 --- a/zlt-web/react-web/src/main/frontend/src/components/RightContent/index.tsx +++ b/zlt-web/react-web/src/main/frontend/src/components/RightContent/index.tsx @@ -47,6 +47,7 @@ const GlobalHeaderRight: React.FC = () => { console.log('input', value); }} /> */} + {/* 注释掉帮助链接 { @@ -55,6 +56,8 @@ const GlobalHeaderRight: React.FC = () => { > + */} + {/* 注释掉GitHub链接 { @@ -63,6 +66,7 @@ const GlobalHeaderRight: React.FC = () => { > + */} history.push('/message')} diff --git a/zlt-web/react-web/src/main/frontend/src/locales/zh-CN/menu.ts b/zlt-web/react-web/src/main/frontend/src/locales/zh-CN/menu.ts index 4f640e8b..6cf7700b 100644 --- a/zlt-web/react-web/src/main/frontend/src/locales/zh-CN/menu.ts +++ b/zlt-web/react-web/src/main/frontend/src/locales/zh-CN/menu.ts @@ -1,5 +1,5 @@ export default { - 'menu.welcome': '欢迎', + 'menu.welcome': '首页', 'menu.more-blocks': '更多区块', 'menu.home': '首页', 'menu.admin': '管理页', diff --git a/zlt-web/react-web/src/main/frontend/src/models/useMessage.ts b/zlt-web/react-web/src/main/frontend/src/models/useMessage.ts index fc37796e..a9fe0d2d 100644 --- a/zlt-web/react-web/src/main/frontend/src/models/useMessage.ts +++ b/zlt-web/react-web/src/main/frontend/src/models/useMessage.ts @@ -1,10 +1,18 @@ import { useState, useEffect } from 'react'; import { getMessages } from '@/services/message/api'; +import { useModel } from 'umi'; export default () => { const [unreadCount, setUnreadCount] = useState(0); + const { initialState } = useModel('@@initialState'); const fetchUnreadCount = async () => { + // 如果未登录,不请求站内信 + if (!initialState?.currentUser) { + setUnreadCount(0); + return; + } + try { const response = await getMessages({ status: 0, pageSize: 1 }); setUnreadCount(response.total || 0); @@ -18,7 +26,7 @@ export default () => { // 设置定时刷新 const timer = setInterval(fetchUnreadCount, 60000); // 每分钟刷新一次 return () => clearInterval(timer); - }, []); + }, [initialState?.currentUser]); // 添加currentUser作为依赖,当登录状态改变时重新获取 return { unreadCount, diff --git a/zlt-web/react-web/src/main/frontend/src/pages/Welcome.less b/zlt-web/react-web/src/main/frontend/src/pages/Welcome.less index 9ded211c..42c4aed2 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/Welcome.less +++ b/zlt-web/react-web/src/main/frontend/src/pages/Welcome.less @@ -2,6 +2,10 @@ @import '~antd/es/style/themes/default.less'; .container { + padding: 24px; + background: #f0f2f5; + min-height: calc(100vh - 48px); + :global { .ant-card { border-radius: 8px; @@ -16,7 +20,8 @@ } .statCard { - height: 180px; + height: auto; + min-height: 180px; .statHeader { display: flex; @@ -35,10 +40,13 @@ display: flex; justify-content: space-between; align-items: flex-end; + flex-wrap: wrap; + gap: 16px; :global { .ant-statistic { flex: 1; + min-width: 120px; } .ant-progress { @@ -77,11 +85,11 @@ } .chartsRow { - margin-top: 16px; + margin-top: 24px; } .businessRow { - margin-top: 16px; + margin-top: 24px; } .rankList { @@ -127,13 +135,24 @@ // 响应式调整 @media screen and (max-width: 768px) { + .container { + padding: 16px; + } + .statCard { - height: auto; margin-bottom: 16px; } .chartsRow, .businessRow { - margin-top: 8px; + margin-top: 16px; + } + + .subStats { + :global { + .ant-statistic { + min-width: 100px; + } + } } } @@ -198,10 +217,6 @@ .ant-card-body { padding: 24px; } - - .ant-empty { - padding: 32px 0; - } } } diff --git a/zlt-web/react-web/src/main/frontend/src/pages/Welcome.tsx b/zlt-web/react-web/src/main/frontend/src/pages/Welcome.tsx index ad302e3f..b7096411 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/Welcome.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/Welcome.tsx @@ -89,7 +89,7 @@ const Welcome: React.FC = () => { smooth: true, animation: true, legend: { - position: 'top', + position: 'top' as const, }, areaStyle: { fillOpacity: 0.6, @@ -114,7 +114,7 @@ const Welcome: React.FC = () => { xField: 'type', yField: 'value', label: { - position: 'middle', + position: 'middle' as const, style: { fill: '#FFFFFF', opacity: 0.6, @@ -219,12 +219,12 @@ const Welcome: React.FC = () => { {/* 图表展示 */} - + - + @@ -233,17 +233,17 @@ const Welcome: React.FC = () => { {/* 业务数据 */} - - - + + + - - + +
- {(statistics.tourismRanking || []).map((item: any, index: number) => ( + {statistics.tourismRanking?.map((item: { id: string; name: string; value: number }, index: number) => (
- + {index + 1} {item.name} diff --git a/zlt-web/react-web/src/main/frontend/src/pages/user/Login/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/user/Login/index.tsx index fc226271..6792fa20 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/user/Login/index.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/user/Login/index.tsx @@ -3,7 +3,7 @@ import { login } from '@/services/login/api'; import { InfoCircleOutlined, LockOutlined, UserOutlined, AppstoreOutlined } from '@ant-design/icons'; import { LoginForm, ProFormCaptcha, ProFormText, ProFormCheckbox } from '@ant-design/pro-components'; import { message, Tooltip, Spin, Form } from 'antd'; -import React, { useState, useEffect } from 'react'; +import React, { useState, useEffect, useRef } from 'react'; import { FormattedMessage, history, useIntl, useModel } from 'umi'; import { v4 as uuidv4 } from 'uuid'; import styles from './index.less'; @@ -14,18 +14,27 @@ const Login: React.FC = () => { const { initialState, setInitialState } = useModel('@@initialState'); const intl = useIntl(); const [form] = Form.useForm(); + const mountedRef = useRef(true); + + useEffect(() => { + return () => { + mountedRef.current = false; + }; + }, []); const fetchUserInfo = async () => { try { const userInfo = await initialState?.fetchUserInfo?.(); - if (userInfo) { + if (userInfo && mountedRef.current) { await setInitialState((s) => ({ ...s, currentUser: userInfo, })); } } catch (error) { - message.error('获取用户信息失败'); + if (mountedRef.current) { + message.error('获取用户信息失败'); + } } }; @@ -42,7 +51,7 @@ const Login: React.FC = () => { // 自动填充缓存的租户标识 useEffect(() => { const clientId = getCachedTenantId(); - if (clientId) { + if (clientId && mountedRef.current) { form.setFieldsValue({ clientId, }); @@ -51,27 +60,36 @@ const Login: React.FC = () => { const handleSubmit = async (values: API.LoginParams) => { try { + if (!mountedRef.current) return; setLoading(true); const msg = await login({ ...values, deviceId: uuid }); - debugger; if (msg.resp_code === 0 && msg.data?.access_token) { sessionStorage.setItem('access_token', msg.data.access_token); - message.success('登录成功!'); - await fetchUserInfo(); - - const { query } = history.location; - const { redirect } = query as { redirect: string }; - history.push(redirect || '/'); - return; + if (mountedRef.current) { + message.success('登录成功!'); + await fetchUserInfo(); + await initialState?.fetchUserInfo?.(); + + const { query } = history.location; + const { redirect } = query as { redirect: string }; + history.push(redirect || '/'); + return; + } } - message.error(msg.resp_msg || '登录失败'); - setUuid(uuidv4()); + if (mountedRef.current) { + message.error(msg.resp_msg || '登录失败'); + setUuid(uuidv4()); + } } catch (error) { - message.error('登录失败,请重试!'); + if (mountedRef.current) { + message.error('登录失败,请重试!'); + } } finally { - setLoading(false); + if (mountedRef.current) { + setLoading(false); + } } }; @@ -151,6 +169,10 @@ const Login: React.FC = () => { onClick={() => setUuid(uuidv4())} /> )} + onGetCaptcha={async () => { + // 由于我们使用的是图片验证码,这里不需要实现 + return Promise.resolve(); + }} rules={[ { required: true, diff --git a/zlt-web/react-web/src/main/frontend/src/services/login/typings.d.ts b/zlt-web/react-web/src/main/frontend/src/services/login/typings.d.ts index e0835d3f..fc231cb9 100644 --- a/zlt-web/react-web/src/main/frontend/src/services/login/typings.d.ts +++ b/zlt-web/react-web/src/main/frontend/src/services/login/typings.d.ts @@ -6,12 +6,14 @@ declare namespace API { resp_code?: number; resp_msg?: number; datas?: T[]; + data?: T; }; type OptionalResult = { resp_code?: number; resp_msg?: number; datas?: T; + data?: T; }; type CurrentUser = SYSTEM.User & { diff --git a/zlt-web/react-web/src/main/frontend/src/services/message/api.ts b/zlt-web/react-web/src/main/frontend/src/services/message/api.ts index 4ab54c05..c282c431 100644 --- a/zlt-web/react-web/src/main/frontend/src/services/message/api.ts +++ b/zlt-web/react-web/src/main/frontend/src/services/message/api.ts @@ -3,7 +3,7 @@ import { request } from 'umi'; /** 获取消息列表 */ export async function getMessages(params: any) { const { current, pageSize, ...restParams } = params; - return request>('/api-order/messages', { + return request>('/api-order/messages', { method: 'GET', params: { page: params.page || 1, From 693be1d9e0fb8113b7d1fd2cb67d325df9826ff3 Mon Sep 17 00:00:00 2001 From: Iamasoldier <1272745473@qq.com> Date: Tue, 17 Jun 2025 10:14:30 +0800 Subject: [PATCH 03/10] =?UTF-8?q?fix:=20=E9=A6=96=E9=A1=B5=E7=99=BB?= =?UTF-8?q?=E5=BD=95=E9=A1=B5=E8=AF=B7=E6=B1=82=E5=BC=82=E5=B8=B8=E6=8F=90?= =?UTF-8?q?=E7=A4=BA=E6=96=87=E6=9C=AC=E5=AE=8C=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- zlt-web/react-web/src/main/frontend/src/app.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zlt-web/react-web/src/main/frontend/src/app.tsx b/zlt-web/react-web/src/main/frontend/src/app.tsx index 3ff85bc5..5a114862 100644 --- a/zlt-web/react-web/src/main/frontend/src/app.tsx +++ b/zlt-web/react-web/src/main/frontend/src/app.tsx @@ -305,7 +305,7 @@ export const request: RequestConfig = { adaptor: (resData) => { return { ...resData, - errorMessage: '请求错误', + errorMessage: '请重新登录', }; }, }, From 69f0e775a9c729f9bb71a6ac87eb95fc43f517f9 Mon Sep 17 00:00:00 2001 From: Iamasoldier <1272745473@qq.com> Date: Tue, 17 Jun 2025 17:06:35 +0800 Subject: [PATCH 04/10] =?UTF-8?q?feat:=E8=AE=BE=E5=A4=87=E8=BF=90=E7=BB=B4?= =?UTF-8?q?ops=E7=AE=A1=E7=90=86=E6=A8=A1=E5=9D=97=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=E6=96=B0=E5=A2=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/token/ApiTokenController.java | 19 +- zlt-business/device-ops-center/pom.xml | 146 +++ .../com/central/device/DeviceCenterApp.java | 22 + .../controller/AgeDeviceController.java | 273 +++++ .../AgeDeviceFirmwareController.java | 76 ++ .../controller/AgeDeviceHmsController.java | 76 ++ .../controller/AgeDeviceLogsController.java | 76 ++ .../AgeDevicePayloadController.java | 76 ++ .../AgeFirmwareModelController.java | 76 ++ .../controller/AgeWorkspaceController.java | 76 ++ .../controller/ApiDeviceController.java | 178 +++ .../device/controller/IaFileController.java | 76 ++ .../device/controller/LineFileController.java | 85 ++ .../device/controller/LineJobController.java | 76 ++ .../controller/LiveStreamController.java | 26 + .../device/controller/SFileController.java | 76 ++ .../controller/SFileIndexController.java | 76 ++ .../controller/token/ApiTokenController.java | 63 + .../device/feign/OrderCenterService.java | 33 + .../OrderCenterServiceFallbackFactory.java | 43 + .../device/listener/DeviceImportListener.java | 73 ++ .../mapper/AgeDeviceFirmwareMapper.java | 27 + .../device/mapper/AgeDeviceHmsMapper.java | 27 + .../device/mapper/AgeDeviceLogsMapper.java | 27 + .../device/mapper/AgeDeviceMapper.java | 45 + .../device/mapper/AgeDevicePayloadMapper.java | 27 + .../device/mapper/AgeFirmwareModelMapper.java | 27 + .../device/mapper/AgeWorkspaceMapper.java | 27 + .../central/device/mapper/IaFileMapper.java | 27 + .../central/device/mapper/LineFileMapper.java | 34 + .../central/device/mapper/LineJobMapper.java | 27 + .../device/mapper/SFileIndexMapper.java | 27 + .../central/device/mapper/SFileMapper.java | 27 + .../central/device/message/ControlEnum.java | 29 + .../message/ControlMessageConstant.java | 91 ++ .../device/message/iot说明#上报主题.md | 747 ++++++++++++ .../com/central/device/model/AgeDevice.java | 49 + .../device/model/AgeDeviceFirmware.java | 41 + .../central/device/model/AgeDeviceHms.java | 38 + .../central/device/model/AgeDeviceLogs.java | 35 + .../device/model/AgeDevicePayload.java | 38 + .../device/model/AgeFirmwareModel.java | 31 + .../central/device/model/AgeWorkspace.java | 34 + .../java/com/central/device/model/IaFile.java | 41 + .../com/central/device/model/LineFile.java | 41 + .../com/central/device/model/LineJob.java | 47 + .../java/com/central/device/model/SFile.java | 37 + .../com/central/device/model/SFileIndex.java | 36 + .../device/model/excel/AgeDeviceExcel.java | 174 +++ .../device/model/vo/DistributionDataVO.java | 16 + .../service/IAgeDeviceFirmwareService.java | 23 + .../device/service/IAgeDeviceHmsService.java | 23 + .../device/service/IAgeDeviceLogsService.java | 23 + .../service/IAgeDevicePayloadService.java | 23 + .../device/service/IAgeDeviceService.java | 44 + .../service/IAgeFirmwareModelService.java | 23 + .../device/service/IAgeWorkspaceService.java | 23 + .../device/service/IIaFileService.java | 23 + .../device/service/ILineFileService.java | 25 + .../device/service/ILineJobService.java | 23 + .../device/service/ISFileIndexService.java | 23 + .../central/device/service/ISFileService.java | 23 + .../device/service/LiveStreamService.java | 58 + .../impl/AgeDeviceFirmwareServiceImpl.java | 36 + .../service/impl/AgeDeviceHmsServiceImpl.java | 36 + .../impl/AgeDeviceLogsServiceImpl.java | 36 + .../impl/AgeDevicePayloadServiceImpl.java | 36 + .../service/impl/AgeDeviceServiceImpl.java | 91 ++ .../impl/AgeFirmwareModelServiceImpl.java | 36 + .../service/impl/AgeWorkspaceServiceImpl.java | 36 + .../service/impl/IaFileServiceImpl.java | 36 + .../service/impl/LineFileServiceImpl.java | 43 + .../service/impl/LineJobServiceImpl.java | 36 + .../service/impl/SFileIndexServiceImpl.java | 36 + .../device/service/impl/SFileServiceImpl.java | 36 + .../central/device/util/IotRequestResult.java | 37 + .../java/com/central/device/util/MapUtil.java | 52 + .../com/central/device/util/RequestUtils.java | 118 ++ .../central/device/util/TencentLiveUtil.java | 30 + .../java/com/central/device/util/Utils.java | 47 + .../central/device/util/http/HeaderUtils.java | 81 ++ .../central/device/util/http/HttpRequest.java | 39 + .../central/device/util/http/Response.java | 13 + .../device/util/http/SimpleHttpRequest.java | 184 +++ .../device/util/http/SimpleResponse.java | 26 + .../src/main/resources/application.yml | 59 + .../src/main/resources/bootstrap.yml | 15 + .../mapper/AgeDeviceFirmwareMapper.xml | 8 + .../resources/mapper/AgeDeviceHmsMapper.xml | 8 + .../resources/mapper/AgeDeviceLogsMapper.xml | 8 + .../main/resources/mapper/AgeDeviceMapper.xml | 8 + .../mapper/AgeDevicePayloadMapper.xml | 8 + .../mapper/AgeFirmwareModelMapper.xml | 8 + .../resources/mapper/AgeWorkspaceMapper.xml | 8 + .../main/resources/mapper/IaFileMapper.xml | 8 + .../main/resources/mapper/LineFileMapper.xml | 8 + .../main/resources/mapper/LineJobMapper.xml | 8 + .../resources/mapper/SFileIndexMapper.xml | 8 + .../src/main/resources/mapper/SFileMapper.xml | 8 + zlt-business/pom.xml | 2 + .../src/main/resources/application.yml | 4 + .../src/main/frontend/config/routes.ts | 38 + .../src/pages/device-ops/device/detail.tsx | 248 ++++ .../src/pages/device-ops/device/index.tsx | 470 ++++++++ .../src/pages/device-ops/group/index.tsx | 299 +++++ .../pages/device-ops/maintenance/index.tsx | 275 +++++ .../src/pages/device-ops/models/device.ts | 44 + .../src/pages/device-ops/monitor/index.tsx | 1021 +++++++++++++++++ .../src/pages/device-ops/services/api.ts | 32 + .../src/pages/device-ops/statistics/index.tsx | 282 +++++ .../src/main/frontend/src/services/device.ts | 48 + 111 files changed, 7999 insertions(+), 7 deletions(-) create mode 100644 zlt-business/device-ops-center/pom.xml create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/DeviceCenterApp.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceController.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceFirmwareController.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceHmsController.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceLogsController.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDevicePayloadController.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeFirmwareModelController.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeWorkspaceController.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/controller/ApiDeviceController.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/controller/IaFileController.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/controller/LineFileController.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/controller/LineJobController.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/controller/LiveStreamController.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/controller/SFileController.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/controller/SFileIndexController.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/controller/token/ApiTokenController.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/feign/OrderCenterService.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/feign/fallback/OrderCenterServiceFallbackFactory.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/listener/DeviceImportListener.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceFirmwareMapper.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceHmsMapper.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceLogsMapper.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceMapper.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDevicePayloadMapper.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeFirmwareModelMapper.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeWorkspaceMapper.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/mapper/IaFileMapper.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/mapper/LineFileMapper.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/mapper/LineJobMapper.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/mapper/SFileIndexMapper.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/mapper/SFileMapper.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/message/ControlEnum.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/message/ControlMessageConstant.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/message/iot说明#上报主题.md create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDevice.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceFirmware.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceHms.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceLogs.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDevicePayload.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeFirmwareModel.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeWorkspace.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/model/IaFile.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/model/LineFile.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/model/LineJob.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/model/SFile.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/model/SFileIndex.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/model/excel/AgeDeviceExcel.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/model/vo/DistributionDataVO.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceFirmwareService.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceHmsService.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceLogsService.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDevicePayloadService.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceService.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeFirmwareModelService.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeWorkspaceService.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/IIaFileService.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/ILineFileService.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/ILineJobService.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/ISFileIndexService.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/ISFileService.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/LiveStreamService.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceFirmwareServiceImpl.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceHmsServiceImpl.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceLogsServiceImpl.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDevicePayloadServiceImpl.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceServiceImpl.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeFirmwareModelServiceImpl.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeWorkspaceServiceImpl.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/IaFileServiceImpl.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/LineFileServiceImpl.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/LineJobServiceImpl.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/SFileIndexServiceImpl.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/SFileServiceImpl.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/util/IotRequestResult.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/util/MapUtil.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/util/RequestUtils.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/util/TencentLiveUtil.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/util/Utils.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/util/http/HeaderUtils.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/util/http/HttpRequest.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/util/http/Response.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/util/http/SimpleHttpRequest.java create mode 100644 zlt-business/device-ops-center/src/main/java/com/central/device/util/http/SimpleResponse.java create mode 100644 zlt-business/device-ops-center/src/main/resources/application.yml create mode 100644 zlt-business/device-ops-center/src/main/resources/bootstrap.yml create mode 100644 zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceFirmwareMapper.xml create mode 100644 zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceHmsMapper.xml create mode 100644 zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceLogsMapper.xml create mode 100644 zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceMapper.xml create mode 100644 zlt-business/device-ops-center/src/main/resources/mapper/AgeDevicePayloadMapper.xml create mode 100644 zlt-business/device-ops-center/src/main/resources/mapper/AgeFirmwareModelMapper.xml create mode 100644 zlt-business/device-ops-center/src/main/resources/mapper/AgeWorkspaceMapper.xml create mode 100644 zlt-business/device-ops-center/src/main/resources/mapper/IaFileMapper.xml create mode 100644 zlt-business/device-ops-center/src/main/resources/mapper/LineFileMapper.xml create mode 100644 zlt-business/device-ops-center/src/main/resources/mapper/LineJobMapper.xml create mode 100644 zlt-business/device-ops-center/src/main/resources/mapper/SFileIndexMapper.xml create mode 100644 zlt-business/device-ops-center/src/main/resources/mapper/SFileMapper.xml create mode 100644 zlt-web/react-web/src/main/frontend/src/pages/device-ops/device/detail.tsx create mode 100644 zlt-web/react-web/src/main/frontend/src/pages/device-ops/device/index.tsx create mode 100644 zlt-web/react-web/src/main/frontend/src/pages/device-ops/group/index.tsx create mode 100644 zlt-web/react-web/src/main/frontend/src/pages/device-ops/maintenance/index.tsx create mode 100644 zlt-web/react-web/src/main/frontend/src/pages/device-ops/models/device.ts create mode 100644 zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx create mode 100644 zlt-web/react-web/src/main/frontend/src/pages/device-ops/services/api.ts create mode 100644 zlt-web/react-web/src/main/frontend/src/pages/device-ops/statistics/index.tsx create mode 100644 zlt-web/react-web/src/main/frontend/src/services/device.ts diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/token/ApiTokenController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/token/ApiTokenController.java index 84330f00..7f582044 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/controller/token/ApiTokenController.java +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/token/ApiTokenController.java @@ -10,11 +10,13 @@ import com.central.device.util.http.Response; import com.central.device.util.http.SimpleHttpRequest; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; @@ -39,24 +41,27 @@ public class ApiTokenController { @Operation(summary = "客户端获取通信平台token") @GetMapping("/query") - public Result token() throws IOException { + public Result token(@RequestParam(required = false) String expires) throws IOException { - String url = jetlinksServiceUrl+"/token"; + if (StringUtils.isBlank(expires)) { + expires = String.valueOf(7200); + } + + String url = jetlinksServiceUrl + "/token"; HttpRequest request = new SimpleHttpRequest(url); - Map param = new HashMap<>(2); - param.put("expires",7200*24); + Map param = new HashMap<>(2); + param.put("expires", expires); request.headers(headerUtils.createHeadersOfJsonString(JSON.toJSONString(param))); request.requestBody(JSON.toJSONString(param)); - Response response = request.post(); Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); JSONObject jsonObject = JSON.parseObject(result.get("")); - Assert.notNull(jsonObject,"获取IOT数据异常"); + Assert.notNull(jsonObject, "获取IOT数据异常"); if (jsonObject.getString("message").equals("success")) { - return Result.succeed(jsonObject,"获取成功"); + return Result.succeed(jsonObject, "获取成功"); } return Result.failed("请重试"); } diff --git a/zlt-business/device-ops-center/pom.xml b/zlt-business/device-ops-center/pom.xml new file mode 100644 index 00000000..3d962348 --- /dev/null +++ b/zlt-business/device-ops-center/pom.xml @@ -0,0 +1,146 @@ + + + 4.0.0 + + com.zlt + zlt-business + 6.0.0 + + + device-ops-center + 设备运维中心 + + + 17 + 17 + UTF-8 + + + + + + com.zlt + zlt-config + + + com.zlt + zlt-log-spring-boot-starter + + + com.zlt + zlt-common-spring-boot-starter + + + com.zlt + zlt-db-spring-boot-starter + + + com.zlt + zlt-redis-spring-boot-starter + + + com.zlt + zlt-loadbalancer-spring-boot-starter + + + com.zlt + zlt-sentinel-spring-boot-starter + + + + com.github.xiaoymin + knife4j-openapi3-jakarta-spring-boot-starter + + + com.zlt + search-client + + + + org.springframework.boot + spring-boot-starter-web + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + org.springframework.boot + spring-boot-starter-actuator + + + + mysql + mysql-connector-java + + + + io.micrometer + micrometer-registry-prometheus + + + junit + junit + test + + + org.hibernate + hibernate-validator + + + + org.springframework.boot + spring-boot-starter-validation + + + cn.hutool + hutool-all + 5.8.25 + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + com.spotify + docker-maven-plugin + + ${docker.image.prefix}/${project.artifactId} + + ${project.version} + latest + + true + ${docker.baseImage} + ${docker.volumes} + + ${docker.java.opts} + + ["sh","-c","java $JAVA_OPTS ${docker.java.security.egd} -jar /${project.build.finalName}.jar"] + + + / + ${project.build.directory} + ${project.build.finalName}.jar + + + + + + ${project.artifactId} + + diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/DeviceCenterApp.java b/zlt-business/device-ops-center/src/main/java/com/central/device/DeviceCenterApp.java new file mode 100644 index 00000000..332428f6 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/DeviceCenterApp.java @@ -0,0 +1,22 @@ +package com.central.device; + +import com.central.common.lb.annotation.EnableFeignInterceptor; +import com.central.search.annotation.EnableSearchClient; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +/** + * @author 作者 lsl E-mail: 1272745473@qq.com + */ +@EnableDiscoveryClient +@EnableSearchClient +@EnableTransactionManagement +@EnableFeignInterceptor +@SpringBootApplication +public class DeviceCenterApp { + public static void main(String[] args) { + SpringApplication.run(DeviceCenterApp.class, args); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceController.java new file mode 100644 index 00000000..954ecc12 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceController.java @@ -0,0 +1,273 @@ +package com.central.device.controller; + +import cn.hutool.core.collection.CollUtil; +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.support.ExcelTypeEnum; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.device.model.AgeDevice; +import com.central.device.model.excel.AgeDeviceExcel; +import com.central.device.service.IAgeDeviceService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Device information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Slf4j +@RestController +@RequestMapping("/device") +@Tag(name = "设备管理") +@RequiredArgsConstructor +public class AgeDeviceController { + + + @Autowired + private IAgeDeviceService ageDeviceService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return ageDeviceService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + AgeDevice model = ageDeviceService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody AgeDevice ageDevice) { + ageDeviceService.saveOrUpdate(ageDevice); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + ageDeviceService.removeById(id); + return Result.succeed("删除成功"); + } + + /** + * 导出设备信息 + */ + @Operation(summary = "导出设备信息") + @PostMapping("/export") + public void exportDevices(@RequestBody Map params, HttpServletResponse response) { + try { + // 设置响应头 + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + String fileName = URLEncoder.encode("设备信息", StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20"); + response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); + + // 查询导出数据 + List deviceList = ageDeviceService.findListByParams(params); + if (CollUtil.isEmpty(deviceList)) { + deviceList = new ArrayList<>(); + } + + // 转换并写入Excel + List excelList = deviceList.stream() + .map(AgeDeviceExcel::fromDevice) + .collect(java.util.stream.Collectors.toList()); + + EasyExcel.write(response.getOutputStream(), AgeDeviceExcel.class) + .excelType(ExcelTypeEnum.XLSX) + .sheet("设备信息") + .doWrite(excelList); + + } catch (Exception e) { + log.error("导出设备信息失败", e); + // 重置response + response.reset(); + response.setContentType("application/json"); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + try { + response.getWriter().println("{\"code\":500,\"msg\":\"导出失败\"}"); + } catch (IOException ex) { + log.error("写入响应失败", ex); + } + } + } + + /** + * 导入设备信息 + */ + @Operation(summary = "导入设备信息") + @PostMapping("/import") + public Result importDevices(@RequestParam("file") MultipartFile file) { + try { + if (file.isEmpty()) { + return Result.failed("请选择要导入的文件"); + } + + // 文件大小校验(10MB) + if (file.getSize() > 10 * 1024 * 1024) { + return Result.failed("文件大小不能超过10MB"); + } + + // 文件类型校验 + String fileName = file.getOriginalFilename(); + if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) { + return Result.failed("请上传Excel文件"); + } + + // 读取Excel数据 + List excelList = EasyExcel.read(file.getInputStream()) + .head(AgeDeviceExcel.class) + .sheet() + .doReadSync(); + + if (CollUtil.isEmpty(excelList)) { + return Result.failed("导入数据为空"); + } + + // 数据校验和转换 + List errorMsgs = new ArrayList<>(); + List deviceList = new ArrayList<>(); + + for (int i = 0; i < excelList.size(); i++) { + AgeDeviceExcel excelData = excelList.get(i); + try { + // 数据校验 + validateExcelData(excelData, i + 1, errorMsgs); + if (errorMsgs.isEmpty()) { + deviceList.add(excelData.toDevice()); + } + } catch (Exception e) { + log.error("第{}行数据处理失败", i + 1, e); + errorMsgs.add(String.format("第%d行数据处理失败:%s", i + 1, e.getMessage())); + } + } + + if (!errorMsgs.isEmpty()) { + return Result.failed("导入失败:" + String.join("; ", errorMsgs)); + } + + // 批量保存数据 + boolean success = ageDeviceService.importDevices(deviceList); + return success ? Result.succeed("导入成功") : Result.failed("导入失败"); + + } catch (Exception e) { + log.error("导入设备信息失败", e); + return Result.failed("导入失败:" + e.getMessage()); + } + } + + @Operation(summary = "下载导入模板") + @GetMapping("/template") + public void downloadTemplate(HttpServletResponse response) { + try { + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + String fileName = URLEncoder.encode("设备导入模板", StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20"); + response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); + + // 创建模板数据 + List templateList = new ArrayList<>(); + // 可以添加一行示例数据 + AgeDeviceExcel template = new AgeDeviceExcel(); + template.setDeviceSn("示例:DEVICE001"); + template.setDeviceName("示例:测试设备1"); + templateList.add(template); + + EasyExcel.write(response.getOutputStream(), AgeDeviceExcel.class) + .excelType(ExcelTypeEnum.XLSX) + .sheet("设备信息") + .doWrite(templateList); + + } catch (Exception e) { + log.error("下载模板失败", e); + response.reset(); + response.setContentType("application/json"); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + try { + response.getWriter().println("{\"code\":500,\"msg\":\"下载模板失败\"}"); + } catch (IOException ex) { + log.error("写入响应失败", ex); + } + } + } + + /** + * 验证Excel数据 + */ + private void validateExcelData(AgeDeviceExcel excelData, int rowIndex, List errorMsgs) { + if (excelData == null) { + errorMsgs.add(String.format("第%d行数据为空", rowIndex)); + return; + } + + // 必填字段校验 + if (org.springframework.util.StringUtils.isEmpty(excelData.getDeviceSn())) { + errorMsgs.add(String.format("第%d行:设备序列号不能为空", rowIndex)); + } + if (org.springframework.util.StringUtils.isEmpty(excelData.getDeviceName())) { + errorMsgs.add(String.format("第%d行:设备名称不能为空", rowIndex)); + } + + // 字段格式校验 + if (excelData.getDeviceType() != null && (excelData.getDeviceType() < 0 || excelData.getDeviceType() > 100)) { + errorMsgs.add(String.format("第%d行:设备类型取值范围为0-100", rowIndex)); + } + + // 重复性校验 + if (!org.springframework.util.StringUtils.isEmpty(excelData.getDeviceSn())) { + boolean exists = ageDeviceService.checkDeviceSnExists(excelData.getDeviceSn()); + if (exists) { + errorMsgs.add(String.format("第%d行:设备序列号已存在", rowIndex)); + } + } + } + + private List convertToExcelList(List deviceList) { + return deviceList.stream().map(device -> { + AgeDeviceExcel excel = new AgeDeviceExcel(); + BeanUtils.copyProperties(device, excel); + return excel; + }).collect(Collectors.toList()); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceFirmwareController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceFirmwareController.java new file mode 100644 index 00000000..b317657e --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceFirmwareController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.AgeDeviceFirmware; +import com.central.device.service.IAgeDeviceFirmwareService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@RestController +@RequestMapping("/firmware") +@Tag(name = "Firmware file information") +@RequiredArgsConstructor +public class AgeDeviceFirmwareController { + private final IAgeDeviceFirmwareService ageDeviceFirmwareService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return ageDeviceFirmwareService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + AgeDeviceFirmware model = ageDeviceFirmwareService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody AgeDeviceFirmware ageDeviceFirmware) { + ageDeviceFirmwareService.saveOrUpdate(ageDeviceFirmware); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + ageDeviceFirmwareService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceHmsController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceHmsController.java new file mode 100644 index 00000000..0c0e4cd6 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceHmsController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.AgeDeviceHms; +import com.central.device.service.IAgeDeviceHmsService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * Device's hms information + * + * @author lsl + * @date 2024-12-19 17:53:01 + */ +@Slf4j +@RestController +@RequestMapping("/hms") +@Tag(name = "Device's hms information") +@RequiredArgsConstructor +public class AgeDeviceHmsController { + private final IAgeDeviceHmsService ageDeviceHmsService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return ageDeviceHmsService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + AgeDeviceHms model = ageDeviceHmsService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody AgeDeviceHms ageDeviceHms) { + ageDeviceHmsService.saveOrUpdate(ageDeviceHms); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + ageDeviceHmsService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceLogsController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceLogsController.java new file mode 100644 index 00000000..8526c968 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceLogsController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.AgeDeviceLogs; +import com.central.device.service.IAgeDeviceLogsService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * Log for uploading logs + * + * @author lsl + * @date 2024-12-19 17:53:03 + */ +@Slf4j +@RestController +@RequestMapping("/logs") +@Tag(name = "Log for uploading logs") +@RequiredArgsConstructor +public class AgeDeviceLogsController { + private final IAgeDeviceLogsService ageDeviceLogsService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return ageDeviceLogsService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + AgeDeviceLogs model = ageDeviceLogsService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody AgeDeviceLogs ageDeviceLogs) { + ageDeviceLogsService.saveOrUpdate(ageDeviceLogs); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + ageDeviceLogsService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDevicePayloadController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDevicePayloadController.java new file mode 100644 index 00000000..2bc7f5fa --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDevicePayloadController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.AgeDevicePayload; +import com.central.device.service.IAgeDevicePayloadService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * The payload information of the device. + * + * @author lsl + * @date 2024-12-19 17:53:19 + */ +@Slf4j +@RestController +@RequestMapping("/payload") +@Tag(name = "The payload information of the device.") +@RequiredArgsConstructor +public class AgeDevicePayloadController { + private final IAgeDevicePayloadService ageDevicePayloadService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return ageDevicePayloadService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + AgeDevicePayload model = ageDevicePayloadService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody AgeDevicePayload ageDevicePayload) { + ageDevicePayloadService.saveOrUpdate(ageDevicePayload); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + ageDevicePayloadService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeFirmwareModelController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeFirmwareModelController.java new file mode 100644 index 00000000..54c3446b --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeFirmwareModelController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.AgeFirmwareModel; +import com.central.device.service.IAgeFirmwareModelService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:53:20 + */ +@Slf4j +@RestController +@RequestMapping("/firmware/model") +@Tag(name = "") +@RequiredArgsConstructor +public class AgeFirmwareModelController { + private final IAgeFirmwareModelService ageFirmwareModelService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return ageFirmwareModelService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + AgeFirmwareModel model = ageFirmwareModelService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody AgeFirmwareModel ageFirmwareModel) { + ageFirmwareModelService.saveOrUpdate(ageFirmwareModel); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + ageFirmwareModelService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeWorkspaceController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeWorkspaceController.java new file mode 100644 index 00000000..56c9e747 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeWorkspaceController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.AgeWorkspace; +import com.central.device.service.IAgeWorkspaceService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:52:26 + */ +@Slf4j +@RestController +@RequestMapping("/workspace") +@Tag(name = "") +@RequiredArgsConstructor +public class AgeWorkspaceController { + private final IAgeWorkspaceService ageWorkspaceService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return ageWorkspaceService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + AgeWorkspace model = ageWorkspaceService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody AgeWorkspace ageWorkspace) { + ageWorkspaceService.saveOrUpdate(ageWorkspace); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + ageWorkspaceService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/ApiDeviceController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/ApiDeviceController.java new file mode 100644 index 00000000..b67da03f --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/ApiDeviceController.java @@ -0,0 +1,178 @@ +package com.central.device.controller; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.nacos.shaded.com.google.gson.Gson; +import com.alibaba.nacos.shaded.com.google.gson.JsonElement; +import com.alibaba.nacos.shaded.com.google.gson.JsonObject; +import com.central.common.model.Result; +import com.central.device.feign.OrderCenterService; +import com.central.device.message.ControlEnum; +import com.central.device.message.ControlMessageConstant; +import com.central.device.model.LineFile; +import com.central.device.service.ILineFileService; +import com.central.device.service.LiveStreamService; +import com.central.device.util.IotRequestResult; +import com.central.device.util.MapUtil; +import com.central.device.util.RequestUtils; +import com.fasterxml.jackson.core.JsonProcessingException; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * 设备操作controller + * @author lishilin + * @date 2024-12-31 + */ +@Tag(name = "MQTT设备管理") +@Slf4j +@RestController +public class ApiDeviceController { + + @Value("${jetlinks.server.baseUrl}") + private String baseUrl;// = "http://119.45.169.13:8848/"; + + @Autowired + private LiveStreamService liveStreamService; + + @Autowired + private RequestUtils requestUtils; + + private ControlMessageConstant controlMessageConstant = new ControlMessageConstant(); + + @Autowired + private OrderCenterService orderCenterService; + + @Autowired + private ILineFileService lineFileService; + /** + * 获取设备属性 + */ + @Operation(summary = "获取设备属性") + @GetMapping("/property/_query/{deviceId}/{property}") + public Result getProperty(@RequestParam Map param,@PathVariable("deviceId") String deviceId) throws IOException { + + //温度属性,属性在设备管理的设备型号中设置 + String property = MapUtil.getStrValue(param, "property"); + String url = baseUrl + "/device/" + deviceId + "/property/" + property; + + Map result = requestUtils.getGetRequestResultMap(url,new HashMap<>()); + return Result.succeed(result,"查询成功"); + + + } + + /** + * 设置设备属性测试 + */ + @Operation(summary = "设备属性设置") + @PostMapping("/setting/{deviceId}/property") + public Result writeProperties(@RequestBody Map param, @PathVariable("deviceId") String deviceId) { + log.info("开始设置设备属性: deviceId={}, param={}", deviceId, param); + try { + // 1. 参数校验 + String control = MapUtil.getStrValue(param, "control"); + String orderNo = MapUtil.getStrValue(param, "order_no"); + if (!validateParams(control, orderNo)) { + return Result.failed("参数错误"); + } + + // 2. 检查订单状态 + String orderStatus = orderCenterService.getOrderStatusByOrderNo(orderNo); + if (!isValidOrderStatus(orderStatus)) { + return Result.succeed("设备已执行"); + } + + // 3. 构建控制消息 + JsonObject controlMessage = buildControlMessage(control, orderNo, deviceId); + if (controlMessage == null) { + return Result.succeed("暂未开放控制权限"); + } + + // 4. 发送设备控制请求 + String url = baseUrl + "/device/instance/" + deviceId + "/property"; + Map result = requestUtils.getPostRequestResultMap(url, controlMessage.toString()); + + // 5. 处理响应结果 + return handleDeviceResponse(result, orderNo); + + } catch (Exception e) { + log.error("设置设备属性异常: deviceId={}, error={}", deviceId, e.getMessage(), e); + return Result.failed("系统异常"); + } + } + + private boolean validateParams(String control, String orderNo) { + return !StringUtils.isEmpty(control) && !StringUtils.isEmpty(orderNo); + } + + private boolean isValidOrderStatus(String orderStatus) { + return !StringUtils.isEmpty(orderStatus) && orderStatus.equals("1"); + } + + private JsonObject buildControlMessage(String control, String orderNo, String deviceId) { + if (!ControlEnum.contains(ControlEnum.valueOf(control.toUpperCase()))) { + return null; + } + + Gson gson = new Gson(); + JsonObject jsonObject = gson.fromJson(controlMessageConstant.CONTROL_MESSAGE_MAP.get(control), JsonObject.class); + JsonObject data = jsonObject.getAsJsonObject("data"); + // 设置订单信息 + data.addProperty("order_no", orderNo); + + // 获取航线信息 + Map wayResult = orderCenterService.getWaylineByOrderNo(orderNo); + String waylineFilePath = MapUtil.getStrValue(wayResult, "waylineFilePath"); + String waylineId = MapUtil.getStrValue(wayResult, "waylineId"); + log.info("waylineFilePath:{}, waylineId:{}", waylineFilePath, waylineId); + data.addProperty("wayline_link_url", waylineFilePath); + LineFile lineFile = lineFileService.findLineFileByWaylineId(waylineId); + Assert.notNull(lineFile,"航线文件签名不正确"); + data.addProperty("file_md5", lineFile.getSign()); + // 设置设备视频流地址 + try { + data.add("stream_urls", gson.fromJson(liveStreamService.generateStreamUrls(deviceId).toJSONString(), JsonElement.class)); + } catch (Exception e) { + log.error("生成设备推流/拉流地址异常: deviceId={}, error={}", deviceId, e.getMessage(), e); + data.addProperty("stream_urls", "{}"); // 或者空字符串 "" + } + + return jsonObject; + } + + private Result handleDeviceResponse(Map result, String orderNo) throws JsonProcessingException { + JSONObject object = JSONObject.parseObject(result.get("")); + if (object == null) { + return Result.failed("请求IOT平台异常"); + } + + IotRequestResult requestResult = IotRequestResult.getInstance(object); + if (requestResult.getStatus() == 200 || requestResult.getStatus() == 500) { + log.info("设置设备属性返回消息: message={}", requestResult.getMessage()); + if (requestResult.getMessage().equals("Device is offline")){ + return Result.failed("设备已离线请稍后重试"); + } + Result updateResult = orderCenterService.updateOrderStatusDoing(orderNo); + if (updateResult.getResp_code() != null && updateResult.getResp_code() == 0) { + return Result.succeed(updateResult.getData(), "设置成功"); + } + } + + return Result.failed("请重试"); + } + + @GetMapping("/device/wayline") + public Result getWayline(@RequestParam String no){ + return Result.succeed(orderCenterService.getWaylineByOrderNo(no)); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/IaFileController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/IaFileController.java new file mode 100644 index 00000000..1bf1806a --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/IaFileController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.IaFile; +import com.central.device.service.IIaFileService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * Media file information + * + * @author lsl + * @date 2024-12-19 17:52:18 + */ +@Slf4j +@RestController +@RequestMapping("/file") +@Tag(name = "Media file information") +@RequiredArgsConstructor +public class IaFileController { + private final IIaFileService iaFileService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return iaFileService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + IaFile model = iaFileService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody IaFile iaFile) { + iaFileService.saveOrUpdate(iaFile); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + iaFileService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LineFileController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LineFileController.java new file mode 100644 index 00000000..f0b072ed --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LineFileController.java @@ -0,0 +1,85 @@ +package com.central.device.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.device.model.LineFile; +import com.central.device.service.ILineFileService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +/** + * Wayline file information + * + * @author lsl + * @date 2024-12-19 17:51:52 + */ +@Slf4j +@RestController +@RequestMapping("/wayline") +@Tag(name = "Wayline file information") +@RequiredArgsConstructor +public class LineFileController { + private final ILineFileService lineFileService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return lineFileService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findById(@PathVariable String id) { + LineFile model = lineFileService.findLineFileByWaylineId(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/sign/{id}") + public String findLineSignById(@PathVariable String id) { + LineFile model = lineFileService.findLineFileByWaylineId(id); + return model.getSign(); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody LineFile lineFile) { + lineFileService.saveOrUpdate(lineFile); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + lineFileService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LineJobController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LineJobController.java new file mode 100644 index 00000000..3cc5af40 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LineJobController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.LineJob; +import com.central.device.service.ILineJobService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * Wayline mission information of the dock. + * + * @author lsl + * @date 2024-12-19 17:51:53 + */ +@Slf4j +@RestController +@RequestMapping("/linejob") +@Tag(name = "Wayline mission information of the dock.") +@RequiredArgsConstructor +public class LineJobController { + private final ILineJobService lineJobService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return lineJobService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + LineJob model = lineJobService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody LineJob lineJob) { + lineJobService.saveOrUpdate(lineJob); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + lineJobService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LiveStreamController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LiveStreamController.java new file mode 100644 index 00000000..04344b2a --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LiveStreamController.java @@ -0,0 +1,26 @@ +package com.central.device.controller; + +import com.alibaba.fastjson.JSONObject; +import com.central.common.model.Result; +import com.central.device.service.LiveStreamService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class LiveStreamController { + + @Autowired + private LiveStreamService liveStreamService; + + @GetMapping("/live/stream-urls") + public JSONObject getJsonStreamUrls(@RequestParam String deviceId) { + return liveStreamService.generateStreamUrls(deviceId); + } + + @GetMapping("/stream-urls") + public Result getStreamUrls(@RequestParam String deviceId) { + return Result.succeed(liveStreamService.generateStreamUrls(deviceId)); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/SFileController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/SFileController.java new file mode 100644 index 00000000..afd99353 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/SFileController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.SFile; +import com.central.device.service.ISFileService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * Logs file information + * + * @author lsl + * @date 2024-12-19 17:53:36 + */ +@Slf4j +@RestController +@RequestMapping("/sfile") +@Tag(name = "Logs file information") +@RequiredArgsConstructor +public class SFileController { + private final ISFileService sFileService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return sFileService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + SFile model = sFileService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody SFile sFile) { + sFileService.saveOrUpdate(sFile); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + sFileService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/SFileIndexController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/SFileIndexController.java new file mode 100644 index 00000000..c41912cb --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/SFileIndexController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.SFileIndex; +import com.central.device.service.ISFileIndexService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * The boot index table corresponding to the logs file. + * + * @author lsl + * @date 2024-12-19 17:53:23 + */ +@Slf4j +@RestController +@RequestMapping("/sfile/index") +@Tag(name = "The boot index table corresponding to the logs file.") +@RequiredArgsConstructor +public class SFileIndexController { + private final ISFileIndexService sFileIndexService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return sFileIndexService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + SFileIndex model = sFileIndexService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody SFileIndex sFileIndex) { + sFileIndexService.saveOrUpdate(sFileIndex); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + sFileIndexService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/token/ApiTokenController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/token/ApiTokenController.java new file mode 100644 index 00000000..84330f00 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/token/ApiTokenController.java @@ -0,0 +1,63 @@ +package com.central.device.controller.token; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.central.common.model.Result; +import com.central.device.util.Utils; +import com.central.device.util.http.HeaderUtils; +import com.central.device.util.http.HttpRequest; +import com.central.device.util.http.Response; +import com.central.device.util.http.SimpleHttpRequest; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * token获取 + * @author lishilin + * @date 2024-12-31 + */ +@Tag(name = "token获取") +@RestController +@RequestMapping("/token") +public class ApiTokenController { + + @Value("${jetlinks.server.baseUrl}") + private String jetlinksServiceUrl;//= "http://119.45.169.13:8848/"; + + @Autowired + private HeaderUtils headerUtils; + + @Operation(summary = "客户端获取通信平台token") + @GetMapping("/query") + public Result token() throws IOException { + + String url = jetlinksServiceUrl+"/token"; + + HttpRequest request = new SimpleHttpRequest(url); + + Map param = new HashMap<>(2); + param.put("expires",7200*24); + request.headers(headerUtils.createHeadersOfJsonString(JSON.toJSONString(param))); + request.requestBody(JSON.toJSONString(param)); + + + Response response = request.post(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + JSONObject jsonObject = JSON.parseObject(result.get("")); + Assert.notNull(jsonObject,"获取IOT数据异常"); + if (jsonObject.getString("message").equals("success")) { + return Result.succeed(jsonObject,"获取成功"); + } + return Result.failed("请重试"); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/feign/OrderCenterService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/feign/OrderCenterService.java new file mode 100644 index 00000000..448d65fd --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/feign/OrderCenterService.java @@ -0,0 +1,33 @@ +package com.central.device.feign; + +import com.central.common.constant.ServiceNameConstants; +import com.central.common.model.Result; +import com.central.device.feign.fallback.OrderCenterServiceFallbackFactory; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; + +import java.util.Map; + +/** + * user-center模块远程调用 + * + * @author lsl + * @version 1.0 + * @description user-center模块远程调用 + * @create 2025/1/13 + **/ +@FeignClient(name = ServiceNameConstants.ORDER_SERVICE, fallbackFactory = OrderCenterServiceFallbackFactory.class, dismiss404 = true) +public interface OrderCenterService { + + @PostMapping("/status") + Result updateOrderStatusDoing(@RequestBody String orderNo); + + @GetMapping("/{orderNo}/status") + String getOrderStatusByOrderNo(@PathVariable("orderNo") String orderNo); + + @GetMapping("/qrcode/wayline/{orderNo}") + Map getWaylineByOrderNo(@PathVariable("orderNo") String orderNo); +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/feign/fallback/OrderCenterServiceFallbackFactory.java b/zlt-business/device-ops-center/src/main/java/com/central/device/feign/fallback/OrderCenterServiceFallbackFactory.java new file mode 100644 index 00000000..80ad4c5f --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/feign/fallback/OrderCenterServiceFallbackFactory.java @@ -0,0 +1,43 @@ +package com.central.device.feign.fallback; + +import com.central.common.model.Result; +import com.central.device.feign.OrderCenterService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.openfeign.FallbackFactory; +import org.springframework.stereotype.Component; + +import java.util.Map; + +/** + * 任务中心调用失败回调 + * + * @author lsl + * @version 1.0 + * @description 任务中心调用失败回调 + * @create 2025/1/17 11:33 + **/ +@Slf4j +@Component +public class OrderCenterServiceFallbackFactory implements FallbackFactory { + + + @Override + public OrderCenterService create(Throwable cause) { + return new OrderCenterService() { + @Override + public Result updateOrderStatusDoing(String orderNo) { + return null; + } + + @Override + public String getOrderStatusByOrderNo(String orderNo) { + return ""; + } + + @Override + public Map getWaylineByOrderNo(String orderNo) { + return null; + } + }; + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/listener/DeviceImportListener.java b/zlt-business/device-ops-center/src/main/java/com/central/device/listener/DeviceImportListener.java new file mode 100644 index 00000000..74a01388 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/listener/DeviceImportListener.java @@ -0,0 +1,73 @@ +package com.central.device.listener; + +import com.alibaba.excel.context.AnalysisContext; +import com.alibaba.excel.read.listener.ReadListener; +import com.central.device.model.AgeDevice; +import com.central.device.model.excel.AgeDeviceExcel; +import com.central.device.service.IAgeDeviceService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +@Slf4j +@RequiredArgsConstructor +public class DeviceImportListener implements ReadListener { + private final IAgeDeviceService deviceService; + private final List deviceList = new ArrayList<>(); + private static final int BATCH_COUNT = 100; + + @Override + public void invoke(AgeDeviceExcel data, AnalysisContext context) { + log.info("解析到一条数据: {}", data); + + // 数据校验 + validateData(data); + + // 转换为实体 + AgeDevice device = data.toDevice(); + + // 设置默认值 + if (device.getCreateTime() == null) { + device.setCreateTime(new Date()); + } + device.setUpdateTime(new Date()); + + deviceList.add(device); + + if (deviceList.size() >= BATCH_COUNT) { + saveData(); + deviceList.clear(); + } + } + + @Override + public void doAfterAllAnalysed(AnalysisContext context) { + saveData(); + log.info("所有数据解析完成!"); + } + + private void validateData(AgeDeviceExcel data) { + if (StringUtils.isEmpty(data.getDeviceSn())) { + throw new IllegalArgumentException("设备序列号不能为空"); + } + if (StringUtils.isEmpty(data.getDeviceName())) { + throw new IllegalArgumentException("设备名称不能为空"); + } + // 检查设备序列号是否已存在 + AgeDevice existDevice = deviceService.getByDeviceSn(data.getDeviceSn()); + if (existDevice != null) { + throw new IllegalArgumentException("设备序列号已存在:" + data.getDeviceSn()); + } + } + + private void saveData() { + if (!deviceList.isEmpty()) { + log.info("开始保存数据,数量:{}", deviceList.size()); + deviceService.saveBatch(deviceList); + } + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceFirmwareMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceFirmwareMapper.java new file mode 100644 index 00000000..b85f42d8 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceFirmwareMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.AgeDeviceFirmware; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Mapper +public interface AgeDeviceFirmwareMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceHmsMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceHmsMapper.java new file mode 100644 index 00000000..2c77e129 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceHmsMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.AgeDeviceHms; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * Device's hms information + * + * @author lsl + * @date 2024-12-19 17:53:01 + */ +@Mapper +public interface AgeDeviceHmsMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceLogsMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceLogsMapper.java new file mode 100644 index 00000000..e6f23dc6 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceLogsMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.AgeDeviceLogs; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * Log for uploading logs + * + * @author lsl + * @date 2024-12-19 17:53:03 + */ +@Mapper +public interface AgeDeviceLogsMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceMapper.java new file mode 100644 index 00000000..9ac2fd69 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceMapper.java @@ -0,0 +1,45 @@ +package com.central.device.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.device.model.AgeDevice; +import com.central.device.model.vo.DistributionDataVO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; +import java.util.Map; + +/** + * Device information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Mapper +public interface AgeDeviceMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); + + @Select("SELECT COUNT(*) FROM manage_device WHERE is_del = 0") + Long getTotalDevices(); + + @Select("SELECT COUNT(*) FROM manage_device WHERE is_del = 0 AND status = 1") + Long getOnlineDevices(); + + @Select({ + "SELECT", + " device_type as type,", + " COUNT(*) as value", + "FROM manage_device", + "WHERE is_del = 0", + "GROUP BY device_type" + }) + List getDeviceDistribution(); +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDevicePayloadMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDevicePayloadMapper.java new file mode 100644 index 00000000..35ffe43c --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDevicePayloadMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.AgeDevicePayload; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * The payload information of the device. + * + * @author lsl + * @date 2024-12-19 17:53:19 + */ +@Mapper +public interface AgeDevicePayloadMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeFirmwareModelMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeFirmwareModelMapper.java new file mode 100644 index 00000000..7ee21448 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeFirmwareModelMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.AgeFirmwareModel; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:53:20 + */ +@Mapper +public interface AgeFirmwareModelMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeWorkspaceMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeWorkspaceMapper.java new file mode 100644 index 00000000..7da5231e --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeWorkspaceMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.AgeWorkspace; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:52:26 + */ +@Mapper +public interface AgeWorkspaceMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/IaFileMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/IaFileMapper.java new file mode 100644 index 00000000..2b92b51a --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/IaFileMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.IaFile; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * Media file information + * + * @author lsl + * @date 2024-12-19 17:52:18 + */ +@Mapper +public interface IaFileMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/LineFileMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/LineFileMapper.java new file mode 100644 index 00000000..1818583a --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/LineFileMapper.java @@ -0,0 +1,34 @@ +package com.central.device.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.device.model.LineFile; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; +import java.util.Map; + +/** + * Wayline file information + * + * @author lsl + * @date 2024-12-19 17:51:52 + */ +@Mapper +public interface LineFileMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); + + @Select("SELECT COUNT(*) FROM wayline_file WHERE is_del = 0") + Long getTotalWaylines(); + + @Select("SELECT COUNT(*) FROM wayline_file WHERE is_del = 0 AND last_use_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)") + Long getActiveWaylines(); +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/LineJobMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/LineJobMapper.java new file mode 100644 index 00000000..f3ccce11 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/LineJobMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.LineJob; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * Wayline mission information of the dock. + * + * @author lsl + * @date 2024-12-19 17:51:53 + */ +@Mapper +public interface LineJobMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/SFileIndexMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/SFileIndexMapper.java new file mode 100644 index 00000000..06d359d9 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/SFileIndexMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.SFileIndex; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * The boot index table corresponding to the logs file. + * + * @author lsl + * @date 2024-12-19 17:53:23 + */ +@Mapper +public interface SFileIndexMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/SFileMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/SFileMapper.java new file mode 100644 index 00000000..793235b3 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/SFileMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.SFile; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * Logs file information + * + * @author lsl + * @date 2024-12-19 17:53:36 + */ +@Mapper +public interface SFileMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/message/ControlEnum.java b/zlt-business/device-ops-center/src/main/java/com/central/device/message/ControlEnum.java new file mode 100644 index 00000000..5d5c0c07 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/message/ControlEnum.java @@ -0,0 +1,29 @@ +package com.central.device.message; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public enum ControlEnum { + RETURN_HOME("return_home"), + TAKEOFF_TO_POINT("takeoff_to_point"), + FLY_TO_POINT("fly_to_point"), + FLY_TO_POINT_STOP("fly_to_point_stop"), + FLY_TO_POINT_UPDATE("fly_to_point_stop"), + FLIGHTTASK_PAUSE("flighttask_pause"), + FLIGHTTASK_PREPARE ("flighttask_prepare"), + FLIGHTTASK_RECOVERY( "flighttask_recovery"); + + private final String name; + + // 静态方法:检查某个参数是否是枚举的一个实例 + public static boolean contains(ControlEnum value) { + for (ControlEnum v : ControlEnum.values()) { + if (v == value) { + return true; + } + } + return false; + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/message/ControlMessageConstant.java b/zlt-business/device-ops-center/src/main/java/com/central/device/message/ControlMessageConstant.java new file mode 100644 index 00000000..15ac1d6c --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/message/ControlMessageConstant.java @@ -0,0 +1,91 @@ +package com.central.device.message; + +import lombok.Getter; + +import java.util.HashMap; +import java.util.Map; + + +@Getter +public class ControlMessageConstant { + + + public final static String TAKEOFF_TO_POINT = "{\n" + + " \"data\": {\n" + + "\t \"flight_id\": flight_id,\n" + + "\t \"max_speed\": 5,\n" + + "\t \"rc_lost_action\": 2,\n" + + "\t \"rth_altitude\": 60.0,\n" + + "\t \"rth_mode\": 1,\n" + + "\t \"security_takeoff_height\": 60.0,\n" + + "\t \"target_height\": 70.0,\n" + + "\t \"target_latitude\": 39.102603,\n" + + "\t \"target_longitude\": 117.711972,\n" + + "\t \"commander_mode_lost_action\": 0,\n" + + "\t \"commander_flight_mode\": 1,\n" + + "\t \"commander_flight_height\": 70.0,\n" + + "\t \"simulate_mission\": {\n" + + "\t },\n" + + "\t \"flight_safety_advance_check\": 0\n" + + "\t},\n" + + "\t\"method\": \"takeoff_to_point\"\n" + + "}"; + + public final static String FLY_TO_ID = "{\n" + + "\t\"data\": {\n" + + "\t\t\"fly_to_id\": \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx\",\n" + + "\t\t\"max_speed\": 12,\n" + + "\t\t\"points\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"height\": 100,\n" + + "\t\t\t\t\"latitude\": 12.23,\n" + + "\t\t\t\t\"longitude\": 12.23\n" + + "\t\t\t}\n" + + "\t\t]\n" + + "\t},\n" + + "\t\"method\": \"fly_to_point\"\n" + + "}"; + public final static String FLY_TO_ID_STOP = "{\n" + + "\t\"data\": {},\n" + + "\t\"method\": \"fly_to_point_stop\"\n" + + "}"; + public final static String FLY_TO_POINT_UPDATE = "{\n" + + "\t\"data\": {\n" + + "\t\t\"max_speed\": 12,\n" + + "\t\t\"points\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"height\": 100,\n" + + "\t\t\t\t\"latitude\": 12.23,\n" + + "\t\t\t\t\"longitude\": 12.23\n" + + "\t\t\t}\n" + + "\t\t]\n" + + "\t},\n" + + "\t\"method\": \"fly_to_point_update\"\n" + + "}"; + public final static String RETURN_HOME = "{\n" + + "\t\"data\": {},\n" + + "\t\"method\": \"return_home\"\n" + + "}"; + + public final static String FLIGHTTASK_PAUSE = "{\"data\": {}, \"method\": \"flighttask_pause\"}"; + + public final static String FLIGHTTASK_PREPARE = "{\"data\": {},\"method\": \"flighttask_prepare\"}"; + + public final static String FLIGHTTASK_RECOVERY = "{\"data\": {}, \"method\": \"flighttask_recovery\"}"; + + public Map CONTROL_MESSAGE_MAP + = new HashMap(); + + public ControlMessageConstant(){ + CONTROL_MESSAGE_MAP.put("fly_to_point_stop", FLY_TO_ID_STOP); + CONTROL_MESSAGE_MAP.put("fly_to_point", FLY_TO_ID); + CONTROL_MESSAGE_MAP.put("fly_to_point_update", FLY_TO_POINT_UPDATE); + CONTROL_MESSAGE_MAP.put("flighttask_pause", FLIGHTTASK_PAUSE); + CONTROL_MESSAGE_MAP.put("flighttask_prepare", FLIGHTTASK_PREPARE); + CONTROL_MESSAGE_MAP.put("return_home", RETURN_HOME); + CONTROL_MESSAGE_MAP.put("flighttask_recovery", FLIGHTTASK_RECOVERY); + + } + + +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/message/iot说明#上报主题.md b/zlt-business/device-ops-center/src/main/java/com/central/device/message/iot说明#上报主题.md new file mode 100644 index 00000000..b515d017 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/message/iot说明#上报主题.md @@ -0,0 +1,747 @@ +# iot说明 + +# 上报主题说明: + +设备运行日志上报主题:/fire_alarm + +# 上报内容: + +## 状态包: + +| home_position_is_valid | Home 点有效性 | enum_int | {"0":"无效","1":"有效"} | | r | 0 | +| --- | --- | --- | --- | --- | --- | --- | +| heading | 机场朝向角 | double | {"max":"180","min":"-180","step":"","unit_name":"度 / °"} | | r | 0 | +| rtcm_info | 机场 RTK 标定源 | struct | | | r | 1 | +| »mount_point | 网络 RTK 挂载点信息 | text | | | | 0 | +| »port | 网络端口信息 | text | | | | 0 | +| »host | 网络 host 信息 | text | | | | 0 | +| »rtcm_device_type | 设备类型 | enum_int | {"1":"机场"} | | | 0 | +| »source_type | 标定类型 | enum_int | {"0":"未标定","1":"自收敛标定","2":"手动标定","3":"网络RTK标定"} | | | 0 | +| wireless_link_topo | 图传连接拓扑 | struct | | | r | 1 | +| »secret_code | 加密编码 | array | {"size": 28, "item_type": int} | | | 0 | +| »center_node | 飞行器对频信息 | struct | | | | 0 | +| »»sdr_id | 扰码信息 | int | | | | 0 | +| »»sn | 设备sn | text | | | | 0 | +| »leaf_nodes | 机场或遥控器对频信息 | array | {"size": -, "item_type": struct} | | | 0 | +| »»sdr_id | 扰码信息 | int | | | | 0 | +| »»sn | 设备sn | text | | | | 0 | +| »»control_source_index | 控制源序号 | int | {"max":"2","min":"1","step":"1","unit_name":"无 / "} | | | 0 | +| air_conditioner | 机场空调工作状态信息 | struct | | | r | 0 | +| »air_conditioner_state | 机场空调状态 | enum_int | {"0":"空闲模式(无制冷、制热、除湿等)","1":"制冷模式","2":"制热模式","3":"除湿模式","4":"制冷退出模式","5":"制热退出模式","6":"除湿退出模式","7":"制冷准备模式","8":"制热准备模式","9":"除湿准备模式"} | 机场空调工作状态信息,空调仅存在一种工作模式 | | 0 | +| »switch_time | 剩余等待可切换时间 | int | {"unit_name":"秒 / s"} | 空调状态顺序为准备模式切换到工作状模式、随后可操作后切换到退出模式、退出完成后切换到空闲模式,因此本物模型表示进行某个指令操作后还需要多久可以切换至下一状态。例如当前为空闲状态,开启制冷模式后将进入制冷准备模式,则本时间表示还需要多久可以进入制冷工作模式。以此类推 | | 0 | +| air_transfer_enable | 空中回传 | bool | {"false":"关闭","true":"开启"} | 用户在指令飞行过程中拍照的照片快速回传至云端 | rw | 1 | +| silent_mode | 机场静音模式 | enum_int | {"0":"非静音模式","1":"静音模式"} | 开启静音模式,意味着:1. 风扇转速降低、空调制冷性能下降、炎热天气下作业间隔变长。2. 蜂鸣器声音将关闭,开关舱盖时请注意周围安全。3. 机场待机状态的白色指示灯关闭,其他运行状态的指示灯正常。 | rw | 1 | +| user_experience_improvement | 用户体验改善计划 | enum_int | {"0":"初始状态","1":"拒绝加入用户体验改善计划","2":"同意加入用户体验改善计划"} | | rw | 1 | +| dongle_infos | 4G Dongle信息 | array | {"size": -, "item_type": struct} | | r | 1 | +| »imei | dongle imei | text | | Dongle 的唯一识别标志 | r | 0 | +| »dongle_type | Dongle 类型 | enum_int | {"6":"旧 Dongle","10":"支持 eSIM 的新 Dongle"} | Dongle 类型 | r | 0 | +| »eid | dongle eid | text | | eSIM 的唯一识别标志,用于公众号查询套餐、购买服务 | r | 0 | +| »esim_activate_state | eSIM 激活状态 | enum_int | {"0":"未激活","1":"已激活"} | 需要激活才能使用 | r | 0 | +| »sim_card_state | SIM 卡状态 | enum_int | {"0":"未插入","1":"已插入"} | Dongle 中实体 SIM 卡的插入状态 | r | 0 | +| »sim_slot | SIM 卡槽使能状态 | enum_int | {"0":"未知","1":"实体 SIM 卡","2":"eSIM"} | 标识 Dongle 当前正在使用的 SIM 卡槽 | r | 0 | +| »esim_infos | eSIM 信息 | array | {"size": -, "item_type": struct} | | r | 0 | +| »»telecom_operator | 支持的运营商 | enum_int | {"0":"未知","1":"移动","2":"联通","3":"电信"} | eSIM 支持的运营商 | r | 0 | +| »»enabled | eSIM 使能状态 | bool | {"false":"未使用","true":"使用中"} | 同时刻只能有一个 eSIM 是使能的 | r | 0 | +| »»iccid | sim iccid | text | | SIM 卡的唯一识别标志,可以用于实体 SIM 卡的套餐购买 | r | 0 | +| »sim_info | SIM 卡信息 | struct | | 可插入 Dongle 的实体 SIM 卡信息 | r | 0 | +| »»telecom_operator | 支持的运营商 | enum_int | {"0":"未知","1":"移动","2":"联通","3":"电信"} | SIM 卡支持的运营商 | r | 0 | +| »»sim_type | SIM 卡类型 | enum_int | {"0":"未知","1":"其他普通 SIM 卡","2":"三网卡"} | 实体 SIM 卡的类型 | r | 0 | +| »»iccid | sim iccid | text | | SIM 卡的唯一识别标志,可以用于实体 SIM 卡的套餐购买 | r | 0 | +| drone_battery_maintenance_info | 飞行器电池保养信息 | struct | | | | 0 | +| »maintenance_state | 保养状态 | enum_int | {"0":"无需保养","1":"待保养","2":"正在保养"} | | | 0 | +| »maintenance_time_left | 电池保养剩余时间 | int | {"unit_name":"小时 / h"} | 向下取整 | | 0 | +| »heat_state | 电池加热保温状态 | enum_int | {"0":"电池未开启加热或保温","1":"电池在加热中","2":"电池在保温中"} | 当飞行器舱内关机时由本物模型上报机场连接飞行器的电池加热保温信息 | | 0 | +| »batteries | 电池详细信息 | array | {"size": -, "item_type": struct} | 当飞行器舱内关机时由本物模型上报机场连接飞行器的电池信息,基本数据与飞行器物模型中电池信息基本保持一致 | | 0 | +| »»capacity_percent | 电池剩余电量 | int | {"max":100,"min":0} | 保留小数点后一位,正常范围0-100,设备端获取不到数据的异常值为 32767 | | 0 | +| »»index | 电池序号 | enum_int | {"0":"左电池","1":"右电池"} | | | 0 | +| »»voltage | 电压 | int | {"unit_name":"毫伏 / mV"} | 正常范围0-28000mV,设备端获取不到数据的异常值为32767 | | 0 | +| »»temperature | 温度 | float | {"unit_name":"摄氏度 / °C"} | 保留小数点后一位,正常范围-40-150°C,设备端获取不到数据的异常值为32767 | | 0 | +| air_conditioner | 机场空调工作状态信息 | struct | | | r | 0 | +| »air_conditioner_state | 机场空调状态 | enum_int | {"0":"空闲模式(无制冷、制热、除湿等)","1":"制冷模式","2":"制热模式","3":"除湿模式","4":"制冷退出模式","5":"制热退出模式","6":"除湿退出模式","7":"制冷准备模式","8":"制热准备模式","9":"除湿准备模式"} | 机场空调工作状态信息,空调仅存在一种工作模式 | | 0 | +| »switch_time | 剩余等待可切换时间 | int | {"unit_name":"秒 / s"} | 模式切换顺序为准备模式、工作(制冷、制热、除湿)模式、退出模式、空闲模式。本属性将上报,可以切换下一个模式指令还需要等待的时间。例如当前机场空调在进入制冷模式后,必须制冷5分钟后才可以退出制冷模式,本属性将上报还需要多久退出制冷模式,为0表示随时可退出 | | 0 | +| maintain_status | 保养信息 | struct | | | r | 0 | +| »maintain_status_array | 保养信息数组 | array | {"size": -, "item_type": struct} | | | 0 | +| »»state | 保养状态 | enum_int | {"0":"无保养","1":"有保养"} | | | 0 | +| »»last_maintain_type | 上一次保养类型 | enum_int | {"0":"无保养","17":"机场常规保养","18":"机场深度保养"} | | | 0 | +| »»last_maintain_time | 上一次保养时间 | date | {"unit_name":"秒 / s"} | | | 0 | +| »»last_maintain_work_sorties | 上一次保养时作业架次 | int | {"max":"2147483647","min":"0","step":"1"} | | | 0 | +| position_state | 搜星状态 | struct | | | r | 0 | +| »is_calibration | 是否标定 | enum_int | {"0":"未标定","1":"已标定"} | | | 0 | +| »is_fixed | 是否收敛 | enum_int | {"0":"未开始","1":"收敛中","2":"收敛成功","3":"收敛失败"} | | | 0 | +| »quality | 搜星档位 | enum_int | {"1":"1档","2":"2档","3":"3档","4":"4档","5":"5档","10":"RTK fixed"} | | | 0 | +| »gps_number | GPS 搜星数量 | int | | | | 0 | +| »rtk_number | RTK 搜星数量 | int | | | | 0 | +| emergency_stop_state | 紧急停止按钮状态 | enum_int | {"0":"关闭","1":"开启"} | | r | 0 | +| drone_charge_state | 飞行器充电状态 | struct | | 飞行器充电状态 | r | 0 | +| »capacity_percent | 电量百分比 | int | {"max":"100","min":"0"} | | | 0 | +| »state | 充电状态 | enum_int | {"0":"空闲","1":"充电中"} | | | 0 | +| backup_battery | 机场备用电池信息 | struct | | | r | 0 | +| »switch | 备用电池开关 | enum_int | {"0":"关闭","1":"开启"} | | | 0 | +| »voltage | 备用电池电压 | int | {"desc":"备用电池关闭时电压为0","max":"30000","min":"0","step":"1","unit_name":"毫伏 / mV"} | | | 0 | +| »temperature | 备用电池温度 | float | {"step":"0.1","unit_name":"摄氏度 / °C"} | 保留小数点后一位 | | 0 | +| alarm_state | 机场声光报警状态 | enum_int | {"0":"关闭","1":"开启"} | | r | 0 | +| battery_store_mode | 电池运行模式 | enum_int | {"1":"计划模式","2":"待命模式"} | 计划模式适合规律作业场景,无任务时电池电量保持在55%~60%,电池寿命较长。待命模式适合应急作业场景,无任务时电池电量保持在90%~95%,电池寿命较短。 | r | 0 | +| activation_time | 机场激活时间(unix 时间戳) | int | {"unit_name":"秒 / s"} | | r | 0 | +| height | 椭球高度 | double | {"unit_name":"米 / m"} | | r | 0 | +| alternate_land_point | 备降点 | struct | | | r | 0 | +| »longitude | 经度 | float | {} | | | 0 | +| »latitude | 纬度 | float | {} | | | 0 | +| »safe_land_height | 安全高度(备降转移高) | float | {} | | | 0 | +| »is_configured | 是否设置备降点 | enum_int | {"0":"未设置","1":"已设置"} | | | 0 | +| »height | 椭球高度 | float | | | | 0 | +| compatible_status | 固件一致性 | enum_int | {"0":"不需要一致性升级","1":"需要一致性升级"} | 一致性升级:指飞行器某些模块的固件版本与系统匹配版本不一致,需要进行升级。常见的情况例如:飞行器与遥控器已经升级至最新版本,但替换电池时发现电池未升级,此时一致性升级将被提示。普通升级:开发者将飞行器所有模块升级至指定固件版本。 | r | 1 | +| acc_time | 机场累计运行时长 | int | {"unit_name":"秒 / s"} | | r | 1 | +| first_power_on | 首次上电时间 | int | {"unit_name":"毫秒 / ms"} | | r | 0 | +| storage | 存储容量 | struct | | | r | 0 | +| »total | 总容量 | int | {"unit_name":"千字节 / KB"} | | | 0 | +| »used | 已使用容量 | int | {"unit_name":"千字节 / KB"} | | | 0 | +| working_current | 工作电流 | float | {"unit_name":"毫安 / mA"} | | r | 0 | +| working_voltage | 工作电压 | int | {"unit_name":"毫伏 / mV"} | | r | 0 | +| humidity | 舱内湿度 | float | {"max":"100","min":"0","step":"0.1","unit_name":"相对湿度 / %RH"} | | r | 0 | +| temperature | 舱内温度 | float | {"unit_name":"摄氏度 / °C"} | | r | 0 | +| environment_temperature | 环境温度 | float | {"unit_name":"摄氏度 / °C"} | | r | 0 | +| wind_speed | 风速 | float | {"unit_name":"米每秒 / m/s"} | | r | 0 | +| rainfall | 降雨量 | enum_int | {"0":"无雨","1":"小雨","2":"中雨","3":"大雨"} | | r | 0 | +| live_capacity | 网关设备直播能力 | struct | | | r | 1 | +| »available_video_number | 可选择推流的码流数量 | int | | | | 0 | +| »coexist_video_number_max | 可同时推流的最大码流数量 | int | | | | 0 | +| »device_list | 可选择的视频设备源 | array | {"size": -, "item_type": struct} | 可选择的视频设备源(设备层,比如飞行器) | | 0 | +| »»sn | 飞行器等视频源设备序列号(SN) | text | | | | 0 | +| »»available_video_number | 该序列号设备可以被选择推流的码流数 | int | | | | 0 | +| »»coexist_video_number_max | 该序列号设备可以同时被推流的码流数 | int | | | | 0 | +| »»camera_list | 该序列号设备上的相机列表 | array | {"size": -, "item_type": struct} | | | 0 | +| »»»camera_index | 相机索引 | text | | 使用 *{type-subtype-gimbalindex}* 的格式 | | 0 | +| »»»available_video_number | 该相机级别的视频源可以被选择推流的码流数 | int | | | | 0 | +| »»»coexist_video_number_max | 该相机级别的视频源可以同时被推流的码流数 | int | | | | 0 | +| »»»video_list | 该相机级别的视频源可以选择的码流列表 | array | {"size": -, "item_type": struct} | | | 0 | +| »»»»video_index | 该相机级别的视频源可以选择的码流索引 | text | | | | 0 | +| »»»»video_type | 该相机级别的视频源可以选择的码流类型 | text | | | | 0 | +| »»»»switchable_video_types | 该视频流支持切换的视频镜头类型 | array | {"size": -, "item_type": text} | | | 0 | +| live_status | 网关当前整体直播状态推送 | array | {"size": -, "item_type": struct} | | r | 1 | +| »video_id | 直播码流标识符 | text | | 某路在推视频码流的标识符,格式为 *{sn}/{camera_index}/{video_index}*。其中 *{sn}* 为视频源设备序列号。*{camera_index}* 为相机索引,使用 *{type-subtype-gimbalindex}* 的格式。*{video_index}* 为该相机级别的视频源可以选择的码流索引。 | | 0 | +| »video_type | 视频类型 | text | {"length":"24"} | 表明视频镜头的类型,如normal/wide/zoom/infrared等 | | 0 | +| »video_quality | 直播码流的质量 | enum_int | {"0":"自适应","1":"流畅","2":"标清","3":"高清","4":"超清"} | | | 0 | +| »status | 直播状态 | enum_int | {"0":"未直播","1":"在直播"} | | | 0 | +| »error_status | 错误码 | int | {"length":6} | | | 0 | +| wireless_link | 图传链路 | struct | | | r | 0 | +| »dongle_number | 飞行器上 Dongle 数量 | int | | | | 0 | +| »4g_link_state | 4G 链路连接状态 | enum_int | {"0":"断开","1":"连接"} | | | 0 | +| »sdr_link_state | SDR 链路连接状态 | enum_int | {"0":"断开","1":"连接"} | | | 0 | +| »link_workmode | 机场的图传链路模式 | enum_int | {"0":"SDR 模式","1":"4G 融合模式"} | | | 0 | +| »sdr_quality | SDR 信号质量 | int | {"max":"5","min":"0","step":"1"} | | | 0 | +| »4g_quality | 总体 4G 信号质量 | int | {"max":"5","min":"0","step":"1"} | | | 0 | +| »4g_uav_quality | 天端 4G 信号质量 | int | {"max":"5","min":"0","step":"1"} | 飞行器端与 4G 服务器之间的信号质量 | | 0 | +| »4g_gnd_quality | 地端 4G 信号质量 | int | {"max":"5","min":"0","step":"1"} | 地面端(如遥控器、DJI Dock等)与 4G 服务器之间的信号质量 | | 0 | +| »sdr_freq_band | SDR 频段 | float | | | | 0 | +| »4g_freq_band | 4G 频段 | float | | | | 0 | +| media_file_detail | 媒体文件上传细节 | struct | | | r | 0 | +| »remain_upload | 待上传数量 | int | | | | 0 | +| job_number | 机场累计作业次数 | int | {"unit_name":"次 / count"} | | r | 0 | +| drone_in_dock | 飞行器是否在舱 | enum_int | {"0":"舱外","1":"舱内"} | | r | 0 | +| network_state | 网络状态 | struct | | | r | 0 | +| »type | 网络类型 | enum_int | {"1":"4G","2":"以太网"} | | | 0 | +| »quality | 网络质量 | enum_int | {"0":"无信号","1":"差","2":"较差","3":"一般","4":"较好","5":"好"} | | | 0 | +| »rate | 网络速率 | float | {"unit_name":"千字节每秒 / KB/s"} | | | 0 | +| supplement_light_state | 补光灯状态 | enum_int | {"0":"关闭","1":"打开"} | | r | 0 | +| cover_state | 舱盖状态 | enum_int | {"0":"关闭","1":"打开","2":"半开","3":"舱盖状态异常"} | | r | 0 | +| sub_device | 子设备状态 | struct | | | r | 0 | +| »device_sn | 子设备序列号(SN) | text | | | | 0 | +| »device_model_key | 子设备枚举值 | text | | 格式为 *{domain-type-subtype}* | | 0 | +| »device_online_status | 机场停机坪上的飞行器开机状态 | enum_int | {"0":"关机","1":"开机"} | | | 0 | +| »device_paired | 机场停机坪上的飞行器是否与机场对频 | enum_int | {"0":"未对频","1":"已对频"} | | | 0 | +| flighttask_step_code | 机场任务状态 | enum_int | {"0":"作业准备中","1":"飞行作业中","2":"作业后状态恢复","3":"自定义飞行区更新中","4":"地形障碍物更新中","5":"任务空闲","255":"飞行器异常","256":"未知状态"} | | r | 0 | +| mode_code | 机场状态 | enum_int | {"0":"空闲中","1":"现场调试","2":"远程调试","3":"固件升级中","4":"作业中"} | | r | 0 | +| firmware_upgrade_status | 固件升级状态 | enum_int | {"0":"未升级","1":"升级中"} | | r | 1 | +| firmware_version | 固件版本 | text | {"length":"64"} | | r | 1 | +| latitude | 纬度 | double | {"max":"90","min":"-90","step":"0.01"} | | r | 0 | +| longitude | 经度 | double | {"max":"180","min":"-180","step":"0.01"} | 网关设备的经度 | r | | + +```json +{ + "bid": "939bf66d-eb0a-4804-baad-7cbc4e175253", + "data": { + "drc_state": 0, + "flighttask_prepare_capacity": 1, + "flighttask_step_code": 1, + "media_file_detail": { "remain_upload": 0 }, + "sdr": { "down_quality": 100, "frequency_band": 2.4, "up_quality": 100 }, + "user_experience_improvement": 3, + "wireless_link": { + "4g_freq_band": 5.8, + "4g_gnd_quality": 5, + "4g_link_state": 1, + "4g_quality": 5, + "4g_uav_quality": 5, + "dongle_number": 1, + "link_workmode": 1, + "sdr_freq_band": 5.8, + "sdr_link_state": 1, + "sdr_quality": 5 + } + }, + "tid": "795e35f0-109c-4ff5-bd83-f9a7ceb8e2c6", + "timestamp": 1735466829704, + "gateway": "7CTDM6F00B744S" +} +``` + +```json +{ + "tid": "3c2afb04-e637-4b16-8cd0-c15094527398", + "bid": "933bac6c-338e-4ecd-90b9-951308c439e0", + "timestamp": 1735466829710, + "data": { + "network_state": { "type": 2, "quality": 0, "rate": 32 }, + "drone_charge_state": { "state": 0, "capacity_percent": 72 }, + "drone_in_dock": 0, + "rainfall": 0, + "wind_speed": 0, + "environment_temperature": 7.1, + "temperature": 6.6, + "humidity": 45, + "heading": -72.980140686035156, + "home_position_is_valid": 1, + "latitude": 39.10260381347603, + "longitude": 117.71197297315571, + "height": 5.8588995933532715, + "alternate_land_point": { + "latitude": 39.102598739909752, + "longitude": 117.71198964942272, + "height": 0, + "safe_land_height": 30, + "is_configured": 1 + }, + "first_power_on": 1631945855969, + "position_state": { + "is_calibration": 1, + "is_fixed": 2, + "quality": 5, + "gps_number": 7, + "rtk_number": 36 + }, + "storage": { "total": 79981124, "used": 69124 }, + "mode_code": 4, + "cover_state": 0, + "silent_mode": 1, + "supplement_light_state": 0, + "emergency_stop_state": 0, + "air_conditioner": { "air_conditioner_state": 0, "switch_time": 0 }, + "battery_store_mode": 2, + "alarm_state": 0, + "putter_state": 0, + "sub_device": { + "device_sn": "1581F6QAD249M00GCRF5", + "device_online_status": 1, + "device_paired": 1 + } + }, + "gateway": "7CTDM6F00B744S" +} +``` + +```json +{ + "tid": "f219d8d5-2c57-4a0e-b9a9-d72c77ea7dbe", + "bid": "f188e509-41d3-4e70-bb63-938b15193387", + "timestamp": 1735466829726, + "data": { + "job_number": 48, + "acc_time": 618911, + "activation_time": 1734482524, + "maintain_status": { + "maintain_status_array": [ + { + "state": 0, + "last_maintain_type": 17, + "last_maintain_time": 0, + "last_maintain_work_sorties": 0 + }, + { + "state": 0, + "last_maintain_type": 18, + "last_maintain_time": 0, + "last_maintain_work_sorties": 0 + } + ] + }, + "electric_supply_voltage": 32767, + "working_voltage": 27742, + "working_current": 0, + "backup_battery": { "voltage": 13601, "temperature": 12.4, "switch": 1 }, + "drone_battery_maintenance_info": { + "maintenance_state": 0, + "maintenance_time_left": 0, + "heat_state": 0, + "batteries": [ + { + "index": 0, + "capacity_percent": 72, + "voltage": 15366, + "temperature": 24.9 + } + ] + } + }, + "gateway": "7CTDM6F00B744S" +} +``` + +```json +{ + "bid": "883e903f-1ff7-4015-8c5c-a0c0c267aff5", + "data": { + "rtcm_info": { + "host": "120.253.226.97", + "mount_point": "RTCM33_GRCEJ", + "port": "8002", + "rtcm_device_type": 1, + "source_type": 3 + } + }, + "need_reply": 1, + "tid": "3116ca3e-3335-4467-8b8e-c2b028fce07f", + "timestamp": 1735466831441, + "gateway": "7CTDM6F00B744S" +} +``` + +飞机: + +| best_link_gateway | 飞行器图传连接质量最好的网关SN | text | | 蛙跳任务场景下,当飞行器对频了两个机场后,推送连接最好的机场SN | r | 1 | +| --- | --- | --- | --- | --- | --- | --- | +| wireless_link_topo | 图传连接拓扑 | struct | | | r | 1 | +| »secret_code | 加密编码 | array | {"size": 28, "item_type": int} | | | 0 | +| »center_node | 飞行器对频信息 | struct | | | | 0 | +| »»sdr_id | 扰码信息 | int | | | | 0 | +| »»sn | 设备sn | text | | | | 0 | +| »leaf_nodes | 当前连接的机场或遥控器对频信息 | array | {"size": -, "item_type": struct} | | | 0 | +| »»sdr_id | 扰码信息 | int | | | | 0 | +| »»sn | 设备sn | text | | | | 0 | +| »»control_source_index | 控制源序号 | int | {"max":"2","min":"1","step":"1","unit_name":"无 / "} | | | 0 | +| cameras | 飞行器相机信息 | array | {"size": -, "item_type": struct} | | r | 0 | +| »remain_photo_num | 剩余拍照张数 | int | | 剩余拍照张数 | | 0 | +| »remain_record_duration | 剩余录像时间 | int | {"unit_name":"秒 / s"} | 剩余录像时间 | | 0 | +| »record_time | 视频录制时长 | int | {"unit_name":"秒 / s"} | 视频录制时长 | | 0 | +| »payload_index | 负载编号 | text | | 负载编号,相机枚举值。非标准的 device_mode_key,格式为 {type-subtype-gimbalindex},可以参考[**产品支持open in new window**](https://developer.dji.com/doc/cloud-api-tutorial/cn/overview/product-support.html) | | 0 | +| »camera_mode | 相机模式 | enum_int | {"0":"拍照","1":"录像","2":"智能低光","3":"全景拍照"} | 相机模式 | | 0 | +| »photo_state | 拍照状态 | enum_int | {"0":"空闲","1":"拍照中"} | 拍照状态 | | 0 | +| »screen_split_enable | 分屏是否使能 | bool | {"0":"分屏使能关闭","1":"分屏使能开启"} | | | 0 | +| »recording_state | 录像状态 | enum_int | {"0":"空闲","1":"录像中"} | 录像状态 | | 0 | +| »zoom_factor | 变焦倍数 | float | | | | 0 | +| »ir_zoom_factor | 红外变焦倍数 | float | | 红外变焦倍数 | | 0 | +| »liveview_world_region | 视场角(FOV)在 liveview 中的区域 | struct | | 变焦相机的视场角相对于广角相机或者红外相机的视场角,在 liveview 中会有所不同。坐标原点为镜头左上角。 | | 0 | +| »»left | 左上角的 x 轴起始点 | float | | 左上角的 x 轴起始点 | r | 0 | +| »»top | 左上角的 y 轴起始点 | float | | 左上角的 y 轴起始点 | r | 0 | +| »»right | 右下角的 x 轴起始点 | float | | 右下角的 x 轴起始点 | r | 0 | +| »»bottom | 右下角的 y 轴起始点 | float | | 右下角的 y 轴起始点 | r | 0 | +| »photo_storage_settings | 照片存储设置集合 | array | {"size": -, "item_type": enum_string} | 取值范围{current, vision, ir} | | 0 | +| »video_storage_settings | 视频存储设置集合 | array | {"size": -, "item_type": enum_string} | 取值范围{current, vision, ir} | | 0 | +| »wide_exposure_mode | 广角镜头曝光模式 | enum_int | {"1":"自动","2":"快门优先曝光","3":"光圈优先曝光","4":"手动曝光"} | 当前配置的广角镜头曝光模式 | | 0 | +| »wide_iso | 广角镜头感光度 | enum_int | {"0":"Auto","1":"Auto(High Sense)","2":"50","3":"100","4":"200","5":"400","6":"800","7":"1600","8":"3200","9":"6400","10":"12800","11":"25600","255":"FIXED"} | 当前配置的广角镜头感光度 | | 0 | +| »wide_shutter_speed | 广角镜头快门速度 | enum_int | {"0":"1/8000 s","1":"1/6400 s","2":"1/6000 s","3":"1/5000 s","4":"1/4000 s","5":"1/3200 s","6":"1/3000 s","7":"1/2500 s","8":"1/2000 s","9":"1/1600 s","10":"1/1500 s","11":"1/1250 s","12":"1/1000 s","13":"1/800 s","14":"1/725 s","15":"1/640 s","16":"1/500 s","17":"1/400 s","18":"1/350 s","19":"1/320 s","20":"1/250 s","21":"1/240 s","22":"1/200 s","23":"1/180 s","24":"1/160 s","25":"1/125 s","26":"1/120 s","27":"1/100 s","28":"1/90 s","29":"1/80 s","30":"1/60 s","31":"1/50 s","32":"1/40 s","33":"1/30 s","34":"1/25 s","35":"1/20 s","36":"1/15 s","37":"1/12.5 s","38":"1/10 s","39":"1/8 s","40":"1/6.25 s","41":"1/5 s","42":"1/4 s","43":"1/3 s","44":"1/2.5 s","45":"1/2 s","46":"1/1.67 s","47":"1/1.25 s","48":"1.0 s","49":"1.3 s","50":"1.6 s","51":"2.0 s","52":"2.5 s","53":"3.0 s","54":"3.2 s","55":"4.0 s","56":"5.0 s","57":"6.0 s","58":"7.0 s","59":"8.0 s","65534":"Auto"} | 当前配置的广角镜头快门速度 | | 0 | +| »wide_exposure_value | 广角镜头曝光值 | enum_int | {"1":"-5.0EV","2":"-4.7EV","3":"-4.3EV","4":"-4.0EV","5":"-3.7EV","6":"-3.3EV","7":"-3.0EV","8":"-2.7EV","9":"-2.3EV","10":"-2.0EV","11":"-1.7EV","12":"-1.3EV","13":"-1.0EV","14":"-0.7EV","15":"-0.3EV","16":"0EV","17":"0.3EV","18":"0.7EV","19":"1.0EV","20":"1.3EV","21":"1.7EV","22":"2.0EV","23":"2.3EV","24":"2.7EV","25":"3.0EV","26":"3.3EV","27":"3.7EV","28":"4.0EV","29":"4.3EV","30":"4.7EV","31":"5.0EV","255":"FIXED"} | 当前配置的广角镜头曝光值 | | 0 | +| »zoom_exposure_mode | 变焦镜头曝光模式 | enum_int | {"1":"自动","2":"快门优先曝光","3":"光圈优先曝光","4":"手动曝光"} | 当前配置的变焦镜头曝光模式 | | 0 | +| »zoom_iso | 变焦镜头感光度 | enum_int | {"0":"Auto","1":"Auto(High Sense)","2":"50","3":"100","4":"200","5":"400","6":"800","7":"1600","8":"3200","9":"6400","10":"12800","11":"25600","255":"FIXED"} | 当前配置的变焦镜头感光度 | | 0 | +| »zoom_shutter_speed | 变焦镜头快门速度 | enum_int | {"0":"1/8000 s","1":"1/6400 s","2":"1/6000 s","3":"1/5000 s","4":"1/4000 s","5":"1/3200 s","6":"1/3000 s","7":"1/2500 s","8":"1/2000 s","9":"1/1600 s","10":"1/1500 s","11":"1/1250 s","12":"1/1000 s","13":"1/800 s","14":"1/725 s","15":"1/640 s","16":"1/500 s","17":"1/400 s","18":"1/350 s","19":"1/320 s","20":"1/250 s","21":"1/240 s","22":"1/200 s","23":"1/180 s","24":"1/160 s","25":"1/125 s","26":"1/120 s","27":"1/100 s","28":"1/90 s","29":"1/80 s","30":"1/60 s","31":"1/50 s","32":"1/40 s","33":"1/30 s","34":"1/25 s","35":"1/20 s","36":"1/15 s","37":"1/12.5 s","38":"1/10 s","39":"1/8 s","40":"1/6.25 s","41":"1/5 s","42":"1/4 s","43":"1/3 s","44":"1/2.5 s","45":"1/2 s","46":"1/1.67 s","47":"1/1.25 s","48":"1.0 s","49":"1.3 s","50":"1.6 s","51":"2.0 s","52":"2.5 s","53":"3.0 s","54":"3.2 s","55":"4.0 s","56":"5.0 s","57":"6.0 s","58":"7.0 s","59":"8.0 s","65534":"Auto"} | 当前配置的变焦镜头快门速度 | | 0 | +| »zoom_exposure_value | 变焦镜头曝光值 | enum_int | {"1":"-5.0EV","2":"-4.7EV","3":"-4.3EV","4":"-4.0EV","5":"-3.7EV","6":"-3.3EV","7":"-3.0EV","8":"-2.7EV","9":"-2.3EV","10":"-2.0EV","11":"-1.7EV","12":"-1.3EV","13":"-1.0EV","14":"-0.7EV","15":"-0.3EV","16":"0EV","17":"0.3EV","18":"0.7EV","19":"1.0EV","20":"1.3EV","21":"1.7EV","22":"2.0EV","23":"2.3EV","24":"2.7EV","25":"3.0EV","26":"3.3EV","27":"3.7EV","28":"4.0EV","29":"4.3EV","30":"4.7EV","31":"5.0EV","255":"FIXED"} | 当前配置的变焦镜头曝光值 | | 0 | +| »zoom_focus_mode | 变焦镜头对焦模式 | enum_int | {"0":"MF","1":"AFS","2":"AFC"} | | | 0 | +| »zoom_focus_value | 变焦镜头对焦值 | int | | | | 0 | +| »zoom_max_focus_value | 变焦镜头最大对焦值 | int | | | | 0 | +| »zoom_min_focus_value | 变焦镜头最小对焦值 | int | | | | 0 | +| »zoom_calibrate_farthest_focus_value | 变焦镜头标定的最远对焦值 | int | | 最清晰的最远位置对焦值 | | 0 | +| »zoom_calibrate_nearest_focus_value | 变焦镜头标定的最近对焦值 | int | | 最清晰的最近位置对焦值 | | 0 | +| »zoom_focus_state | 变焦镜头对焦状态 | enum_int | {"0":"空闲","1":"对焦中","2":"对焦成功","3":"对焦失败"} | | | 0 | +| »ir_metering_mode | 红外测温模式 | enum_int | {"0":"关闭测温","1":"点测温","2":"区域测温"} | | | 0 | +| »ir_metering_point | 红外测温点 | struct | | 红外测温点相关信息 | | 0 | +| »»x | 测温点坐标 x | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,水平方向为 x | r | 0 | +| »»y | 测温点坐标 y | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,竖直方向为 y | r | 0 | +| »»temperature | 测温点的温度 | double | | | r | 0 | +| »ir_metering_area | 红外测温区域 | struct | | 红外测温区域相关信息 | | 0 | +| »»x | 测温区域左上角点坐标 x | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,水平方向为 x | r | 0 | +| »»y | 测温区域左上角点坐标 y | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,竖直方向为 y | r | 0 | +| »»width | 测温区域宽度 | double | {"max":1,"min":0} | 测温区域宽度 | r | 0 | +| »»height | 测温区域高度 | double | {"max":1,"min":0} | 测温区域高度 | r | 0 | +| »»aver_temperature | 测温区域平均温度 | double | | 测温区域平均温度 | r | 0 | +| »»min_temperature_point | 测温区域最低温度点 | struct | | 测温区域最低温度点相关信息 | r | 0 | +| »»»x | 最低温度点坐标 x | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,水平方向为 x | r | 0 | +| »»»y | 最低温度点坐标 y | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,竖直方向为 y | r | 0 | +| »»»temperature | 最低温度点的温度 | double | | 最低温度点的温度 | r | 0 | +| »»max_temperature_point | 测温区域最高温度点 | struct | | 测温区域最高温度点相关信息 | r | 0 | +| »»»x | 最高温度点坐标 x | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,水平方向为 x | r | 0 | +| »»»y | 最高温度点坐标 y | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,竖直方向为 y | r | 0 | +| »»»temperature | 最高温度点的温度 | double | | 最高温度点的温度 | r | 0 | +| flysafe_database_version | 飞行安全数据库版本 | text | {"length":"64"} | | r | 1 | +| offline_map_enable | 离线地图开关 | bool | {"0":"关闭","1":"开启"} | 当离线地图关闭后,离线地图同步不再进行自动同步 | r | 1 | +| dongle_infos | 4G Dongle信息 | array | {"size": -, "item_type": struct} | | r | 1 | +| »imei | dongle imei | text | | Dongle 的唯一识别标志 | r | 0 | +| »dongle_type | Dongle 类型 | enum_int | {"6":"旧 Dongle","10":"支持 eSIM 的新 Dongle"} | Dongle 类型 | r | 0 | +| »eid | dongle eid | text | | eSIM 的唯一识别标志,用于公众号查询套餐、购买服务 | r | 0 | +| »esim_activate_state | eSIM 激活状态 | enum_int | {"0":"未激活","1":"已激活"} | 需要激活才能使用 | r | 0 | +| »sim_card_state | SIM 卡状态 | enum_int | {"0":"未插入","1":"已插入"} | Dongle 中实体 SIM 卡的插入状态 | r | 0 | +| »sim_slot | SIM 卡槽使能状态 | enum_int | {"0":"未知","1":"实体 SIM 卡","2":"eSIM"} | 标识 Dongle 当前正在使用的 SIM 卡槽 | r | 0 | +| »esim_infos | eSIM 信息 | array | {"size": -, "item_type": struct} | | r | 0 | +| »»telecom_operator | 支持的运营商 | enum_int | {"0":"未知","1":"移动","2":"联通","3":"电信"} | eSIM 支持的运营商 | r | 0 | +| »»enabled | eSIM 使能状态 | bool | {"false":"未使用","true":"使用中"} | 同时刻只能有一个 eSIM 是使能的 | r | 0 | +| »»iccid | sim iccid | text | | SIM 卡的唯一识别标志,可以用于实体 SIM 卡的套餐购买 | r | 0 | +| »sim_info | SIM 卡信息 | struct | | 可插入 Dongle 的实体 SIM 卡信息 | r | 0 | +| »»telecom_operator | 支持的运营商 | enum_int | {"0":"未知","1":"移动","2":"联通","3":"电信"} | SIM 卡支持的运营商 | r | 0 | +| »»sim_type | SIM 卡类型 | enum_int | {"0":"未知","1":"其他普通 SIM 卡","2":"三网卡"} | 实体 SIM 卡的类型 | r | 0 | +| »»iccid | sim iccid | text | | SIM 卡的唯一识别标志,可以用于实体 SIM 卡的套餐购买 | r | 0 | +| current_rth_mode | 返航高度模式当前值 | enum_int | {"0":"智能高度","1":"设定高度"} | 大疆机场当前实际使用的返航高度模式 | r | 1 | +| rth_mode | 返航高度模式设置值 | enum_int | {"0":"智能高度","1":"设定高度"} | 智能返航模式下,飞行器将自动规划最佳返航高度。大疆机场当前不支持设置返航高度模式,只能选择'设定高度'模式。当环境,光线不满足视觉系统要求时(譬如傍晚阳光直射、夜间弱光无光),飞行器将使用您设定的返航高度进行直线返航 | r | 1 | +| obstacle_avoidance | 飞行器避障状态 | struct | | | rw | 0 | +| »horizon | 水平避障状态 | enum_int | {"0":"关闭","1":"开启"} | | | 0 | +| »upside | 上视避障状态 | enum_int | {"0":"关闭","1":"开启"} | | | 0 | +| »downside | 下视避障状态 | enum_int | {"0":"关闭","1":"开启"} | | | 0 | +| is_near_area_limit | 是否接近限飞区 | enum_int | {"0":"未达到限飞区","1":"接近限飞区"} | | r | 0 | +| is_near_height_limit | 是否接近设定的限制高度 | enum_int | {"0":"未达到设定的限制高度","1":"接近设定的限制高度"} | | r | 0 | +| height_limit | 飞行器限高 | int | {"max":"1500","min":"20","step":"1","unit_name":"米 / m"} | | rw | 0 | +| night_lights_state | 飞行器夜航灯状态 | enum_int | {"0":"关闭","1":"打开"} | | rw | 0 | +| activation_time | 飞行器激活时间(unix 时间戳) | int | {"unit_name":"秒 / s"} | | r | 0 | +| maintain_status | 保养信息 | struct | | | r | 0 | +| »maintain_status_array | 保养信息数组 | array | {"size": -, "item_type": struct} | | | 0 | +| »»state | 保养状态 | enum_int | {"0":"无保养","1":"有保养"} | | | 0 | +| »»last_maintain_type | 上一次保养类型 | enum_int | {"1":"飞行器基础保养","2":"飞行器常规保养","3":"飞行器深度保养"} | | | 0 | +| »»last_maintain_time | 上一次保养时间 | date | {"unit_name":"秒 / s"} | | | 0 | +| »»last_maintain_flight_time | 上一次保养时飞行航时 | int | {"unit_name":"小时 / h"} | | | 0 | +| »»last_maintain_flight_sorties | 上一次保养时飞行架次 | int | {"max":"2147483647","min":"0","step":"1"} | | | 0 | +| total_flight_sorties | 飞行器累计飞行总架次 | int | {"max":"2147483647","min":"0","step":"1"} | | r | 0 | +| type_subtype_gimbalindex | 负载编号 | struct | | 与字段 payload_index 保持一致 | r | 0 | +| »gimbal_pitch | 云台俯仰轴角度 | double | {"max":"180","min":"-180","step":0.1,"unit_name":"度 / °"} | | | 0 | +| »gimbal_roll | 云台横滚轴角度 | double | {"max":"180","min":"-180","step":0.1,"unit_name":"度 / °"} | | | 0 | +| »gimbal_yaw | 云台偏航轴角度 | double | {"max":"180","min":"-180","step":0.1,"unit_name":"度 / °"} | | | 0 | +| »payload_index | 负载索引,格式为 *{type-subtype-gimbalindex}* | text | | | | 0 | +| »zoom_factor | 变焦倍数 | double | | | | 0 | +| track_id | 航迹 ID | text | {"length":"64"} | | r | 0 | +| position_state | 搜星状态 | struct | | | r | 0 | +| »is_fixed | 是否收敛 | enum_int | {"0":"未开始","1":"收敛中","2":"收敛成功","3":"收敛失败"} | | | 0 | +| »quality | 搜星档位 | enum_int | {"1":"1档","2":"2档","3":"3档","4":"4档","5":"5档","10":"RTK fixed"} | | | 0 | +| »gps_number | GPS 搜星数量 | int | | | | 0 | +| »rtk_number | RTK 搜星数量 | int | | | | 0 | +| storage | 存储容量 | struct | | kb | r | 0 | +| »total | 总容量 | int | {"unit_name":"千字节 / KB"} | | | 0 | +| »used | 已使用容量 | int | {"unit_name":"千字节 / KB"} | | | 0 | +| battery | 飞行器电池信息 | struct | | | r | 0 | +| »capacity_percent | 电池的总剩余电量 | int | {"max":100,"min":0} | | | 0 | +| »remain_flight_time | 剩余飞行时间 | int | {"unit_name":"秒 / s"} | | | 0 | +| »return_home_power | 返航所需电量百分比 | int | {"max":100,"min":0} | | | 0 | +| »landing_power | 强制降落电量百分比 | int | {"max":100,"min":0} | | | 0 | +| »batteries | 电池详细信息 | array | {"size": -, "item_type": struct} | | | 0 | +| »»capacity_percent | 电池剩余电量 | int | {"max":100,"min":0} | | | 0 | +| »»index | 电池序号 | int | {"min":"0"} | | | 0 | +| »»sn | 电池序列号(SN) | text | | | | 0 | +| »»type | 电池类型 | enum_int | {} | | | 0 | +| »»sub_type | 电池子类型 | enum_int | {} | | | 0 | +| »»firmware_version | 固件版本 | text | | | | 0 | +| »»loop_times | 电池循环次数 | int | | | | 0 | +| »»voltage | 电压 | int | {"unit_name":"毫伏 / mV"} | | | 0 | +| »»temperature | 温度 | float | {"unit_name":"摄氏度 / °C"} | 保留小数点后一位 | | 0 | +| »»high_voltage_storage_days | 高电压存储天数 | int | {"unit_name":"日 / day"} | | | 0 | +| total_flight_distance | 飞行器累计飞行总里程 | float | {"unit_name":"米 / m"} | | r | 0 | +| total_flight_time | 飞行器累计飞行航时 | int | {"unit_name":"秒 / s"} | | r | 0 | +| serious_low_battery_warning_threshold | 严重低电量告警 | int | | 用户设置的电池严重低电量告警百分比 | r | 1 | +| low_battery_warning_threshold | 低电量告警 | int | | 用户设置的电池低电量告警百分比 | r | 1 | +| control_source | 当前控制源 | text | | 可以为设备,也可以为某个浏览器。设备使用 A/B 表示 A 控,B 控,浏览器以自生成的 uuid 作为标识符 | r | 1 | +| wind_direction | 当前风向 | enum_int | {"1":"正北","2":"东北","3":"东","4":"东南","5":"南","6":"西南","7":"西","8":"西北"} | | r | 0 | +| wind_speed | 风速 | float | | 风速估计,该风速是通过飞行器姿态推测出的,有一定的误差,仅供参考,不能作为气象数据使用 | r | 0 | +| home_distance | 距离 Home 点的距离 | float | | | r | 0 | +| home_latitude | Home 点纬度 | float | | | r | 1 | +| home_longitude | Home 点经度 | float | | | r | 1 | +| attitude_head | 偏航轴角度 | int | | 偏航轴角度与真北角(经线)的角度,0到6点钟方向为正值,6到12点钟方向为负值 | r | 0 | +| attitude_roll | 横滚轴角度 | float | | | r | 0 | +| attitude_pitch | 俯仰轴角度 | float | | | r | 0 | +| elevation | 相对起飞点高度 | float | | | r | 0 | +| height | 绝对高度 | float | | 相对地球椭球面高度, 计算:相对起飞点的高度 + 起飞点的椭球高 | r | 0 | +| latitude | 当前位置纬度 | float | {"max":"3.4028235E38","min":"-1.4E-45","step":"0.1"} | | r | 0 | +| longitude | 当前位置经度 | float | {"max":"3.4028235E38","min":"-1.4E-45","step":"0.1"} | | r | 0 | +| vertical_speed | 垂直速度 | float | {"unit_name":"米每秒 / m/s"} | | r | 0 | +| horizontal_speed | 水平速度 | float | | | r | 0 | +| firmware_upgrade_status | 固件升级状态 | enum_int | {"0":"未升级","1":"升级中"} | | r | 1 | +| compatible_status | 固件一致性 | enum_int | {"0":"不需要一致性升级","1":"需要一致性升级"} | 一致性升级:指飞行器某些模块的固件版本与系统匹配版本不一致,需要进行升级。常见的情况例如:飞行器与遥控器已经升级至最新版本,但替换电池时发现电池未升级,此时一致性升级将被提示。普通升级:开发者将飞行器所有模块升级至指定固件版本。 | r | 1 | +| firmware_version | 固件版本 | text | {"length":"64"} | | r | 1 | +| gear | 档位 | enum_int | {"0":"A","1":"P","2":"NAV","3":"FPV","4":"FARM","5":"S","6":"F","7":"M","8":"G","9":"T"} | | r | 0 | +| mode_code_reason | 飞行器进入当前状态的原因 | enum_int | {"0":"无意义","1":"电池电量不足(返航、降落)","2":"电池电压不足(返航、降落)","3":"电压严重过低(返航、降落)","4":"遥控器按键请求(起飞、返航、降落)","5":"App 请求(起飞、返航、降落)","6":"遥控信号丢失(返航、降落、悬停)","7":"导航、SDK 等外部设备触发(起飞、返航、降落)","8":"进入机场限飞区(降落)","9":"虽然触发了返航但是因为距离 Home 点距离太近(降落)","10":"虽然触发了返航但是因为距离 Home 点距离太远(降落)","11":"执行航点任务时请求(起飞)","12":"返航阶段到达 Home 点上方后请求(降落)","13":"飞行器高度下降,距地面 0.7m(二段降落限低)时,继续下降导致(降落)","14":"App、SDK 等设备强制突破限低保护进行(降落)","15":"因为周围有航班经过而请求(返航、降落)","16":"因为高度控制失败请求(返航、降落)","17":"智能低电量返航后进入(降落)","18":"AP控制飞行模式(手动飞行)","19":"硬件异常(返航、降落)","20":"防触地保护结束(降落)","21":"返航取消 (悬停)","22":"返航时遇到障碍物(降落)","23":"机场场景下大风触发(返航)"} | | r | 1 | +| commander_flight_height | 指点飞行高度 | float | {"max":3000,"min":2,"step":0.1,"unit_name":"米 / m"} | 相对(机场)起飞点的高度,相对高 ALT | rw | 1 | +| commander_flight_mode | 指点飞行模式设置值 | enum_int | {"0":"智能高度飞行","1":"设定高度飞行"} | 指点飞行模式设置值 | rw | 1 | +| commander_mode_lost_action | 指点飞行失控动作 | enum_int | {"0":"继续执行指点飞行任务","1":"退出指点飞行任务,执行普通失控行为"} | 执行指点飞行时失控了,选择继续执行完,还是执行普通失控行为 | rw | 1 | +| camera_watermark_settings | 相机水印设置 | struct | | 用户对相机拍摄的照片和录像文件进行水印配置, 目前暂不支持直播画面水印 | rw | 1 | +| »global_enable | 水印显示全局开关 | enum_int | {"0":"关闭","1":"开启"} | 需要开启全局开关才能显示水印 | rw | 1 | +| »drone_type_enable | 机型显示开关 | enum_int | {"0":"关闭","1":"开启"} | | rw | 1 | +| »drone_sn_enable | 飞行器序列号显示开关 | enum_int | {"0":"关闭","1":"开启"} | | rw | 1 | +| »datetime_enable | 日期时间显示开关 | enum_int | {"0":"关闭","1":"开启"} | 时区默认为当地时区 | rw | 1 | +| »gps_enable | 经纬度&海拔高显示开关 | enum_int | {"0":"关闭","1":"开启"} | | rw | 1 | +| »user_custom_string_enable | 自定义文案显示开关 | enum_int | {"0":"关闭","1":"开启"} | | rw | 1 | +| »user_custom_string | 自定义文案内容 | text | | 最多可显示 250 字节 | rw | 1 | +| »layout | 水印在画面中位置 | enum_int | {"0":"左上","1":"左下","2":"右上","3":"右下"} | | rw | 1 | +| mode_code | 飞行器状态 | enum_int | {"0":"待机","1":"起飞准备","2":"起飞准备完毕","3":"手动飞行","4":"自动起飞","5":"航线飞行","6":"全景拍照","7":"智能跟随","8":"ADS-B 躲避","9":"自动返航","10":"自动降落","11":"强制降落","12":"三桨叶降落","13":"升级中","14":"未连接","15":"APAS","16":"虚拟摇杆状态","17":"指令飞行","18":"空中 RTK 收敛模式","19":"机场选址中"} | 机场选址指飞行器在空中悬停,为机场选址以及检查 RTK 信号质量 | r | 0 | + +```json +{ + "bid": "f7f2dd20-a08a-4865-9211-f0ced31a798c", + "data": { + "80-0-0": { + "gimbal_pitch": 0, + "gimbal_roll": 0, + "gimbal_yaw": -72.9804724552571, + "payload_index": "80-0-0", + "zoom_factor": 0.56782334384858046 + }, + "activation_time": 1734637617, + "attitude_head": -72.9, + "attitude_pitch": -0.4, + "attitude_roll": -3, + "battery": { + "batteries": [ + { + "capacity_percent": 78, + "firmware_version": "26.03.00.48", + "high_voltage_storage_days": 8, + "index": 0, + "loop_times": 6, + "sn": "6Q7PM4ADA100QQ", + "sub_type": 0, + "temperature": 23.9, + "type": 0, + "voltage": 15544 + } + ], + "capacity_percent": 78, + "landing_power": 8, + "remain_flight_time": 1553, + "return_home_power": 26 + }, + "best_link_gateway": "7CTDM6F00B744S", + "cameras": [ + { + "camera_mode": 1, + "liveview_world_region": { + "bottom": 1, + "left": 1, + "right": 1, + "top": 1 + }, + "payload_index": "80-0-0", + "photo_state": 0, + "record_time": 0, + "recording_state": 0, + "remain_photo_num": 0, + "remain_record_duration": 29207, + "wide_calibrate_farthest_focus_value": 35, + "wide_calibrate_nearest_focus_value": 84, + "wide_exposure_mode": 1, + "wide_exposure_value": 16, + "wide_focus_mode": 2, + "wide_focus_state": 1, + "wide_focus_value": 26, + "wide_iso": 9, + "wide_max_focus_value": 84, + "wide_min_focus_value": 35, + "wide_shutter_speed": 33, + "zoom_calibrate_farthest_focus_value": 35, + "zoom_calibrate_nearest_focus_value": 84, + "zoom_exposure_mode": 1, + "zoom_exposure_value": 16, + "zoom_factor": 1, + "zoom_focus_mode": 2, + "zoom_focus_state": 1, + "zoom_focus_value": 26, + "zoom_iso": 9, + "zoom_max_focus_value": 84, + "zoom_min_focus_value": 35, + "zoom_shutter_speed": 33 + } + ], + "country": "CN", + "distance_limit_status": { + "distance_limit": 5000, + "is_near_distance_limit": 0, + "state": 0 + }, + "elevation": 64, + "gear": 1, + "height": 69.8617935180664, + "height_limit": 220, + "home_distance": 0.11966302990913391, + "horizontal_speed": 0, + "is_near_area_limit": 1, + "is_near_height_limit": 0, + "latitude": 39.102602928799222, + "longitude": 117.71197176283638, + "maintain_status": { + "maintain_status_array": [ + { + "last_maintain_flight_sorties": 0, + "last_maintain_flight_time": 0, + "last_maintain_time": 0, + "last_maintain_type": 1, + "state": 0 + }, + { + "last_maintain_flight_sorties": 0, + "last_maintain_flight_time": 0, + "last_maintain_time": 0, + "last_maintain_type": 2, + "state": 0 + }, + { + "last_maintain_flight_sorties": 0, + "last_maintain_flight_time": 0, + "last_maintain_time": 0, + "last_maintain_type": 3, + "state": 0 + } + ] + }, + "mode_code": 9, + "night_lights_state": 0, + "obstacle_avoidance": { "downside": 0, "horizon": 0, "upside": 0 }, + "position_state": { + "gps_number": 32, + "is_fixed": 2, + "quality": 5, + "rtk_number": 33 + }, + "rc_lost_action": 2, + "rid_state": true, + "rth_altitude": 60, + "storage": { "total": 243702000, "used": 4000 }, + "total_flight_distance": 174010.89760393579, + "total_flight_sorties": 57, + "total_flight_time": 28866.739354778081, + "track_id": "586f7b33-4727-4026-a203-cf35a68626e5", + "vertical_speed": 0, + "wind_direction": 6, + "wind_speed": 35 + }, + "tid": "795fbf18-8bc1-43f7-bd10-895973319cb5", + "timestamp": 1735473362062, + "gateway": "7CTDM6F00B744S" +} +``` + +```json +{ + "bid": "78f3725d-34c3-4498-b0d5-98d50dc0310d", + "data": { "mode_code_reason": 12 }, + "need_reply": 1, + "tid": "88933f47-e55e-4e9e-a100-7a073cc09086", + "timestamp": 1735473362258, + "gateway": "7CTDM6F00B744S" +} +``` + +## 指令 + +### 起飞指令: + +| target_latitude | 目标点纬度 | double | {"max":90,"min":-90} | 目标点纬度,角度值,南纬是负,北纬是正,精度到小数点后6位 | +| --- | --- | --- | --- | --- | +| target_longitude | 目标点经度 | double | {"max":180,"min":-180} | 目标点经度,角度值,东经是正,西经是负,精度到小数点后6位 | +| target_height | 目标点高度 | float | {"max":1500,"min":2,"step":0.1,"unit_name":"米 / m"} | 目标点高度(椭球高),使用 WGS84 模型,飞行器到点后默认行为:悬停 | +| security_takeoff_height | 安全起飞高度 | float | {"max":1500,"min":20,"step":0.1,"unit_name":"米 / m"} | 相对(机场)起飞点的高度(ALT),飞行器先升到特定的高度,然后再飞向目标点。 | +| rth_mode | 【必填】返航模式设置值 | enum_int | {"0":"智能高度","1":"设定高度"} | 智能返航模式下,飞行器将自动规划最佳返航高度。大疆机场当前不支持设置返航高度模式,只能选择'设定高度'模式。当环境,光线不满足视觉系统要求时(譬如傍晚阳光直射、夜间弱光无光),飞行器将使用您设定的返航高度进行直线返航 | +| rth_altitude | 返航高度 | int | {"max":1500,"min":2,"step":1,"unit_name":"米 / m"} | 相对(机场)起飞点的高度,相对高 ALT | +| rc_lost_action | 遥控器失控动作 | enum_int | {"0":"悬停","1":"着陆(降落)","2":"返航"} | 遥控器失控动作 | +| commander_mode_lost_action | 【必填】指点飞行失控动作 | enum_int | {"0":"继续执行指点飞行任务","1":"退出指点飞行任务,执行普通失控行为"} | | +| commander_flight_mode | 【必填】指点飞行模式设置值 | enum_int | {"0":"智能高度飞行","1":"设定高度飞行"} | | +| commander_flight_height | 【必填】指点飞行高度 | float | {"max":3000,"min":2,"step":0.1,"unit_name":"米 / m"} | 相对(机场)起飞点的高度,相对高 ALT | +| flight_id | 一键起飞任务 UUID | text | | 任务 UUID,全局唯一,用于染色,云端区分该值是普通计划任务还是一键起飞任务 | +| max_speed | 一键起飞的飞行过程中能达到的最大速度 | int | {"max":15,"min":1,"unit_name":"米每秒 / m/s"} | | +| simulate_mission | 是否在模拟器中执行任务 | struct | | 可选字段,用于在室内进行模拟任务调试。 | +| »is_enable | 是否开启模拟器任务 | enum_int | {"0":"不开启","1":"开启"} | 当次任务打开或关闭模拟器 | +| »latitude | 纬度 | double | {"max":"90.0","min":"-90.0"} | | +| »longitude | 经度 | double | {"max":"180.0","min":"-180.0"} | | +| flight_safety_advance_check | 飞行安全预检查 | bool | {"0":"关闭","1":"开启"} | 设置一键起飞和航线任务中的飞行安全是否预先检查。此字段为可选,默认为0,值为0表示关闭,1表示开启。飞行安全预先检查表示: 飞行器执行任务前,检查自身作业区文件是否与云端一致,如果不一致则拉取文件更新,如果一致则不处理 | + +```json +{ + "data": { + "flight_id": flight_id, + "max_speed": 5, + "rc_lost_action": 2, + "rth_altitude": 60.0, + "rth_mode": 1, + "security_takeoff_height": 60.0, + "target_height": 70.0, + "target_latitude": 39.102603, + "target_longitude": 117.711972, + "commander_mode_lost_action": 0, + "commander_flight_mode": 1, + "commander_flight_height": 70.0, + "simulate_mission": { + }, + "flight_safety_advance_check": 0 + }, + "method": "takeoff_to_point" +} +``` + +### 飞向目标点: + +| fly_to_id | 飞向目标点 ID | text | | | +| --- | --- | --- | --- | --- | +| max_speed | flyto 的飞行过程中能达到的最大速度 | int | {"max":15,"min":0,"unit_name":"米每秒 / m/s"} | | +| points | flyto 目标点列表 | array | {"size": -, "item_type": struct} | 仅支持 1 个目标点 | +| »latitude | 目标点纬度 | double | {"max":90,"min":-90} | 目标点纬度,角度值,南纬是负,北纬是正,精度到小数点后6位 | +| »longitude | 目标点经度 | double | {"max":180,"min":-180} | 目标点经度,角度值,东经是正,西经是负,精度到小数点后6位 | +| »height | 目标点高度 | float | {"max":10000,"min":2,"step":0.1,"unit_name":"米 / m"} | 目标点高度(椭球高),使用 WGS84 模型 | + +```json +{ + "data": { + "fly_to_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx", + "max_speed": 12, + "points": [ + { + "height": 100, + "latitude": 12.23, + "longitude": 12.23 + } + ] + }, + "method": "fly_to_point" +} +``` + +### 结束飞向目标点: + +```json +{ + "data": {}, + "method": "fly_to_point_stop" +} +``` + +### 更新飞向目标点: + +| max_speed | 指令飞行过程中能达到的最大速度 | int | {"max":15,"min":1,"unit_name":"米每秒 / m/s"} | | +| --- | --- | --- | --- | --- | +| points | 更新的目标点列表 | array | {"size": -, "item_type": struct} | 仅支持 1 个目标点 | +| »latitude | 目标点纬度 | double | {"max":90,"min":-90} | 目标点纬度,角度值,南纬是负,北纬是正,精度到小数点后6位 | +| »longitude | 目标点经度 | double | {"max":180,"min":-180} | 目标点经度,角度值,东经是正,西经是负,精度到小数点后6位 | +| »height | 目标点高度 | float | {"max":10000,"min":2,"step":0.1,"unit_name":"米 / m"} | 目标点高度(椭球高),使用 WGS84 模型 | + +```json +{ + "data": { + "max_speed": 12, + "points": [ + { + "height": 100, + "latitude": 12.23, + "longitude": 12.23 + } + ] + }, + "method": "fly_to_point_update" +} +``` + +### 返航: + +```json +{ + "data": {}, + "method": "return_home" +} +``` diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDevice.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDevice.java new file mode 100644 index 00000000..0611d524 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDevice.java @@ -0,0 +1,49 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * Device information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("manage_device") +public class AgeDevice extends SuperEntity { + + private String deviceSn; + private String deviceName; + private String userId; + private String nickname; + private String workspaceId; + private Integer deviceType; + private Integer subType; + private Integer domain; + private String firmwareVersion; + private Integer compatibleStatus; + private String version; + private String deviceIndex; + private String childSn; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + private Long boundTime; + private Integer boundStatus; + private Long loginTime; + private String deviceDesc; + private String urlNormal; + private String urlSelect; + private String tenantId; +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceFirmware.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceFirmware.java new file mode 100644 index 00000000..1f9e6ada --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceFirmware.java @@ -0,0 +1,41 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("manage_device_firmware") +public class AgeDeviceFirmware extends SuperEntity { + private static final long serialVersionUID=1L; + + private String firmwareId; + private String fileName; + private String firmwareVersion; + private String objectKey; + private Long fileSize; + private String fileMd5; + private String workspaceId; + private String releaseNote; + private Long releaseDate; + private String userName; + private Integer status; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceHms.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceHms.java new file mode 100644 index 00000000..4137d1e2 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceHms.java @@ -0,0 +1,38 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * Device's hms information + * + * @author lsl + * @date 2024-12-19 17:53:01 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("manage_device_hms") +public class AgeDeviceHms extends SuperEntity { + private static final long serialVersionUID=1L; + + private String hmsId; + private String tid; + private String bid; + private String sn; + private Integer level; + private Integer module; + private String hmsKey; + private String messageZh; + private String messageEn; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceLogs.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceLogs.java new file mode 100644 index 00000000..89a3e500 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceLogs.java @@ -0,0 +1,35 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * Log for uploading logs + * + * @author lsl + * @date 2024-12-19 17:53:03 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("manage_device_logs") +public class AgeDeviceLogs extends SuperEntity { + private static final long serialVersionUID=1L; + + private String logsId; + private String username; + private String deviceSn; + private String logsInfo; + private Long happenTime; + private Integer status; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDevicePayload.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDevicePayload.java new file mode 100644 index 00000000..ffbdf5eb --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDevicePayload.java @@ -0,0 +1,38 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * The payload information of the device. + * + * @author lsl + * @date 2024-12-19 17:53:19 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("manage_device_payload") +public class AgeDevicePayload extends SuperEntity { + private static final long serialVersionUID=1L; + + private String payloadSn; + private String payloadName; + private Integer payloadType; + private Integer subType; + private String firmwareVersion; + private Integer payloadIndex; + private String deviceSn; + private String payloadDesc; + private String controlSource; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeFirmwareModel.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeFirmwareModel.java new file mode 100644 index 00000000..ea19462f --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeFirmwareModel.java @@ -0,0 +1,31 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:53:20 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("manage_firmware_model") +public class AgeFirmwareModel extends SuperEntity { + private static final long serialVersionUID=1L; + + private String firmwareId; + private String deviceName; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeWorkspace.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeWorkspace.java new file mode 100644 index 00000000..ce85a7cd --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeWorkspace.java @@ -0,0 +1,34 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:52:26 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("manage_workspace") +public class AgeWorkspace extends SuperEntity { + private static final long serialVersionUID=1L; + + private String workspaceId; + private String workspaceName; + private String workspaceDesc; + private String platformName; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + private String bindCode; +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/IaFile.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/IaFile.java new file mode 100644 index 00000000..f10e5d7d --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/model/IaFile.java @@ -0,0 +1,41 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * Media file information + * + * @author lsl + * @date 2024-12-19 17:52:18 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("media_file") +public class IaFile extends SuperEntity { + private static final long serialVersionUID=1L; + + private String fileId; + private String fileName; + private String filePath; + private String workspaceId; + private String fingerprint; + private String tinnyFingerprint; + private String objectKey; + private Integer subFileType; + private Integer isOriginal; + private String drone; + private String payload; + private String jobId; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/LineFile.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/LineFile.java new file mode 100644 index 00000000..29240efa --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/model/LineFile.java @@ -0,0 +1,41 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * Wayline file information + * + * @author lsl + * @date 2024-12-19 17:51:52 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("wayline_file") +public class LineFile extends SuperEntity { + private static final long serialVersionUID=1L; + + private String name; + private String waylineId; + private String droneModelKey; + private String payloadModelKeys; + private String workspaceId; + private String sign; + private Integer favorited; + private String templateTypes; + private String objectKey; + private String userName; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + private String tenantId; +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/LineJob.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/LineJob.java new file mode 100644 index 00000000..2ce273d0 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/model/LineJob.java @@ -0,0 +1,47 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * Wayline mission information of the dock. + * + * @author lsl + * @date 2024-12-19 17:51:53 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("wayline_job") +public class LineJob extends SuperEntity { + private static final long serialVersionUID=1L; + + private String jobId; + private String name; + private String fileId; + private String dockSn; + private String workspaceId; + private Integer taskType; + private Integer waylineType; + private Long executeTime; + private Long completedTime; + private String username; + private Long beginTime; + private Long endTime; + private Integer errorCode; + private Integer status; + private Integer rthAltitude; + private Integer outOfControl; + private Integer mediaCount; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + private String parentId; +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/SFile.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/SFile.java new file mode 100644 index 00000000..2006dc7b --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/model/SFile.java @@ -0,0 +1,37 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * Logs file information + * + * @author lsl + * @date 2024-12-19 17:53:36 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("logs_file") +public class SFile extends SuperEntity { + private static final long serialVersionUID=1L; + + private String fileId; + private String name; + private Long size; + private String logsId; + private String deviceSn; + private String fingerprint; + private String objectKey; + private Integer status; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/SFileIndex.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/SFileIndex.java new file mode 100644 index 00000000..1aed54a5 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/model/SFileIndex.java @@ -0,0 +1,36 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * The boot index table corresponding to the logs file. + * + * @author lsl + * @date 2024-12-19 17:53:23 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("logs_file_index") +public class SFileIndex extends SuperEntity { + private static final long serialVersionUID=1L; + + private Integer bootIndex; + private String fileId; + private Long startTime; + private Long endTime; + private Long size; + private String deviceSn; + private Integer domain; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/excel/AgeDeviceExcel.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/excel/AgeDeviceExcel.java new file mode 100644 index 00000000..2aed8665 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/model/excel/AgeDeviceExcel.java @@ -0,0 +1,174 @@ +package com.central.device.model.excel; + +import com.alibaba.excel.annotation.ExcelIgnore; +import com.alibaba.excel.annotation.ExcelProperty; +import com.alibaba.excel.annotation.write.style.ColumnWidth; +import com.central.device.model.AgeDevice; +import com.fasterxml.jackson.annotation.JsonFormat; +import jakarta.validation.constraints.NotBlank; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.Date; + +/** + * 设备信息Excel导入导出实体 + * + * @author lsl + * @date 2024-12-19 + */ +@Data +@EqualsAndHashCode(callSuper = false) +public class AgeDeviceExcel { + + @ExcelProperty(value = "设备序列号", index = 0) + @ColumnWidth(20) + @NotBlank(message = "设备序列号不能为空") + private String deviceSn; + + @ExcelProperty(value = "设备名称", index = 1) + @ColumnWidth(20) + @NotBlank(message = "设备名称不能为空") + private String deviceName; + + @ExcelProperty(value = "设备类型", index = 2) + @ColumnWidth(15) + private Integer deviceType; + + @ExcelProperty(value = "子类型", index = 3) + @ColumnWidth(15) + private Integer subType; + + @ExcelProperty(value = "固件版本", index = 4) + @ColumnWidth(20) + private String firmwareVersion; + + @ExcelProperty(value = "设备描述", index = 6) + @ColumnWidth(30) + private String deviceDesc; + + @ExcelProperty(value = "工作空间ID", index = 7) + @ColumnWidth(20) + private String workspaceId; + + @ExcelProperty(value = "域", index = 8) + @ColumnWidth(15) + private Integer domain; + + @ExcelProperty(value = "兼容状态", index = 9) + @ColumnWidth(15) + private Integer compatibleStatus; + + @ExcelProperty(value = "版本", index = 10) + @ColumnWidth(15) + private String version; + + @ExcelProperty(value = "设备索引", index = 11) + @ColumnWidth(20) + private String deviceIndex; + + @ExcelProperty(value = "子设备序列号", index = 12) + @ColumnWidth(20) + private String childSn; + + @ExcelProperty(value = "绑定状态", index = 13) + @ColumnWidth(15) + private Integer boundStatus; + + @ExcelProperty(value = "租户ID", index = 14) + @ColumnWidth(20) + private String tenantId; + + // 以下字段在Excel中不显示,但在实体转换时需要 + @ExcelIgnore + private String userId; + + @ExcelIgnore + private String nickname; + + @ExcelIgnore + private Long boundTime; + + @ExcelIgnore + private Long loginTime; + + @ExcelIgnore + private String urlNormal; + + @ExcelIgnore + private String urlSelect; + + @ExcelProperty(value = "创建时间", index = 15) + @ColumnWidth(20) + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date createTime; + + @ExcelProperty(value = "更新时间", index = 16) + @ColumnWidth(20) + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date updateTime; + + /** + * 转换为设备实体 + */ + public AgeDevice toDevice() { + AgeDevice device = new AgeDevice(); + // 必填字段 + device.setDeviceSn(this.deviceSn); + device.setDeviceName(this.deviceName); + device.setDeviceType(this.deviceType); + + // 可选字段,需要判空 + device.setSubType(this.subType); + device.setFirmwareVersion(this.firmwareVersion); + device.setDeviceDesc(this.deviceDesc); + device.setWorkspaceId(this.workspaceId); + device.setDomain(this.domain); + device.setCompatibleStatus(this.compatibleStatus); + device.setVersion(this.version); + device.setDeviceIndex(this.deviceIndex); + device.setChildSn(this.childSn); + device.setBoundStatus(this.boundStatus); + device.setTenantId(this.tenantId); + + // 系统字段 + device.setCreateTime(this.createTime); + device.setUpdateTime(this.updateTime); + + return device; + } + + /** + * 从设备实体转换 + */ + public static AgeDeviceExcel fromDevice(AgeDevice device) { + if (device == null) { + return null; + } + + AgeDeviceExcel excel = new AgeDeviceExcel(); + // 必填字段 + excel.setDeviceSn(device.getDeviceSn()); + excel.setDeviceName(device.getDeviceName()); + excel.setDeviceType(device.getDeviceType()); + + // 可选字段 + excel.setSubType(device.getSubType()); + excel.setFirmwareVersion(device.getFirmwareVersion()); + excel.setDeviceDesc(device.getDeviceDesc()); + excel.setWorkspaceId(device.getWorkspaceId()); + excel.setDomain(device.getDomain()); + excel.setCompatibleStatus(device.getCompatibleStatus()); + excel.setVersion(device.getVersion()); + excel.setDeviceIndex(device.getDeviceIndex()); + excel.setChildSn(device.getChildSn()); + excel.setBoundStatus(device.getBoundStatus()); + excel.setTenantId(device.getTenantId()); + + // 系统字段 + excel.setCreateTime(device.getCreateTime()); + excel.setUpdateTime(device.getUpdateTime()); + + return excel; + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/vo/DistributionDataVO.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/vo/DistributionDataVO.java new file mode 100644 index 00000000..d02f41d8 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/model/vo/DistributionDataVO.java @@ -0,0 +1,16 @@ +package com.central.device.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "分布数据") +public class DistributionDataVO { + @Schema(description = "类型") + private String type; + + @Schema(description = "数值") + private BigDecimal value; +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceFirmwareService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceFirmwareService.java new file mode 100644 index 00000000..33c98966 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceFirmwareService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.AgeDeviceFirmware; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface IAgeDeviceFirmwareService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceHmsService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceHmsService.java new file mode 100644 index 00000000..ee8f1ceb --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceHmsService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.AgeDeviceHms; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * Device's hms information + * + * @author lsl + * @date 2024-12-19 17:53:01 + */ +public interface IAgeDeviceHmsService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceLogsService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceLogsService.java new file mode 100644 index 00000000..3fcc6be4 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceLogsService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.AgeDeviceLogs; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * Log for uploading logs + * + * @author lsl + * @date 2024-12-19 17:53:03 + */ +public interface IAgeDeviceLogsService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDevicePayloadService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDevicePayloadService.java new file mode 100644 index 00000000..91f3de0d --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDevicePayloadService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.AgeDevicePayload; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * The payload information of the device. + * + * @author lsl + * @date 2024-12-19 17:53:19 + */ +public interface IAgeDevicePayloadService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceService.java new file mode 100644 index 00000000..4f342ab7 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceService.java @@ -0,0 +1,44 @@ +package com.central.device.service; + +import com.central.device.model.AgeDevice; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.List; +import java.util.Map; + +/** + * Device information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +public interface IAgeDeviceService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 根据参数查询设备列表 + */ + List findListByParams(Map params); + + /** + * 根据设备序列号查询设备 + */ + AgeDevice getByDeviceSn(String deviceSn); + + /** + * 检查设备序列号是否存在 + */ + boolean checkDeviceSnExists(String deviceSn); + + /** + * 批量导入设备信息 + */ + boolean importDevices(List deviceList); +} + diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeFirmwareModelService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeFirmwareModelService.java new file mode 100644 index 00000000..c2a674eb --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeFirmwareModelService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.AgeFirmwareModel; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:53:20 + */ +public interface IAgeFirmwareModelService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeWorkspaceService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeWorkspaceService.java new file mode 100644 index 00000000..97375734 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeWorkspaceService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.AgeWorkspace; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:52:26 + */ +public interface IAgeWorkspaceService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IIaFileService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IIaFileService.java new file mode 100644 index 00000000..8477e62a --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IIaFileService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.IaFile; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * Media file information + * + * @author lsl + * @date 2024-12-19 17:52:18 + */ +public interface IIaFileService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/ILineFileService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/ILineFileService.java new file mode 100644 index 00000000..5071320f --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/ILineFileService.java @@ -0,0 +1,25 @@ +package com.central.device.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.device.model.LineFile; + +import java.util.Map; + +/** + * Wayline file information + * + * @author lsl + * @date 2024-12-19 17:51:52 + */ +public interface ILineFileService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + LineFile findLineFileByWaylineId(String waylineId); +} + diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/ILineJobService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/ILineJobService.java new file mode 100644 index 00000000..e7af5fc2 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/ILineJobService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.LineJob; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * Wayline mission information of the dock. + * + * @author lsl + * @date 2024-12-19 17:51:53 + */ +public interface ILineJobService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/ISFileIndexService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/ISFileIndexService.java new file mode 100644 index 00000000..c05a71a5 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/ISFileIndexService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.SFileIndex; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * The boot index table corresponding to the logs file. + * + * @author lsl + * @date 2024-12-19 17:53:23 + */ +public interface ISFileIndexService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/ISFileService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/ISFileService.java new file mode 100644 index 00000000..6dc34343 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/ISFileService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.SFile; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * Logs file information + * + * @author lsl + * @date 2024-12-19 17:53:36 + */ +public interface ISFileService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/LiveStreamService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/LiveStreamService.java new file mode 100644 index 00000000..851573d7 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/LiveStreamService.java @@ -0,0 +1,58 @@ +package com.central.device.service; + +import com.alibaba.fastjson.JSONObject; +import com.central.device.util.TencentLiveUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; + +import java.util.concurrent.TimeUnit; + +@Service +public class LiveStreamService { + + @Value("${tencent.live.push-domain}") + private String pushDomain; + @Value("${tencent.live.play-domain}") + private String playDomain; + @Value("${tencent.live.app-name}") + private String appName; + @Value("${tencent.live.key}") + private String key; + @Value("${tencent.live.expire-seconds:3600}") + private long expireSeconds; + + private static final String STREAM_URL_KEY_PREFIX = "device:stream_urls:"; + + @Autowired + private StringRedisTemplate redisTemplate; + + /** + * 生成设备推流和拉流地址,并缓存到Redis + */ + public JSONObject generateStreamUrls(String deviceId) { + String cacheKey = STREAM_URL_KEY_PREFIX + deviceId; + String cacheValue = redisTemplate.opsForValue().get(cacheKey); + if (cacheValue != null) { + return JSONObject.parseObject(cacheValue); + } + + long expire = System.currentTimeMillis() / 1000 + expireSeconds; + String pushUrl = TencentLiveUtil.generatePushUrl(pushDomain, appName, deviceId, key, expire); + String playRtmpUrl = TencentLiveUtil.generatePlayUrl(playDomain, appName, deviceId, "rtmp"); + String playFlvUrl = TencentLiveUtil.generatePlayUrl(playDomain, appName, deviceId, "flv"); + String playM3u8Url = TencentLiveUtil.generatePlayUrl(playDomain, appName, deviceId, "m3u8"); + + JSONObject result = new JSONObject(); + result.put("pushUrl", pushUrl); + result.put("playRtmpUrl", playRtmpUrl); + result.put("playFlvUrl", playFlvUrl); + result.put("playM3u8Url", playM3u8Url); + + // 缓存到redis,设置过期时间(如1小时) + redisTemplate.opsForValue().set(cacheKey, result.toJSONString(), 1, TimeUnit.HOURS); + + return result; + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceFirmwareServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceFirmwareServiceImpl.java new file mode 100644 index 00000000..99ffce09 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceFirmwareServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.AgeDeviceFirmwareMapper; +import com.central.device.model.AgeDeviceFirmware; +import com.central.device.service.IAgeDeviceFirmwareService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +public class AgeDeviceFirmwareServiceImpl extends SuperServiceImpl implements IAgeDeviceFirmwareService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceHmsServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceHmsServiceImpl.java new file mode 100644 index 00000000..7061a557 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceHmsServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.AgeDeviceHmsMapper; +import com.central.device.model.AgeDeviceHms; +import com.central.device.service.IAgeDeviceHmsService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Device's hms information + * + * @author lsl + * @date 2024-12-19 17:53:01 + */ +@Slf4j +@Service +public class AgeDeviceHmsServiceImpl extends SuperServiceImpl implements IAgeDeviceHmsService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceLogsServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceLogsServiceImpl.java new file mode 100644 index 00000000..fd7ad125 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceLogsServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.AgeDeviceLogsMapper; +import com.central.device.model.AgeDeviceLogs; +import com.central.device.service.IAgeDeviceLogsService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Log for uploading logs + * + * @author lsl + * @date 2024-12-19 17:53:03 + */ +@Slf4j +@Service +public class AgeDeviceLogsServiceImpl extends SuperServiceImpl implements IAgeDeviceLogsService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDevicePayloadServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDevicePayloadServiceImpl.java new file mode 100644 index 00000000..555676c5 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDevicePayloadServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.AgeDevicePayloadMapper; +import com.central.device.model.AgeDevicePayload; +import com.central.device.service.IAgeDevicePayloadService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * The payload information of the device. + * + * @author lsl + * @date 2024-12-19 17:53:19 + */ +@Slf4j +@Service +public class AgeDevicePayloadServiceImpl extends SuperServiceImpl implements IAgeDevicePayloadService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceServiceImpl.java new file mode 100644 index 00000000..68ae00cd --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceServiceImpl.java @@ -0,0 +1,91 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.AgeDeviceMapper; +import com.central.device.model.AgeDevice; +import com.central.device.service.IAgeDeviceService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; + +import java.util.List; +import java.util.Map; + +/** + * Device information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Slf4j +@Service +public class AgeDeviceServiceImpl extends SuperServiceImpl implements IAgeDeviceService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public List findListByParams(Map params) { + QueryWrapper wrapper = new QueryWrapper<>(); + // 添加查询条件 + if (params.get("deviceSn") != null) { + wrapper.like("device_sn", params.get("deviceSn")); + } + if (params.get("deviceName") != null) { + wrapper.like("device_name", params.get("deviceName")); + } + if (params.get("deviceType") != null) { + wrapper.eq("device_type", params.get("deviceType")); + } + // 可以添加更多查询条件... + return this.list(wrapper); + } + + @Override + public AgeDevice getByDeviceSn(String deviceSn) { + return this.getOne(new QueryWrapper().eq("device_sn", deviceSn)); + } + + @Override + public boolean checkDeviceSnExists(String deviceSn) { + return this.baseMapper.exists(new QueryWrapper() + .eq("device_sn", deviceSn)); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public boolean importDevices(List deviceList) { + if (CollectionUtils.isEmpty(deviceList)) { + return false; + } + + try { + // 批量保存,每批100条 + int batchSize = 100; + int totalSize = deviceList.size(); + + for (int i = 0; i < totalSize; i += batchSize) { + int endIndex = Math.min(i + batchSize, totalSize); + List batch = deviceList.subList(i, endIndex); + this.saveBatch(batch, batchSize); + } + return true; + } catch (Exception e) { + log.error("批量导入设备信息失败", e); + throw new RuntimeException("批量导入设备信息失败", e); + } + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeFirmwareModelServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeFirmwareModelServiceImpl.java new file mode 100644 index 00000000..c9f2485e --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeFirmwareModelServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.AgeFirmwareModelMapper; +import com.central.device.model.AgeFirmwareModel; +import com.central.device.service.IAgeFirmwareModelService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:53:20 + */ +@Slf4j +@Service +public class AgeFirmwareModelServiceImpl extends SuperServiceImpl implements IAgeFirmwareModelService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeWorkspaceServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeWorkspaceServiceImpl.java new file mode 100644 index 00000000..99c1c297 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeWorkspaceServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.AgeWorkspaceMapper; +import com.central.device.model.AgeWorkspace; +import com.central.device.service.IAgeWorkspaceService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:52:26 + */ +@Slf4j +@Service +public class AgeWorkspaceServiceImpl extends SuperServiceImpl implements IAgeWorkspaceService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/IaFileServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/IaFileServiceImpl.java new file mode 100644 index 00000000..23bd3271 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/IaFileServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.IaFileMapper; +import com.central.device.model.IaFile; +import com.central.device.service.IIaFileService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Media file information + * + * @author lsl + * @date 2024-12-19 17:52:18 + */ +@Slf4j +@Service +public class IaFileServiceImpl extends SuperServiceImpl implements IIaFileService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/LineFileServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/LineFileServiceImpl.java new file mode 100644 index 00000000..50a65f8b --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/LineFileServiceImpl.java @@ -0,0 +1,43 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.LineFileMapper; +import com.central.device.model.LineFile; +import com.central.device.service.ILineFileService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Wayline file information + * + * @author lsl + * @date 2024-12-19 17:51:52 + */ +@Slf4j +@Service +public class LineFileServiceImpl extends SuperServiceImpl implements ILineFileService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public LineFile findLineFileByWaylineId(String waylineId) { + return baseMapper.selectOne(new QueryWrapper() + .eq("wayline_id",waylineId)); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/LineJobServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/LineJobServiceImpl.java new file mode 100644 index 00000000..8f3b1c95 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/LineJobServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.LineJobMapper; +import com.central.device.model.LineJob; +import com.central.device.service.ILineJobService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Wayline mission information of the dock. + * + * @author lsl + * @date 2024-12-19 17:51:53 + */ +@Slf4j +@Service +public class LineJobServiceImpl extends SuperServiceImpl implements ILineJobService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/SFileIndexServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/SFileIndexServiceImpl.java new file mode 100644 index 00000000..40ec93b1 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/SFileIndexServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.SFileIndexMapper; +import com.central.device.model.SFileIndex; +import com.central.device.service.ISFileIndexService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * The boot index table corresponding to the logs file. + * + * @author lsl + * @date 2024-12-19 17:53:23 + */ +@Slf4j +@Service +public class SFileIndexServiceImpl extends SuperServiceImpl implements ISFileIndexService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/SFileServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/SFileServiceImpl.java new file mode 100644 index 00000000..3d508db3 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/SFileServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.SFileMapper; +import com.central.device.model.SFile; +import com.central.device.service.ISFileService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Logs file information + * + * @author lsl + * @date 2024-12-19 17:53:36 + */ +@Slf4j +@Service +public class SFileServiceImpl extends SuperServiceImpl implements ISFileService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/IotRequestResult.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/IotRequestResult.java new file mode 100644 index 00000000..b0dffef1 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/util/IotRequestResult.java @@ -0,0 +1,37 @@ +package com.central.device.util; + +import com.alibaba.fastjson.JSONObject; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.Getter; +import lombok.Setter; + +import java.util.List; + +/** + * IOT request result model + * @author lsl + * @date 2025-02-25 + * + */ +@Setter +@Getter +public class IotRequestResult { + + private String message; + private Integer status; + private Long timestamp; + private String code; + private List result; + + public static IotRequestResult getInstance(JSONObject message) throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + + // 将JSONObject转换为JsonNode,因为ObjectMapper不直接接受JSONObject + JsonNode jsonNode = objectMapper.readTree(message.toString()); + + // 将JsonNode转换为指定的Java类 + return objectMapper.treeToValue(jsonNode, IotRequestResult.class); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/MapUtil.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/MapUtil.java new file mode 100644 index 00000000..d86a6208 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/util/MapUtil.java @@ -0,0 +1,52 @@ +package com.central.device.util; + +import java.util.Map; + +/** + * 获取map各类型值工具类 + * @author lishilin + * @date 2020/03/12 + */ +public class MapUtil { + public static String getStrValue(Map param, String id) { + Object val = getValue(param, id); + if (null == val) { + return null; + } + return val.toString(); + } + + public static Integer getIntValue(Map param, String id) { + Object val = getValue(param, id); + if (null == val) { + return null; + } + try { + return Integer.parseInt(param.get(id).toString()); + } catch (NumberFormatException exp) { + return null; + } + } + + public static Long getLongValue(Map param, String id) { + Object val = getValue(param, id); + if (null == val) { + return null; + } + try { + return Long.parseLong(param.get(id).toString()); + } catch (NumberFormatException exp) { + return null; + } + } + + public static Object getValue(Map param, String id) { + if (null == param && null == id) { + return null; + } + if (param.containsKey(id)) { + return param.get(id); + } + return null; + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/RequestUtils.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/RequestUtils.java new file mode 100644 index 00000000..f59b5422 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/util/RequestUtils.java @@ -0,0 +1,118 @@ +package com.central.device.util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.central.device.util.http.HeaderUtils; +import com.central.device.util.http.HttpRequest; +import com.central.device.util.http.Response; +import com.central.device.util.http.SimpleHttpRequest; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.util.Map; + +/** + * @author LSL + */ +@Slf4j +@Component +public class RequestUtils { + + @Autowired + private HeaderUtils headerUtils; + + /** + * 获取post请求result + * @param url 请求url + * @param jsonObject 请求参数 + * @return + * @throws IOException + */ + public Map getPostRequestResultMap(String url, JSONObject jsonObject) throws IOException { + log.debug(url); + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfJsonString(jsonObject.toJSONString())); + request.requestBody(jsonObject.toJSONString()); + Response response = request.post(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + return result; + } + + /** + * 获取post请求result + * @param url 请求url + * @param param 请求参数 + * @return + * @throws IOException + */ + public Map getPostRequestResultMap(String url, Map param) throws IOException { + log.debug(url); + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfJsonString(JSON.toJSONString(param))); + request.requestBody(JSON.toJSONString(param)); + Response response = request.post(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + return result; + } + + /** + * 获取post请求result + * @param url 请求url + * @param body 请求参数 + * @return + * @throws IOException + */ + public Map getPostRequestResultMap(String url, String body) throws IOException { + log.debug(url); + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfJsonString(body)); + request.requestBody(body); + Response response = request.post(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + log.debug(""+result.get("")); + return result; + } + + /** + * @param url 请求url + * @param map 请求参数map + * @return + * @throws IOException + */ + public Map getGetRequestResultMap(String url,Map map) throws IOException { + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfParams(map)); + + Response response = request.get(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + return result; + } + + /** + * 获取post请求result + * @param url 请求url + * @param param 请求参数 + * @return + * @throws IOException + */ + public Map getThirdPartyPostRequestResultMap(String url, Map param) { + log.info("url:{} , {}",url,param); + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfJsonString(JSON.toJSONString(param))); + request.requestBody(JSON.toJSONString(param)); + Response response; + Map result = null; + try { + response = request.post(); + result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + } catch (IOException e) { + log.info("查询异常:{}",e.getMessage()); + e.printStackTrace(); + } + return result; + } + + +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/TencentLiveUtil.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/TencentLiveUtil.java new file mode 100644 index 00000000..13250dfa --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/util/TencentLiveUtil.java @@ -0,0 +1,30 @@ +package com.central.device.util; + +import org.apache.commons.codec.digest.DigestUtils; + +public class TencentLiveUtil { + + /** + * 生成推流地址 + */ + public static String generatePushUrl(String pushDomain, String appName, String streamName, String key, long expireTime) { + String txTime = Long.toHexString(expireTime).toUpperCase(); + String txSecret = DigestUtils.md5Hex(key + streamName + txTime).toLowerCase(); + return String.format("rtmp://%s/%s/%s?txSecret=%s&txTime=%s", pushDomain, appName, streamName, txSecret, txTime); + } + + /** + * 生成拉流地址 + */ + public static String generatePlayUrl(String playDomain, String appName, String streamName, String type) { + switch (type.toLowerCase()) { + case "flv": + return String.format("http://%s/%s/%s.flv", playDomain, appName, streamName); + case "m3u8": + return String.format("http://%s/%s/%s.m3u8", playDomain, appName, streamName); + case "rtmp": + default: + return String.format("rtmp://%s/%s/%s", playDomain, appName, streamName); + } + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/Utils.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/Utils.java new file mode 100644 index 00000000..fc2af9a5 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/util/Utils.java @@ -0,0 +1,47 @@ +package com.central.device.util; + +import java.io.*; +import java.net.URLDecoder; +import java.util.HashMap; +import java.util.Map; + +/** + * @author lishilin + * @see + * @since 2.0 + */ +public class Utils { + public static Map queryStringToMap(String queryString, String charset){ + try { + Map map = new HashMap<>(); + + String[] decode = URLDecoder.decode(queryString,charset).split("&"); + for (String keyValue : decode) { + String[] kv = keyValue.split("[=]",2); + map.put(kv.length>1?kv[1]:"",kv[0]); + } + return map; + } catch (UnsupportedEncodingException e) { + throw new UnsupportedOperationException(e); + } + } + + /** + * 读文件 + * + * @param file 文件 + * @return + * @throws IOException + * @throws IOException + */ + public static String readTxt(File file) throws IOException { + String s = ""; + InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8"); + BufferedReader br = new BufferedReader(in); + StringBuffer content = new StringBuffer(); + while ((s = br.readLine()) != null) { + content = content.append(s); + } + return content.toString(); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/HeaderUtils.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/HeaderUtils.java new file mode 100644 index 00000000..c066c6d5 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/HeaderUtils.java @@ -0,0 +1,81 @@ +package com.central.device.util.http; + +import org.apache.commons.codec.binary.Hex; +import org.apache.commons.codec.digest.DigestUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.security.MessageDigest; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.Collectors; + +/** + * @author lishilin + * @see + * @since 1.0 + */ +@Component +public class HeaderUtils { + + @Value("${jetlinks.clientId}") + private String xClientId;// = "WFMfEGS8iHrEPRBH" ; + + @Value("${jetlinks.secureKey}") + private String secureKey;// = "ihat3zHC6T7xPZYFAEnG3tExQiFANd2n" ; + public Map createHeadersOfParams(Map params) { + //时间戳 + String xTimestamp = String.valueOf(System.currentTimeMillis()); + //openApi客户端id +// String xClientId = "rN7cpmQb884W4hcH"; + //密钥 +// String secureKey = "hBYtiNxQrA8FZbtetGhCZJPi"; + //将参数按ASCII排序后拼接为k1=v1&k2=v2的格式 + String paramString = new TreeMap<>(params).entrySet() + .stream() + .map(e -> e.getKey().concat("=").concat(String.valueOf(e.getValue()))) + .collect(Collectors.joining("&")); + + System.out.println(paramString); + + //param+X-Timestamp+SecureKey通过MD5加密 + MessageDigest digest = DigestUtils.getMd5Digest(); + System.out.println(paramString + xTimestamp + secureKey); + digest.update(paramString.getBytes()); + digest.update(xTimestamp.getBytes()); + digest.update(secureKey.getBytes()); + + Map headers = new HashMap<>(); + headers.put("X-Sign", Hex.encodeHexString(digest.digest())); + headers.put("X-Client-Id", xClientId); + headers.put("X-Timestamp", xTimestamp); + + return headers; + } + + + public Map createHeadersOfJsonString(String jsonString) { + //时间戳 + String xTimestamp = String.valueOf(System.currentTimeMillis()); + //openApi客户端id +// String xClientId = "rN7cpmQb884W4hcH"; + //密钥 +// String secureKey = "hBYtiNxQrA8FZbtetGhCZJPi"; + + + //param+X-Timestamp+SecureKey通过MD5加密 + MessageDigest digest = DigestUtils.getMd5Digest(); + System.out.println(jsonString + xTimestamp + secureKey); + digest.update(jsonString.getBytes()); + digest.update(xTimestamp.getBytes()); + digest.update(secureKey.getBytes()); + + Map headers = new HashMap<>(5); + headers.put("X-Sign", Hex.encodeHexString(digest.digest())); + headers.put("X-Client-Id", xClientId); + headers.put("X-Timestamp", xTimestamp); + + return headers; + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/HttpRequest.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/HttpRequest.java new file mode 100644 index 00000000..595298df --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/HttpRequest.java @@ -0,0 +1,39 @@ +package com.central.device.util.http; + +import java.io.Closeable; +import java.io.IOException; +import java.util.Map; + +/** + * @author wang + * @see + * @since 1.0 + */ +public interface HttpRequest extends Closeable { + + Response get() throws IOException; + + Response post() throws IOException; + + Response put() throws IOException; + + Response delete() throws IOException; + + Response patch() throws IOException; + + HttpRequest encode(String encode); + + HttpRequest contentType(String type); + + HttpRequest param(String name, String value); + + HttpRequest params(Map params); + + HttpRequest header(String name, String value); + + HttpRequest headers(Map headers); + + HttpRequest requestBody(String body); + + HttpRequest resultAsJsonString(); +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/Response.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/Response.java new file mode 100644 index 00000000..628d7faf --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/Response.java @@ -0,0 +1,13 @@ +package com.central.device.util.http; + +import java.io.IOException; + +/** + * @author wang + * @see + * @since 1.0 + */ +public interface Response { + + byte[] asBytes() throws IOException; +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/SimpleHttpRequest.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/SimpleHttpRequest.java new file mode 100644 index 00000000..d48136fe --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/SimpleHttpRequest.java @@ -0,0 +1,184 @@ +package com.central.device.util.http; + +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.*; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @author wang + * @see + * @since 1.0 + */ +public class SimpleHttpRequest implements HttpRequest { + + private Map params = new LinkedHashMap<>(); + private Map headers = new LinkedHashMap<>(); + private String url; + private String requestBody; + private String contentType; + private String encode = "utf-8"; + protected HttpClient httpClient; + + public SimpleHttpRequest(String url) { + this.url = url; + createHttpClient(); + } + + public SimpleHttpRequest(String url, HttpClient client) { + this.url = url; + this.httpClient = client; + } + + protected void createHttpClient() { + if (httpClient == null) { + HttpClientBuilder builder = HttpClientBuilder.create(); + httpClient = builder.build(); + + } + } + + @Override + public Response get() throws IOException { + String param = EntityUtils.toString(createUrlEncodedFormEntity()); + String tmpUrl = url + (url.contains("?") ? "&" : "?") + param; + HttpGet get = new HttpGet(tmpUrl); + HttpResponse response = execute(get); + return getResultValue(response); + } + + + @Override + public Response post() throws IOException { + HttpPost post = new HttpPost(url); + if (requestBody != null) + post.setEntity(new StringEntity(requestBody, ContentType.create(contentType,encode))); + else { + post.setEntity(createUrlEncodedFormEntity()); + } + HttpResponse response = execute(post); + return getResultValue(response); + } + + @Override + public Response put() throws IOException { + HttpPut put = new HttpPut(url); + if (requestBody != null) + put.setEntity(new StringEntity(requestBody, ContentType.create(contentType, encode))); + else { + + put.setEntity(createUrlEncodedFormEntity()); + } + HttpResponse response = execute(put); + return getResultValue(response); + } + + protected UrlEncodedFormEntity createUrlEncodedFormEntity() throws UnsupportedEncodingException { + List nameValuePair = params.entrySet() + .stream().map(stringStringEntry -> + new BasicNameValuePair(stringStringEntry.getKey(), String.valueOf(stringStringEntry.getValue()))) + .collect(Collectors.toList()); + return new UrlEncodedFormEntity(nameValuePair, encode); + } + + @Override + public Response delete() throws IOException { + HttpDelete delete = new HttpDelete(url); + HttpResponse response = execute(delete); + return getResultValue(response); + } + + @Override + public Response patch() throws IOException { + HttpPatch delete = new HttpPatch(url); + if (requestBody != null) + delete.setEntity(new StringEntity(requestBody, ContentType.create(contentType))); + else { + delete.setEntity(createUrlEncodedFormEntity()); + } + return getResultValue(execute(delete)); + } + + @Override + public void close() throws IOException { + if (httpClient != null && httpClient instanceof CloseableHttpClient) { + ((CloseableHttpClient) httpClient).close(); + } + } + + @Override + public HttpRequest resultAsJsonString() { + header("Accept", "application/json"); + return this; + } + + @Override + public HttpRequest requestBody(String body) { + contentType("application/json"); + this.requestBody = body; + return this; + } + + @Override + public HttpRequest encode(String encode) { + this.encode = encode; + return this; + } + + @Override + public HttpRequest contentType(String type) { + this.contentType = type; + return this; + } + + @Override + public HttpRequest param(String name, String value) { + this.params.put(name, value); + return this; + } + + @Override + public HttpRequest params(Map params) { + this.params.putAll(params); + return this; + } + + @Override + public HttpRequest header(String name, String value) { + this.headers.put(name, value); + return this; + } + + @Override + public HttpRequest headers(Map header) { + this.headers.putAll(header); + return this; + } + + private Response getResultValue(HttpResponse res) throws IOException { + return new SimpleResponse(res); + } + + private HttpResponse execute(HttpRequestBase request) throws IOException { + putHeader(request); + return httpClient.execute(request); + } + + private void putHeader(HttpUriRequest request) { + headers.forEach(request::setHeader); + } +} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/SimpleResponse.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/SimpleResponse.java new file mode 100644 index 00000000..6444f876 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/SimpleResponse.java @@ -0,0 +1,26 @@ +package com.central.device.util.http; + +import org.apache.http.HttpResponse; +import org.apache.http.util.EntityUtils; + +import java.io.IOException; + +/** + * @author wang + * @see + * @since 1.0 + */ +public class SimpleResponse implements Response { + + HttpResponse response; + + public SimpleResponse(HttpResponse response) { + this.response = response; + } + + + @Override + public byte[] asBytes() throws IOException { + return EntityUtils.toByteArray(response.getEntity()); + } +} diff --git a/zlt-business/device-ops-center/src/main/resources/application.yml b/zlt-business/device-ops-center/src/main/resources/application.yml new file mode 100644 index 00000000..32f0c2e5 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/resources/application.yml @@ -0,0 +1,59 @@ +spring: + datasource: +# url: jdbc:mysql://${zlt.datasource.ip}:3306/device-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai + url: jdbc:mysql://${zlt.datasource.ip}/device-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai + username: ${zlt.datasource.username} + password: ${zlt.datasource.password} + driver-class-name: com.mysql.cj.jdbc.Driver + +mybatis-plus: + mapper-locations: classpath:/mapper/*Mapper.xml + #实体扫描,多个package用逗号或者分号分隔 + typeAliasesPackage: com.central.device.model + global-config: + db-config: + id-type: auto + +springdoc: + group-configs: + - group: 'default' + paths-to-match: '/**' + packages-to-scan: com.central.device.controller + +knife4j: + enable: true + setting: + swagger-model-name: 设备中心接口文档 + +jetlinks: + clientId: WFMfEGS8iHrEPRBH + secureKey: ihat3zHC6T7xPZYFAEnG3tExQiFANd2n + server: + baseUrl: http://119.45.169.13:8848/ + + #审计日志 +# audit-log: +# enabled: true +# log-type: db +# datasource: +# driver-class-name: com.mysql.cj.jdbc.Driver +# jdbc-url: jdbc:mysql://${zlt.datasource.ip}:3306/logger-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai +# username: ${zlt.datasource.username} +# password: ${zlt.datasource.password} +tencent: + live: + push-domain: 208280.push.tlivecloud.com + play-domain: goflytec.com + expire-seconds: 3600 #过期时间为1小时 + app-name: live + key: 06b20e5b7d637c1128fa1b48ea91a13e + +zlt: + #多租户配置 + tenant: + enable: false + ignoreTables: + ignoreSqls: + noIgnoreSqls: + - com.central.device.mapper.AgeDeviceMapper.findList + - com.central.device.mapper.LineFileMapper.findList diff --git a/zlt-business/device-ops-center/src/main/resources/bootstrap.yml b/zlt-business/device-ops-center/src/main/resources/bootstrap.yml new file mode 100644 index 00000000..089b3db0 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/resources/bootstrap.yml @@ -0,0 +1,15 @@ +server: + port: 7002 + +spring: + application: + name: device-ops-center + cloud: + nacos: + discovery: + ip: 119.45.169.13 +# cloud: +# nacos: +# discovery: +# metadata: +# version: zlt diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceFirmwareMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceFirmwareMapper.xml new file mode 100644 index 00000000..33de4e1c --- /dev/null +++ b/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceFirmwareMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceHmsMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceHmsMapper.xml new file mode 100644 index 00000000..2bcf9d0b --- /dev/null +++ b/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceHmsMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceLogsMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceLogsMapper.xml new file mode 100644 index 00000000..09722eb0 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceLogsMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceMapper.xml new file mode 100644 index 00000000..efa174ba --- /dev/null +++ b/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/AgeDevicePayloadMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/AgeDevicePayloadMapper.xml new file mode 100644 index 00000000..ea9fd213 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/resources/mapper/AgeDevicePayloadMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/AgeFirmwareModelMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/AgeFirmwareModelMapper.xml new file mode 100644 index 00000000..32e77875 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/resources/mapper/AgeFirmwareModelMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/AgeWorkspaceMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/AgeWorkspaceMapper.xml new file mode 100644 index 00000000..9ba31ce1 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/resources/mapper/AgeWorkspaceMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/IaFileMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/IaFileMapper.xml new file mode 100644 index 00000000..4e6723cd --- /dev/null +++ b/zlt-business/device-ops-center/src/main/resources/mapper/IaFileMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/LineFileMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/LineFileMapper.xml new file mode 100644 index 00000000..b5fcb3e5 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/resources/mapper/LineFileMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/LineJobMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/LineJobMapper.xml new file mode 100644 index 00000000..b498a16d --- /dev/null +++ b/zlt-business/device-ops-center/src/main/resources/mapper/LineJobMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/SFileIndexMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/SFileIndexMapper.xml new file mode 100644 index 00000000..38f304e6 --- /dev/null +++ b/zlt-business/device-ops-center/src/main/resources/mapper/SFileIndexMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/SFileMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/SFileMapper.xml new file mode 100644 index 00000000..3b2002ce --- /dev/null +++ b/zlt-business/device-ops-center/src/main/resources/mapper/SFileMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/pom.xml b/zlt-business/pom.xml index 4ee19a6e..4a756a26 100644 --- a/zlt-business/pom.xml +++ b/zlt-business/pom.xml @@ -22,5 +22,7 @@ device-center order-center + + device-ops-center diff --git a/zlt-gateway/sc-gateway/src/main/resources/application.yml b/zlt-gateway/sc-gateway/src/main/resources/application.yml index 66b7ae7f..c0d649a4 100644 --- a/zlt-gateway/sc-gateway/src/main/resources/application.yml +++ b/zlt-gateway/sc-gateway/src/main/resources/application.yml @@ -123,6 +123,10 @@ knife4j: service-name: order-center url: /api-order/v3/api-docs/default context-path: /api-order + - name: 设备运维服务 + service-name: device-ops-center + url: /api-device-ops/v3/api-docs/default + context-path: /api-device-ops zlt: security: diff --git a/zlt-web/react-web/src/main/frontend/config/routes.ts b/zlt-web/react-web/src/main/frontend/config/routes.ts index 66c8facd..2492d721 100644 --- a/zlt-web/react-web/src/main/frontend/config/routes.ts +++ b/zlt-web/react-web/src/main/frontend/config/routes.ts @@ -184,6 +184,44 @@ icon: 'VideoCameraOutlined', component: './orders/EditTask', }, + { + path: '/device-ops', + name: '设备运维', + icon: 'monitor', + routes: [ + { + path: '/device-ops/device.html', + name: '设备管理', + component: './device-ops/device', + }, + { + path: '/device-ops/device/:id', + name: '设备详情', + component: './device-ops/device/detail', + hideInMenu: true, + }, + { + path: '/device-ops/group.html', + name: '分组管理', + component: './device-ops/group', + }, + { + path: '/device-ops/maintenance.html', + name: '运维管理', + component: './device-ops/maintenance', + }, + { + path: '/device-ops/monitor.html', + name: '设备监控', + component: './device-ops/monitor', + }, + { + path: '/device-ops/statistics.html', + name: '统计分析', + component: './device-ops/statistics', + }, + ], + }, { component: './404', }, diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/device/detail.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/device/detail.tsx new file mode 100644 index 00000000..efcbb90e --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/device/detail.tsx @@ -0,0 +1,248 @@ +import React, { useState } from 'react'; +import { PageContainer } from '@ant-design/pro-layout'; +import { Card, Row, Col, Descriptions, Tag, Timeline, Table, Statistic } from 'antd'; +import { Line } from '@ant-design/plots'; +import { useParams } from 'umi'; + +interface DeviceDetail { + id: string; + name: string; + type: string; + status: string; + model: string; + serialNumber: string; + location: string; + installDate: string; + lastMaintenance: string; + nextMaintenance: string; + manufacturer: string; + specifications: string; +} + +interface MaintenanceRecord { + id: string; + date: string; + type: string; + operator: string; + description: string; + result: string; +} + +interface AlertRecord { + id: string; + time: string; + type: string; + level: string; + message: string; + status: string; +} + +const mockDeviceDetail: DeviceDetail = { + id: '1', + name: '设备A', + type: '传感器', + status: '在线', + model: 'SENSOR-2024', + serialNumber: 'SN20240320001', + location: '1号车间', + installDate: '2024-01-15', + lastMaintenance: '2024-02-15', + nextMaintenance: '2024-04-15', + manufacturer: '某某科技', + specifications: '温度范围:-20℃~80℃,精度:±0.1℃', +}; + +const mockMaintenanceRecords: MaintenanceRecord[] = [ + { + id: '1', + date: '2024-02-15', + type: '定期保养', + operator: '张三', + description: '更换滤芯,校准参数', + result: '正常', + }, + { + id: '2', + date: '2024-01-15', + type: '安装调试', + operator: '李四', + description: '设备安装及初始调试', + result: '正常', + }, +]; + +const mockAlertRecords: AlertRecord[] = [ + { + id: '1', + time: '2024-03-20 09:30:00', + type: '温度告警', + level: '高', + message: '设备温度超过阈值', + status: '已处理', + }, + { + id: '2', + time: '2024-03-19 15:20:00', + type: '通信告警', + level: '中', + message: '设备通信中断', + status: '已处理', + }, +]; + +// 模拟性能数据 +const generatePerformanceData = () => { + const data = []; + for (let i = 0; i < 24; i++) { + data.push({ + time: `${i}:00`, + value: Math.floor(Math.random() * 100), + type: 'CPU使用率', + }); + data.push({ + time: `${i}:00`, + value: Math.floor(Math.random() * 100), + type: '内存使用率', + }); + } + return data; +}; + +const DeviceDetailPage: React.FC = () => { + const { id } = useParams<{ id: string }>(); + const [deviceDetail] = useState(mockDeviceDetail); + const [maintenanceRecords] = useState(mockMaintenanceRecords); + const [alertRecords] = useState(mockAlertRecords); + const [performanceData] = useState(generatePerformanceData()); + + const getStatusColor = (status: string) => { + return status === '在线' ? 'green' : 'red'; + }; + + const getAlertLevelColor = (level: string) => { + const colorMap: { [key: string]: string } = { + '高': 'red', + '中': 'orange', + '低': 'blue', + }; + return colorMap[level] || 'default'; + }; + + const maintenanceColumns = [ + { title: '日期', dataIndex: 'date' }, + { title: '类型', dataIndex: 'type' }, + { title: '操作人', dataIndex: 'operator' }, + { title: '描述', dataIndex: 'description' }, + { title: '结果', dataIndex: 'result' }, + ]; + + const alertColumns = [ + { title: '时间', dataIndex: 'time' }, + { title: '类型', dataIndex: 'type' }, + { + title: '级别', + dataIndex: 'level', + render: (level: string) => ( + {level} + ), + }, + { title: '信息', dataIndex: 'message' }, + { title: '状态', dataIndex: 'status' }, + ]; + + return ( + + + + + + {deviceDetail.name} + {deviceDetail.type} + + {deviceDetail.status} + + {deviceDetail.model} + {deviceDetail.serialNumber} + {deviceDetail.location} + {deviceDetail.installDate} + {deviceDetail.lastMaintenance} + {deviceDetail.nextMaintenance} + {deviceDetail.manufacturer} + {deviceDetail.specifications} + + + + + + + + + + + + + + 0 ? '#cf1322' : '#3f8600' }} + /> + + + + + + + + + + + + + + + + + + + + + +
+ + + + + ); +}; + +export default DeviceDetailPage; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/device/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/device/index.tsx new file mode 100644 index 00000000..83198d39 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/device/index.tsx @@ -0,0 +1,470 @@ +import React, { useRef, useState, useEffect } from 'react'; +import { PageContainer } from '@ant-design/pro-layout'; +import { ProTable, ProColumns, ModalForm, ProFormText, ProFormSelect, ProFormUploadButton } from '@ant-design/pro-components'; +import { Button, Space, message, Popconfirm, Tag, Select, Modal, Dropdown, Menu, Upload, Card, Row, Col, Statistic } from 'antd'; +import { history } from 'umi'; +import { DownOutlined, UploadOutlined, DownloadOutlined, FileExcelOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons'; +import type { UploadFile } from 'antd/es/upload/interface'; +import * as XLSX from 'xlsx'; +import { Pie, Column } from '@ant-design/plots'; +import { device, saveOrUpdateDevice, deleteDevice } from '@/services/device/api'; + +const { Option } = Select; + +interface Device { + deviceSn: string; + deviceName: string; + nickname: string; + deviceType: number; + firmwareVersion: string; + compatibleStatus: number; + boundStatus: number; + createTime: string; + loginTime: string; +} + +const DEVICE_TYPE = { + DOCK: 1, + DRONE: 2, + REMOTE_CONTROL: 3, +} as const; + +const DEVICE_TYPE_OPTIONS = [ + { label: '机场', value: DEVICE_TYPE.DOCK }, + { label: '无人机', value: DEVICE_TYPE.DRONE }, + { label: '遥控器', value: DEVICE_TYPE.REMOTE_CONTROL }, +]; + +const COMPATIBLE_STATUS = { + INCONSISTENT: 0, + CONSISTENT: 1, +} as const; + +const DeviceList: React.FC = () => { + const [createModalVisible, setCreateModalVisible] = useState(false); + const [editModalVisible, setEditModalVisible] = useState(false); + const [currentRow, setCurrentRow] = useState(); + const [selectedGroup, setSelectedGroup] = useState('all'); + const [selectedRowKeys, setSelectedRowKeys] = useState([]); + const [batchGroupModalVisible, setBatchGroupModalVisible] = useState(false); + const [batchStatusModalVisible, setBatchStatusModalVisible] = useState(false); + const [importModalVisible, setImportModalVisible] = useState(false); + const [importFileList, setImportFileList] = useState([]); + const [statistics, setStatistics] = useState({ + total: 0, + online: 0, + offline: 0, + byType: {} as Record, + }); + const actionRef = useRef(); + + // 计算统计数据 + const calculateStatistics = (data: Device[]) => { + const stats = { + total: data.length, + online: data.filter(item => item.boundStatus === 1).length, + offline: data.filter(item => item.boundStatus === 0).length, + byType: {} as Record, + }; + + // 按类型统计 + data.forEach(item => { + const typeName = DEVICE_TYPE_OPTIONS.find(opt => opt.value === item.deviceType)?.label || '未知'; + stats.byType[typeName] = (stats.byType[typeName] || 0) + 1; + }); + + return stats; + }; + + const handleAdd = async (values: any) => { + try { + const response = await saveOrUpdateDevice({ + ...values, + deviceType: Number(values.deviceType), + }); + if (response.resp_code === 0) { + message.success('新增成功'); + if (actionRef.current) { + actionRef.current.reload(); + } + return true; + } + message.error(response.resp_msg || '新增失败'); + return false; + } catch (error) { + message.error('新增失败'); + return false; + } + }; + + const handleEdit = async (values: any) => { + try { + const response = await saveOrUpdateDevice({ + ...values, + deviceType: Number(values.deviceType), + }); + if (response.resp_code === 0) { + message.success('编辑成功'); + if (actionRef.current) { + actionRef.current.reload(); + } + return true; + } + message.error(response.resp_msg || '编辑失败'); + return false; + } catch (error) { + message.error('编辑失败'); + return false; + } + }; + + const handleDelete = async (deviceSn: string) => { + try { + const response = await deleteDevice(deviceSn); + if (response.resp_code === 0) { + message.success('删除成功'); + if (actionRef.current) { + actionRef.current.reload(); + } + } else { + message.error(response.resp_msg || '删除失败'); + } + } catch (error) { + message.error('删除失败'); + } + }; + + const handleBatchDelete = async () => { + if (selectedRowKeys.length === 0) { + message.warning('请选择要删除的设备'); + return; + } + Modal.confirm({ + title: '批量删除', + content: `确定要删除选中的 ${selectedRowKeys.length} 个设备吗?`, + onOk: async () => { + try { + const promises = selectedRowKeys.map(key => deleteDevice(key)); + await Promise.all(promises); + message.success('批量删除成功'); + setSelectedRowKeys([]); + if (actionRef.current) { + actionRef.current.reload(); + } + } catch (error) { + message.error('批量删除失败'); + } + }, + }); + }; + + const columns: ProColumns[] = [ + { + dataIndex: 'index', + valueType: 'indexBorder', + width: 48, + }, + { + title: '设备序列号', + dataIndex: 'deviceSn', + copyable: true, + fixed: 'left', + }, + { + title: '设备名称', + dataIndex: 'deviceName', + }, + { + title: '昵称', + dataIndex: 'nickname', + }, + { + title: '设备类型', + dataIndex: 'deviceType', + valueType: 'select', + valueEnum: { + [DEVICE_TYPE.DOCK]: { text: '机场' }, + [DEVICE_TYPE.DRONE]: { text: '无人机' }, + [DEVICE_TYPE.REMOTE_CONTROL]: { text: '遥控器' }, + }, + }, + { + title: '固件版本', + dataIndex: 'firmwareVersion', + }, + { + title: '固件状态', + dataIndex: 'compatibleStatus', + valueType: 'select', + valueEnum: { + [COMPATIBLE_STATUS.CONSISTENT]: { text: '一致', status: 'Success' }, + [COMPATIBLE_STATUS.INCONSISTENT]: { text: '不一致', status: 'Error' }, + }, + }, + { + title: '绑定状态', + dataIndex: 'boundStatus', + render: (_, record) => ( + + {record.boundStatus === 1 ? : } + {record.boundStatus === 1 ? '已绑定' : '未绑定'} + + ), + }, + { + title: '最后登录', + dataIndex: 'loginTime', + valueType: 'dateTime', + }, + { + title: '创建时间', + dataIndex: 'createTime', + valueType: 'dateTime', + }, + { + title: '操作', + valueType: 'option', + render: (_, record) => [ + { + setCurrentRow(record); + setEditModalVisible(true); + }} + > + 编辑 + , + handleDelete(record.deviceSn)} + > + 删除 + , + ], + }, + ]; + + return ( + + {/* 统计卡片 */} + + + + + + + + + } + /> + + + + + } + /> + + + + + + + + + + + headerTitle="设备管理" + actionRef={actionRef} + rowKey="deviceSn" + search={{ + labelWidth: 120, + }} + toolBarRender={() => [ + , + , + , + , + ]} + request={async (params) => { + const response = await device({ + page: params.current, + limit: params.pageSize, + searchKey: params.searchKey, + searchValue: params.searchValue, + }); + + if (response.resp_code === 0) { + const data = response.data || []; + setStatistics(calculateStatistics(data)); + return { + data, + success: true, + total: response.count || 0, + }; + } + return { + data: [], + success: false, + total: 0, + }; + }} + columns={columns} + rowSelection={{ + selectedRowKeys, + onChange: (keys) => setSelectedRowKeys(keys as string[]), + }} + /> + + + + + + + + + + + + + + + + + + setImportModalVisible(false)} + footer={null} + > + setImportFileList(fileList)} + beforeUpload={() => false} + > + + +
+ +
+
+ + ); +}; + +export default DeviceList; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/group/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/group/index.tsx new file mode 100644 index 00000000..c4e703e0 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/group/index.tsx @@ -0,0 +1,299 @@ +import React, { useRef, useState } from 'react'; +import { PageContainer } from '@ant-design/pro-layout'; +import { ProTable, ProColumns, ModalForm, ProFormText, ProFormSelect } from '@ant-design/pro-components'; +import { Button, Space, message, Popconfirm, Tag, Card, Row, Col, Statistic } from 'antd'; +import { Pie } from '@ant-design/plots'; +import { device } from '@/services/device/api'; + +interface Device { + deviceSn: string; + deviceName: string; + deviceType: number; + boundStatus: number; + createTime: string; + loginTime: string; +} + +interface DeviceGroup { + id: string; + name: string; + description: string; + deviceCount: number; + createTime: string; +} + +const DEVICE_TYPE = { + DOCK: 1, + DRONE: 2, + REMOTE_CONTROL: 3, +} as const; + +const DEVICE_TYPE_OPTIONS = [ + { label: '机场', value: DEVICE_TYPE.DOCK }, + { label: '无人机', value: DEVICE_TYPE.DRONE }, + { label: '遥控器', value: DEVICE_TYPE.REMOTE_CONTROL }, +]; + +const DeviceGroup: React.FC = () => { + const [createModalVisible, setCreateModalVisible] = useState(false); + const [editModalVisible, setEditModalVisible] = useState(false); + const [currentRow, setCurrentRow] = useState(); + const [deviceList, setDeviceList] = useState([]); + const [statistics, setStatistics] = useState({ + totalGroups: 0, + totalDevices: 0, + byType: {} as Record, + }); + const actionRef = useRef(); + + // 获取设备列表 + const fetchDeviceList = async () => { + try { + const response = await device({ + page: 1, + limit: 1000, + }); + if (response.resp_code === 0) { + const data = response.data || []; + setDeviceList(data); + + // 计算统计数据 + const stats = { + totalGroups: 0, // 待实现 + totalDevices: data.length, + byType: {} as Record, + }; + + // 按类型统计 + data.forEach((item: Device) => { + const typeName = DEVICE_TYPE_OPTIONS.find(opt => opt.value === item.deviceType)?.label || '未知'; + stats.byType[typeName] = (stats.byType[typeName] || 0) + 1; + }); + + setStatistics(stats); + } + } catch (error) { + console.error('获取设备列表失败:', error); + } + }; + + const handleAdd = async (values: any) => { + try { + // 待实现:调用创建分组API + message.success('新增成功'); + if (actionRef.current) { + actionRef.current.reload(); + } + return true; + } catch (error) { + message.error('新增失败'); + return false; + } + }; + + const handleEdit = async (values: any) => { + try { + // 待实现:调用更新分组API + message.success('编辑成功'); + if (actionRef.current) { + actionRef.current.reload(); + } + return true; + } catch (error) { + message.error('编辑失败'); + return false; + } + }; + + const handleDelete = async (id: string) => { + try { + // 待实现:调用删除分组API + message.success('删除成功'); + if (actionRef.current) { + actionRef.current.reload(); + } + } catch (error) { + message.error('删除失败'); + } + }; + + const columns: ProColumns[] = [ + { + dataIndex: 'index', + valueType: 'indexBorder', + width: 48, + }, + { + title: '分组名称', + dataIndex: 'name', + }, + { + title: '描述', + dataIndex: 'description', + }, + { + title: '设备数量', + dataIndex: 'deviceCount', + sorter: (a, b) => a.deviceCount - b.deviceCount, + }, + { + title: '创建时间', + dataIndex: 'createTime', + valueType: 'dateTime', + }, + { + title: '操作', + valueType: 'option', + render: (_, record) => [ + { + setCurrentRow(record); + setEditModalVisible(true); + }} + > + 编辑 + , + handleDelete(record.id)} + > + 删除 + , + ], + }, + ]; + + // 准备图表数据 + const typeChartData = Object.entries(statistics.byType).map(([type, count]) => ({ + type, + value: count, + })); + + return ( + + {/* 统计卡片 */} + +
+ + + + + + + + + + + + + + + + + {/* 设备类型分布图 */} + + + + + + + + + + headerTitle="设备分组" + actionRef={actionRef} + rowKey="id" + search={{ + labelWidth: 120, + }} + toolBarRender={() => [ + , + ]} + request={async (params) => { + // 待实现:调用获取分组列表API + return { + data: [], + success: true, + total: 0, + }; + }} + columns={columns} + /> + + + + + + + + + + + + ); +}; + +export default DeviceGroup; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/maintenance/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/maintenance/index.tsx new file mode 100644 index 00000000..2cf26c00 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/maintenance/index.tsx @@ -0,0 +1,275 @@ +import React, { useRef, useState } from 'react'; +import { PageContainer } from '@ant-design/pro-layout'; +import { ProTable, ProColumns, ModalForm, ProFormText, ProFormSelect, ProFormDatePicker } from '@ant-design/pro-components'; +import { Button, Space, message, Popconfirm, Tag } from 'antd'; + +interface MaintenanceTask { + id: string; + deviceName: string; + taskType: string; + status: string; + priority: string; + assignee: string; + startTime: string; + endTime?: string; + description: string; +} + +const TASK_TYPE_OPTIONS = [ + { label: '日常巡检', value: '日常巡检' }, + { label: '故障维修', value: '故障维修' }, + { label: '设备保养', value: '设备保养' }, + { label: '系统升级', value: '系统升级' }, +]; + +const STATUS_OPTIONS = [ + { label: '待处理', value: '待处理' }, + { label: '进行中', value: '进行中' }, + { label: '已完成', value: '已完成' }, + { label: '已取消', value: '已取消' }, +]; + +const PRIORITY_OPTIONS = [ + { label: '高', value: '高' }, + { label: '中', value: '中' }, + { label: '低', value: '低' }, +]; + +const initialMockData: MaintenanceTask[] = [ + { + id: '1', + deviceName: '设备A', + taskType: '日常巡检', + status: '待处理', + priority: '高', + assignee: '张三', + startTime: '2024-03-20 10:00:00', + description: '定期设备巡检', + }, + { + id: '2', + deviceName: '设备B', + taskType: '故障维修', + status: '进行中', + priority: '高', + assignee: '李四', + startTime: '2024-03-19 14:30:00', + description: '设备异常报警处理', + }, +]; + +const MaintenanceList: React.FC = () => { + const [data, setData] = useState(initialMockData); + const [createModalVisible, setCreateModalVisible] = useState(false); + const [editModalVisible, setEditModalVisible] = useState(false); + const [currentRow, setCurrentRow] = useState(); + const actionRef = useRef(); + + const handleAdd = async (values: MaintenanceTask) => { + setData([...data, { ...values, id: Date.now().toString() }]); + message.success('新增成功'); + return true; + }; + + const handleEdit = async (values: MaintenanceTask) => { + setData(data.map((item) => (item.id === values.id ? { ...item, ...values } : item))); + message.success('编辑成功'); + return true; + }; + + const handleDelete = async (record: MaintenanceTask) => { + setData(data.filter((item) => item.id !== record.id)); + message.success('删除成功'); + }; + + const getStatusColor = (status: string) => { + const colorMap: { [key: string]: string } = { + '待处理': 'orange', + '进行中': 'blue', + '已完成': 'green', + '已取消': 'red', + }; + return colorMap[status] || 'default'; + }; + + const getPriorityColor = (priority: string) => { + const colorMap: { [key: string]: string } = { + '高': 'red', + '中': 'orange', + '低': 'green', + }; + return colorMap[priority] || 'default'; + }; + + const columns: ProColumns[] = [ + { title: '设备名称', dataIndex: 'deviceName' }, + { title: '任务类型', dataIndex: 'taskType' }, + { + title: '状态', + dataIndex: 'status', + render: (_, record) => ( + {record.status} + ), + }, + { + title: '优先级', + dataIndex: 'priority', + render: (_, record) => ( + {record.priority} + ), + }, + { title: '负责人', dataIndex: 'assignee' }, + { title: '开始时间', dataIndex: 'startTime' }, + { title: '结束时间', dataIndex: 'endTime' }, + { title: '描述', dataIndex: 'description', ellipsis: true }, + { + title: '操作', + valueType: 'option', + render: (_, record) => ( + + { + setCurrentRow(record); + setEditModalVisible(true); + }} + > + 编辑 + + handleDelete(record)}> + 删除 + + + ), + }, + ]; + + return ( + + + headerTitle="运维任务列表" + rowKey="id" + search={false} + dataSource={data} + columns={columns} + actionRef={actionRef} + toolBarRender={() => [ + , + ]} + /> + {/* 新增任务弹窗 */} + { + await handleAdd(values as MaintenanceTask); + setCreateModalVisible(false); + return true; + }} + > + + + + + + + + + + {/* 编辑任务弹窗 */} + { + await handleEdit({ ...currentRow, ...values } as MaintenanceTask); + setEditModalVisible(false); + setCurrentRow(undefined); + return true; + }} + > + + + + + + + + + + + ); +}; + +export default MaintenanceList; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/models/device.ts b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/models/device.ts new file mode 100644 index 00000000..df9761a5 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/models/device.ts @@ -0,0 +1,44 @@ +import { getDeviceList } from '../services/api'; + +export interface Device { + id: string; + name: string; + type: string; + status: string; + group?: string; +} + +export interface DeviceModelState { + deviceList: Device[]; + total: number; +} + +const DeviceModel = { + namespace: 'deviceOpsDevice', + state: { + deviceList: [], + total: 0, + }, + effects: { + *fetchDeviceList({ payload }: any, { call, put }: any): any { + const response = yield call(getDeviceList, payload); + yield put({ + type: 'saveDeviceList', + payload: { + deviceList: response?.data?.records || [], + total: response?.data?.total || 0, + }, + }); + }, + }, + reducers: { + saveDeviceList(state: any, { payload }: any): any { + return { + ...state, + ...payload, + }; + }, + }, +}; + +export default DeviceModel; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx new file mode 100644 index 00000000..58e411da --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx @@ -0,0 +1,1021 @@ +import React, { useState, useEffect, useRef } from 'react'; +import { PageContainer } from '@ant-design/pro-layout'; +import { Card, Row, Col, DatePicker, Select, Space, Table, Tag, Statistic, message } from 'antd'; +import { Line } from '@ant-design/plots'; +import moment from 'moment'; +import { CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons'; +import { device } from '@/services/device/api'; +import { request } from 'umi'; + +const { RangePicker } = DatePicker; + +interface Device { + deviceSn: string; + deviceName: string; + deviceType: number; + boundStatus: number; + createTime: string; + loginTime: string; + metrics: { + temperature: number; + humidity: number; + windSpeed: number; + rainfall: number; + environmentTemperature: number; + positionQuality: number; + networkQuality: number; + droneInDock: number; + batteryCapacity: number; + batteryState: number; + workingVoltage: number; + workingCurrent: number; + acdcPowerInput: number; + backupBatteryVoltage: number; + flightTaskStep: number; + tiltAngle: number; + sdrUpQuality: number; + sdrDownQuality: number; + wirelessLinkState: number; + wirelessLinkQuality: number; + '4gLinkState': number; + '4gLinkQuality': number; + }; +} + +interface DeviceMetrics { + time: string; + value: number; + type: string; +} + +interface AlertRecord { + id: string; + deviceSn: string; + deviceName: string; + alertType: string; + alertLevel: string; + alertTime: string; + status: string; +} + +interface WebSocketMessage { + type: string; + topic: string; + parameter: { + messageType: string; + properties: { + method: string; + data: any; + }; + headers: { + async: boolean; + }; + }; + id: string; +} + +interface TokenResponse { + data: { + result: string; + message: string; + status: number; + timestamp: number; + expires?: number; + }; + resp_code: number; + resp_msg: string; +} + +interface FireAlarmPayload { + headers: { + deviceName: string; + productName: string; + productId: string; + }; + messageId: string; + deviceId: string; + timestamp: number; + event: string; + data: { + data: { + // 环境数据 + temperature?: number; + humidity?: number; + wind_speed?: number; + rainfall?: number; + environment_temperature?: number; + latitude?: number; + longitude?: number; + height?: number; + heading?: number; + // 设备状态 + drone_charge_state?: { + capacity_percent: number; + state: number; + }; + position_state?: { + is_calibration: number; + rtk_number: number; + gps_number: number; + is_fixed: number; + quality: number; + }; + network_state?: { + rate: number; + type: number; + quality: number; + }; + drone_in_dock?: number; + // 飞行任务数据 + flighttask_step_code?: number; + sdr?: { + frequency_band: number; + up_quality: number; + down_quality: number; + }; + tilt_angle?: { + valid: number; + value: number; + }; + wireless_link?: { + sdr_link_state: number; + '4g_freq_band': number; + '4g_quality': number; + link_workmode: number; + sdr_quality: number; + '4g_uav_quality': number; + sdr_freq_band: number; + '4g_link_state': number; + '4g_gnd_quality': number; + dongle_number: number; + }; + }; + deviceId: string; + timestamp: number; + }; + messageType: string; +} + +const DEFAULT_EXPIRES = 7200; // 2小时,单位秒 + +const DeviceMonitor: React.FC = () => { + const [timeRange, setTimeRange] = useState<[moment.Moment, moment.Moment]>([ + moment().subtract(24, 'hours'), + moment(), + ]); + const [selectedDevice, setSelectedDevice] = useState('all'); + const [deviceList, setDeviceList] = useState([]); + const [metricsMap, setMetricsMap] = useState>({}); + const [alerts, setAlerts] = useState([]); + const [loading, setLoading] = useState(false); + const wsRef = useRef(null); + const [wsConnected, setWsConnected] = useState(false); + const reconnectTimerRef = useRef(); + const heartbeatTimerRef = useRef(); + + // token自动续期相关 + const tokenCache = { + value: '', + expire: 0, + timer: null as NodeJS.Timeout | null, + }; + + const refreshTokenAndReconnect = async () => { + // 强制获取新token + tokenCache.value = ''; + await getToken(); + // 关闭旧ws并重建 + if (wsRef.current) { + wsRef.current.close(); + } + await initWebSocket(); + }; + + const getToken = async (expires: number = DEFAULT_EXPIRES) => { + const now = Date.now(); + if (tokenCache.value && tokenCache.expire > now) { + return tokenCache.value; + } + // 传递 expires 参数 + const tokenResponse = await request('/api-device/token/query', { + method: 'GET', + params: { expires }, + }); + if (tokenResponse.resp_code !== 0) { + throw new Error(tokenResponse.resp_msg || '获取token失败'); + } + const { result: token, expires: expiresFromServer } = tokenResponse.data; + // 优先用后端返回的 expires,否则用请求时的 + const expireSeconds = expiresFromServer ?? expires; + tokenCache.value = token; + tokenCache.expire = now + expireSeconds * 1000; + // 清除旧定时器 + if (tokenCache.timer) clearTimeout(tokenCache.timer); + // 提前5分钟自动续期 + tokenCache.timer = setTimeout(() => { + refreshTokenAndReconnect(); + }, expireSeconds * 1000 - 5 * 60 * 1000); + return token; + }; + + // 获取设备列表 + const fetchDeviceList = async () => { + try { + setLoading(true); + const response = await device({ + page: 1, + limit: 1000, + }); + if (response.resp_code === 0) { + const devices = response.data || []; + // 初始化设备数据 + const initializedDevices = devices.map((item: Device) => ({ + ...item, + metrics: { + temperature: 0, + humidity: 0, + windSpeed: 0, + rainfall: 0, + environmentTemperature: 0, + positionQuality: 0, + networkQuality: 0, + droneInDock: 0, + batteryCapacity: 0, + batteryState: 0, + workingVoltage: 0, + workingCurrent: 0, + acdcPowerInput: 0, + backupBatteryVoltage: 0, + flightTaskStep: 0, + tiltAngle: 0, + sdrUpQuality: 0, + sdrDownQuality: 0, + wirelessLinkState: 0, + wirelessLinkQuality: 0, + '4gLinkState': 0, + '4gLinkQuality': 0, + } + })); + setDeviceList(initializedDevices); + console.log('设备列表已更新:', initializedDevices); + } + } catch (error) { + console.error('获取设备列表失败:', error); + message.error('获取设备列表失败'); + } finally { + setLoading(false); + } + }; + + // 修改 WebSocket 连接初始化 + const initWebSocket = async () => { + try { + console.log('开始初始化WebSocket连接...'); + const token = await getToken(); + console.log('获取到WebSocket token:', token); + + // 如果已经存在连接,且未关闭,不重复建立 + if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) { + console.log('WebSocket已连接,无需重复建立'); + return; + } + if (wsRef.current) { + console.log('关闭已存在的WebSocket连接'); + wsRef.current.close(); + } + + // 建立WebSocket连接 + const wsUrl = `ws://119.45.169.13:8848/messaging/${token}`; + console.log('正在连接WebSocket:', wsUrl); + const ws = new WebSocket(wsUrl); + wsRef.current = ws; + + ws.onopen = () => { + console.log('WebSocket连接已建立'); + setWsConnected(true); + // 启动心跳检测 + startHeartbeat(); + // 根据当前选中的设备订阅消息 + if (selectedDevice !== 'all') { + console.log('当前选中的设备:', selectedDevice); + subscribeDeviceMessages(selectedDevice); + } else { + console.log('未选择具体设备,订阅所有设备在线状态'); + subscribeDeviceMessages(); + } + }; + + ws.onmessage = (event) => { + console.log('收到WebSocket原始消息:', event.data); + try { + const data = JSON.parse(event.data); + console.log('解析后的WebSocket消息:', JSON.stringify(data, null, 2)); + // 处理心跳响应 + if (data.type === 'pong') { + console.log('收到心跳响应'); + return; + } + // 添加调试信息 + console.log('准备处理WebSocket消息...'); + console.log('消息类型:', data.type); + console.log('消息主题:', data.topic); + console.log('消息负载:', JSON.stringify(data.payload, null, 2)); + handleWebSocketMessage(data); + } catch (error) { + console.error('解析WebSocket消息失败:', error); + console.error('原始消息内容:', event.data); + } + }; + + ws.onerror = (error) => { + console.error('WebSocket错误:', error); + message.error('WebSocket连接错误'); + setWsConnected(false); + // 尝试重连 + scheduleReconnect(); + }; + + ws.onclose = (event) => { + console.log('WebSocket连接已关闭,代码:', event.code, '原因:', event.reason); + setWsConnected(false); + // 尝试重连 + scheduleReconnect(); + }; + } catch (error) { + console.error('初始化WebSocket失败:', error); + message.error('初始化WebSocket失败'); + // 尝试重连 + scheduleReconnect(); + } + }; + + // 切换设备时只发订阅,不重建ws + useEffect(() => { + console.log('选中的设备已更改:', selectedDevice); + if (wsRef.current?.readyState === WebSocket.OPEN) { + if (selectedDevice !== 'all') { + console.log('WebSocket已连接,开始订阅设备消息:', selectedDevice); + subscribeDeviceMessages(selectedDevice); + } else { + console.log('WebSocket已连接,订阅所有设备在线状态'); + subscribeDeviceMessages(); + } + } else { + console.log('WebSocket未连接,尝试重新连接...'); + initWebSocket(); + } + }, [selectedDevice]); + + // 重连机制 + const scheduleReconnect = () => { + if (reconnectTimerRef.current) { + clearTimeout(reconnectTimerRef.current); + } + reconnectTimerRef.current = setTimeout(() => { + console.log('尝试重新连接WebSocket...'); + initWebSocket(); + }, 5000); // 5秒后重试 + }; + + // 心跳检测 + const startHeartbeat = () => { + if (heartbeatTimerRef.current) { + clearInterval(heartbeatTimerRef.current); + } + heartbeatTimerRef.current = setInterval(() => { + if (wsRef.current?.readyState === WebSocket.OPEN) { + wsRef.current.send(JSON.stringify({ type: 'ping' })); + } + }, 30000); // 每30秒发送一次心跳 + }; + + // 清理函数 + const cleanup = () => { + if (reconnectTimerRef.current) { + clearTimeout(reconnectTimerRef.current); + } + if (heartbeatTimerRef.current) { + clearInterval(heartbeatTimerRef.current); + } + if (wsRef.current) { + wsRef.current.close(); + } + }; + + // 添加调试函数 + const debugWebSocketMessage = (data: any) => { + console.log('WebSocket消息调试信息:'); + console.log('消息类型:', data.type); + console.log('消息主题:', data.topic); + console.log('消息负载:', JSON.stringify(data.payload, null, 2)); + console.log('消息ID:', data.id); + }; + + // 修改WebSocket消息处理 + const handleWebSocketMessage = (data: any) => { + console.log('开始处理WebSocket消息:', JSON.stringify(data, null, 2)); + debugWebSocketMessage(data); + + if (data.type === 'result') { + const { topic, payload } = data; + + // 正确提取 deviceSn + const topicParts = topic.split('/'); + // topic: /device/{productId}/{deviceSn}/message/event/fire_alarm + const deviceSn = topicParts[3]; + console.log('从主题中提取的设备编号:', deviceSn); + + // 处理设备在线状态 + if (topic.endsWith('/online')) { + console.log('处理设备在线状态:', deviceSn); + updateDeviceStatus(deviceSn, 1); + } + + // 处理设备离线状态 + if (topic.endsWith('/offline')) { + console.log('处理设备离线状态:', deviceSn); + updateDeviceStatus(deviceSn, 0); + } + + // 处理设备属性上报 + if (topic.includes('/message/property/report')) { + console.log('处理设备属性上报:', deviceSn, JSON.stringify(payload, null, 2)); + handlePropertyReport(deviceSn, payload); + } + + // 处理设备火警事件 + if (topic.includes('/message/event/fire_alarm')) { + console.log('处理设备火警事件:', deviceSn, JSON.stringify(payload, null, 2)); + handleDeviceEvent(deviceSn, payload); + } + } else if (data.type === 'error') { + console.error('WebSocket消息错误:', data); + message.error(data.message || '消息处理错误'); + } + }; + + // 更新设备状态 + const updateDeviceStatus = (deviceSn: string, status: number) => { + console.log('更新设备状态:', deviceSn, status); + setDeviceList(prev => { + const newList = prev.map(device => + device.deviceSn === deviceSn + ? { + ...device, + boundStatus: status, + loginTime: status === 1 ? moment().format('YYYY-MM-DD HH:mm:ss') : device.loginTime + } + : device + ); + console.log('设备状态更新后:', newList); + return newList; + }); + }; + + // 处理属性上报 + const handlePropertyReport = (deviceSn: string, payload: any) => { + console.log('处理属性上报:', deviceSn, payload); + // 更新性能指标数据 + if (payload.properties) { + const newMetrics: DeviceMetrics[] = []; + const time = moment().format('YYYY-MM-DD HH:mm:ss'); + + if (payload.properties.cpu_usage !== undefined) { + newMetrics.push({ + time, + value: payload.properties.cpu_usage, + type: 'CPU使用率', + }); + } + + if (payload.properties.memory_usage !== undefined) { + newMetrics.push({ + time, + value: payload.properties.memory_usage, + type: '内存使用率', + }); + } + + if (payload.properties.temperature !== undefined) { + newMetrics.push({ + time, + value: payload.properties.temperature, + type: '温度', + }); + } + + // 新增:同步更新 deviceList 里对应设备的 metrics 字段 + setDeviceList(prev => prev.map(d => + d.deviceSn === deviceSn + ? { + ...d, + metrics: { + ...d.metrics, + temperature: payload.properties.temperature ?? d.metrics.temperature, + humidity: payload.properties.humidity ?? d.metrics.humidity, + windSpeed: payload.properties.wind_speed ?? d.metrics.windSpeed, + rainfall: payload.properties.rainfall ?? d.metrics.rainfall, + environmentTemperature: payload.properties.environment_temperature ?? d.metrics.environmentTemperature, + positionQuality: payload.properties.position_state?.quality ?? d.metrics.positionQuality, + networkQuality: payload.properties.network_state?.quality ?? d.metrics.networkQuality, + droneInDock: payload.properties.drone_in_dock ?? d.metrics.droneInDock, + batteryCapacity: payload.properties.drone_charge_state?.capacity_percent ?? d.metrics.batteryCapacity, + batteryState: payload.properties.drone_charge_state?.state ?? d.metrics.batteryState, + } + } + : d + )); + + if (newMetrics.length > 0) { + setMetricsMap(prev => ({ + ...prev, + [deviceSn]: [...(prev[deviceSn] || []), ...newMetrics].slice(-72) + })); + } + } + }; + + // 处理设备事件 + const handleDeviceEvent = (deviceSn: string, payload: FireAlarmPayload) => { + console.log('开始处理设备事件:', deviceSn); + console.log('设备列表当前状态:', JSON.stringify(deviceList, null, 2)); + + const device = deviceList.find(d => d.deviceSn === deviceSn); + if (!device) { + console.log('未找到设备:', deviceSn); + return; + } + + const { data } = payload; + const deviceData = data.data; + console.log('设备数据:', JSON.stringify(deviceData, null, 2)); + + // 更新设备状态和实时数据 + setDeviceList(prev => { + console.log('更新前的设备列表:', JSON.stringify(prev, null, 2)); + const newList = prev.map(d => { + if (d.deviceSn === deviceSn) { + console.log('更新设备数据:', deviceSn, JSON.stringify(deviceData, null, 2)); + const updatedMetrics = { + ...d.metrics, + // 环境数据 + temperature: deviceData.temperature ?? d.metrics.temperature, + humidity: deviceData.humidity ?? d.metrics.humidity, + windSpeed: deviceData.wind_speed ?? d.metrics.windSpeed, + rainfall: deviceData.rainfall ?? d.metrics.rainfall, + environmentTemperature: deviceData.environment_temperature ?? d.metrics.environmentTemperature, + // 设备状态 + positionQuality: deviceData.position_state?.quality ?? d.metrics.positionQuality, + networkQuality: deviceData.network_state?.quality ?? d.metrics.networkQuality, + droneInDock: deviceData.drone_in_dock ?? d.metrics.droneInDock, + batteryCapacity: deviceData.drone_charge_state?.capacity_percent ?? d.metrics.batteryCapacity, + batteryState: deviceData.drone_charge_state?.state ?? d.metrics.batteryState, + }; + console.log('更新后的设备指标:', JSON.stringify(updatedMetrics, null, 2)); + const updatedDevice = { + ...d, + boundStatus: 1, + loginTime: moment(payload.timestamp).format('YYYY-MM-DD HH:mm:ss'), + metrics: updatedMetrics + }; + console.log('更新后的设备数据:', JSON.stringify(updatedDevice, null, 2)); + return updatedDevice; + } + return d; + }); + console.log('更新后的设备列表:', JSON.stringify(newList, null, 2)); + return newList; + }); + + // 更新性能指标 + const newMetrics: DeviceMetrics[] = []; + const timestamp = moment(payload.timestamp).format('YYYY-MM-DD HH:mm:ss'); + + // 添加环境数据指标 + if (deviceData.temperature !== undefined) { + newMetrics.push({ + time: timestamp, + value: deviceData.temperature, + type: '温度', + }); + } + if (deviceData.humidity !== undefined) { + newMetrics.push({ + time: timestamp, + value: deviceData.humidity, + type: '湿度', + }); + } + if (deviceData.environment_temperature !== undefined) { + newMetrics.push({ + time: timestamp, + value: deviceData.environment_temperature, + type: '环境温度', + }); + } + if (deviceData.wind_speed !== undefined) { + newMetrics.push({ + time: timestamp, + value: deviceData.wind_speed, + type: '风速', + }); + } + if (deviceData.rainfall !== undefined) { + newMetrics.push({ + time: timestamp, + value: deviceData.rainfall, + type: '降雨量', + }); + } + + // 添加设备状态指标 + if (deviceData.drone_charge_state?.capacity_percent !== undefined) { + newMetrics.push({ + time: timestamp, + value: deviceData.drone_charge_state.capacity_percent, + type: '电池电量', + }); + } + if (deviceData.position_state?.quality !== undefined) { + newMetrics.push({ + time: timestamp, + value: deviceData.position_state.quality, + type: '定位质量', + }); + } + if (deviceData.network_state?.quality !== undefined) { + newMetrics.push({ + time: timestamp, + value: deviceData.network_state.quality, + type: '网络质量', + }); + } + + if (newMetrics.length > 0) { + console.log('新的性能指标:', JSON.stringify(newMetrics, null, 2)); + setMetricsMap(prev => ({ + ...prev, + [deviceSn]: [...(prev[deviceSn] || []), ...newMetrics].slice(-72) + })); + } + }; + + useEffect(() => { + console.log('组件初始化'); + (async () => { + await fetchDeviceList(); + await initWebSocket(); + })(); + return cleanup; + }, []); + + // 在组件中添加调试日志 + useEffect(() => { + console.log('选中的设备:', selectedDevice); + console.log('当前设备列表:', JSON.stringify(deviceList, null, 2)); + console.log('当前性能指标:', JSON.stringify(metricsMap, null, 2)); + }, [selectedDevice, deviceList, metricsMap]); + + const alertColumns = [ + { + title: '设备序列号', + dataIndex: 'deviceSn', + key: 'deviceSn', + }, + { + title: '设备名称', + dataIndex: 'deviceName', + key: 'deviceName', + }, + { + title: '告警类型', + dataIndex: 'alertType', + key: 'alertType', + }, + { + title: '告警级别', + dataIndex: 'alertLevel', + key: 'alertLevel', + render: (level: string) => ( + + {level} + + ), + }, + { + title: '告警时间', + dataIndex: 'alertTime', + key: 'alertTime', + }, + { + title: '状态', + dataIndex: 'status', + key: 'status', + render: (status: string) => ( + + {status} + + ), + }, + ]; + + const deviceStatusColumns = [ + { + title: '设备序列号', + dataIndex: 'deviceSn', + key: 'deviceSn', + }, + { + title: '设备名称', + dataIndex: 'deviceName', + key: 'deviceName', + }, + { + title: '状态', + dataIndex: 'boundStatus', + key: 'boundStatus', + render: (status: number) => ( + + {status === 1 ? : } + {status === 1 ? '在线' : '离线'} + + ), + }, + { + title: '最后登录时间', + dataIndex: 'loginTime', + key: 'loginTime', + }, + { + title: '操作', + key: 'action', + render: (_: unknown, record: Device) => ( + + setSelectedDevice(record.deviceSn)}>查看监控 + + ), + }, + ]; + + // 修改实时数据卡片的渲染逻辑 + const renderRealTimeData = () => { + const device = deviceList.find(d => d.deviceSn === selectedDevice); + console.log('渲染实时数据卡片,当前设备:', JSON.stringify(device, null, 2)); + + if (!device) { + console.log('未找到选中的设备'); + return null; + } + + // 添加设备指标值的日志 + console.log('设备指标值:', { + temperature: device.metrics.temperature, + humidity: device.metrics.humidity, + environmentTemperature: device.metrics.environmentTemperature, + batteryCapacity: device.metrics.batteryCapacity, + windSpeed: device.metrics.windSpeed, + rainfall: device.metrics.rainfall, + positionQuality: device.metrics.positionQuality, + networkQuality: device.metrics.networkQuality, + }); + + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ); + }; + + // 订阅设备消息 + const subscribeDeviceMessages = (deviceSn?: string) => { + if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) { + console.log('WebSocket未连接,无法订阅消息'); + return; + } + + console.log('开始订阅设备消息:', deviceSn); + + // 取消所有现有订阅 + const unsubAll = { + type: 'unsub', + topic: '/device/*', + id: 'unsub-all', + }; + console.log('取消所有订阅:', JSON.stringify(unsubAll, null, 2)); + wsRef.current.send(JSON.stringify(unsubAll)); + + if (deviceSn) { + // 订阅指定设备的消息 + const subscriptions = [ + { + type: 'sub', + topic: `/device/*/${deviceSn}/online`, + id: 'online-sub', + }, + { + type: 'sub', + topic: `/device/*/${deviceSn}/offline`, + id: 'offline-sub', + }, + { + type: 'sub', + topic: `/device/*/${deviceSn}/message/property/report`, + id: 'property-sub', + }, + { + type: 'sub', + topic: `/device/*/${deviceSn}/message/event/fire_alarm`, + id: 'fire-alarm-sub', + }, + ]; + subscriptions.forEach(sub => { + console.log('发送订阅请求:', JSON.stringify(sub, null, 2)); + wsRef.current?.send(JSON.stringify(sub)); + }); + } else { + // 订阅所有设备的在线状态 + const onlineSub = { + type: 'sub', + topic: '/device/*/online', + id: 'online-sub', + }; + console.log('发送在线状态订阅请求:', JSON.stringify(onlineSub, null, 2)); + wsRef.current.send(JSON.stringify(onlineSub)); + } + console.log('设备消息订阅请求已发送'); + }; + + return ( + + + + + + + { + if (dates && dates[0] && dates[1]) { + setTimeRange([dates[0], dates[1]]); + } + }} + disabled={loading} + /> + + + + + {/* 实时数据卡片 */} + {selectedDevice !== 'all' && ( + + d.deviceSn === selectedDevice)?.deviceName || ''} 实时数据`}> + {renderRealTimeData()} + + + )} + + {/* 性能趋势图 */} + {selectedDevice !== 'all' && ( + + d.deviceSn === selectedDevice)?.deviceName || ''} 性能趋势`} loading={loading}> + `${v}%`, + }, + }} + /> + + + )} + + {/* 设备状态列表 */} + + +
+ + + + {/* 告警记录 */} + + +
+ + + + + ); +}; + +export default DeviceMonitor; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/services/api.ts b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/services/api.ts new file mode 100644 index 00000000..7f9341d3 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/services/api.ts @@ -0,0 +1,32 @@ +import { request } from 'umi'; + +// 设备列表 +export async function getDeviceList(params?: any) { + return request('/api/device-ops/device/list', { + method: 'GET', + params, + }); +} + +// 新增设备 +export async function addDevice(data: any) { + return request('/api/device-ops/device', { + method: 'POST', + data, + }); +} + +// 编辑设备 +export async function updateDevice(data: any) { + return request('/api/device-ops/device', { + method: 'PUT', + data, + }); +} + +// 删除设备 +export async function deleteDevice(id: string) { + return request(`/api/device-ops/device/${id}`, { + method: 'DELETE', + }); +} \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/statistics/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/statistics/index.tsx new file mode 100644 index 00000000..6d22acb7 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/statistics/index.tsx @@ -0,0 +1,282 @@ +import React, { useState, useEffect } from 'react'; +import { PageContainer } from '@ant-design/pro-layout'; +import { Card, Row, Col, DatePicker, Select, Space, Statistic, message } from 'antd'; +import { Line, Column } from '@ant-design/plots'; +import moment from 'moment'; +import { CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons'; +import { device } from '@/services/device/api'; + +const { RangePicker } = DatePicker; + +interface Device { + deviceSn: string; + deviceName: string; + deviceType: number; + boundStatus: number; + createTime: string; + loginTime: string; +} + +interface TrendData { + date: string; + value: number; + type: string; +} + +interface DeviceGrowth { + date: string; + count: number; +} + +interface PerformanceData { + time: string; + value: number; + type: string; +} + +interface StatisticsData { + totalDevices: number; + averageOnlineRate: number; + totalGrowth: number; +} + +const DeviceStatistics: React.FC = () => { + const [timeRange, setTimeRange] = useState<[moment.Moment, moment.Moment]>([ + moment().subtract(30, 'days'), + moment(), + ]); + const [selectedDevice, setSelectedDevice] = useState('all'); + const [loading, setLoading] = useState(false); + const [deviceList, setDeviceList] = useState([]); + const [statusTrendData, setStatusTrendData] = useState([]); + const [deviceGrowthData, setDeviceGrowthData] = useState([]); + const [performanceData, setPerformanceData] = useState([]); + const [statistics, setStatistics] = useState({ + totalDevices: 0, + averageOnlineRate: 0, + totalGrowth: 0, + }); + + // 获取设备列表 + const fetchDeviceList = async () => { + try { + setLoading(true); + const response = await device({ + page: 1, + limit: 1000, + searchKey: selectedDevice === 'all' ? undefined : 'deviceSn', + searchValue: selectedDevice === 'all' ? undefined : selectedDevice, + }); + + if (response.resp_code === 0) { + const data = response.data || []; + setDeviceList(data); + + // 计算统计数据 + const totalDevices = data.length; + const onlineDevices = data.filter((item: Device) => item.boundStatus === 1).length; + const averageOnlineRate = totalDevices > 0 ? (onlineDevices / totalDevices) * 100 : 0; + const totalGrowth = data.filter((item: Device) => + moment(item.createTime).isBetween(timeRange[0], timeRange[1]) + ).length; + + setStatistics({ + totalDevices, + averageOnlineRate, + totalGrowth, + }); + + // 生成状态趋势数据 + const statusTrend: TrendData[] = Array.from({ length: 30 }, (_, i) => { + const date = moment().subtract(29 - i, 'days'); + const devicesOnDay = data.filter((item: Device) => + moment(item.createTime).isSameOrBefore(date) && + (item.boundStatus === 1 || moment(item.loginTime).isSameOrAfter(date)) + ); + return { + date: date.format('YYYY-MM-DD HH:mm:ss'), + value: devicesOnDay.length > 0 ? (devicesOnDay.filter((d: Device) => d.boundStatus === 1).length / devicesOnDay.length) * 100 : 0, + type: '在线率', + }; + }); + + // 生成设备增长数据 + const growthTrend: DeviceGrowth[] = Array.from({ length: 30 }, (_, i) => { + const date = moment().subtract(29 - i, 'days'); + return { + date: date.format('YYYY-MM-DD HH:mm:ss'), + count: data.filter((item: Device) => + moment(item.createTime).isSame(date, 'day') + ).length, + }; + }); + + // 生成性能指标数据 + const performanceTrend: PerformanceData[] = Array.from({ length: 24 }, (_, i) => [ + { + time: moment().subtract(23 - i, 'hours').format('YYYY-MM-DD HH:mm:ss'), + value: Math.floor(Math.random() * 100), + type: 'CPU使用率', + }, + { + time: moment().subtract(23 - i, 'hours').format('YYYY-MM-DD HH:mm:ss'), + value: Math.floor(Math.random() * 100), + type: '内存使用率', + }, + { + time: moment().subtract(23 - i, 'hours').format('YYYY-MM-DD HH:mm:ss'), + value: Math.floor(Math.random() * 50) + 20, + type: '温度', + }, + ]).flat(); + + setStatusTrendData(statusTrend); + setDeviceGrowthData(growthTrend); + setPerformanceData(performanceTrend); + } else { + message.error(response.resp_msg || '获取数据失败'); + } + } catch (error) { + message.error('获取数据失败'); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + fetchDeviceList(); + }, [timeRange, selectedDevice]); + + return ( + + + + + + + { + if (dates && dates[0] && dates[1]) { + setTimeRange([dates[0], dates[1]]); + } + }} + disabled={loading} + /> + + + + + {/* 统计卡片 */} + + + + + + + + 80 ? '#3f8600' : '#cf1322' }} + prefix={statistics.averageOnlineRate > 80 ? : } + /> + + + + + 0 ? '#3f8600' : '#cf1322' }} + /> + + + + {/* 设备状态趋势 */} + + + `${v}%`, + }, + }} + /> + + + + {/* 设备增长趋势 */} + + + `${v}台`, + }, + }} + /> + + + + {/* 性能指标趋势 */} + + + `${v}%`, + }, + }} + /> + + + + + ); +}; + +export default DeviceStatistics; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/services/device.ts b/zlt-web/react-web/src/main/frontend/src/services/device.ts new file mode 100644 index 00000000..36f104fb --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/services/device.ts @@ -0,0 +1,48 @@ +import { request } from 'umi'; + +// 获取设备状态趋势数据 +export async function getDeviceStatusTrend(params: { + deviceId?: string; + startTime: string; + endTime: string; +}) { + return request('/api/device-ops/statistics/status-trend', { + method: 'GET', + params, + }); +} + +// 获取设备增长趋势数据 +export async function getDeviceGrowthTrend(params: { + startTime: string; + endTime: string; +}) { + return request('/api/device-ops/statistics/growth-trend', { + method: 'GET', + params, + }); +} + +// 获取设备性能指标趋势数据 +export async function getDevicePerformanceTrend(params: { + deviceId?: string; + startTime: string; + endTime: string; +}) { + return request('/api/device-ops/statistics/performance-trend', { + method: 'GET', + params, + }); +} + +// 获取设备统计数据 +export async function getDeviceStatistics(params: { + deviceId?: string; + startTime: string; + endTime: string; +}) { + return request('/api/device-ops/statistics/overview', { + method: 'GET', + params, + }); +} \ No newline at end of file From 7f41ffc67843061f280136923836a8836c86b2af Mon Sep 17 00:00:00 2001 From: Iamasoldier <1272745473@qq.com> Date: Wed, 18 Jun 2025 10:01:48 +0800 Subject: [PATCH 05/10] =?UTF-8?q?feat:=E8=AE=BE=E5=A4=87=E8=BF=90=E7=BB=B4?= =?UTF-8?q?ops=E7=AE=A1=E7=90=86=E6=A8=A1=E5=9D=97=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=E8=AE=BE=E5=A4=87=E7=9B=91=E6=8E=A7=E5=8A=9F=E8=83=BD=E5=AE=8C?= =?UTF-8?q?=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/frontend/src/locales/zh-CN/menu.ts | 7 + .../src/main/frontend/src/pages/Welcome.tsx | 16 +- .../src/pages/device-ops/device/detail.tsx | 2 +- .../src/pages/device-ops/device/index.tsx | 3 +- .../src/pages/device-ops/group/index.tsx | 3 +- .../pages/device-ops/maintenance/index.tsx | 7 +- .../src/pages/device-ops/monitor/index.tsx | 698 +++++++++++------- .../device/Wayline/components/UpdateForm.tsx | 2 +- .../src/pages/device/Wayline/index.tsx | 2 +- .../TourismFile/components/UpdateForm.tsx | 2 +- .../system/Menu/components/UpdateForm.tsx | 6 +- 11 files changed, 442 insertions(+), 306 deletions(-) diff --git a/zlt-web/react-web/src/main/frontend/src/locales/zh-CN/menu.ts b/zlt-web/react-web/src/main/frontend/src/locales/zh-CN/menu.ts index 6cf7700b..7276d851 100644 --- a/zlt-web/react-web/src/main/frontend/src/locales/zh-CN/menu.ts +++ b/zlt-web/react-web/src/main/frontend/src/locales/zh-CN/menu.ts @@ -50,4 +50,11 @@ export default { 'menu.editor.mind': '脑图编辑器', 'menu.editor.koni': '拓扑编辑器', 'menu.首页': '首页', + 'menu.设备运维': '设备运维', + 'menu.设备运维.设备管理': '设备管理', + 'menu.设备运维.分组管理': '分组管理', + 'menu.设备运维.运维管理': '运维管理', + 'menu.设备运维.设备监控': '设备监控', + 'menu.设备运维.统计分析': '统计分析', + 'menu.设备运维.设备详情': '设备详情', }; diff --git a/zlt-web/react-web/src/main/frontend/src/pages/Welcome.tsx b/zlt-web/react-web/src/main/frontend/src/pages/Welcome.tsx index b7096411..0fdfadbb 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/Welcome.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/Welcome.tsx @@ -29,24 +29,24 @@ interface Statistics { totalDevices: number; onlineDevices: number; deviceOnlineRate: number; - orderTrend: Array<{ + orderTrend: { date: string; type: string; value: number; - }>; - deviceDistribution: Array<{ + }[]; + deviceDistribution: { type: string; value: number; - }>; - incomeData: Array<{ + }[]; + incomeData: { type: string; value: number; - }>; - tourismRanking: Array<{ + }[]; + tourismRanking: { id: string; name: string; value: number; - }>; + }[]; } const Welcome: React.FC = () => { diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/device/detail.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/device/detail.tsx index efcbb90e..a69b0889 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/device/detail.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/device/detail.tsx @@ -120,7 +120,7 @@ const DeviceDetailPage: React.FC = () => { }; const getAlertLevelColor = (level: string) => { - const colorMap: { [key: string]: string } = { + const colorMap: Record = { '高': 'red', '中': 'orange', '低': 'blue', diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/device/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/device/index.tsx index 83198d39..38c022a3 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/device/index.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/device/index.tsx @@ -1,6 +1,7 @@ import React, { useRef, useState, useEffect } from 'react'; import { PageContainer } from '@ant-design/pro-layout'; -import { ProTable, ProColumns, ModalForm, ProFormText, ProFormSelect, ProFormUploadButton } from '@ant-design/pro-components'; +import type { ProColumns} from '@ant-design/pro-components'; +import { ProTable, ModalForm, ProFormText, ProFormSelect, ProFormUploadButton } from '@ant-design/pro-components'; import { Button, Space, message, Popconfirm, Tag, Select, Modal, Dropdown, Menu, Upload, Card, Row, Col, Statistic } from 'antd'; import { history } from 'umi'; import { DownOutlined, UploadOutlined, DownloadOutlined, FileExcelOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons'; diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/group/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/group/index.tsx index c4e703e0..b61793cf 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/group/index.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/group/index.tsx @@ -1,6 +1,7 @@ import React, { useRef, useState } from 'react'; import { PageContainer } from '@ant-design/pro-layout'; -import { ProTable, ProColumns, ModalForm, ProFormText, ProFormSelect } from '@ant-design/pro-components'; +import type { ProColumns} from '@ant-design/pro-components'; +import { ProTable, ModalForm, ProFormText, ProFormSelect } from '@ant-design/pro-components'; import { Button, Space, message, Popconfirm, Tag, Card, Row, Col, Statistic } from 'antd'; import { Pie } from '@ant-design/plots'; import { device } from '@/services/device/api'; diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/maintenance/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/maintenance/index.tsx index 2cf26c00..d3e6335f 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/maintenance/index.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/maintenance/index.tsx @@ -1,6 +1,7 @@ import React, { useRef, useState } from 'react'; import { PageContainer } from '@ant-design/pro-layout'; -import { ProTable, ProColumns, ModalForm, ProFormText, ProFormSelect, ProFormDatePicker } from '@ant-design/pro-components'; +import type { ProColumns} from '@ant-design/pro-components'; +import { ProTable, ModalForm, ProFormText, ProFormSelect, ProFormDatePicker } from '@ant-design/pro-components'; import { Button, Space, message, Popconfirm, Tag } from 'antd'; interface MaintenanceTask { @@ -83,7 +84,7 @@ const MaintenanceList: React.FC = () => { }; const getStatusColor = (status: string) => { - const colorMap: { [key: string]: string } = { + const colorMap: Record = { '待处理': 'orange', '进行中': 'blue', '已完成': 'green', @@ -93,7 +94,7 @@ const MaintenanceList: React.FC = () => { }; const getPriorityColor = (priority: string) => { - const colorMap: { [key: string]: string } = { + const colorMap: Record = { '高': 'red', '中': 'orange', '低': 'green', diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx index 58e411da..458e2035 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx @@ -180,17 +180,6 @@ const DeviceMonitor: React.FC = () => { timer: null as NodeJS.Timeout | null, }; - const refreshTokenAndReconnect = async () => { - // 强制获取新token - tokenCache.value = ''; - await getToken(); - // 关闭旧ws并重建 - if (wsRef.current) { - wsRef.current.close(); - } - await initWebSocket(); - }; - const getToken = async (expires: number = DEFAULT_EXPIRES) => { const now = Date.now(); if (tokenCache.value && tokenCache.expire > now) { @@ -218,18 +207,29 @@ const DeviceMonitor: React.FC = () => { return token; }; + const refreshTokenAndReconnect = async () => { + // 强制获取新token + tokenCache.value = ''; + await getToken(); + // 关闭旧ws并重建 + if (wsRef.current) { + wsRef.current.close(); + } + await initWebSocket(); + }; + // 获取设备列表 const fetchDeviceList = async () => { + setLoading(true); try { - setLoading(true); const response = await device({ page: 1, limit: 1000, }); - if (response.resp_code === 0) { - const devices = response.data || []; - // 初始化设备数据 - const initializedDevices = devices.map((item: Device) => ({ + console.log('设备列表API响应:', response); + + if (response.resp_code === 0 && response.data) { + const devices = response.data.map((item: any) => ({ ...item, metrics: { temperature: 0, @@ -256,8 +256,11 @@ const DeviceMonitor: React.FC = () => { '4gLinkQuality': 0, } })); - setDeviceList(initializedDevices); - console.log('设备列表已更新:', initializedDevices); + setDeviceList(devices); + console.log('设备列表已更新:', devices); + } else { + console.error('获取设备列表失败:', response.resp_msg); + message.error(response.resp_msg || '获取设备列表失败'); } } catch (error) { console.error('获取设备列表失败:', error); @@ -267,105 +270,6 @@ const DeviceMonitor: React.FC = () => { } }; - // 修改 WebSocket 连接初始化 - const initWebSocket = async () => { - try { - console.log('开始初始化WebSocket连接...'); - const token = await getToken(); - console.log('获取到WebSocket token:', token); - - // 如果已经存在连接,且未关闭,不重复建立 - if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) { - console.log('WebSocket已连接,无需重复建立'); - return; - } - if (wsRef.current) { - console.log('关闭已存在的WebSocket连接'); - wsRef.current.close(); - } - - // 建立WebSocket连接 - const wsUrl = `ws://119.45.169.13:8848/messaging/${token}`; - console.log('正在连接WebSocket:', wsUrl); - const ws = new WebSocket(wsUrl); - wsRef.current = ws; - - ws.onopen = () => { - console.log('WebSocket连接已建立'); - setWsConnected(true); - // 启动心跳检测 - startHeartbeat(); - // 根据当前选中的设备订阅消息 - if (selectedDevice !== 'all') { - console.log('当前选中的设备:', selectedDevice); - subscribeDeviceMessages(selectedDevice); - } else { - console.log('未选择具体设备,订阅所有设备在线状态'); - subscribeDeviceMessages(); - } - }; - - ws.onmessage = (event) => { - console.log('收到WebSocket原始消息:', event.data); - try { - const data = JSON.parse(event.data); - console.log('解析后的WebSocket消息:', JSON.stringify(data, null, 2)); - // 处理心跳响应 - if (data.type === 'pong') { - console.log('收到心跳响应'); - return; - } - // 添加调试信息 - console.log('准备处理WebSocket消息...'); - console.log('消息类型:', data.type); - console.log('消息主题:', data.topic); - console.log('消息负载:', JSON.stringify(data.payload, null, 2)); - handleWebSocketMessage(data); - } catch (error) { - console.error('解析WebSocket消息失败:', error); - console.error('原始消息内容:', event.data); - } - }; - - ws.onerror = (error) => { - console.error('WebSocket错误:', error); - message.error('WebSocket连接错误'); - setWsConnected(false); - // 尝试重连 - scheduleReconnect(); - }; - - ws.onclose = (event) => { - console.log('WebSocket连接已关闭,代码:', event.code, '原因:', event.reason); - setWsConnected(false); - // 尝试重连 - scheduleReconnect(); - }; - } catch (error) { - console.error('初始化WebSocket失败:', error); - message.error('初始化WebSocket失败'); - // 尝试重连 - scheduleReconnect(); - } - }; - - // 切换设备时只发订阅,不重建ws - useEffect(() => { - console.log('选中的设备已更改:', selectedDevice); - if (wsRef.current?.readyState === WebSocket.OPEN) { - if (selectedDevice !== 'all') { - console.log('WebSocket已连接,开始订阅设备消息:', selectedDevice); - subscribeDeviceMessages(selectedDevice); - } else { - console.log('WebSocket已连接,订阅所有设备在线状态'); - subscribeDeviceMessages(); - } - } else { - console.log('WebSocket未连接,尝试重新连接...'); - initWebSocket(); - } - }, [selectedDevice]); - // 重连机制 const scheduleReconnect = () => { if (reconnectTimerRef.current) { @@ -402,67 +306,60 @@ const DeviceMonitor: React.FC = () => { } }; - // 添加调试函数 - const debugWebSocketMessage = (data: any) => { - console.log('WebSocket消息调试信息:'); - console.log('消息类型:', data.type); - console.log('消息主题:', data.topic); - console.log('消息负载:', JSON.stringify(data.payload, null, 2)); - console.log('消息ID:', data.id); - }; - - // 修改WebSocket消息处理 - const handleWebSocketMessage = (data: any) => { - console.log('开始处理WebSocket消息:', JSON.stringify(data, null, 2)); - debugWebSocketMessage(data); - - if (data.type === 'result') { - const { topic, payload } = data; - - // 正确提取 deviceSn - const topicParts = topic.split('/'); - // topic: /device/{productId}/{deviceSn}/message/event/fire_alarm - const deviceSn = topicParts[3]; - console.log('从主题中提取的设备编号:', deviceSn); - - // 处理设备在线状态 - if (topic.endsWith('/online')) { - console.log('处理设备在线状态:', deviceSn); - updateDeviceStatus(deviceSn, 1); - } - - // 处理设备离线状态 - if (topic.endsWith('/offline')) { - console.log('处理设备离线状态:', deviceSn); - updateDeviceStatus(deviceSn, 0); - } - - // 处理设备属性上报 - if (topic.includes('/message/property/report')) { - console.log('处理设备属性上报:', deviceSn, JSON.stringify(payload, null, 2)); - handlePropertyReport(deviceSn, payload); - } - - // 处理设备火警事件 - if (topic.includes('/message/event/fire_alarm')) { - console.log('处理设备火警事件:', deviceSn, JSON.stringify(payload, null, 2)); - handleDeviceEvent(deviceSn, payload); - } - } else if (data.type === 'error') { - console.error('WebSocket消息错误:', data); - message.error(data.message || '消息处理错误'); - } - }; - // 更新设备状态 const updateDeviceStatus = (deviceSn: string, status: number) => { console.log('更新设备状态:', deviceSn, status); setDeviceList(prev => { + // 检查设备是否已存在 + const existingDevice = prev.find(d => d.deviceSn === deviceSn); + + if (!existingDevice) { + console.log('设备不存在,创建新设备记录:', deviceSn); + // 如果设备不存在,创建一个新的设备记录 + const newDevice: Device = { + deviceSn: deviceSn, + deviceName: deviceSn, // 使用设备编号作为名称 + deviceType: 1, // 默认类型 + boundStatus: (status as 0 | 1), + createTime: moment().format('YYYY-MM-DD HH:mm:ss'), + loginTime: status === 1 ? moment().format('YYYY-MM-DD HH:mm:ss') : '', + metrics: { + temperature: 0, + humidity: 0, + windSpeed: 0, + rainfall: 0, + environmentTemperature: 0, + positionQuality: 0, + networkQuality: 0, + droneInDock: 0, + batteryCapacity: 0, + batteryState: 0, + workingVoltage: 0, + workingCurrent: 0, + acdcPowerInput: 0, + backupBatteryVoltage: 0, + flightTaskStep: 0, + tiltAngle: 0, + sdrUpQuality: 0, + sdrDownQuality: 0, + wirelessLinkState: 0, + wirelessLinkQuality: 0, + '4gLinkState': 0, + '4gLinkQuality': 0, + } + }; + console.log('创建的新设备:', JSON.stringify(newDevice, null, 2)); + const newList = [...prev, newDevice]; + console.log('设备状态更新后:', newList); + return newList; + } + + // 如果设备存在,更新现有设备 const newList = prev.map(device => device.deviceSn === deviceSn ? { ...device, - boundStatus: status, + boundStatus: (status as 0 | 1), loginTime: status === 1 ? moment().format('YYYY-MM-DD HH:mm:ss') : device.loginTime } : device @@ -505,28 +402,74 @@ const DeviceMonitor: React.FC = () => { } // 新增:同步更新 deviceList 里对应设备的 metrics 字段 - setDeviceList(prev => prev.map(d => - d.deviceSn === deviceSn - ? { - ...d, - metrics: { - ...d.metrics, - temperature: payload.properties.temperature ?? d.metrics.temperature, - humidity: payload.properties.humidity ?? d.metrics.humidity, - windSpeed: payload.properties.wind_speed ?? d.metrics.windSpeed, - rainfall: payload.properties.rainfall ?? d.metrics.rainfall, - environmentTemperature: payload.properties.environment_temperature ?? d.metrics.environmentTemperature, - positionQuality: payload.properties.position_state?.quality ?? d.metrics.positionQuality, - networkQuality: payload.properties.network_state?.quality ?? d.metrics.networkQuality, - droneInDock: payload.properties.drone_in_dock ?? d.metrics.droneInDock, - batteryCapacity: payload.properties.drone_charge_state?.capacity_percent ?? d.metrics.batteryCapacity, - batteryState: payload.properties.drone_charge_state?.state ?? d.metrics.batteryState, - } + setDeviceList(prev => { + // 检查设备是否已存在 + const existingDevice = prev.find(d => d.deviceSn === deviceSn); + + if (!existingDevice) { + console.log('设备不存在,创建新设备记录:', deviceSn); + // 如果设备不存在,创建一个新的设备记录 + const newDevice: Device = { + deviceSn: deviceSn, + deviceName: deviceSn, // 使用设备编号作为名称 + deviceType: 1, // 默认类型 + boundStatus: 1, + createTime: moment().format('YYYY-MM-DD HH:mm:ss'), + loginTime: moment().format('YYYY-MM-DD HH:mm:ss'), + metrics: { + temperature: payload.properties.temperature ?? 0, + humidity: payload.properties.humidity ?? 0, + windSpeed: payload.properties.wind_speed ?? 0, + rainfall: payload.properties.rainfall ?? 0, + environmentTemperature: payload.properties.environment_temperature ?? 0, + positionQuality: payload.properties.position_state?.quality ?? 0, + networkQuality: payload.properties.network_state?.quality ?? 0, + droneInDock: payload.properties.drone_in_dock ?? 0, + batteryCapacity: payload.properties.drone_charge_state?.capacity_percent ?? 0, + batteryState: payload.properties.drone_charge_state?.state ?? 0, + workingVoltage: 0, + workingCurrent: 0, + acdcPowerInput: 0, + backupBatteryVoltage: 0, + flightTaskStep: 0, + tiltAngle: 0, + sdrUpQuality: 0, + sdrDownQuality: 0, + wirelessLinkState: 0, + wirelessLinkQuality: 0, + '4gLinkState': 0, + '4gLinkQuality': 0, } - : d - )); + }; + console.log('创建的新设备:', JSON.stringify(newDevice, null, 2)); + return [...prev, newDevice]; + } + + // 如果设备存在,更新现有设备 + return prev.map(d => + d.deviceSn === deviceSn + ? { + ...d, + metrics: { + ...d.metrics, + temperature: payload.properties.temperature ?? d.metrics.temperature, + humidity: payload.properties.humidity ?? d.metrics.humidity, + windSpeed: payload.properties.wind_speed ?? d.metrics.windSpeed, + rainfall: payload.properties.rainfall ?? d.metrics.rainfall, + environmentTemperature: payload.properties.environment_temperature ?? d.metrics.environmentTemperature, + positionQuality: payload.properties.position_state?.quality ?? d.metrics.positionQuality, + networkQuality: payload.properties.network_state?.quality ?? d.metrics.networkQuality, + droneInDock: payload.properties.drone_in_dock ?? d.metrics.droneInDock, + batteryCapacity: payload.properties.drone_charge_state?.capacity_percent ?? d.metrics.batteryCapacity, + batteryState: payload.properties.drone_charge_state?.state ?? d.metrics.batteryState, + } + } + : d + ); + }); if (newMetrics.length > 0) { + console.log('新的性能指标:', JSON.stringify(newMetrics, null, 2)); setMetricsMap(prev => ({ ...prev, [deviceSn]: [...(prev[deviceSn] || []), ...newMetrics].slice(-72) @@ -540,12 +483,6 @@ const DeviceMonitor: React.FC = () => { console.log('开始处理设备事件:', deviceSn); console.log('设备列表当前状态:', JSON.stringify(deviceList, null, 2)); - const device = deviceList.find(d => d.deviceSn === deviceSn); - if (!device) { - console.log('未找到设备:', deviceSn); - return; - } - const { data } = payload; const deviceData = data.data; console.log('设备数据:', JSON.stringify(deviceData, null, 2)); @@ -553,6 +490,52 @@ const DeviceMonitor: React.FC = () => { // 更新设备状态和实时数据 setDeviceList(prev => { console.log('更新前的设备列表:', JSON.stringify(prev, null, 2)); + + // 检查设备是否已存在 + const existingDevice = prev.find(d => d.deviceSn === deviceSn); + + if (!existingDevice) { + console.log('设备不存在,创建新设备记录:', deviceSn); + // 如果设备不存在,创建一个新的设备记录 + const newDevice: Device = { + deviceSn: deviceSn, + deviceName: payload.headers.deviceName || deviceSn, + deviceType: 1, // 默认类型 + boundStatus: 1, + createTime: moment().format('YYYY-MM-DD HH:mm:ss'), + loginTime: moment(payload.timestamp).format('YYYY-MM-DD HH:mm:ss'), + metrics: { + temperature: deviceData.temperature ?? 0, + humidity: deviceData.humidity ?? 0, + windSpeed: deviceData.wind_speed ?? 0, + rainfall: deviceData.rainfall ?? 0, + environmentTemperature: deviceData.environment_temperature ?? 0, + positionQuality: deviceData.position_state?.quality ?? 0, + networkQuality: deviceData.network_state?.quality ?? 0, + droneInDock: deviceData.drone_in_dock ?? 0, + batteryCapacity: deviceData.drone_charge_state?.capacity_percent ?? 0, + batteryState: deviceData.drone_charge_state?.state ?? 0, + workingVoltage: 0, + workingCurrent: 0, + acdcPowerInput: 0, + backupBatteryVoltage: 0, + flightTaskStep: 0, + tiltAngle: 0, + sdrUpQuality: 0, + sdrDownQuality: 0, + wirelessLinkState: 0, + wirelessLinkQuality: 0, + '4gLinkState': 0, + '4gLinkQuality': 0, + } + }; + console.log('创建的新设备:', JSON.stringify(newDevice, null, 2)); + const newList = [...prev, newDevice]; + console.log('更新后的设备列表:', JSON.stringify(newList, null, 2)); + return newList; + } + + // 如果设备存在,更新现有设备 const newList = prev.map(d => { if (d.deviceSn === deviceSn) { console.log('更新设备数据:', deviceSn, JSON.stringify(deviceData, null, 2)); @@ -660,21 +643,223 @@ const DeviceMonitor: React.FC = () => { } }; + // 修改WebSocket消息处理 + const handleWebSocketMessage = (data: any) => { + console.log('开始处理WebSocket消息:', JSON.stringify(data, null, 2)); + + if (data.type === 'result') { + const { topic, payload } = data; + + // 正确提取 deviceSn + const topicParts = topic.split('/'); + // topic: /device/{productId}/{deviceSn}/message/event/fire_alarm + const deviceSn = topicParts[3]; + console.log('从主题中提取的设备编号:', deviceSn); + + // 处理设备在线状态 + if (topic.endsWith('/online')) { + console.log('处理设备在线状态:', deviceSn); + updateDeviceStatus(deviceSn, 1); + } + + // 处理设备离线状态 + if (topic.endsWith('/offline')) { + console.log('处理设备离线状态:', deviceSn); + updateDeviceStatus(deviceSn, 0); + } + + // 处理设备属性上报 + if (topic.includes('/message/property/report')) { + console.log('处理设备属性上报:', deviceSn, JSON.stringify(payload, null, 2)); + handlePropertyReport(deviceSn, payload); + } + + // 处理设备火警事件 + if (topic.includes('/message/event/fire_alarm')) { + console.log('处理设备火警事件:', deviceSn, JSON.stringify(payload, null, 2)); + handleDeviceEvent(deviceSn, payload); + } + } else if (data.type === 'error') { + console.error('WebSocket消息错误:', data); + message.error(data.message || '消息处理错误'); + } + }; + + // 订阅设备消息 + const subscribeDeviceMessages = (deviceSn?: string) => { + if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) { + console.log('WebSocket未连接,无法订阅消息'); + return; + } + + console.log('开始订阅设备消息:', deviceSn); + + // 取消所有现有订阅 + const unsubAll = { + type: 'unsub', + topic: '/device/*', + id: 'unsub-all', + }; + console.log('取消所有订阅:', JSON.stringify(unsubAll, null, 2)); + wsRef.current.send(JSON.stringify(unsubAll)); + + if (deviceSn) { + // 订阅指定设备的消息 + const subscriptions = [ + { + type: 'sub', + topic: `/device/*/${deviceSn}/online`, + id: 'online-sub', + }, + { + type: 'sub', + topic: `/device/*/${deviceSn}/offline`, + id: 'offline-sub', + }, + { + type: 'sub', + topic: `/device/*/${deviceSn}/message/property/report`, + id: 'property-sub', + }, + { + type: 'sub', + topic: `/device/*/${deviceSn}/message/event/fire_alarm`, + id: 'fire-alarm-sub', + }, + ]; + subscriptions.forEach(sub => { + console.log('发送订阅请求:', JSON.stringify(sub, null, 2)); + wsRef.current?.send(JSON.stringify(sub)); + }); + } else { + // 订阅所有设备的在线状态 + const onlineSub = { + type: 'sub', + topic: '/device/*/online', + id: 'online-sub', + }; + console.log('发送在线状态订阅请求:', JSON.stringify(onlineSub, null, 2)); + wsRef.current.send(JSON.stringify(onlineSub)); + } + console.log('设备消息订阅请求已发送'); + }; + + // 修改 WebSocket 连接初始化 + const initWebSocket = async () => { + try { + console.log('开始初始化WebSocket连接...'); + const token = await getToken(); + console.log('获取到WebSocket token:', token); + + // 如果已经存在连接,且未关闭,不重复建立 + if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) { + console.log('WebSocket已连接,无需重复建立'); + return; + } + if (wsRef.current) { + console.log('关闭已存在的WebSocket连接'); + wsRef.current.close(); + } + + // 建立WebSocket连接 + const wsUrl = `ws://119.45.169.13:8848/messaging/${token}`; + console.log('正在连接WebSocket:', wsUrl); + const ws = new WebSocket(wsUrl); + wsRef.current = ws; + + ws.onopen = () => { + console.log('WebSocket连接已建立'); + setWsConnected(true); + // 启动心跳检测 + startHeartbeat(); + // 根据当前选中的设备订阅消息 + if (selectedDevice !== 'all') { + console.log('当前选中的设备:', selectedDevice); + subscribeDeviceMessages(selectedDevice); + } else { + console.log('未选择具体设备,订阅所有设备在线状态'); + subscribeDeviceMessages(); + } + }; + + ws.onmessage = (event) => { + console.log('收到WebSocket原始消息:', event.data); + try { + const data = JSON.parse(event.data); + console.log('解析后的WebSocket消息:', JSON.stringify(data, null, 2)); + // 处理心跳响应 + if (data.type === 'pong') { + console.log('收到心跳响应'); + return; + } + // 添加调试信息 + console.log('准备处理WebSocket消息...'); + console.log('消息类型:', data.type); + console.log('消息主题:', data.topic); + console.log('消息负载:', JSON.stringify(data.payload, null, 2)); + handleWebSocketMessage(data); + } catch (error) { + console.error('解析WebSocket消息失败:', error); + console.error('原始消息内容:', event.data); + } + }; + + ws.onerror = (error) => { + console.error('WebSocket错误:', error); + message.error('WebSocket连接错误'); + setWsConnected(false); + // 尝试重连 + scheduleReconnect(); + }; + + ws.onclose = (event) => { + console.log('WebSocket连接已关闭,代码:', event.code, '原因:', event.reason); + setWsConnected(false); + // 尝试重连 + scheduleReconnect(); + }; + } catch (error) { + console.error('初始化WebSocket失败:', error); + message.error('初始化WebSocket失败'); + // 尝试重连 + scheduleReconnect(); + } + }; + useEffect(() => { - console.log('组件初始化'); - (async () => { - await fetchDeviceList(); - await initWebSocket(); - })(); - return cleanup; + console.log('设备监控页面初始化'); + fetchDeviceList(); + initWebSocket(); + + return () => { + console.log('设备监控页面卸载,清理资源'); + cleanup(); + }; }, []); - // 在组件中添加调试日志 + // 切换设备时只发订阅,不重建ws useEffect(() => { - console.log('选中的设备:', selectedDevice); - console.log('当前设备列表:', JSON.stringify(deviceList, null, 2)); - console.log('当前性能指标:', JSON.stringify(metricsMap, null, 2)); - }, [selectedDevice, deviceList, metricsMap]); + console.log('选中的设备已更改:', selectedDevice); + if (wsRef.current?.readyState === WebSocket.OPEN) { + if (selectedDevice !== 'all') { + console.log('WebSocket已连接,开始订阅设备消息:', selectedDevice); + subscribeDeviceMessages(selectedDevice); + } else { + console.log('WebSocket已连接,订阅所有设备在线状态'); + subscribeDeviceMessages(); + } + } else { + console.log('WebSocket未连接,尝试重新连接...'); + initWebSocket(); + } + }, [selectedDevice]); + + useEffect(() => { + if (selectedDevice !== 'all') { + console.log(`设备选择变更: ${selectedDevice}`); + subscribeDeviceMessages(selectedDevice); + } + }, [selectedDevice]); const alertColumns = [ { @@ -759,25 +944,25 @@ const DeviceMonitor: React.FC = () => { // 修改实时数据卡片的渲染逻辑 const renderRealTimeData = () => { - const device = deviceList.find(d => d.deviceSn === selectedDevice); - console.log('渲染实时数据卡片,当前设备:', JSON.stringify(device, null, 2)); + const currentDevice = deviceList.find(d => d.deviceSn === selectedDevice); + console.log('渲染实时数据卡片,当前设备:', JSON.stringify(currentDevice, null, 2)); - if (!device) { + if (!currentDevice) { console.log('未找到选中的设备'); return null; } // 添加设备指标值的日志 - console.log('设备指标值:', { - temperature: device.metrics.temperature, - humidity: device.metrics.humidity, - environmentTemperature: device.metrics.environmentTemperature, - batteryCapacity: device.metrics.batteryCapacity, - windSpeed: device.metrics.windSpeed, - rainfall: device.metrics.rainfall, - positionQuality: device.metrics.positionQuality, - networkQuality: device.metrics.networkQuality, - }); + console.log('设备指标值:', JSON.stringify({ + temperature: currentDevice.metrics.temperature, + humidity: currentDevice.metrics.humidity, + environmentTemperature: currentDevice.metrics.environmentTemperature, + batteryCapacity: currentDevice.metrics.batteryCapacity, + windSpeed: currentDevice.metrics.windSpeed, + rainfall: currentDevice.metrics.rainfall, + positionQuality: currentDevice.metrics.positionQuality, + networkQuality: currentDevice.metrics.networkQuality, + }, null, 2)); return ( @@ -785,7 +970,7 @@ const DeviceMonitor: React.FC = () => { @@ -795,7 +980,7 @@ const DeviceMonitor: React.FC = () => { @@ -805,7 +990,7 @@ const DeviceMonitor: React.FC = () => { @@ -815,7 +1000,7 @@ const DeviceMonitor: React.FC = () => { @@ -825,7 +1010,7 @@ const DeviceMonitor: React.FC = () => { @@ -835,7 +1020,7 @@ const DeviceMonitor: React.FC = () => { @@ -845,7 +1030,7 @@ const DeviceMonitor: React.FC = () => { @@ -855,7 +1040,7 @@ const DeviceMonitor: React.FC = () => { @@ -865,65 +1050,6 @@ const DeviceMonitor: React.FC = () => { ); }; - // 订阅设备消息 - const subscribeDeviceMessages = (deviceSn?: string) => { - if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) { - console.log('WebSocket未连接,无法订阅消息'); - return; - } - - console.log('开始订阅设备消息:', deviceSn); - - // 取消所有现有订阅 - const unsubAll = { - type: 'unsub', - topic: '/device/*', - id: 'unsub-all', - }; - console.log('取消所有订阅:', JSON.stringify(unsubAll, null, 2)); - wsRef.current.send(JSON.stringify(unsubAll)); - - if (deviceSn) { - // 订阅指定设备的消息 - const subscriptions = [ - { - type: 'sub', - topic: `/device/*/${deviceSn}/online`, - id: 'online-sub', - }, - { - type: 'sub', - topic: `/device/*/${deviceSn}/offline`, - id: 'offline-sub', - }, - { - type: 'sub', - topic: `/device/*/${deviceSn}/message/property/report`, - id: 'property-sub', - }, - { - type: 'sub', - topic: `/device/*/${deviceSn}/message/event/fire_alarm`, - id: 'fire-alarm-sub', - }, - ]; - subscriptions.forEach(sub => { - console.log('发送订阅请求:', JSON.stringify(sub, null, 2)); - wsRef.current?.send(JSON.stringify(sub)); - }); - } else { - // 订阅所有设备的在线状态 - const onlineSub = { - type: 'sub', - topic: '/device/*/online', - id: 'online-sub', - }; - console.log('发送在线状态订阅请求:', JSON.stringify(onlineSub, null, 2)); - wsRef.current.send(JSON.stringify(onlineSub)); - } - console.log('设备消息订阅请求已发送'); - }; - return ( diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device/Wayline/components/UpdateForm.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device/Wayline/components/UpdateForm.tsx index e91a2dd9..183bf9e2 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/device/Wayline/components/UpdateForm.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/device/Wayline/components/UpdateForm.tsx @@ -7,7 +7,7 @@ import { ProFormText, } from '@ant-design/pro-components'; import { Button, Form, message, Upload } from 'antd'; -import { RcFile } from 'antd/lib/upload'; +import type { RcFile } from 'antd/lib/upload'; import { useState, useRef, useEffect } from 'react'; import styles from '../index.less'; import { TOURISM_OPTIONS, TYPE_OPTIONS, WORKSPACE_OPTIONS } from '../index'; diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device/Wayline/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device/Wayline/index.tsx index fb69ae1a..34c86f70 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/device/Wayline/index.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/device/Wayline/index.tsx @@ -17,7 +17,7 @@ import React, { useRef, useState, useCallback } from 'react'; import UpdateForm from './components/UpdateForm'; import styles from './index.less'; import SparkMD5 from 'spark-md5'; -import { DefaultOptionType } from 'antd/es/select'; +import type { DefaultOptionType } from 'antd/es/select'; const { Link } = Typography; diff --git a/zlt-web/react-web/src/main/frontend/src/pages/orders/TourismFile/components/UpdateForm.tsx b/zlt-web/react-web/src/main/frontend/src/pages/orders/TourismFile/components/UpdateForm.tsx index b66283ef..826e7cb0 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/orders/TourismFile/components/UpdateForm.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/orders/TourismFile/components/UpdateForm.tsx @@ -9,7 +9,7 @@ import { import { Button, Upload, Image, message, Form } from 'antd'; import type { RcFile } from 'antd/lib/upload'; import React, { useState } from 'react'; -import { TYPE_OPTIONS } from '../constants'; +import type { TYPE_OPTIONS } from '../constants'; interface UpdateFormProps { onSubmit: (values: any) => Promise; diff --git a/zlt-web/react-web/src/main/frontend/src/pages/system/Menu/components/UpdateForm.tsx b/zlt-web/react-web/src/main/frontend/src/pages/system/Menu/components/UpdateForm.tsx index 0a52cd30..7614164c 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/system/Menu/components/UpdateForm.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/system/Menu/components/UpdateForm.tsx @@ -49,11 +49,11 @@ const UpdateForm: React.FC = (props) => { request={async () => { const menus = await menuOnes(); if (menus) { - let a = menus.map(item => { + const a = menus.map(item => { return { ...item, key: item.id, title: item.name, value: item.id } }) - let treeData = treeify(a, {}); - let root = { + const treeData = treeify(a, {}); + const root = { title: '顶级目录', value: -1, key: -1, From 2fd5d578be13ba72a48cbec044e4e718cf57ec09 Mon Sep 17 00:00:00 2001 From: Iamasoldier <1272745473@qq.com> Date: Wed, 18 Jun 2025 11:54:24 +0800 Subject: [PATCH 06/10] =?UTF-8?q?fix:=E4=BF=AE=E5=A4=8D=E8=AE=BE=E5=A4=87w?= =?UTF-8?q?s=E8=AE=A2=E9=98=85=E9=80=BB=E8=BE=91=EF=BC=8C=E5=88=87?= =?UTF-8?q?=E8=8A=B1=E8=AE=BE=E5=A4=87=E5=90=8E=E8=AE=A2=E9=98=85=E9=80=BB?= =?UTF-8?q?=E8=BE=91=E5=AE=8C=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/pages/device-ops/monitor/index.tsx | 532 ++++++++++++------ 1 file changed, 356 insertions(+), 176 deletions(-) diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx index 458e2035..22359b07 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx @@ -172,6 +172,9 @@ const DeviceMonitor: React.FC = () => { const [wsConnected, setWsConnected] = useState(false); const reconnectTimerRef = useRef(); const heartbeatTimerRef = useRef(); + const [currentSubscribedDevice, setCurrentSubscribedDevice] = useState('all'); + // 添加订阅ID跟踪 + const [currentSubscriptions, setCurrentSubscriptions] = useState([]); // token自动续期相关 const tokenCache = { @@ -301,6 +304,20 @@ const DeviceMonitor: React.FC = () => { if (heartbeatTimerRef.current) { clearInterval(heartbeatTimerRef.current); } + + // 取消所有订阅 + if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN && currentSubscriptions.length > 0) { + console.log('页面卸载,取消所有订阅:', currentSubscriptions); + currentSubscriptions.forEach(subId => { + const unsubMessage = { + type: 'unsub', + id: subId, + }; + console.log('发送取消订阅请求:', JSON.stringify(unsubMessage, null, 2)); + wsRef.current?.send(JSON.stringify(unsubMessage)); + }); + } + if (wsRef.current) { wsRef.current.close(); } @@ -372,109 +389,165 @@ const DeviceMonitor: React.FC = () => { // 处理属性上报 const handlePropertyReport = (deviceSn: string, payload: any) => { console.log('处理属性上报:', deviceSn, payload); + + // 提取设备数据,可能在不同的位置 + let deviceData = null; + if (payload.data && payload.data.data) { + deviceData = payload.data.data; + console.log('从payload.data.data中提取设备数据:', JSON.stringify(deviceData, null, 2)); + } else if (payload.properties) { + deviceData = payload.properties; + console.log('从payload.properties中提取设备数据:', JSON.stringify(deviceData, null, 2)); + } + + if (!deviceData) { + console.log('未找到设备数据'); + return; + } + // 更新性能指标数据 - if (payload.properties) { - const newMetrics: DeviceMetrics[] = []; - const time = moment().format('YYYY-MM-DD HH:mm:ss'); + const newMetrics: DeviceMetrics[] = []; + const time = moment().format('YYYY-MM-DD HH:mm:ss'); - if (payload.properties.cpu_usage !== undefined) { - newMetrics.push({ - time, - value: payload.properties.cpu_usage, - type: 'CPU使用率', - }); - } - - if (payload.properties.memory_usage !== undefined) { - newMetrics.push({ - time, - value: payload.properties.memory_usage, - type: '内存使用率', - }); - } - - if (payload.properties.temperature !== undefined) { - newMetrics.push({ - time, - value: payload.properties.temperature, - type: '温度', - }); - } - - // 新增:同步更新 deviceList 里对应设备的 metrics 字段 - setDeviceList(prev => { - // 检查设备是否已存在 - const existingDevice = prev.find(d => d.deviceSn === deviceSn); - - if (!existingDevice) { - console.log('设备不存在,创建新设备记录:', deviceSn); - // 如果设备不存在,创建一个新的设备记录 - const newDevice: Device = { - deviceSn: deviceSn, - deviceName: deviceSn, // 使用设备编号作为名称 - deviceType: 1, // 默认类型 - boundStatus: 1, - createTime: moment().format('YYYY-MM-DD HH:mm:ss'), - loginTime: moment().format('YYYY-MM-DD HH:mm:ss'), - metrics: { - temperature: payload.properties.temperature ?? 0, - humidity: payload.properties.humidity ?? 0, - windSpeed: payload.properties.wind_speed ?? 0, - rainfall: payload.properties.rainfall ?? 0, - environmentTemperature: payload.properties.environment_temperature ?? 0, - positionQuality: payload.properties.position_state?.quality ?? 0, - networkQuality: payload.properties.network_state?.quality ?? 0, - droneInDock: payload.properties.drone_in_dock ?? 0, - batteryCapacity: payload.properties.drone_charge_state?.capacity_percent ?? 0, - batteryState: payload.properties.drone_charge_state?.state ?? 0, - workingVoltage: 0, - workingCurrent: 0, - acdcPowerInput: 0, - backupBatteryVoltage: 0, - flightTaskStep: 0, - tiltAngle: 0, - sdrUpQuality: 0, - sdrDownQuality: 0, - wirelessLinkState: 0, - wirelessLinkQuality: 0, - '4gLinkState': 0, - '4gLinkQuality': 0, - } - }; - console.log('创建的新设备:', JSON.stringify(newDevice, null, 2)); - return [...prev, newDevice]; - } - - // 如果设备存在,更新现有设备 - return prev.map(d => - d.deviceSn === deviceSn - ? { - ...d, - metrics: { - ...d.metrics, - temperature: payload.properties.temperature ?? d.metrics.temperature, - humidity: payload.properties.humidity ?? d.metrics.humidity, - windSpeed: payload.properties.wind_speed ?? d.metrics.windSpeed, - rainfall: payload.properties.rainfall ?? d.metrics.rainfall, - environmentTemperature: payload.properties.environment_temperature ?? d.metrics.environmentTemperature, - positionQuality: payload.properties.position_state?.quality ?? d.metrics.positionQuality, - networkQuality: payload.properties.network_state?.quality ?? d.metrics.networkQuality, - droneInDock: payload.properties.drone_in_dock ?? d.metrics.droneInDock, - batteryCapacity: payload.properties.drone_charge_state?.capacity_percent ?? d.metrics.batteryCapacity, - batteryState: payload.properties.drone_charge_state?.state ?? d.metrics.batteryState, - } - } - : d - ); + // 处理环境数据 + if (deviceData.temperature !== undefined) { + newMetrics.push({ + time, + value: deviceData.temperature, + type: '温度', }); + } - if (newMetrics.length > 0) { - console.log('新的性能指标:', JSON.stringify(newMetrics, null, 2)); - setMetricsMap(prev => ({ - ...prev, - [deviceSn]: [...(prev[deviceSn] || []), ...newMetrics].slice(-72) - })); + if (deviceData.humidity !== undefined) { + newMetrics.push({ + time, + value: deviceData.humidity, + type: '湿度', + }); + } + + if (deviceData.environment_temperature !== undefined) { + newMetrics.push({ + time, + value: deviceData.environment_temperature, + type: '环境温度', + }); + } + + if (deviceData.wind_speed !== undefined) { + newMetrics.push({ + time, + value: deviceData.wind_speed, + type: '风速', + }); + } + + if (deviceData.rainfall !== undefined) { + newMetrics.push({ + time, + value: deviceData.rainfall, + type: '降雨量', + }); + } + + // 处理设备状态数据 + if (deviceData.drone_charge_state?.capacity_percent !== undefined) { + newMetrics.push({ + time, + value: deviceData.drone_charge_state.capacity_percent, + type: '电池电量', + }); + } + + if (deviceData.position_state?.quality !== undefined) { + newMetrics.push({ + time, + value: deviceData.position_state.quality, + type: '定位质量', + }); + } + + if (deviceData.network_state?.quality !== undefined) { + newMetrics.push({ + time, + value: deviceData.network_state.quality, + type: '网络质量', + }); + } + + // 同步更新 deviceList 里对应设备的 metrics 字段 + setDeviceList(prev => { + // 检查设备是否已存在 + const existingDevice = prev.find(d => d.deviceSn === deviceSn); + + if (!existingDevice) { + console.log('设备不存在,创建新设备记录:', deviceSn); + // 如果设备不存在,创建一个新的设备记录 + const newDevice: Device = { + deviceSn: deviceSn, + deviceName: deviceSn, // 使用设备编号作为名称 + deviceType: 1, // 默认类型 + boundStatus: 1, + createTime: moment().format('YYYY-MM-DD HH:mm:ss'), + loginTime: moment().format('YYYY-MM-DD HH:mm:ss'), + metrics: { + temperature: deviceData.temperature ?? 0, + humidity: deviceData.humidity ?? 0, + windSpeed: deviceData.wind_speed ?? 0, + rainfall: deviceData.rainfall ?? 0, + environmentTemperature: deviceData.environment_temperature ?? 0, + positionQuality: deviceData.position_state?.quality ?? 0, + networkQuality: deviceData.network_state?.quality ?? 0, + droneInDock: deviceData.drone_in_dock ?? 0, + batteryCapacity: deviceData.drone_charge_state?.capacity_percent ?? 0, + batteryState: deviceData.drone_charge_state?.state ?? 0, + workingVoltage: 0, + workingCurrent: 0, + acdcPowerInput: 0, + backupBatteryVoltage: 0, + flightTaskStep: 0, + tiltAngle: 0, + sdrUpQuality: 0, + sdrDownQuality: 0, + wirelessLinkState: 0, + wirelessLinkQuality: 0, + '4gLinkState': 0, + '4gLinkQuality': 0, + } + }; + console.log('创建的新设备:', JSON.stringify(newDevice, null, 2)); + return [...prev, newDevice]; } + + // 如果设备存在,更新现有设备 + return prev.map(d => + d.deviceSn === deviceSn + ? { + ...d, + metrics: { + ...d.metrics, + temperature: deviceData.temperature ?? d.metrics.temperature, + humidity: deviceData.humidity ?? d.metrics.humidity, + windSpeed: deviceData.wind_speed ?? d.metrics.windSpeed, + rainfall: deviceData.rainfall ?? d.metrics.rainfall, + environmentTemperature: deviceData.environment_temperature ?? d.metrics.environmentTemperature, + positionQuality: deviceData.position_state?.quality ?? d.metrics.positionQuality, + networkQuality: deviceData.network_state?.quality ?? d.metrics.networkQuality, + droneInDock: deviceData.drone_in_dock ?? d.metrics.droneInDock, + batteryCapacity: deviceData.drone_charge_state?.capacity_percent ?? d.metrics.batteryCapacity, + batteryState: deviceData.drone_charge_state?.state ?? d.metrics.batteryState, + } + } + : d + ); + }); + + if (newMetrics.length > 0) { + console.log('新的性能指标:', JSON.stringify(newMetrics, null, 2)); + setMetricsMap(prev => ({ + ...prev, + [deviceSn]: [...(prev[deviceSn] || []), ...newMetrics].slice(-72) + })); } }; @@ -655,6 +728,8 @@ const DeviceMonitor: React.FC = () => { // topic: /device/{productId}/{deviceSn}/message/event/fire_alarm const deviceSn = topicParts[3]; console.log('从主题中提取的设备编号:', deviceSn); + console.log('消息主题:', topic); + console.log('消息负载:', JSON.stringify(payload, null, 2)); // 处理设备在线状态 if (topic.endsWith('/online')) { @@ -682,9 +757,36 @@ const DeviceMonitor: React.FC = () => { } else if (data.type === 'error') { console.error('WebSocket消息错误:', data); message.error(data.message || '消息处理错误'); + } else if (data.type === 'sub') { + // 处理订阅响应 + console.log('收到订阅响应:', JSON.stringify(data, null, 2)); + if (data.success) { + console.log('订阅成功:', data.id); + } else { + console.error('订阅失败:', data.id, data.message); + } + } else if (data.type === 'unsub') { + // 处理取消订阅响应 + console.log('收到取消订阅响应:', JSON.stringify(data, null, 2)); + if (data.success) { + console.log('取消订阅成功:', data.id); + } else { + console.error('取消订阅失败:', data.id, data.message); + } + } else { + console.log('未处理的WebSocket消息类型:', data.type); } }; + // 添加订阅状态检查 + const checkSubscriptionStatus = () => { + console.log('当前订阅状态:'); + console.log('- 当前订阅的设备:', currentSubscribedDevice); + console.log('- 当前订阅列表:', currentSubscriptions); + console.log('- WebSocket连接状态:', wsRef.current?.readyState); + console.log('- 设备列表:', deviceList.map(d => ({ deviceSn: d.deviceSn, deviceName: d.deviceName }))); + }; + // 订阅设备消息 const subscribeDeviceMessages = (deviceSn?: string) => { if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) { @@ -694,73 +796,129 @@ const DeviceMonitor: React.FC = () => { console.log('开始订阅设备消息:', deviceSn); - // 取消所有现有订阅 - const unsubAll = { - type: 'unsub', - topic: '/device/*', - id: 'unsub-all', - }; - console.log('取消所有订阅:', JSON.stringify(unsubAll, null, 2)); - wsRef.current.send(JSON.stringify(unsubAll)); + try { + // 生成唯一的时间戳作为ID前缀 + const timestamp = Date.now(); + const newSubscriptions: string[] = []; - if (deviceSn) { - // 订阅指定设备的消息 - const subscriptions = [ - { - type: 'sub', - topic: `/device/*/${deviceSn}/online`, - id: 'online-sub', - }, - { - type: 'sub', - topic: `/device/*/${deviceSn}/offline`, - id: 'offline-sub', - }, - { - type: 'sub', - topic: `/device/*/${deviceSn}/message/property/report`, - id: 'property-sub', - }, - { - type: 'sub', - topic: `/device/*/${deviceSn}/message/event/fire_alarm`, - id: 'fire-alarm-sub', - }, - ]; - subscriptions.forEach(sub => { - console.log('发送订阅请求:', JSON.stringify(sub, null, 2)); - wsRef.current?.send(JSON.stringify(sub)); - }); - } else { - // 订阅所有设备的在线状态 - const onlineSub = { - type: 'sub', - topic: '/device/*/online', - id: 'online-sub', - }; - console.log('发送在线状态订阅请求:', JSON.stringify(onlineSub, null, 2)); - wsRef.current.send(JSON.stringify(onlineSub)); + // 先取消所有当前订阅 + if (currentSubscriptions.length > 0) { + console.log('取消当前订阅:', currentSubscriptions); + currentSubscriptions.forEach(subId => { + const unsubMessage = { + type: 'unsub', + id: subId, + }; + console.log('发送取消订阅请求:', JSON.stringify(unsubMessage, null, 2)); + wsRef.current?.send(JSON.stringify(unsubMessage)); + }); + // 清空当前订阅列表 + setCurrentSubscriptions([]); + } + + // 等待一段时间让服务器处理取消订阅 + setTimeout(() => { + if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) { + console.log('WebSocket连接已断开,取消订阅'); + return; + } + + if (deviceSn) { + // 订阅指定设备的消息,每个订阅使用唯一的ID + const subscriptions = [ + { + type: 'sub', + topic: `/device/*/${deviceSn}/online`, + id: `online-sub-${timestamp}-${deviceSn}`, + }, + { + type: 'sub', + topic: `/device/*/${deviceSn}/offline`, + id: `offline-sub-${timestamp}-${deviceSn}`, + }, + { + type: 'sub', + topic: `/device/*/${deviceSn}/message/property/report`, + id: `property-sub-${timestamp}-${deviceSn}`, + }, + { + type: 'sub', + topic: `/device/*/${deviceSn}/message/event/fire_alarm`, + id: `fire-alarm-sub-${timestamp}-${deviceSn}`, + }, + ]; + + console.log('准备发送设备订阅请求:', JSON.stringify(subscriptions, null, 2)); + + // 逐个发送订阅请求,确保每个请求都被正确处理 + const sendSubscriptions = (index: number) => { + if (index >= subscriptions.length) { + console.log('所有订阅请求已发送完成'); + // 更新当前订阅列表 + setCurrentSubscriptions(newSubscriptions); + console.log('设备消息订阅请求已发送,当前订阅:', newSubscriptions); + return; + } + + const sub = subscriptions[index]; + if (wsRef.current?.readyState === WebSocket.OPEN) { + console.log(`发送订阅请求 ${index + 1}/${subscriptions.length}:`, JSON.stringify(sub, null, 2)); + wsRef.current.send(JSON.stringify(sub)); + newSubscriptions.push(sub.id); + + // 延迟发送下一个订阅请求 + setTimeout(() => { + sendSubscriptions(index + 1); + }, 200); + } + }; + + // 开始发送订阅请求 + sendSubscriptions(0); + } else { + // 订阅所有设备的在线状态,修正topic格式 + const onlineSub = { + type: 'sub', + topic: '/device/*/*/online', + id: `online-sub-${timestamp}-all`, + }; + console.log('发送在线状态订阅请求:', JSON.stringify(onlineSub, null, 2)); + wsRef.current.send(JSON.stringify(onlineSub)); + newSubscriptions.push(onlineSub.id); + + // 更新当前订阅列表 + setCurrentSubscriptions(newSubscriptions); + console.log('设备消息订阅请求已发送,当前订阅:', newSubscriptions); + } + }, 500); // 等待500ms让服务器处理取消订阅 + } catch (error) { + console.error('订阅设备消息失败:', error); } - console.log('设备消息订阅请求已发送'); }; // 修改 WebSocket 连接初始化 const initWebSocket = async () => { try { console.log('开始初始化WebSocket连接...'); - const token = await getToken(); - console.log('获取到WebSocket token:', token); - + // 如果已经存在连接,且未关闭,不重复建立 if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) { console.log('WebSocket已连接,无需重复建立'); return; } + + // 如果存在连接但状态不是OPEN,先关闭 if (wsRef.current) { console.log('关闭已存在的WebSocket连接'); wsRef.current.close(); + wsRef.current = null; + // 等待一小段时间确保连接完全关闭 + await new Promise(resolve => setTimeout(resolve, 100)); } + const token = await getToken(); + console.log('获取到WebSocket token:', token); + // 建立WebSocket连接 const wsUrl = `ws://119.45.169.13:8848/messaging/${token}`; console.log('正在连接WebSocket:', wsUrl); @@ -772,14 +930,19 @@ const DeviceMonitor: React.FC = () => { setWsConnected(true); // 启动心跳检测 startHeartbeat(); - // 根据当前选中的设备订阅消息 - if (selectedDevice !== 'all') { - console.log('当前选中的设备:', selectedDevice); - subscribeDeviceMessages(selectedDevice); - } else { - console.log('未选择具体设备,订阅所有设备在线状态'); - subscribeDeviceMessages(); - } + + // 延迟一点时间确保连接稳定后再订阅 + setTimeout(() => { + console.log('准备发送订阅请求,当前选中的设备:', selectedDevice); + // 根据当前选中的设备订阅消息 + if (selectedDevice !== 'all') { + console.log('WebSocket连接稳定,订阅设备消息:', selectedDevice); + subscribeDeviceMessages(selectedDevice); + } else { + console.log('WebSocket连接稳定,订阅所有设备在线状态'); + subscribeDeviceMessages(); + } + }, 200); }; ws.onmessage = (event) => { @@ -837,29 +1000,38 @@ const DeviceMonitor: React.FC = () => { }; }, []); - // 切换设备时只发订阅,不重建ws + // 切换设备时只更新订阅,不重建连接 useEffect(() => { console.log('选中的设备已更改:', selectedDevice); - if (wsRef.current?.readyState === WebSocket.OPEN) { - if (selectedDevice !== 'all') { - console.log('WebSocket已连接,开始订阅设备消息:', selectedDevice); - subscribeDeviceMessages(selectedDevice); - } else { - console.log('WebSocket已连接,订阅所有设备在线状态'); - subscribeDeviceMessages(); - } - } else { - console.log('WebSocket未连接,尝试重新连接...'); - initWebSocket(); - } - }, [selectedDevice]); + + // 检查当前订阅状态 + checkSubscriptionStatus(); + + // 如果切换到了不同的设备,更新订阅状态 + if (currentSubscribedDevice !== selectedDevice) { + console.log('设备切换,更新订阅:', currentSubscribedDevice, '->', selectedDevice); + + // 更新当前订阅的设备 + setCurrentSubscribedDevice(selectedDevice); + + // 延迟一点时间确保WebSocket连接稳定 + const timer = setTimeout(() => { + if (wsRef.current?.readyState === WebSocket.OPEN) { + console.log('WebSocket已连接,开始订阅设备消息:', selectedDevice); + if (selectedDevice !== 'all') { + subscribeDeviceMessages(selectedDevice); + } else { + subscribeDeviceMessages(); + } + } else { + console.log('WebSocket未连接,尝试重新连接...'); + initWebSocket(); + } + }, 300); - useEffect(() => { - if (selectedDevice !== 'all') { - console.log(`设备选择变更: ${selectedDevice}`); - subscribeDeviceMessages(selectedDevice); + return () => clearTimeout(timer); } - }, [selectedDevice]); + }, [selectedDevice]); // 只监听selectedDevice的变化 const alertColumns = [ { @@ -936,7 +1108,10 @@ const DeviceMonitor: React.FC = () => { key: 'action', render: (_: unknown, record: Device) => ( - setSelectedDevice(record.deviceSn)}>查看监控 + { + console.log('点击查看监控按钮,设备:', record.deviceSn); + setSelectedDevice(record.deviceSn); + }}>查看监控 ), }, @@ -946,6 +1121,8 @@ const DeviceMonitor: React.FC = () => { const renderRealTimeData = () => { const currentDevice = deviceList.find(d => d.deviceSn === selectedDevice); console.log('渲染实时数据卡片,当前设备:', JSON.stringify(currentDevice, null, 2)); + console.log('当前订阅的设备:', currentSubscribedDevice); + console.log('WebSocket连接状态:', wsRef.current?.readyState); if (!currentDevice) { console.log('未找到选中的设备'); @@ -1059,7 +1236,10 @@ const DeviceMonitor: React.FC = () => { { ))} + { }} disabled={loading} /> - - - - - - {/* 实时数据卡片 */} - {selectedDevice !== 'all' && ( - - d.deviceSn === selectedDevice)?.deviceName || ''} 实时数据`}> - {renderRealTimeData()} - - - )} - - {/* 性能趋势图 */} - {selectedDevice !== 'all' && ( - - d.deviceSn === selectedDevice)?.deviceName || ''} 性能趋势`} loading={loading}> - `${v}%`, - }, - }} + + setSearchKeyword(e.target.value)} + onKeyPress={(e) => e.key === 'Enter' && searchDevice(searchKeyword)} + style={{ width: 150 }} + prefix={} /> - + - )} + + + + + + + + + + + + + + - {/* 设备状态列表 */} - - -
+ + + } + valueStyle={{ color: '#1890ff' }} /> - - {/* 告警记录 */} - - -
+ + } + valueStyle={{ color: '#52c41a' }} + suffix={`/ ${getDeviceStatistics().total}`} + /> + + + + + } + valueStyle={{ color: '#52c41a' }} + suffix={`/ ${getDeviceStatistics().total}`} + /> + + + + + } + valueStyle={{ color: '#faad14' }} /> - - {/* 地图组件 */} - {mapVisible && ( - - - {mapInitialized ? ( - renderDeviceMap() - ) : ( -
-
地图加载中...
-
- )} -
- - )} + {/* 主要监控内容 */} + + {/* 概览标签页 */} + + + {/* 实时数据卡片 */} + {selectedDevice !== 'all' && ( + + d.deviceSn === selectedDevice)?.deviceName || ''} 实时数据`} + extra={ + + } + > + {renderRealTimeData()} + + + )} + + {/* 地图组件 */} + {mapVisible && ( + + + {mapInitialized ? ( + renderDeviceMap() + ) : ( +
+
地图加载中...
+
+ )} +
+ + )} + + {/* 设备状态列表 */} + + +
+ + + + + + {/* 健康监控标签页 */} + + + {deviceList.map(device => { + const health = deviceHealth[device.deviceSn]; + if (!health) return null; + + return ( + + = 80 ? 'green' : health.overall >= 60 ? 'orange' : 'red'}> + {health.overall}分 + + } + > + + + `${percent}分`} + strokeColor={health.overall >= 80 ? '#52c41a' : health.overall >= 60 ? '#faad14' : '#ff4d4f'} + /> + + + +
+ 电池: + +
+
+ 网络: + +
+
+ 硬件: + +
+
+ 软件: + +
+
+ 环境: + +
+
+ + + + {health.issues.length > 0 && ( + + {health.issues.map((issue, index) => ( +
  • {issue}
  • + ))} + + } + type="warning" + showIcon + style={{ marginTop: 16 }} + /> + )} + + + ); + })} + + + + {/* 性能分析标签页 */} + + + {deviceList.map(device => { + const performance = devicePerformance[device.deviceSn]; + if (!performance) return null; + + return ( +
    + + + + + + + 50 ? '#52c41a' : '#faad14' }} + /> + + + 99 ? '#52c41a' : '#faad14' }} + /> + + + 95 ? '#52c41a' : '#faad14' }} + /> + + + + + ); + })} + + + + {/* 告警管理标签页 */} + + + + + + + + } + > +
    { + if (alertFilters.type !== 'all' && alert.type !== alertFilters.type) return false; + if (alertFilters.status !== 'all' && alert.status !== alertFilters.status) return false; + return true; + })} + columns={[ + { + title: '设备名称', + dataIndex: 'deviceName', + key: 'deviceName', + }, + { + title: '告警类型', + dataIndex: 'type', + key: 'type', + render: (type: string) => ( + + {type === 'critical' ? '严重' : type === 'warning' ? '警告' : '信息'} + + ) + }, + { + title: '告警类别', + dataIndex: 'category', + key: 'category', + render: (category: string) => ( + {category} + ) + }, + { + title: '标题', + dataIndex: 'title', + key: 'title', + }, + { + title: '时间', + dataIndex: 'timestamp', + key: 'timestamp', + }, + { + title: '状态', + dataIndex: 'status', + key: 'status', + render: (status: string) => ( + + {status === 'active' ? '活跃' : status === 'acknowledged' ? '已确认' : '已解决'} + + ) + }, + { + title: '操作', + key: 'action', + render: (_, record: DeviceAlert) => ( + + {record.status === 'active' && ( + { + setDeviceAlerts(prev => prev.map(a => + a.id === record.id ? { ...a, status: 'acknowledged' } : a + )); + }}> + 确认 + + )} + {record.status === 'acknowledged' && ( + { + setDeviceAlerts(prev => prev.map(a => + a.id === record.id ? { ...a, status: 'resolved' } : a + )); + }}> + 解决 + + )} + { + setDeviceAlerts(prev => prev.filter(a => a.id !== record.id)); + }} style={{ color: '#ff4d4f' }}> + 删除 + + + ) + } + ]} + rowKey="id" + pagination={{ pageSize: 10 }} + /> + + + + + + {/* 维护管理标签页 */} + + + + }> + 添加维护计划 + + } + > +
    { + const device = deviceList.find(d => d.deviceSn === deviceSn); + return device?.deviceName || deviceSn; + } + }, + { + title: '维护类型', + dataIndex: 'type', + key: 'type', + render: (type: string) => ( + + {type === 'preventive' ? '预防性' : type === 'corrective' ? '纠正性' : '紧急'} + + ) + }, + { + title: '描述', + dataIndex: 'description', + key: 'description', + }, + { + title: '计划日期', + dataIndex: 'scheduledDate', + key: 'scheduledDate', + }, + { + title: '状态', + dataIndex: 'status', + key: 'status', + render: (status: string) => ( + + {status === 'completed' ? '已完成' : status === 'in_progress' ? '进行中' : '已计划'} + + ) + }, + { + title: '操作', + key: 'action', + render: (_, record: MaintenanceRecord) => ( + + 查看详情 + 编辑 + 删除 + + ) + } + ]} + rowKey="id" + pagination={{ pageSize: 10 }} + /> + + + + + + + {/* 设置抽屉 */} + setShowSettings(false)} + > + + + +
    + 健康监控: + setMonitoringConfig(prev => ({ ...prev, enableHealthMonitoring: checked }))} + /> +
    +
    + 性能跟踪: + setMonitoringConfig(prev => ({ ...prev, enablePerformanceTracking: checked }))} + /> +
    +
    + 预测性维护: + setMonitoringConfig(prev => ({ ...prev, enablePredictiveMaintenance: checked }))} + /> +
    +
    + 异常检测: + setMonitoringConfig(prev => ({ ...prev, enableAnomalyDetection: checked }))} + /> +
    +
    +
    + + + +
    + 电池电量阈值: {monitoringConfig.alertThresholds.battery}% + setMonitoringConfig(prev => ({ + ...prev, + alertThresholds: { ...prev.alertThresholds, battery: value } + }))} + /> +
    +
    + 温度阈值: {monitoringConfig.alertThresholds.temperature}°C + setMonitoringConfig(prev => ({ + ...prev, + alertThresholds: { ...prev.alertThresholds, temperature: value } + }))} + /> +
    +
    + 网络质量阈值: {monitoringConfig.alertThresholds.networkQuality}% + setMonitoringConfig(prev => ({ + ...prev, + alertThresholds: { ...prev.alertThresholds, networkQuality: value } + }))} + /> +
    +
    +
    + + + +
    + 启用自动刷新: + +
    +
    + 刷新间隔: {refreshInterval}秒 + +
    +
    +
    +
    +
    + {/* 设备详情弹窗 */} } + onClick={() => { + if (selectedMapDevice) { + handlePlayVideo(selectedMapDevice); + closeMapDeviceInfo(); + } + }} + > + 视频流 + , + , + ]} width={600} > {selectedMapDevice && ( @@ -1541,6 +3060,117 @@ const DeviceMonitor: React.FC = () => { )} + + {/* 视频流播放弹窗 */} + + + {currentVideoDevice ? `${currentVideoDevice.deviceName} 视频流` : '设备视频流'} + + } + open={videoStreamVisible} + onCancel={handleCloseVideo} + footer={[ + , + , + , + , + , + ]} + width={800} + destroyOnClose + > +
    + {videoLoading && ( +
    +
    正在加载视频流...
    +
    + )} + + {videoError && ( + + )} + + {videoStreamUrl && !videoLoading && !videoError && ( +
    + {/* 使用新的视频播放器组件 */} + {renderVideoPlayer()} + + {/* 视频流信息 */} +
    + + + {currentVideoDevice?.deviceName} + + + {currentVideoDevice?.deviceSn} + + + + {currentVideoDevice?.boundStatus === 1 ? '在线' : '离线'} + + + + + {videoStreamUrl.includes('.m3u8') ? 'HLS' : + videoStreamUrl.startsWith('rtmp://') ? 'RTMP' : + videoStreamUrl.startsWith('webrtc://') ? 'WebRTC' : 'HTTP'} + + + + + + + + {videoStreamUrl} + + + +
    +
    + )} + + {!videoStreamUrl && !videoLoading && !videoError && ( +
    + +
    点击重新加载按钮获取视频流
    +
    + )} +
    +
    ); }; From 6eeba373e475f6f608b81b3a7299b6e445a17aee Mon Sep 17 00:00:00 2001 From: Iamasoldier <1272745473@qq.com> Date: Wed, 18 Jun 2025 17:03:41 +0800 Subject: [PATCH 09/10] =?UTF-8?q?fix:=E8=AE=BE=E5=A4=87=E7=9B=91=E6=8E=A7?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=E8=A7=86=E9=A2=91=E6=B5=81=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/pages/device-ops/monitor/index.tsx | 372 ++++++++++++++---- 1 file changed, 301 insertions(+), 71 deletions(-) diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx index 61a32194..f4f39aeb 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx @@ -18,6 +18,7 @@ import { import { device, getStreamUrls } from '@/services/device/api'; import { request } from 'umi'; import { Amap } from '@amap/amap-react'; +import ReactPlayer from 'react-player'; const { RangePicker } = DatePicker; const { TabPane } = Tabs; @@ -424,10 +425,14 @@ const DeviceMonitor: React.FC = () => { const [videoFullscreen, setVideoFullscreen] = useState(false); const [videoQuality, setVideoQuality] = useState('auto'); const [allStreamUrls, setAllStreamUrls] = useState<{ + pushUrl: string; playFlvUrl: string; playM3u8Url: string; playRtmpUrl: string; } | null>(null); + const [currentStreamType, setCurrentStreamType] = useState<'hls' | 'flv' | 'rtmp'>('hls'); + const [useReactPlayer, setUseReactPlayer] = useState(true); + const [videoStreamStatus, setVideoStreamStatus] = useState<'loading' | 'playing' | 'error' | 'ended' | 'stalled'>('loading'); const tokenCache = { value: '', @@ -1937,24 +1942,28 @@ const DeviceMonitor: React.FC = () => { console.log('视频流API响应:', response); - if (response && response.data) { - const { playFlvUrl, playM3u8Url, playRtmpUrl } = response.data; - console.log('获取到视频流地址:', { playFlvUrl, playM3u8Url, playRtmpUrl }); + if (response && response.resp_code === 0 && response.data) { + const { pushUrl, playFlvUrl, playM3u8Url, playRtmpUrl } = response.data; + console.log('获取到视频流地址:', { pushUrl, playFlvUrl, playM3u8Url, playRtmpUrl }); // 保存所有流URL - setAllStreamUrls({ playFlvUrl, playM3u8Url, playRtmpUrl }); + setAllStreamUrls({ pushUrl, playFlvUrl, playM3u8Url, playRtmpUrl }); // 优先使用HLS流,然后是FLV,最后是RTMP const streamUrl = playM3u8Url || playFlvUrl || playRtmpUrl; if (streamUrl) { + console.log('选择的流URL:', streamUrl); + console.log('流类型:', streamUrl.includes('.m3u8') ? 'HLS' : + streamUrl.includes('.flv') ? 'FLV' : + streamUrl.startsWith('rtmp://') ? 'RTMP' : '未知'); setVideoStreamUrl(streamUrl); return streamUrl; } else { throw new Error('未找到可用的视频流地址'); } } else { - throw new Error('获取视频流地址失败'); + throw new Error(String(response?.resp_msg || '获取视频流地址失败')); } } catch (error) { console.error('获取视频流地址失败:', error); @@ -1976,6 +1985,8 @@ const DeviceMonitor: React.FC = () => { setVideoStreamVisible(true); setVideoError(''); setVideoStreamUrl(''); + setAllStreamUrls(null); + setCurrentStreamType('hls'); // 获取视频流地址 const streamUrl = await getVideoStreamUrl(device.deviceSn); @@ -1994,6 +2005,10 @@ const DeviceMonitor: React.FC = () => { setVideoStreamUrl(''); setVideoError(''); setVideoLoading(false); + setAllStreamUrls(null); + setCurrentStreamType('hls'); + setUseReactPlayer(true); // 重置为ReactPlayer + setVideoStreamStatus('loading'); // 重置状态 }; // 重新加载视频流 @@ -2001,6 +2016,8 @@ const DeviceMonitor: React.FC = () => { if (currentVideoDevice) { setVideoError(''); setVideoStreamUrl(''); + setAllStreamUrls(null); + setCurrentStreamType('hls'); const streamUrl = await getVideoStreamUrl(currentVideoDevice.deviceSn); if (streamUrl) { setVideoStreamUrl(streamUrl); @@ -2009,6 +2026,31 @@ const DeviceMonitor: React.FC = () => { } }; + // 切换流格式 + const handleSwitchStreamType = (type: 'hls' | 'flv' | 'rtmp') => { + if (!allStreamUrls) return; + + let newUrl = ''; + switch (type) { + case 'hls': + newUrl = allStreamUrls.playM3u8Url; + break; + case 'flv': + newUrl = allStreamUrls.playFlvUrl; + break; + case 'rtmp': + newUrl = allStreamUrls.playRtmpUrl; + break; + } + + if (newUrl) { + setCurrentStreamType(type); + setVideoStreamUrl(newUrl); + setVideoPlayerKey(prev => prev + 1); + console.log(`切换到${type}格式:`, newUrl); + } + }; + // 截图功能 const handleScreenshot = () => { const video = document.querySelector('video'); @@ -2063,35 +2105,13 @@ const DeviceMonitor: React.FC = () => { const renderVideoPlayer = () => { if (!videoStreamUrl) return null; - // 判断视频流类型 - const isHLS = videoStreamUrl.includes('.m3u8') || videoStreamUrl.includes('application/x-mpegURL'); - const isRTMP = videoStreamUrl.startsWith('rtmp://'); - const isWebRTC = videoStreamUrl.startsWith('webrtc://'); + console.log('渲染视频播放器,URL:', videoStreamUrl); + console.log('当前流类型:', currentStreamType); + console.log('ReactPlayer组件:', ReactPlayer); - if (isHLS) { - // HLS流播放器 - return ( - - ); - } else if (isRTMP) { - // RTMP流播放器(需要Flash或特殊播放器) + // 检查ReactPlayer是否可用 + if (!ReactPlayer) { + console.error('ReactPlayer组件未加载'); return (
    { justifyContent: 'center', color: '#fff' }}> -
    -
    RTMP流地址: {videoStreamUrl}
    -
    - 需要特殊的RTMP播放器支持 -
    -
    +
    ReactPlayer组件未加载,请检查依赖
    ); - } else if (isWebRTC) { - // WebRTC流播放器 - return ( + } + + // 使用ReactPlayer组件,支持多种流格式 + return ( +
    + { + console.error('ReactPlayer播放错误:', error); + setVideoStreamStatus('error'); + // 根据错误类型显示不同的错误信息 + if (error && error.message) { + if (error.message.includes('404') || error.message.includes('not found')) { + setVideoError('视频流地址不存在,请检查设备是否在线并开始推流'); + } else if (error.message.includes('timeout') || error.message.includes('time out')) { + setVideoError('视频流连接超时,设备可能未开始推流'); + } else if (error.message.includes('network') || error.message.includes('connection')) { + setVideoError('网络连接失败,请检查网络状态'); + } else { + setVideoError(`视频播放失败: ${error.message}`); + } + } else { + setVideoError('视频播放失败,设备可能未开始推流'); + } + }} + onReady={() => { + console.log('ReactPlayer准备就绪'); + setVideoError(''); + setVideoStreamStatus('playing'); + }} + onStart={() => { + console.log('ReactPlayer开始播放'); + setVideoError(''); + setVideoStreamStatus('playing'); + }} + onBuffer={() => { + console.log('ReactPlayer缓冲中'); + setVideoStreamStatus('loading'); + }} + onEnded={() => { + console.log('ReactPlayer播放结束'); + setVideoStreamStatus('ended'); + setVideoError('视频流播放结束,设备可能已停止推流'); + }} + config={{ + file: { + attributes: { + style: { + width: '100%', + height: '100%', + }, + }, + forceVideo: true, + forceHLS: currentStreamType === 'hls', + hlsOptions: { + maxBufferLength: 30, + maxMaxBufferLength: 60, + maxBufferSize: 0, + maxBufferHole: 0.5, + // 添加重试配置 + maxLoadingDelay: 4, + lowLatencyMode: false, + backBufferLength: 90, + // 禁用自动重试,避免无限重试 + enableWorker: true, + debug: false, + }, + }, + }} + /> +
    + ); + }; + + // 备用播放器(如果ReactPlayer不工作) + const renderFallbackPlayer = () => { + if (!videoStreamUrl) return null; + + console.log('使用备用播放器,URL:', videoStreamUrl); + + return ( +
    - ); - } else { - // 通用视频播放器 - return ( - - ); - } +
    + ); }; // 解析机场状态数据 @@ -3116,8 +3244,29 @@ const DeviceMonitor: React.FC = () => { {videoStreamUrl && !videoLoading && !videoError && (
    - {/* 使用新的视频播放器组件 */} - {renderVideoPlayer()} + {/* 播放器切换按钮 */} +
    + + 播放器类型: + + + +
    + + {/* 使用选择的播放器组件 */} + {useReactPlayer ? renderVideoPlayer() : renderFallbackPlayer()} {/* 视频流信息 */}
    @@ -3135,9 +3284,24 @@ const DeviceMonitor: React.FC = () => { - {videoStreamUrl.includes('.m3u8') ? 'HLS' : - videoStreamUrl.startsWith('rtmp://') ? 'RTMP' : - videoStreamUrl.startsWith('webrtc://') ? 'WebRTC' : 'HTTP'} + {currentStreamType === 'hls' ? 'HLS' : + currentStreamType === 'flv' ? 'FLV' : + currentStreamType === 'rtmp' ? 'RTMP' : '未知'} + + + + + {videoStreamStatus === 'playing' ? '播放中' : + videoStreamStatus === 'loading' ? '加载中' : + videoStreamStatus === 'error' ? '错误' : + videoStreamStatus === 'ended' ? '已结束' : + videoStreamStatus === 'stalled' ? '停滞' : '未知'} @@ -3153,11 +3317,77 @@ const DeviceMonitor: React.FC = () => { 流畅 + + + + + + + {videoStreamUrl} + {allStreamUrls && ( + + + {allStreamUrls.pushUrl && ( +
    + 推流地址 + + {allStreamUrls.pushUrl} + +
    + )} + {allStreamUrls.playM3u8Url && ( +
    + HLS播放 + + {allStreamUrls.playM3u8Url} + +
    + )} + {allStreamUrls.playFlvUrl && ( +
    + FLV播放 + + {allStreamUrls.playFlvUrl} + +
    + )} + {allStreamUrls.playRtmpUrl && ( +
    + RTMP播放 + + {allStreamUrls.playRtmpUrl} + +
    + )} +
    +
    + )}
    From 2c7e37f41ad5ef589ad1b01298bd9f69a335744e Mon Sep 17 00:00:00 2001 From: Iamasoldier <1272745473@qq.com> Date: Thu, 19 Jun 2025 12:10:02 +0800 Subject: [PATCH 10/10] =?UTF-8?q?fix:=E5=9C=B0=E5=9B=BE=E4=BB=AA=E8=A1=A8?= =?UTF-8?q?=E7=9B=98=E5=8A=9F=E8=83=BD=E6=A8=A1=E5=9D=97=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/frontend/config/routes.ts | 5 + .../pages/device-ops/map-dashboard/index.tsx | 2366 +++++++++++++++++ .../device-ops/map-dashboard/mock/devices.ts | 217 ++ .../src/pages/device-ops/monitor/index.tsx | 541 +++- 4 files changed, 3122 insertions(+), 7 deletions(-) create mode 100644 zlt-web/react-web/src/main/frontend/src/pages/device-ops/map-dashboard/index.tsx create mode 100644 zlt-web/react-web/src/main/frontend/src/pages/device-ops/map-dashboard/mock/devices.ts diff --git a/zlt-web/react-web/src/main/frontend/config/routes.ts b/zlt-web/react-web/src/main/frontend/config/routes.ts index 2492d721..575179ca 100644 --- a/zlt-web/react-web/src/main/frontend/config/routes.ts +++ b/zlt-web/react-web/src/main/frontend/config/routes.ts @@ -194,6 +194,11 @@ name: '设备管理', component: './device-ops/device', }, + { + path: '/device-ops/map-dashboard.html', + name: '地图仪表板', + component: './device-ops/map-dashboard', + }, { path: '/device-ops/device/:id', name: '设备详情', diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/map-dashboard/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/map-dashboard/index.tsx new file mode 100644 index 00000000..dc52df80 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/map-dashboard/index.tsx @@ -0,0 +1,2366 @@ +import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react'; +import { PageContainer } from '@ant-design/pro-layout'; +import { + Card, Row, Col, Button, Space, Select, Input, Badge, Tag, Statistic, + message, Modal, Drawer, Tooltip, Divider, Typography, Collapse, + Descriptions, Progress, Alert, Switch, Slider, DatePicker +} from 'antd'; +import { + EnvironmentOutlined, DashboardOutlined, SettingOutlined, + VideoCameraOutlined, ToolOutlined, ReloadOutlined, FilterOutlined, + CheckCircleOutlined, CloseCircleOutlined, ExclamationCircleOutlined, + ClockCircleOutlined, WarningOutlined, InfoCircleOutlined, + EyeOutlined, PlayCircleOutlined, PauseCircleOutlined, HomeOutlined, + CameraOutlined, ControlOutlined, BellOutlined, BarChartOutlined, + PauseOutlined +} from '@ant-design/icons'; +import moment from 'moment'; +import { Amap } from '@amap/amap-react'; +import ReactPlayer from 'react-player'; +import { device, getStreamUrls } from '@/services/device/api'; +import { request } from 'umi'; +import { + Device, DeviceStatus, DEVICE_STATUS_CONFIG, + generateMockDevices, calculateDeviceStats, DeviceStats +} from './mock/devices'; + +// 高德地图全局类型声明 +declare global { + interface Window { + AMap: any; + } +} + +const { RangePicker } = DatePicker; +const { Title, Text } = Typography; +const { Panel } = Collapse; + +// 真实设备接口(从监控页面复制) +interface RealDevice { + deviceSn: string; + deviceName: string; + deviceType: number; + boundStatus: number; + createTime: string; + loginTime: string; + lastUpdateTime?: string; + location?: { + latitude: number; + longitude: number; + height?: number; + heading?: number; + updateTime: string; + }; + metrics: { + temperature: number; + humidity: number; + windSpeed: number; + rainfall: number; + environmentTemperature: number; + positionQuality: number; + networkQuality: number; + droneInDock: number; + batteryCapacity: number; + batteryState: number; + workingVoltage: number; + workingCurrent: number; + acdcPowerInput: number; + backupBatteryVoltage: number; + flightTaskStep: number; + tiltAngle: number; + sdrUpQuality: number; + sdrDownQuality: number; + wirelessLinkState: number; + wirelessLinkQuality: number; + '4gLinkState': number; + '4gLinkQuality': number; + signalStrength: number; + dataRate: number; + packetLoss: number; + latency: number; + cpuUsage: number; + memoryUsage: number; + diskUsage: number; + errorCount: number; + warningCount: number; + uptime: number; + lastMaintenance: string; + nextMaintenance: string; + modeCode: number; + }; + airportStatus?: { + flightTaskStep: number; + flightTaskStepText: string; + sdrFrequency: number; + sdrUpQuality: number; + sdrDownQuality: number; + tiltAngle: number; + tiltAngleValid: number; + wirelessLink: { + sdrLinkState: number; + sdrQuality: number; + sdrFreqBand: number; + '4gLinkState': number; + '4gQuality': number; + '4gFreqBand': number; + linkWorkMode: number; + dongleNumber: number; + }; + departurePoint: { + latitude: number; + longitude: number; + height: number; + status: number; + }; + drcState: number; + mediaRemainUpload: number; + flightTaskPrepareCapacity: number; + }; +} + +// WebSocket相关接口 +interface TokenResponse { + data: { + result: string; + message: string; + status: number; + timestamp: number; + expires?: number; + }; + resp_code: number; + resp_msg: string; +} + +interface FireAlarmPayload { + headers: { + deviceName: string; + productName: string; + productId: string; + }; + messageId: string; + deviceId: string; + timestamp: number; + event: string; + data: { + data: { + temperature?: number; + humidity?: number; + wind_speed?: number; + rainfall?: number; + environment_temperature?: number; + latitude?: number; + longitude?: number; + height?: number; + heading?: number; + drone_charge_state?: { + capacity_percent: number; + state: number; + }; + position_state?: { + is_calibration: number; + rtk_number: number; + gps_number: number; + is_fixed: number; + quality: number; + }; + network_state?: { + rate: number; + type: number; + quality: number; + }; + drone_in_dock?: number; + flighttask_step_code?: number; + sdr?: { + frequency_band: number; + up_quality: number; + down_quality: number; + }; + tilt_angle?: { + valid: number; + value: number; + }; + wireless_link?: { + sdr_link_state: number; + '4g_freq_band': number; + '4g_quality': number; + link_workmode: number; + sdr_quality: number; + '4g_uav_quality': number; + sdr_freq_band: number; + '4g_link_state': number; + '4g_gnd_quality': number; + dongle_number: number; + }; + }; + deviceId: string; + timestamp: number; + }; + messageType: string; +} + +// 地图设备标记 +interface MapDeviceMarker { + device: RealDevice; + position: [number, number]; + color: string; + status: DeviceStatus; +} + +const DEFAULT_EXPIRES = 7200; // 2小时,单位秒 + +const DeviceMapDashboard: React.FC = () => { + // 基础状态 + const [devices, setDevices] = useState([]); + const [selectedDevice, setSelectedDevice] = useState(null); + const [mapCenter, setMapCenter] = useState<[number, number]>([116.397428, 39.90923]); + const [mapZoom, setMapZoom] = useState(11); + const [loading, setLoading] = useState(false); + + // 面板控制 + const [leftPanelVisible, setLeftPanelVisible] = useState(true); + const [rightPanelVisible, setRightPanelVisible] = useState(false); + const [leftPanelCollapsed, setLeftPanelCollapsed] = useState(false); + const [rightPanelCollapsed, setRightPanelCollapsed] = useState(false); + + // 筛选和搜索 + const [statusFilter, setStatusFilter] = useState('all'); + const [typeFilter, setTypeFilter] = useState('all'); + const [groupFilter, setGroupFilter] = useState('all'); + const [searchKeyword, setSearchKeyword] = useState(''); + + // 视频流相关 + const [videoStreamVisible, setVideoStreamVisible] = useState(false); + const [videoStreamUrl, setVideoStreamUrl] = useState(''); + const [videoLoading, setVideoLoading] = useState(false); + const [allStreamUrls, setAllStreamUrls] = useState<{ + pushUrl: string; + playFlvUrl: string; + playM3u8Url: string; + playRtmpUrl: string; + } | null>(null); + const [currentStreamType, setCurrentStreamType] = useState<'hls' | 'flv' | 'rtmp'>('hls'); + + // 地图相关 + const [mapInitialized, setMapInitialized] = useState(false); + const [showDeviceCard, setShowDeviceCard] = useState(false); + const [hoveredDevice, setHoveredDevice] = useState(null); + const [deviceCardPosition, setDeviceCardPosition] = useState<{ x: number; y: number }>({ x: 0, y: 0 }); + const [mapType, setMapType] = useState<'normal' | 'dark' | 'satellite'>('normal'); + + // 高德地图实例和标记管理 + const mapRef = useRef(null); + const markersRef = useRef>(new Map()); + const mapContainerRef = useRef(null); + + // WebSocket相关 + const wsRef = useRef(null); + const [wsConnected, setWsConnected] = useState(false); + const reconnectTimerRef = useRef(); + const heartbeatTimerRef = useRef(); + const [currentSubscribedDevice, setCurrentSubscribedDevice] = useState('all'); + const [currentSubscriptions, setCurrentSubscriptions] = useState([]); + + // Token缓存 + const tokenCache = { + value: '', + expire: 0, + timer: null as NodeJS.Timeout | null, + }; + + // 地图样式配置 + const mapStyles = { + normal: "amap://styles/normal", + dark: "amap://styles/dark", + satellite: "amap://styles/satellite" + }; + + // 地图样式名称 + const mapStyleNames = { + normal: '普通图', + dark: '暗夜图', + satellite: '卫星图' + }; + + // 获取WebSocket Token + const getToken = async (expires: number = DEFAULT_EXPIRES) => { + const now = Date.now(); + if (tokenCache.value && tokenCache.expire > now) { + return tokenCache.value; + } + + // 根据SDK文档更新Token获取地址 + const tokenResponse = await request('http://119.45.169.13:9900/api-device/token/query', { + method: 'GET', + params: { expires }, + }); + + if (tokenResponse.resp_code !== 0) { + throw new Error(tokenResponse.resp_msg || '获取token失败'); + } + + const { result: token, expires: expiresFromServer } = tokenResponse.data; + const expireSeconds = expiresFromServer ?? expires; + tokenCache.value = token; + tokenCache.expire = now + expireSeconds * 1000; + + if (tokenCache.timer) clearTimeout(tokenCache.timer); + tokenCache.timer = setTimeout(() => { + refreshTokenAndReconnect(); + }, expireSeconds * 1000 - 5 * 60 * 1000); + + return token; + }; + + // 刷新Token并重连 + const refreshTokenAndReconnect = async () => { + tokenCache.value = ''; + await getToken(); + if (wsRef.current) { + wsRef.current.close(); + } + await initWebSocket(); + }; + + // 获取真实设备列表 + const fetchDeviceList = async () => { + setLoading(true); + try { + const response = await device({ + page: 1, + limit: 1000, + }); + + if (response.resp_code === 0 && response.data) { + setDevices(response.data.map((item: any) => ({ + ...item, + metrics: { + temperature: 0, + humidity: 0, + windSpeed: 0, + rainfall: 0, + environmentTemperature: 0, + positionQuality: 0, + networkQuality: 0, + droneInDock: 0, + batteryCapacity: 0, + batteryState: 0, + workingVoltage: 0, + workingCurrent: 0, + acdcPowerInput: 0, + backupBatteryVoltage: 0, + flightTaskStep: 0, + tiltAngle: 0, + sdrUpQuality: 0, + sdrDownQuality: 0, + wirelessLinkState: 0, + wirelessLinkQuality: 0, + '4gLinkState': 0, + '4gLinkQuality': 0, + signalStrength: 0, + dataRate: 0, + packetLoss: 0, + latency: 0, + cpuUsage: 0, + memoryUsage: 0, + diskUsage: 0, + errorCount: 0, + warningCount: 0, + uptime: 0, + lastMaintenance: '', + nextMaintenance: '', + modeCode: 0, + } + }))); + } else { + console.error('获取设备列表失败:', response.resp_msg); + // 如果真实数据获取失败,使用mock数据 + const mockDevices = generateMockDevices(); + setDevices(convertMockDevicesToRealDevices(mockDevices)); + } + } catch (error) { + console.error('获取设备列表失败:', error); + // 使用mock数据作为备用 + const mockDevices = generateMockDevices(); + setDevices(convertMockDevicesToRealDevices(mockDevices)); + } finally { + setLoading(false); + } + }; + + // 将真实设备状态转换为地图状态 + const getDeviceStatus = (device: RealDevice): DeviceStatus => { + // 基于实时数据上报判断设备在线状态 + // 如果设备有最近的实时数据上报,则认为在线 + const hasRecentData = device.lastUpdateTime && + (Date.now() - new Date(device.lastUpdateTime).getTime()) < 5 * 60 * 1000; // 5分钟内有数据 + + if (!hasRecentData) return DeviceStatus.OFFLINE; + + // 检查告警状态 + if (device.metrics.errorCount > 0 || device.metrics.warningCount > 0) { + return DeviceStatus.ERROR; + } + + // 检查电量状态 + if (device.metrics.batteryCapacity < 20) { + return DeviceStatus.ERROR; + } + + // 检查网络质量 + if (device.metrics.networkQuality < 30) { + return DeviceStatus.MAINTENANCE; + } + + // 检查无人机是否在机库中 + if (device.metrics.droneInDock === 1) { + return DeviceStatus.STANDBY; + } + + // 检查模式代码(飞行任务) + if (device.metrics.modeCode > 0) { + return DeviceStatus.TASK; + } + + return DeviceStatus.STANDBY; + }; + + // 获取过滤后的设备列表 + const getFilteredDevices = (): RealDevice[] => { + return devices.filter(device => { + const status = getDeviceStatus(device); + + // 状态筛选 + if (statusFilter !== 'all' && status !== statusFilter) return false; + + // 类型筛选 + if (typeFilter !== 'all' && device.deviceType.toString() !== typeFilter) return false; + + // 分组筛选(暂时使用设备类型作为分组) + if (groupFilter !== 'all' && device.deviceType.toString() !== groupFilter) return false; + + // 关键词搜索 + if (searchKeyword && !device.deviceName.toLowerCase().includes(searchKeyword.toLowerCase()) && + !device.deviceSn.toLowerCase().includes(searchKeyword.toLowerCase())) return false; + + return true; + }); + }; + + // 获取地图设备标记 + const getMapDeviceMarkers = (): MapDeviceMarker[] => { + return getFilteredDevices() + .filter(device => device.location && device.location.latitude && device.location.longitude) + .map(device => ({ + device, + position: [device.location!.longitude, device.location!.latitude], + color: DEVICE_STATUS_CONFIG[getDeviceStatus(device)].color, + status: getDeviceStatus(device) + })); + }; + + // 计算设备统计 + const calculateDeviceStats = (): DeviceStats => { + const stats: DeviceStats = { + total: devices.length, + online: devices.filter(d => getDeviceStatus(d) !== DeviceStatus.OFFLINE).length, + offline: devices.filter(d => getDeviceStatus(d) === DeviceStatus.OFFLINE).length, + task: devices.filter(d => getDeviceStatus(d) === DeviceStatus.TASK).length, + standby: devices.filter(d => getDeviceStatus(d) === DeviceStatus.STANDBY).length, + maintenance: devices.filter(d => getDeviceStatus(d) === DeviceStatus.MAINTENANCE).length, + error: devices.filter(d => getDeviceStatus(d) === DeviceStatus.ERROR).length, + byGroup: {}, + byType: {} + }; + + // 按分组统计(使用设备类型) + devices.forEach(device => { + const group = `设备类型${device.deviceType}`; + stats.byGroup[group] = (stats.byGroup[group] || 0) + 1; + stats.byType[device.deviceType.toString()] = (stats.byType[device.deviceType.toString()] || 0) + 1; + }); + + return stats; + }; + + // 转换mock设备为RealDevice类型 + const convertMockDevicesToRealDevices = (mockDevices: any[]): RealDevice[] => { + return mockDevices.map(device => ({ + deviceSn: device.sn, + deviceName: device.name, + deviceType: device.type === '无人机' ? 1 : 2, + boundStatus: device.status === DeviceStatus.OFFLINE ? 0 : 1, + createTime: new Date().toISOString(), + loginTime: device.lastUpdate, + location: device.location ? { + latitude: device.location.latitude, + longitude: device.location.longitude, + height: device.location.altitude, + updateTime: device.lastUpdate + } : undefined, + metrics: { + temperature: device.temperature, + humidity: device.humidity, + windSpeed: 0, + rainfall: 0, + environmentTemperature: device.temperature, + positionQuality: device.signal, + networkQuality: device.signal, + droneInDock: 0, + batteryCapacity: device.battery, + batteryState: 0, + workingVoltage: 0, + workingCurrent: 0, + acdcPowerInput: 0, + backupBatteryVoltage: 0, + flightTaskStep: 0, + tiltAngle: 0, + sdrUpQuality: 0, + sdrDownQuality: 0, + wirelessLinkState: 0, + wirelessLinkQuality: 0, + '4gLinkState': 0, + '4gLinkQuality': 0, + signalStrength: device.signal, + dataRate: 0, + packetLoss: 0, + latency: 0, + cpuUsage: 0, + memoryUsage: 0, + diskUsage: 0, + errorCount: 0, + warningCount: 0, + uptime: 0, + lastMaintenance: device.lastMaintenance || '', + nextMaintenance: device.nextMaintenance || '', + modeCode: 0, + } + })); + }; + + // 处理设备点击 + const handleDeviceClick = (device: RealDevice, event: React.MouseEvent) => { + setSelectedDevice(device); + setRightPanelVisible(true); + setRightPanelCollapsed(false); + + // 定位到设备位置 + if (device.location && device.location.longitude && device.location.latitude) { + setMapCenter([device.location.longitude, device.location.latitude]); + setMapZoom(15); + message.info(`已选中设备: ${device.deviceName}`); + } else { + message.warning(`设备 ${device.deviceName} 暂无位置信息`); + } + }; + + // 处理设备悬停 + const handleDeviceHover = (device: RealDevice, event: React.MouseEvent) => { + setHoveredDevice(device); + setShowDeviceCard(true); + setDeviceCardPosition({ x: event.clientX, y: event.clientY }); + }; + + // 处理设备离开 + const handleDeviceLeave = () => { + setHoveredDevice(null); + setShowDeviceCard(false); + }; + + // 定位设备到地图 + const locateDeviceOnMap = (device: RealDevice) => { + if (device.location && device.location.longitude && device.location.latitude) { + setMapCenter([device.location.longitude, device.location.latitude]); + setMapZoom(15); + setSelectedDevice(device); + setRightPanelVisible(true); + setRightPanelCollapsed(false); + } else { + message.warning(`设备 ${device.deviceName} 暂无位置信息`); + } + }; + + // 播放视频流 + const handlePlayVideo = async (device: RealDevice) => { + setVideoLoading(true); + setVideoStreamVisible(true); + + try { + const streamUrls = await getVideoStreamUrl(device.deviceSn); + if (streamUrls) { + setVideoStreamUrl(streamUrls.playM3u8Url); + setCurrentStreamType('hls'); + message.success('视频流加载成功'); + } else { + message.error('获取视频流地址失败'); + } + } catch (error) { + console.error('播放视频失败:', error); + message.error('播放视频失败'); + } finally { + setVideoLoading(false); + } + }; + + // 关闭视频流 + const handleCloseVideo = () => { + setVideoStreamVisible(false); + setVideoStreamUrl(''); + setVideoLoading(false); + }; + + // 刷新设备数据 + const handleRefresh = () => { + setLoading(true); + setTimeout(() => { + const newDevices = generateMockDevices(); + setDevices(convertMockDevicesToRealDevices(newDevices)); + setLoading(false); + message.success('设备数据已刷新'); + }, 1000); + }; + + // 初始化数据 + useEffect(() => { + fetchDeviceList(); + initWebSocket(); + + return () => { + if (wsRef.current) { + wsRef.current.close(); + } + if (reconnectTimerRef.current) { + clearTimeout(reconnectTimerRef.current); + } + if (heartbeatTimerRef.current) { + clearInterval(heartbeatTimerRef.current); + } + if (tokenCache.timer) { + clearTimeout(tokenCache.timer); + } + }; + }, []); + + // 初始化地图 + useEffect(() => { + const initMap = () => { + console.log('initMap called, window.AMap:', typeof window !== 'undefined' ? !!window.AMap : 'undefined'); + console.log('mapContainerRef.current:', mapContainerRef.current); + + if (typeof window !== 'undefined' && window.AMap && mapContainerRef.current) { + console.log('开始初始化高德地图...'); + + try { + // 确保地图容器有正确的尺寸 + if (mapContainerRef.current) { + mapContainerRef.current.style.width = '100%'; + mapContainerRef.current.style.height = '100%'; + mapContainerRef.current.style.position = 'relative'; + } + + // 使用安全的地图初始化方法 + mapRef.current = safeInitMap(mapContainerRef.current); + + // 强制触发地图重绘 + setTimeout(() => { + safeRefreshMap(); + console.log('地图重绘完成'); + }, 100); + + setMapInitialized(true); + console.log('高德地图初始化成功'); + + // 验证地图是否正确显示 + setTimeout(() => { + if (mapRef.current && mapContainerRef.current) { + const mapDiv = mapContainerRef.current; + const mapCanvas = mapDiv.querySelector('canvas'); + if (mapCanvas) { + console.log('地图Canvas已创建,尺寸:', mapCanvas.width, 'x', mapCanvas.height); + } else { + console.warn('地图Canvas未找到'); + } + } + }, 500); + } catch (error) { + console.error('地图初始化失败:', error); + message.error('地图初始化失败'); + setMapInitialized(true); + } + } else if (typeof window !== 'undefined' && !window.AMap) { + console.log('开始加载高德地图...'); + const script = document.createElement('script'); + script.src = `https://webapi.amap.com/maps?v=1.4.15&key=7df3685709e341daed76e877e417e5be&plugin=AMap.Scale,AMap.ToolBar`; + script.async = true; + script.onload = () => { + console.log('高德地图加载成功'); + // 延迟初始化,确保DOM已准备好 + setTimeout(initMap, 500); + }; + script.onerror = () => { + console.error('高德地图加载失败'); + message.error('地图加载失败,请检查网络连接'); + setMapInitialized(true); + }; + document.head.appendChild(script); + } else if (typeof window !== 'undefined' && window.AMap && !mapContainerRef.current) { + console.log('AMap已加载但地图容器未创建,等待DOM渲染...'); + // AMap已加载但容器未创建,等待DOM渲染完成 + setTimeout(initMap, 200); + } else { + console.log('地图初始化条件不满足,延迟重试'); + setTimeout(initMap, 1000); + } + }; + + // 延迟初始化,确保DOM已准备好 + const timer = setTimeout(initMap, 500); + return () => clearTimeout(timer); + }, []); + + // 监听地图容器创建 + useEffect(() => { + if (mapContainerRef.current && typeof window !== 'undefined' && window.AMap && !mapRef.current) { + console.log('地图容器已创建,开始初始化地图...'); + const timer = setTimeout(() => { + if (mapContainerRef.current && !mapRef.current) { + try { + mapRef.current = safeInitMap(mapContainerRef.current); + setMapInitialized(true); + console.log('地图容器监听初始化成功'); + } catch (error) { + console.error('地图容器监听初始化失败:', error); + } + } + }, 100); + return () => clearTimeout(timer); + } + }, [mapContainerRef.current]); + + // 当设备列表更新时,重新订阅WebSocket消息 + useEffect(() => { + if (wsConnected && devices.length > 0) { + console.log(`开始订阅 ${devices.length} 个设备的实时数据`); + subscribeDeviceMessages(); + } + }, [wsConnected, devices.length]); + + // 页面加载完成后立即订阅所有设备 + useEffect(() => { + if (wsConnected && devices.length > 0) { + // 延迟订阅,确保WebSocket连接稳定 + const timer = setTimeout(() => { + subscribeDeviceMessages(); + }, 1000); + return () => clearTimeout(timer); + } + }, [wsConnected, devices.length]); + + const deviceStats = calculateDeviceStats(); + const filteredDevices = getFilteredDevices(); + const mapMarkers = getMapDeviceMarkers(); + + // 使用useMemo缓存设备列表,减少重新渲染 + const memoizedDeviceList = useMemo(() => { + return filteredDevices.map(device => ({ + ...device, + status: getDeviceStatus(device), + statusConfig: DEVICE_STATUS_CONFIG[getDeviceStatus(device)] + })); + }, [filteredDevices]); + + // 获取分组选项 + const groupOptions = Array.from(new Set(devices.map(d => d.deviceType.toString()).filter(Boolean))); + + // 创建标记图标 + const createMarkerIcon = (color: string, status: DeviceStatus) => { + const canvas = document.createElement('canvas'); + canvas.width = 32; + canvas.height = 32; + const ctx = canvas.getContext('2d'); + + if (ctx) { + // 绘制圆形背景 + ctx.beginPath(); + ctx.arc(16, 16, 14, 0, 2 * Math.PI); + ctx.fillStyle = color; + ctx.fill(); + + // 绘制白色边框 + ctx.strokeStyle = '#fff'; + ctx.lineWidth = 2; + ctx.stroke(); + + // 绘制图标 + ctx.fillStyle = '#fff'; + ctx.font = '16px Arial'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillText(DEVICE_STATUS_CONFIG[status].icon, 16, 16); + } + + return canvas.toDataURL(); + }; + + // 更新设备标记 + const updateDeviceMarkers = useCallback(() => { + if (!mapRef.current || !window.AMap) return; + + const currentMarkers = markersRef.current; + const newMarkers = getMapDeviceMarkers(); + + // 清除不存在的标记 + currentMarkers.forEach((marker, deviceSn) => { + if (!newMarkers.find(m => m.device.deviceSn === deviceSn)) { + marker.remove(); + currentMarkers.delete(deviceSn); + } + }); + + // 添加或更新标记 + newMarkers.forEach((markerData) => { + const { device, position, color, status } = markerData; + const existingMarker = currentMarkers.get(device.deviceSn); + + if (existingMarker) { + // 更新现有标记 + existingMarker.setPosition(position); + existingMarker.setIcon({ + type: 'image', + image: createMarkerIcon(color, status), + size: [32, 32], + anchor: 'bottom-center' + }); + } else { + // 创建新标记 + const newMarker = new window.AMap.Marker({ + position, + icon: { + type: 'image', + image: createMarkerIcon(color, status), + size: [32, 32], + anchor: 'bottom-center' + }, + offset: [0, -16], + title: `${device.deviceName} (${DEVICE_STATUS_CONFIG[status].text})` + }); + + // 添加点击事件 + newMarker.on('click', () => { + handleDeviceClick(device, {} as React.MouseEvent); + }); + + // 添加鼠标事件 + newMarker.on('mouseover', () => { + setHoveredDevice(device); + setShowDeviceCard(true); + }); + + newMarker.on('mouseout', () => { + setHoveredDevice(null); + setShowDeviceCard(false); + }); + + newMarker.setMap(mapRef.current); + currentMarkers.set(device.deviceSn, newMarker); + } + }); + }, [devices, mapMarkers]); + + // 当设备数据更新时,更新地图标记 + useEffect(() => { + if (mapInitialized && mapRef.current) { + updateDeviceMarkers(); + } + }, [devices, mapInitialized, updateDeviceMarkers]); + + // WebSocket相关功能 + const initWebSocket = async () => { + try { + const token = await getToken(); + // 根据SDK文档调整WebSocket连接地址 + const wsUrl = `ws://119.45.169.13:8848/messaging/${token}`; + + wsRef.current = new WebSocket(wsUrl); + + wsRef.current.onopen = () => { + console.log('WebSocket连接已建立'); + setWsConnected(true); + startHeartbeat(); + // 连接成功后立即订阅所有设备消息 + console.log('准备订阅所有设备消息...'); + }; + + wsRef.current.onmessage = (event) => { + try { + const data = JSON.parse(event.data); + handleWebSocketMessage(data); + } catch (error) { + console.error('解析WebSocket消息失败:', error); + } + }; + + wsRef.current.onclose = () => { + console.log('WebSocket连接已关闭'); + setWsConnected(false); + scheduleReconnect(); + }; + + wsRef.current.onerror = (error) => { + console.error('WebSocket连接错误:', error); + setWsConnected(false); + }; + } catch (error) { + console.error('初始化WebSocket失败:', error); + setWsConnected(false); + } + }; + + const handleWebSocketMessage = (data: any) => { + console.log('收到WebSocket消息:', data); + + // 根据SDK文档调整消息处理逻辑 + if (data.type === 'result') { + // 处理订阅结果 + if (data.topic && data.topic.includes('/message/property/report')) { + // 设备属性上报 - 从topic中提取产品ID和设备SN + const topicParts = data.topic.split('/'); + if (topicParts.length >= 4) { + const productId = topicParts[2]; + const deviceSn = topicParts[3]; + updateDeviceMetrics(deviceSn, data.payload); + } + } else if (data.topic && data.topic.includes('/message/event/fire_alarm')) { + // 设备事件 - 从topic中提取产品ID和设备SN + const topicParts = data.topic.split('/'); + if (topicParts.length >= 5) { + const productId = topicParts[2]; + const deviceSn = topicParts[3]; + console.log(`处理设备 ${deviceSn} 的实时数据:`, data.payload); + updateDeviceMetricsFromEvent(deviceSn, data.payload); + } + } else if (data.topic && data.topic.includes('/online')) { + // 设备上线 - 从topic中提取产品ID和设备SN + const topicParts = data.topic.split('/'); + if (topicParts.length >= 4) { + const productId = topicParts[2]; + const deviceSn = topicParts[3]; + handleDeviceOnline(deviceSn); + } + } else if (data.topic && data.topic.includes('/offline')) { + // 设备离线 - 从topic中提取产品ID和设备SN + const topicParts = data.topic.split('/'); + if (topicParts.length >= 4) { + const productId = topicParts[2]; + const deviceSn = topicParts[3]; + handleDeviceOffline(deviceSn); + } + } + } else if (data.type === 'authError') { + // 认证失败 + console.error('WebSocket认证失败:', data.message); + message.error('WebSocket认证失败,请检查Token'); + setWsConnected(false); + } else if (data.type === 'error') { + // 其他错误 + console.error('WebSocket错误:', data); + } + }; + + const updateDeviceMetrics = (deviceSn: string, payload: any) => { + setDevices(prevDevices => + prevDevices.map(device => + device.deviceSn === deviceSn + ? { + ...device, + metrics: { ...device.metrics, ...payload }, + lastUpdateTime: new Date().toISOString() + } + : device + ) + ); + }; + + const updateDeviceMetricsFromEvent = (deviceSn: string, payload: any) => { + // 从fire_alarm事件中提取实时数据 + const eventData = payload.data?.data; + if (!eventData) { + console.warn(`设备 ${deviceSn} 的实时数据格式不正确:`, payload); + return; + } + + // 提取位置信息 + const location = eventData.latitude && eventData.longitude ? { + latitude: eventData.latitude, + longitude: eventData.longitude, + height: eventData.height, + heading: eventData.heading, + updateTime: new Date().toISOString() + } : undefined; + + // 提取电量信息 + const batteryCapacity = eventData.drone_charge_state?.capacity_percent || 0; + const batteryState = eventData.drone_charge_state?.state || 0; + + // 提取环境信息 + const temperature = eventData.temperature || 0; + const humidity = eventData.humidity || 0; + const windSpeed = eventData.wind_speed || 0; + const rainfall = eventData.rainfall || 0; + const environmentTemperature = eventData.environment_temperature || 0; + + // 提取位置质量信息 + const positionQuality = eventData.position_state?.quality || 0; + const isFixed = eventData.position_state?.is_fixed || 0; + const rtkNumber = eventData.position_state?.rtk_number || 0; + const gpsNumber = eventData.position_state?.gps_number || 0; + + // 提取网络信息 + const networkQuality = eventData.network_state?.quality || 0; + const networkRate = eventData.network_state?.rate || 0; + const networkType = eventData.network_state?.type || 0; + + // 提取无人机状态 + const droneInDock = eventData.drone_in_dock || 0; + const modeCode = eventData.mode_code || 0; + + // 提取存储信息 + const storageTotal = eventData.storage?.total || 0; + const storageUsed = eventData.storage?.used || 0; + const diskUsage = storageTotal > 0 ? (storageUsed / storageTotal) * 100 : 0; + + // 提取告警状态 + const alarmState = eventData.alarm_state || 0; + const emergencyStopState = eventData.emergency_stop_state || 0; + + setDevices(prevDevices => + prevDevices.map(device => + device.deviceSn === deviceSn + ? { + ...device, + location: location || device.location, // 保持原有位置信息如果新数据中没有 + metrics: { + ...device.metrics, + // 环境数据 + temperature, + humidity, + windSpeed, + rainfall, + environmentTemperature, + // 电量数据 + batteryCapacity, + batteryState, + // 位置数据 + positionQuality, + // 网络数据 + networkQuality, + networkRate, + networkType, + // 无人机状态 + droneInDock, + modeCode, + // 存储数据 + diskUsage, + // 告警状态 + errorCount: alarmState > 0 ? (device.metrics.errorCount || 0) + 1 : device.metrics.errorCount || 0, + warningCount: emergencyStopState > 0 ? (device.metrics.warningCount || 0) + 1 : device.metrics.warningCount || 0, + // 信号强度(基于网络质量) + signalStrength: networkQuality, + // 数据速率(基于网络速率) + dataRate: networkRate, + // 更新时间 + uptime: Date.now() - (eventData.first_power_on || Date.now()) + }, + lastUpdateTime: new Date().toISOString() + } + : device + ) + ); + + console.log(`设备 ${deviceSn} 实时数据更新:`, { + location, + batteryCapacity, + temperature, + humidity, + positionQuality, + networkQuality, + droneInDock + }); + }; + + const handleDeviceOnline = (deviceSn: string) => { + console.log(`设备 ${deviceSn} 上线`); + setDevices(prevDevices => + prevDevices.map(device => + device.deviceSn === deviceSn + ? { ...device, boundStatus: 1 } + : device + ) + ); + }; + + const handleDeviceOffline = (deviceSn: string) => { + console.log(`设备 ${deviceSn} 离线`); + setDevices(prevDevices => + prevDevices.map(device => + device.deviceSn === deviceSn + ? { ...device, boundStatus: 0 } + : device + ) + ); + }; + + const subscribeDeviceMessages = (deviceSn?: string) => { + if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) { + return; + } + + const devicesToSubscribe = deviceSn ? [deviceSn] : devices.map(d => d.deviceSn); + setCurrentSubscriptions(devicesToSubscribe); + + // 订阅设备属性上报 - 使用通配符匹配所有设备 + const propertyMessage = { + type: 'sub', + topic: '/device/*/*/message/property/report', + parameter: {}, + id: `sub_property_all_${Date.now()}` + }; + wsRef.current.send(JSON.stringify(propertyMessage)); + console.log('订阅设备属性上报:', propertyMessage.topic); + + // 订阅设备事件 - 使用通配符匹配所有设备 + const eventMessage = { + type: 'sub', + topic: '/device/*/*/message/event/fire_alarm', + parameter: {}, + id: `sub_event_all_${Date.now()}` + }; + wsRef.current.send(JSON.stringify(eventMessage)); + console.log('订阅设备事件:', eventMessage.topic); + + // 订阅设备上线状态 - 使用通配符匹配所有设备 + const onlineMessage = { + type: 'sub', + topic: '/device/*/*/online', + parameter: {}, + id: `sub_online_all_${Date.now()}` + }; + wsRef.current.send(JSON.stringify(onlineMessage)); + console.log('订阅设备上线:', onlineMessage.topic); + + // 订阅设备离线状态 - 使用通配符匹配所有设备 + const offlineMessage = { + type: 'sub', + topic: '/device/*/*/offline', + parameter: {}, + id: `sub_offline_all_${Date.now()}` + }; + wsRef.current.send(JSON.stringify(offlineMessage)); + console.log('订阅设备离线:', offlineMessage.topic); + }; + + const startHeartbeat = () => { + if (heartbeatTimerRef.current) { + clearInterval(heartbeatTimerRef.current); + } + + heartbeatTimerRef.current = setInterval(() => { + if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) { + wsRef.current.send(JSON.stringify({ type: 'ping', timestamp: Date.now() })); + } + }, 30000); // 30秒心跳 + }; + + const scheduleReconnect = () => { + if (reconnectTimerRef.current) { + clearTimeout(reconnectTimerRef.current); + } + + reconnectTimerRef.current = setTimeout(() => { + console.log('尝试重新连接WebSocket...'); + initWebSocket(); + }, 5000); // 5秒后重连 + }; + + // 获取视频流地址 + const getVideoStreamUrl = async (deviceSn: string) => { + try { + const response = await getStreamUrls(deviceSn); + if (response.resp_code === 0 && response.data) { + setAllStreamUrls(response.data); + setVideoStreamUrl(response.data.playM3u8Url); + setCurrentStreamType('hls'); + return response.data; + } else { + message.error('获取视频流地址失败'); + return null; + } + } catch (error) { + console.error('获取视频流地址失败:', error); + message.error('获取视频流地址失败'); + return null; + } + }; + + // 切换视频流类型 + const handleSwitchStreamType = (type: 'hls' | 'flv' | 'rtmp') => { + if (!allStreamUrls) return; + + let url = ''; + switch (type) { + case 'hls': + url = allStreamUrls.playM3u8Url; + break; + case 'flv': + url = allStreamUrls.playFlvUrl; + break; + case 'rtmp': + url = allStreamUrls.playRtmpUrl; + break; + } + + if (url) { + setVideoStreamUrl(url); + setCurrentStreamType(type); + } + }; + + // 无人机控制功能 + const sendControlCommand = async (deviceSn: string, method: string, data: any = {}) => { + if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) { + message.error('WebSocket连接已断开,无法发送控制指令'); + return false; + } + + // 使用正确的主题格式:/device/{产品ID}/{设备SN} + const controlMessage = { + type: 'sub', + topic: `/device/D-Dock2/${deviceSn}`, + parameter: { + messageType: 'WRITE_PROPERTY', + properties: { + method: method, + data: data + }, + headers: { + async: false + } + }, + id: `control_${method}_${deviceSn}_${Date.now()}` + }; + + try { + wsRef.current.send(JSON.stringify(controlMessage)); + console.log(`发送控制指令: ${method}`, controlMessage); + return true; + } catch (error) { + console.error('发送控制指令失败:', error); + message.error('发送控制指令失败'); + return false; + } + }; + + // 摇杆控制 + const handleStickControl = async (deviceSn: string, axis: string, value: number) => { + const controlData = { + roll: 1024, // 右手左右控制(范围:0-2048,1024为中立位) + pitch: 1024, // 右手上下控制(范围:0-2048,1024为中立位) + throttle: 1024, // 左手上下控制(范围:0-2048,1024为中立位) + yaw: 1024, // 左手左右控制(范围:1024±100) + gimbal_pitch: 1024 // 云台画面上下划(范围:0-2048,1024为中立位) + }; + + controlData[axis as keyof typeof controlData] = value; + + const success = await sendControlCommand(deviceSn, 'stick_control', controlData); + if (success) { + message.success(`摇杆控制指令已发送: ${axis} = ${value}`); + } + }; + + // 相机模式切换 + const handleCameraModeSwitch = async (deviceSn: string, mode: number) => { + const modeText = ['拍照', '录像', '智能低光', '全景拍照'][mode] || '未知模式'; + const success = await sendControlCommand(deviceSn, 'camera_mode_switch', { camera_mode: mode }); + if (success) { + message.success(`相机模式已切换为: ${modeText}`); + } + }; + + // 拍照 + const handleTakePhoto = async (deviceSn: string) => { + const success = await sendControlCommand(deviceSn, 'camera_photo_take', {}); + if (success) { + message.success('拍照指令已发送'); + } + }; + + // 开始录像 + const handleStartRecording = async (deviceSn: string) => { + const success = await sendControlCommand(deviceSn, 'camera_recording_start', {}); + if (success) { + message.success('开始录像指令已发送'); + } + }; + + // 停止录像 + const handleStopRecording = async (deviceSn: string) => { + const success = await sendControlCommand(deviceSn, 'camera_recording_stop', {}); + if (success) { + message.success('停止录像指令已发送'); + } + }; + + // 暂停航线任务 + const handlePauseTask = async (deviceSn: string) => { + const success = await sendControlCommand(deviceSn, 'flighttask_pause', {}); + if (success) { + message.success('航线任务已暂停'); + } + }; + + // 返航 + const handleReturnHome = async (deviceSn: string) => { + const success = await sendControlCommand(deviceSn, 'return_home', {}); + if (success) { + message.success('返航指令已发送'); + } + }; + + // 进入指令飞行模式 + const handleEnterDRCMode = async (deviceSn: string) => { + const success = await sendControlCommand(deviceSn, 'drc_mode_enter', {}); + if (success) { + message.success('已进入指令飞行模式'); + } + }; + + // 地图样式切换处理 + const handleMapStyleChange = () => { + const styleOrder: ('normal' | 'dark' | 'satellite')[] = ['normal', 'dark', 'satellite']; + const currentIndex = styleOrder.indexOf(mapType); + const nextIndex = (currentIndex + 1) % styleOrder.length; + const nextStyle = styleOrder[nextIndex]; + + setMapType(nextStyle); + + // 更新地图样式 + if (mapRef.current) { + mapRef.current.setMapStyle(mapStyles[nextStyle]); + } + }; + + // 地图加载错误处理 + const handleMapError = (error: any) => { + console.error('地图加载错误:', error); + if (mapType === 'satellite') { + message.warning('卫星图加载失败,已切换到普通图'); + setMapType('normal'); + } + }; + + // 安全的地图初始化方法 + const safeInitMap = (container: HTMLElement) => { + try { + const map = new window.AMap.Map(container, { + zoom: mapZoom, + center: mapCenter, + mapStyle: mapStyles[mapType], + viewMode: '2D', + features: ['bg', 'road'], + showBuildingBlock: false, + resizeEnable: true, + }); + + // 添加地图控件 + try { + if (window.AMap.Scale) { + map.addControl(new window.AMap.Scale()); + } + if (window.AMap.ToolBar) { + map.addControl(new window.AMap.ToolBar()); + } + } catch (error) { + console.warn('添加地图控件失败:', error); + } + + // 监听地图事件 + try { + map.on('zoomend', () => { + setMapZoom(map.getZoom()); + }); + + map.on('moveend', () => { + const center = map.getCenter(); + setMapCenter([center.lng, center.lat]); + }); + } catch (error) { + console.warn('添加地图事件监听失败:', error); + } + + return map; + } catch (error) { + console.error('创建地图实例失败:', error); + throw error; + } + }; + + // 安全的地图刷新方法 + const safeRefreshMap = () => { + if (mapRef.current) { + try { + // 尝试不同的刷新方法 + if (typeof mapRef.current.resize === 'function') { + mapRef.current.resize(); + return true; + } else if (typeof mapRef.current.setFitView === 'function') { + mapRef.current.setFitView(); + return true; + } else if (typeof mapRef.current.setZoomAndCenter === 'function') { + mapRef.current.setZoomAndCenter(mapZoom, mapCenter); + return true; + } else { + console.log('地图刷新方法不可用'); + return false; + } + } catch (error) { + console.warn('地图刷新失败:', error); + return false; + } + } + return false; + }; + + return ( +
    + {/* 顶部控制栏 */} +
    + +
    + + 设备运维地图 + + + + + + + + setSearchKeyword(e.target.value)} + style={{ width: 200 }} + prefix={} + /> + + + + + + + + + + + + + + + + + + + + + + + 设备: {devices.length} | 在线: {deviceStats.online} | 离线: {deviceStats.offline} + + + {wsConnected && ( + + 已订阅: 属性上报 | 事件 | 上线/离线 + + )} + + {devices.some(d => d.lastUpdateTime) && ( + + 最后更新: {new Date(Math.max(...devices.filter(d => d.lastUpdateTime).map(d => new Date(d.lastUpdateTime!).getTime()))).toLocaleTimeString()} + + )} + + + + + + {/* 地图区域 */} +
    +
    + {/* 高德地图容器 */} +
    + + {/* 设备卡片(悬停显示) */} + {showDeviceCard && hoveredDevice && ( +
    +
    + {hoveredDevice.deviceName} + + {DEVICE_STATUS_CONFIG[getDeviceStatus(hoveredDevice)].text} + +
    +
    +
    编号: {hoveredDevice.deviceSn}
    +
    类型: {hoveredDevice.deviceType}
    +
    电量: {hoveredDevice.metrics.batteryCapacity}%
    +
    网络: {hoveredDevice.metrics.networkQuality}%
    +
    温度: {hoveredDevice.metrics.temperature}°C
    +
    湿度: {hoveredDevice.metrics.humidity}%
    + {hoveredDevice.metrics.droneInDock !== undefined && ( +
    机库: {hoveredDevice.metrics.droneInDock === 1 ? '在库' : '离库'}
    + )} + {hoveredDevice.location && ( +
    位置: {hoveredDevice.location.latitude.toFixed(4)}, {hoveredDevice.location.longitude.toFixed(4)}
    + )} + {hoveredDevice.lastUpdateTime && ( +
    更新: {new Date(hoveredDevice.lastUpdateTime).toLocaleTimeString()}
    + )} +
    +
    + )} + + {/* 地图加载状态覆盖层 */} + {!mapInitialized && ( +
    +
    地图加载中...
    +
    + mapInitialized: {mapInitialized ? 'true' : 'false'} +
    +
    + 设备数量: {mapMarkers.length} +
    +
    + AMap: {typeof window !== 'undefined' && window.AMap ? '已加载' : '未加载'} +
    +
    + 地图容器: {mapContainerRef.current ? '已创建' : '未创建'} +
    +
    + 地图实例: {mapRef.current ? '已创建' : '未创建'} +
    +
    + )} +
    +
    + + {/* 左侧统计面板 */} + {leftPanelVisible && ( +
    + setLeftPanelCollapsed(true)} + > + - + + )} + style={{ height: '100%', overflow: 'auto' }} + > + {leftPanelCollapsed ? ( +
    + +
    + ) : ( + <> + {/* 统计卡片 */} + +
    + + } + valueStyle={{ color: '#1890ff' }} + /> + + + + + } + valueStyle={{ color: '#52c41a' }} + suffix={`/ ${deviceStats.total}`} + /> + + + + + } + valueStyle={{ color: '#52c41a' }} + /> + + + + + } + valueStyle={{ color: '#ff4d4f' }} + /> + + + + + {/* 按分组统计 */} +
    +
    + 景区分布 +
    + {Object.entries(deviceStats.byGroup).map(([group, count]) => ( +
    + {group} + {count} +
    + ))} +
    + + {/* 设备列表 */} +
    +
    + 设备列表 ({memoizedDeviceList.length}) +
    +
    + {memoizedDeviceList.map(device => ( +
    locateDeviceOnMap(device)} + onMouseEnter={(e) => { + e.currentTarget.style.backgroundColor = '#f5f5f5'; + }} + onMouseLeave={(e) => { + e.currentTarget.style.backgroundColor = selectedDevice?.deviceSn === device.deviceSn ? '#e6f7ff' : '#fff'; + }} + > +
    +
    +
    + {device.deviceName} +
    +
    + {device.deviceSn} +
    +
    + + {device.statusConfig.text} + +
    +
    + 电量: {device.metrics.batteryCapacity}% | 网络: {device.metrics.networkQuality}% | 温度: {device.metrics.temperature}°C + {device.lastUpdateTime && ( + + {new Date(device.lastUpdateTime).toLocaleTimeString()} + + )} +
    +
    + ))} +
    +
    + + )} + + + )} + + {/* 右侧详情面板 */} + {rightPanelVisible && selectedDevice && ( +
    + + + + + )} + style={{ height: '100%', overflow: 'auto' }} + > + {rightPanelCollapsed ? ( +
    + +
    + ) : ( + <> + {/* 设备基本信息 */} + + {selectedDevice.deviceName} + {selectedDevice.deviceSn} + {selectedDevice.deviceType} + + + {DEVICE_STATUS_CONFIG[getDeviceStatus(selectedDevice)].text} + + + {selectedDevice.loginTime} + {selectedDevice.lastUpdateTime && ( + {selectedDevice.lastUpdateTime} + )} + {selectedDevice.metrics.lastMaintenance && ( + {selectedDevice.metrics.lastMaintenance} + )} + {selectedDevice.metrics.nextMaintenance && ( + {selectedDevice.metrics.nextMaintenance} + )} + + + + + {/* 操作按钮 */} +
    + 设备操作 + + + + + +
    + + {/* 无人机控制面板 */} + {selectedDevice.deviceType === 1 && ( + <> + +
    + 无人机控制 + + {/* 相机控制 */} +
    +
    相机控制
    + + + + + +
    + + {/* 相机模式切换 */} +
    +
    相机模式
    + + + + + + +
    + + {/* 飞行控制 */} +
    +
    飞行控制
    + + + + + +
    + + {/* 摇杆控制 */} +
    +
    摇杆控制
    +
    + 范围:0-2048,1024为中立位 +
    + +
    +
    Roll (左右)
    + handleStickControl(selectedDevice.deviceSn, 'roll', value)} + style={{ width: '100%' }} + /> + + +
    Pitch (上下)
    + handleStickControl(selectedDevice.deviceSn, 'pitch', value)} + style={{ width: '100%' }} + /> + + +
    Throttle (油门)
    + handleStickControl(selectedDevice.deviceSn, 'throttle', value)} + style={{ width: '100%' }} + /> + + +
    Yaw (偏航)
    + handleStickControl(selectedDevice.deviceSn, 'yaw', value)} + style={{ width: '100%' }} + /> + + + + + + )} + + {/* 实时数据 */} +
    + 实时数据 + +
    +
    +
    电量
    +
    + {selectedDevice.metrics.batteryCapacity}% +
    +
    + + +
    +
    网络质量
    +
    + {selectedDevice.metrics.networkQuality}% +
    +
    + + +
    +
    温度
    +
    + {selectedDevice.metrics.temperature}°C +
    +
    + + +
    +
    湿度
    +
    + {selectedDevice.metrics.humidity}% +
    +
    + + +
    +
    风速
    +
    + {selectedDevice.metrics.windSpeed}m/s +
    +
    + + +
    +
    降雨量
    +
    + {selectedDevice.metrics.rainfall}mm +
    +
    + + + + + {/* 无人机特有信息 */} + {selectedDevice.deviceType === 1 && ( + <> + +
    + 飞行信息 + +
    +
    +
    飞行模式
    +
    + {selectedDevice.metrics.modeCode > 0 ? '执行中' : '待机'} +
    +
    + + +
    +
    机库状态
    +
    + {selectedDevice.metrics.droneInDock === 1 ? '在库' : '离库'} +
    +
    + + +
    +
    位置质量
    +
    = 4 ? '#52c41a' : '#ff4d4f' }}> + {selectedDevice.metrics.positionQuality}/5 +
    +
    + + +
    +
    告警状态
    +
    0 ? '#ff4d4f' : '#52c41a' }}> + {(selectedDevice.metrics.errorCount + selectedDevice.metrics.warningCount) > 0 ? '异常' : '正常'} +
    +
    + + + + + )} + + {/* 维护信息 */} + {(selectedDevice.metrics.lastMaintenance || selectedDevice.metrics.nextMaintenance) && ( + <> + +
    + 维护信息 + {selectedDevice.metrics.lastMaintenance && ( +
    + 最后维护: + {selectedDevice.metrics.lastMaintenance} +
    + )} + {selectedDevice.metrics.nextMaintenance && ( +
    + 下次维护: + {selectedDevice.metrics.nextMaintenance} +
    + )} +
    + + )} + + + + {/* 位置信息 */} +
    + 位置信息 + {selectedDevice.location ? ( +
    +
    纬度: {selectedDevice.location.latitude.toFixed(6)}
    +
    经度: {selectedDevice.location.longitude.toFixed(6)}
    + {selectedDevice.location.height && ( +
    高度: {selectedDevice.location.height}m
    + )} +
    + ) : ( +
    + 暂无位置信息 +
    + )} +
    + + )} + + + )} + + {/* 视频播放弹窗 */} + setVideoStreamVisible(false)} + width={800} + footer={null} + destroyOnClose + > +
    + {videoLoading ? ( +
    +
    正在加载视频流...
    +
    + ) : videoStreamUrl ? ( +
    +
    + + + + + +
    +
    + { + console.error('视频播放错误:', error); + message.error('视频播放失败,请检查网络连接'); + }} + /> +
    +
    + ) : ( +
    +
    暂无视频流
    +
    + )} +
    +
    + + ); +}; + +export default DeviceMapDashboard; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/map-dashboard/mock/devices.ts b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/map-dashboard/mock/devices.ts new file mode 100644 index 00000000..8e596ecc --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/map-dashboard/mock/devices.ts @@ -0,0 +1,217 @@ +import moment from 'moment'; + +// 设备状态枚举 +export enum DeviceStatus { + TASK = 'task', // 任务中 - 绿色 + STANDBY = 'standby', // 待机 - 蓝色 + MAINTENANCE = 'maintenance', // 维护 - 橙色 + ERROR = 'error', // 异常 - 红色 + OFFLINE = 'offline' // 离线 - 灰色 +} + +// 设备状态配置 +export const DEVICE_STATUS_CONFIG = { + [DeviceStatus.TASK]: { + color: '#52c41a', + icon: '▶️', + text: '任务中', + bgColor: '#f6ffed' + }, + [DeviceStatus.STANDBY]: { + color: '#1890ff', + icon: '⏰', + text: '待机', + bgColor: '#f0f8ff' + }, + [DeviceStatus.MAINTENANCE]: { + color: '#fa8c16', + icon: '🔧', + text: '维护', + bgColor: '#fff7e6' + }, + [DeviceStatus.ERROR]: { + color: '#ff4d4f', + icon: '⚠️', + text: '异常', + bgColor: '#fff2f0' + }, + [DeviceStatus.OFFLINE]: { + color: '#8c8c8c', + icon: '❌', + text: '离线', + bgColor: '#f5f5f5' + } +}; + +// 设备类型 +export interface Device { + id: string; + name: string; + sn: string; + type: string; + status: DeviceStatus; + location: { + latitude: number; + longitude: number; + altitude?: number; + }; + battery: number; + signal: number; + temperature: number; + humidity: number; + lastUpdate: string; + group?: string; + description?: string; + // 新增字段 + batteryCycles?: number; // 电池循环次数 + flightHours?: number; // 飞行时长 + lastMaintenance?: string; // 最后维护时间 + nextMaintenance?: string; // 下次维护时间 + operator?: string; // 操作员 + ipAddress?: string; // IP地址 + firmwareVersion?: string; // 固件版本 +} + +// 景区位置数据(北京周边景区) +const SCENIC_SPOTS = [ + { name: '颐和园', lat: 39.9999, lng: 116.2755, group: '颐和园景区' }, + { name: '天坛公园', lat: 39.8822, lng: 116.4066, group: '天坛景区' }, + { name: '故宫博物院', lat: 39.9163, lng: 116.3972, group: '故宫景区' }, + { name: '八达岭长城', lat: 40.3569, lng: 116.0200, group: '长城景区' }, + { name: '圆明园', lat: 40.0084, lng: 116.2995, group: '圆明园景区' }, + { name: '香山公园', lat: 39.9944, lng: 116.1955, group: '香山景区' }, + { name: '北海公园', lat: 39.9254, lng: 116.3897, group: '北海景区' }, + { name: '景山公园', lat: 39.9244, lng: 116.3974, group: '景山景区' }, + { name: '天安门广场', lat: 39.9054, lng: 116.3976, group: '天安门景区' }, + { name: '奥林匹克公园', lat: 40.0024, lng: 116.3974, group: '奥体景区' }, +]; + +// 设备类型配置 +const DEVICE_TYPES = [ + { type: '无人机', prefix: 'UAV', description: '航拍无人机设备' }, + { type: '摄像头', prefix: 'CAM', description: '监控摄像头设备' }, + { type: '传感器', prefix: 'SEN', description: '环境监测传感器' }, + { type: '控制器', prefix: 'CTL', description: '智能控制器设备' }, + { type: '基站', prefix: 'BS', description: '通信基站设备' }, +]; + +// 生成随机位置(在指定景区附近) +const generateLocation = (scenicSpot: any) => { + // 在景区周围500米范围内随机生成位置 + const radius = 0.005; // 约500米 + const angle = Math.random() * 2 * Math.PI; + const distance = Math.random() * radius; + + const lat = scenicSpot.lat + distance * Math.cos(angle); + const lng = scenicSpot.lng + distance * Math.sin(angle); + + return { + latitude: lat, + longitude: lng, + altitude: Math.floor(Math.random() * 100) + 50 + }; +}; + +// 生成模拟设备数据 +export const generateMockDevices = (): Device[] => { + const mockDevices: Device[] = []; + + // 为每个景区生成2-4个设备 + SCENIC_SPOTS.forEach((spot, spotIndex) => { + const deviceCount = Math.floor(Math.random() * 3) + 2; // 2-4个设备 + + for (let i = 1; i <= deviceCount; i++) { + const deviceType = DEVICE_TYPES[Math.floor(Math.random() * DEVICE_TYPES.length)]; + const status = Object.values(DeviceStatus)[Math.floor(Math.random() * Object.values(DeviceStatus).length)]; + const deviceId = `${spotIndex + 1}_${i}`; + + // 生成设备编号 + const sn = `${deviceType.prefix}${(spotIndex + 1).toString().padStart(2, '0')}${i.toString().padStart(2, '0')}`; + + // 生成位置 + const location = generateLocation(spot); + + // 生成电池循环次数(仅无人机) + const batteryCycles = deviceType.type === '无人机' ? Math.floor(Math.random() * 200) + 1 : undefined; + + // 生成飞行时长(仅无人机) + const flightHours = deviceType.type === '无人机' ? Math.floor(Math.random() * 1000) + 10 : undefined; + + // 生成维护时间 + const lastMaintenance = moment().subtract(Math.floor(Math.random() * 30), 'days').format('YYYY-MM-DD'); + const nextMaintenance = moment().add(Math.floor(Math.random() * 30) + 7, 'days').format('YYYY-MM-DD'); + + mockDevices.push({ + id: `device_${deviceId}`, + name: `${deviceType.type}${deviceId}`, + sn, + type: deviceType.type, + status, + location, + battery: Math.floor(Math.random() * 100) + 1, + signal: Math.floor(Math.random() * 100) + 1, + temperature: Math.floor(Math.random() * 40) + 10, + humidity: Math.floor(Math.random() * 60) + 20, + lastUpdate: moment().subtract(Math.floor(Math.random() * 60), 'minutes').format('YYYY-MM-DD HH:mm:ss'), + group: spot.group, + description: `${deviceType.description},位于${spot.name}`, + batteryCycles, + flightHours, + lastMaintenance, + nextMaintenance, + operator: `操作员${Math.floor(Math.random() * 10) + 1}`, + ipAddress: `192.168.${Math.floor(Math.random() * 255) + 1}.${Math.floor(Math.random() * 255) + 1}`, + firmwareVersion: `v${Math.floor(Math.random() * 5) + 1}.${Math.floor(Math.random() * 10)}.${Math.floor(Math.random() * 10)}` + }); + } + }); + + return mockDevices; +}; + +// 设备统计接口 +export interface DeviceStats { + total: number; + online: number; + offline: number; + task: number; + standby: number; + maintenance: number; + error: number; + byGroup: Record; + byType: Record; +} + +// 计算设备统计 +export const calculateDeviceStats = (devices: Device[]): DeviceStats => { + const stats: DeviceStats = { + total: devices.length, + online: devices.filter(d => d.status !== DeviceStatus.OFFLINE).length, + offline: devices.filter(d => d.status === DeviceStatus.OFFLINE).length, + task: devices.filter(d => d.status === DeviceStatus.TASK).length, + standby: devices.filter(d => d.status === DeviceStatus.STANDBY).length, + maintenance: devices.filter(d => d.status === DeviceStatus.MAINTENANCE).length, + error: devices.filter(d => d.status === DeviceStatus.ERROR).length, + byGroup: {}, + byType: {} + }; + + // 按分组统计 + devices.forEach(device => { + if (device.group) { + stats.byGroup[device.group] = (stats.byGroup[device.group] || 0) + 1; + } + stats.byType[device.type] = (stats.byType[device.type] || 0) + 1; + }); + + return stats; +}; + +// 获取景区列表 +export const getScenicSpots = () => { + return SCENIC_SPOTS.map(spot => ({ + name: spot.name, + group: spot.group, + location: { latitude: spot.lat, longitude: spot.lng } + })); +}; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx index f4f39aeb..eb9cd6d5 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx @@ -13,7 +13,9 @@ import { DashboardOutlined, BarChartOutlined, SettingOutlined, BellOutlined, EyeOutlined, ReloadOutlined, DownloadOutlined, FilterOutlined, PlayCircleOutlined, PauseCircleOutlined, StopOutlined, CameraOutlined, - VideoCameraOutlined, SoundOutlined, BulbOutlined, ToolOutlined + VideoCameraOutlined, SoundOutlined, BulbOutlined, ToolOutlined, + ControlOutlined, HomeOutlined, PauseOutlined, PlayOutlined, + CameraOutlined as CameraIcon, VideoCameraOutlined as VideoIcon } from '@ant-design/icons'; import { device, getStreamUrls } from '@/services/device/api'; import { request } from 'umi'; @@ -434,6 +436,30 @@ const DeviceMonitor: React.FC = () => { const [useReactPlayer, setUseReactPlayer] = useState(true); const [videoStreamStatus, setVideoStreamStatus] = useState<'loading' | 'playing' | 'error' | 'ended' | 'stalled'>('loading'); + // 设备控制相关状态 + const [controlVisible, setControlVisible] = useState(false); + const [currentControlDevice, setCurrentControlDevice] = useState(null); + const [controlLoading, setControlLoading] = useState(false); + const [controlError, setControlError] = useState(''); + const [controlSuccess, setControlSuccess] = useState(''); + + // 摇杆控制状态 + const [stickControl, setStickControl] = useState({ + roll: 1024, // 右手左右控制 + pitch: 1024, // 右手上下控制 + throttle: 1024, // 左手上下控制 + yaw: 1024, // 左手左右控制 + gimbal_pitch: 1024 // 云台画面上下划 + }); + + // 相机控制状态 + const [cameraMode, setCameraMode] = useState(0); // 0=拍照,1=录像,2=智能低光,3=全景拍照 + const [isRecording, setIsRecording] = useState(false); + + // 飞行控制状态 + const [flightMode, setFlightMode] = useState<'idle' | 'manual' | 'task' | 'return'>('idle'); + const [isInDRCMode, setIsInDRCMode] = useState(false); + const tokenCache = { value: '', expire: 0, @@ -1487,6 +1513,9 @@ const DeviceMonitor: React.FC = () => { handlePlayVideo(record)}> 视频流 + handleOpenControl(record)}> + 设备控制 + ), }, @@ -2069,11 +2098,20 @@ const DeviceMonitor: React.FC = () => { } }; - // 录制功能 - const handleToggleRecording = () => { - setVideoRecording(!videoRecording); - // 这里可以添加实际的录制逻辑 - console.log('录制状态:', !videoRecording); + // 开始/停止录像 + const handleToggleVideoRecording = async () => { + if (!currentControlDevice) return; + + const method = isRecording ? 'camera_recording_stop' : 'camera_recording_start'; + const success = await sendControlCommand( + currentControlDevice.deviceSn, + method + ); + + if (success) { + setIsRecording(!isRecording); + setControlSuccess(isRecording ? '停止录像指令已发送' : '开始录像指令已发送'); + } }; // 全屏功能 @@ -2481,6 +2519,218 @@ const DeviceMonitor: React.FC = () => { ); }; + // 发送设备控制指令 + const sendControlCommand = async (deviceSn: string, method: string, data: any = {}) => { + if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) { + setControlError('WebSocket连接未建立,无法发送控制指令'); + return false; + } + + try { + setControlLoading(true); + setControlError(''); + setControlSuccess(''); + + const messageId = `control-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; + + const controlMessage = { + type: "sub", + topic: `/device-message-sender/D-Dock2/${deviceSn}`, + parameter: { + messageType: "WRITE_PROPERTY", + properties: { + method: method, + data: data + }, + headers: { + async: false + } + }, + id: messageId + }; + + console.log('发送控制指令:', JSON.stringify(controlMessage, null, 2)); + + wsRef.current.send(JSON.stringify(controlMessage)); + + // 等待响应 + return new Promise((resolve) => { + const timeout = setTimeout(() => { + setControlError('控制指令超时,请检查设备状态'); + setControlLoading(false); + resolve(false); + }, 10000); // 10秒超时 + + const originalOnMessage = wsRef.current!.onmessage; + wsRef.current!.onmessage = (event) => { + try { + const data = JSON.parse(event.data); + if (data.type === 'result' && data.id === messageId) { + clearTimeout(timeout); + setControlLoading(false); + + if (data.payload && data.payload.success !== false) { + setControlSuccess('控制指令执行成功'); + resolve(true); + } else { + setControlError(data.payload?.message || '控制指令执行失败'); + resolve(false); + } + + // 恢复原始消息处理 + if (originalOnMessage) { + wsRef.current!.onmessage = originalOnMessage; + } + } else { + // 继续处理其他消息 + if (originalOnMessage) { + originalOnMessage.call(wsRef.current!, event); + } + } + } catch (error) { + console.error('解析控制响应失败:', error); + } + }; + }); + } catch (error) { + console.error('发送控制指令失败:', error); + setControlError('发送控制指令失败'); + setControlLoading(false); + return false; + } + }; + + // 摇杆控制 + const handleStickControl = async (axis: string, value: number) => { + if (!currentControlDevice) return; + + const newStickControl = { ...stickControl, [axis]: value }; + setStickControl(newStickControl); + + const success = await sendControlCommand( + currentControlDevice.deviceSn, + 'stick_control', + newStickControl + ); + + if (success) { + console.log('摇杆控制成功:', axis, value); + } + }; + + // 相机模式切换 + const handleCameraModeSwitch = async (mode: number) => { + if (!currentControlDevice) return; + + const success = await sendControlCommand( + currentControlDevice.deviceSn, + 'camera_mode_switch', + { camera_mode: mode } + ); + + if (success) { + setCameraMode(mode); + setControlSuccess(`相机模式切换为: ${getCameraModeText(mode)}`); + } + }; + + // 拍照 + const handleTakePhoto = async () => { + if (!currentControlDevice) return; + + const success = await sendControlCommand( + currentControlDevice.deviceSn, + 'camera_photo_take' + ); + + if (success) { + setControlSuccess('拍照指令已发送'); + } + }; + + // 暂停航线任务 + const handlePauseTask = async () => { + if (!currentControlDevice) return; + + const success = await sendControlCommand( + currentControlDevice.deviceSn, + 'flighttask_pause' + ); + + if (success) { + setFlightMode('idle'); + setControlSuccess('航线任务已暂停'); + } + }; + + // 返航 + const handleReturnHome = async () => { + if (!currentControlDevice) return; + + const success = await sendControlCommand( + currentControlDevice.deviceSn, + 'return_home' + ); + + if (success) { + setFlightMode('return'); + setControlSuccess('返航指令已发送'); + } + }; + + // 进入DRC模式 + const handleEnterDRCMode = async () => { + if (!currentControlDevice) return; + + const success = await sendControlCommand( + currentControlDevice.deviceSn, + 'drc_mode_enter' + ); + + if (success) { + setIsInDRCMode(true); + setFlightMode('manual'); + setControlSuccess('已进入指令飞行模式'); + } + }; + + // 获取相机模式文本 + const getCameraModeText = (mode: number) => { + const modeMap: Record = { + 0: '拍照', + 1: '录像', + 2: '智能低光', + 3: '全景拍照' + }; + return modeMap[mode] || '未知模式'; + }; + + // 打开设备控制面板 + const handleOpenControl = (device: Device) => { + setCurrentControlDevice(device); + setControlVisible(true); + setControlError(''); + setControlSuccess(''); + setControlLoading(false); + }; + + // 关闭设备控制面板 + const handleCloseControl = () => { + setControlVisible(false); + setCurrentControlDevice(null); + setControlError(''); + setControlSuccess(''); + setControlLoading(false); + // 重置摇杆到中立位 + setStickControl({ + roll: 1024, + pitch: 1024, + throttle: 1024, + yaw: 1024, + gimbal_pitch: 1024 + }); + }; + return ( {/* 顶部控制栏 */} @@ -3208,7 +3458,7 @@ const DeviceMonitor: React.FC = () => { , , + ]} + width={1000} + destroyOnClose + > +
    + {/* 状态提示 */} + {controlError && ( + + )} + + {controlSuccess && ( + + )} + + {controlLoading && ( + + )} + + + {/* 飞行控制标签页 */} + + +
    + + + + + + + + + + + + + + + + + {flightMode === 'idle' ? '空闲' : + flightMode === 'manual' ? '手动控制' : + flightMode === 'task' ? '任务执行' : + flightMode === 'return' ? '返航中' : '未知'} + + + + + {isInDRCMode ? '已启用' : '未启用'} + + + + + {currentControlDevice?.boundStatus === 1 ? '在线' : '离线'} + + + + + + + + + {/* 摇杆控制标签页 */} + + + + + +
    + 左右控制 (Roll): {stickControl.roll} + handleStickControl('roll', value)} + disabled={controlLoading || !isInDRCMode} + /> +
    +
    + 上下控制 (Pitch): {stickControl.pitch} + handleStickControl('pitch', value)} + disabled={controlLoading || !isInDRCMode} + /> +
    +
    +
    + + + + + +
    + 上下控制 (Throttle): {stickControl.throttle} + handleStickControl('throttle', value)} + disabled={controlLoading || !isInDRCMode} + /> +
    +
    + 左右控制 (Yaw): {stickControl.yaw} + handleStickControl('yaw', value)} + disabled={controlLoading || !isInDRCMode} + /> +
    +
    +
    + + + + +
    + 云台上下 (Gimbal Pitch): {stickControl.gimbal_pitch} + handleStickControl('gimbal_pitch', value)} + disabled={controlLoading || !isInDRCMode} + /> +
    +
    + + + + + {/* 相机控制标签页 */} + + + + + +
    + 当前模式: {getCameraModeText(cameraMode)} +
    + + + + +
    +
    + + + + + + + + + + + + + + + + ); };