[React] forge 指定設備顯示

This commit is contained in:
Celeste6666 2023-02-06 00:06:41 +08:00
parent 338e209ced
commit 79e0ec3e76
22 changed files with 282 additions and 168 deletions

View File

@ -4,10 +4,17 @@
<JavaScriptTestRoot>src\</JavaScriptTestRoot> <JavaScriptTestRoot>src\</JavaScriptTestRoot>
<JavaScriptTestFramework>Jest</JavaScriptTestFramework> <JavaScriptTestFramework>Jest</JavaScriptTestFramework>
<!-- Command to run on project build --> <!-- Command to run on project build -->
<BuildCommand></BuildCommand> <BuildCommand>
</BuildCommand>
<!-- Command to create an optimized build of the project that's ready for publishing --> <!-- Command to create an optimized build of the project that's ready for publishing -->
<ProductionBuildCommand>npm run build</ProductionBuildCommand> <ProductionBuildCommand>npm run build</ProductionBuildCommand>
<!-- Folder where production build objects will be placed --> <!-- Folder where production build objects will be placed -->
<BuildOutputFolder>$(MSBuildProjectDirectory)\build</BuildOutputFolder> <BuildOutputFolder>$(MSBuildProjectDirectory)\build</BuildOutputFolder>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Remove="src\utils\baja\bajaUtil.js" />
</ItemGroup>
<ItemGroup>
<None Remove="src\utils\baja\bajaUtil.js" />
</ItemGroup>
</Project> </Project>

View File

@ -1,38 +0,0 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

View File

@ -1,4 +1,4 @@
import { useMemo, useEffect, useState } from "react"; import { useMemo, useEffect, useState, useCallback } from "react";
import { Outlet, NavLink } from "react-router-dom"; import { Outlet, NavLink } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux"; import { useSelector, useDispatch } from "react-redux";
import { Container, Nav, Navbar, NavDropdown } from "react-bootstrap"; import { Container, Nav, Navbar, NavDropdown } from "react-bootstrap";
@ -49,6 +49,16 @@ function App() {
dispatch(fetchSysMainSub(selectedBuiTag)); dispatch(fetchSysMainSub(selectedBuiTag));
} }
}, [selectedBuiTag]); }, [selectedBuiTag]);
// 離開頁面就清除所有 cookie
//const removeAllCookie = useCallback(() => {
// console.log("關閉分頁時,清除所有 cookie")
// window.addEventListener("beforeunload",() => {
// document.cookie.match(/[^ =;]+(?=\=)/g).forEach(key => {
// document.cookie = `${key}=""; max-age=0`;
// }) })
//}, [])
return ( return (
<div className="App"> <div className="App">
{/* 主選單 */} {/* 主選單 */}

View File

@ -1,8 +0,0 @@
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

View File

@ -1,17 +1,29 @@
import React, { useEffect, useRef, useState } from "react"; import React, { useEffect, useRef, useMemo } from "react";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import * as THREE from "three"; import * as THREE from "three";
import { fetchForge, shutdownForge } from "@STORE/forgeSlice"; import { fetchForge, shutdownForge } from "@STORE/forgeSlice";
import { SubscribeDeviceTempByBaja } from "@UTIL"
import hotspot from "@ASSET/img/hotspot.svg"; import hotspot from "@ASSET/img/hotspot.svg";
function ForgeModel({ forgeHeight, sprites = [] }) { function ForgeModel({ forgeHeight, deviceList = [] }) {
const dispatch = useDispatch(); const dispatch = useDispatch();
const viewerEl = useRef(null); const viewerEl = useRef(null);
const { const {
buildingInfo: { urn_3D }, buildingInfo: { urn_3D },
forgeViewer: { viewer, dataVizExtn, DataVizCore }, forgeViewer: { viewer, model,dataVizExtn, DataVizCore, structureInfo },
device: { selectedDeviceSysTag,selectedDeviceNameTag,tempsensorDevList }
} = useSelector((store) => store); } = useSelector((store) => store);
const deviceArray = useMemo(()=> deviceList.map(({ device_number, device_coordinate_3d, room_dbid }) => {
return {
id: device_number, // An ID to identify this device
position: JSON.parse(device_coordinate_3d), // World coordinates of this device
roomId: room_dbid,
sensorTypes: ["temperature", "humidity"], // The types/properties this device exposes
temp: 0,
}
}), [selectedDeviceNameTag])
// 載入 Forge Viewer // 載入 Forge Viewer
useEffect(() => { useEffect(() => {
if (urn_3D) { if (urn_3D) {
@ -21,9 +33,9 @@ function ForgeModel({ forgeHeight, sprites = [] }) {
urn: urn_3D, urn: urn_3D,
}), }),
); );
};
return () => { return () => {
dispatch(shutdownForge()); dispatch(shutdownForge());
};
} }
}, [urn_3D]); }, [urn_3D]);
@ -38,7 +50,7 @@ function ForgeModel({ forgeHeight, sprites = [] }) {
// 熱點點擊事件 // 熱點點擊事件
const onSpriteClicked = (event) => { const onSpriteClicked = (event) => {
const targetDbIds = [event.dbId]; const targetDbIds = [event.dbId];
spriteUpdate(event, targetDbIds, { scale: 1.3, color: { r: 1, g: 0, b: 0 } }); spriteUpdate(event, targetDbIds, { scale: 1.3, color: { r: 1.0, g: 0, b: 0 } });
console.log(`Sprite clicked:${targetDbIds}`); console.log(`Sprite clicked:${targetDbIds}`);
}; };
@ -51,10 +63,9 @@ function ForgeModel({ forgeHeight, sprites = [] }) {
// 進入系統監控頁面,出現熱點 // 進入系統監控頁面,出現熱點
useEffect(() => { useEffect(() => {
if (sprites.length !== 0 && viewer && dataVizExtn) { if (deviceList.length !== 0 && viewer && dataVizExtn) {
// const filterSprites = sprites.map;
dataVizExtn.removeAllViewables(); dataVizExtn.removeAllViewables();
sprites.forEach(async ({ device_coordinate_3d, forge_dbid }, index) => { deviceList.forEach(async ({ device_coordinate_3d, forge_dbid }, index) => {
const viewableType = DataVizCore.ViewableType.SPRITE; const viewableType = DataVizCore.ViewableType.SPRITE;
const spriteColor = new THREE.Color(0xffffff); const spriteColor = new THREE.Color(0xffffff);
const spriteIconUrl = hotspot; const spriteIconUrl = hotspot;
@ -78,12 +89,84 @@ function ForgeModel({ forgeHeight, sprites = [] }) {
} }
return () => { return () => {
if (sprites.length !== 0 && viewer && dataVizExtn) { if (deviceList.length !== 0 && viewer && dataVizExtn) {
viewer.removeEventListener(DataVizCore.MOUSE_CLICK, onSpriteClicked); viewer.removeEventListener(DataVizCore.MOUSE_CLICK, onSpriteClicked);
viewer.removeEventListener(DataVizCore.MOUSE_CLICK_OUT, onSpriteClickedOut); viewer.removeEventListener(DataVizCore.MOUSE_CLICK_OUT, onSpriteClickedOut);
} }
}; };
}, [sprites, dataVizExtn, viewer]); }, [deviceList, dataVizExtn]);
// 熱圖
const getSensorValue = (surfaceShadingPoint) => {
// The `SurfaceShadingPoint.id` property matches one of the identifiers passed to `generateSurfaceShadingData`
const { temp } = surfaceShadingPoint;
return temp / 40;
}
// 構建熱圖
const establishHeatMaps = async (deviceList, dataVizExtn) => {
// 不重複的房間值
const uniqueRoomIds = [...new Set(deviceArray.map(r => r.roomId))]; // 房間唯一值
const {
SurfaceShadingData,
SurfaceShadingPoint,
SurfaceShadingNode,
} = DataVizCore;
const heatmapData = new SurfaceShadingData();
uniqueRoomIds.forEach(room_Id => {
// 為每個房間都建立一個 Node
const shadingNode = new SurfaceShadingNode("TemperatureSensor", room_Id);
deviceArray.forEach(({ id, position, roomId, sensorTypes }) => {
// 設備對應的 roomId 用來判斷要加入哪個 Node
if (room_Id === roomId) {
const pt = new SurfaceShadingPoint(id, position, sensorTypes);
shadingNode.addPoint(pt);
}
})
heatmapData.addChild(shadingNode);
heatmapData.initialize(viewer.model);
})
await dataVizExtn.setupSurfaceShading(viewer.model, heatmapData, {
type: "PlanarHeatmap",
slicingPosition: 0.5, // Slicing happens at the vertical mid-point of the geometry
placementPosition: 1.0, // The sliced planar heatmap placed at the base of geometry
minOpacity: 0.0, // The default value if this option is omitted
maxOpacity: 0.5, // The default value if this option is omitted
});
// 對 "temperature" 的溫度設定兩種顏色:紅色和藍色
dataVizExtn.registerSurfaceShadingColors("temperature", [0x0000ff, 0x00ff00, 0xffff00, 0xff0000]);
if (deviceArray.length !== 0) {
const sensorType = "temperature";
deviceArray.forEach(({ id }) => {
dataVizExtn.renderSurfaceShading(id, sensorType, getSensorValue);
})
}
}
useEffect(() => {
if (deviceList && structureInfo && dataVizExtn && selectedDeviceSysTag == "ME") {
// 訂閱有 Temp 的設備
deviceList.forEach(({ device_number }) => {
SubscribeDeviceTempByBaja(device_number, dispatch)
})
establishHeatMaps(deviceList, dataVizExtn, structureInfo);
}
return () => { }
}, [selectedDeviceNameTag]);
useEffect(() => {
if (tempsensorDevList.length !== 0) {
deviceArray.forEach((device) => {
if (tempsensorDevList.findIndex(({ device_number }) => device_number === device.id) !== -1) {
const newTempObj = tempsensorDevList.find(({ device_number }) => device_number === device.id)
device.temp = newTempObj.temp;
dataVizExtn.updateSurfaceShading(getSensorValue);
}
})
}
}, [tempsensorDevList])
return <div ref={viewerEl} id="forgeViewer" style={{ height: forgeHeight }}></div>; return <div ref={viewerEl} id="forgeViewer" style={{ height: forgeHeight }}></div>;
} }

View File

@ -1,13 +0,0 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

View File

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

Before

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -3,26 +3,49 @@ import { useParams } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux"; import { useSelector, useDispatch } from "react-redux";
import { Container, Row, Col, Card, ButtonGroup, Button } from "react-bootstrap"; import { Container, Row, Col, Card, ButtonGroup, Button } from "react-bootstrap";
import ForgeModel from "@COM/forges/ForgeModel"; import ForgeModel from "@COM/forges/ForgeModel";
import { fetchSelectedDeviceMenu, fetchSelectedDeviceList, fetchSelectedDevFlTags } from "@STORE"; import { fetchSelectedDeviceMenu, fetchSelectedDeviceList, fetchSelectedDevFlTags, changeMainSubSys } from "@STORE";
import defdev from "@ASSET/img/defdev.png"; import defdev from "@ASSET/img/defdev.png";
function Monitor() { function Monitor() {
const params = useParams().systemId; // main_sub const params = useParams().systemId; // main_sub
const [main_system_tag, sub_system_tag] = params.split("_"); const [main_system_tag, sub_system_tag] = params.split("_");
const dispatch = useDispatch(); const dispatch = useDispatch();
const { const {
buildingInfo: { selectedBuiTag },
device: { selectedDeviceMenu, selectedDeviceList, selectedDeviceFloorTags }, device: { selectedDeviceMenu, selectedDeviceList, selectedDeviceFloorTags },
system: { mainSub }, system: { mainSub },
forgeViewer: { viewer, model },
} = useSelector((state) => state); } = useSelector((state) => state);
useEffect(() => { useEffect(() => {
if (selectedBuiTag && main_system_tag && sub_system_tag) { if (main_system_tag && sub_system_tag) {
dispatch(changeMainSubSys({ main_system_tag, sub_system_tag }))
dispatch(fetchSelectedDeviceMenu({ main_system_tag, sub_system_tag })); dispatch(fetchSelectedDeviceMenu({ main_system_tag, sub_system_tag }));
dispatch(fetchSelectedDeviceList({ sub_system_tag })); dispatch(fetchSelectedDeviceList({ sub_system_tag }));
dispatch(fetchSelectedDevFlTags({ sub_system_tag })); dispatch(fetchSelectedDevFlTags({ sub_system_tag }));
} }
// 載入資料 // 載入資料
}, [main_system_tag, sub_system_tag, selectedBuiTag]); }, [main_system_tag, sub_system_tag]);
// 只顯示指定的設備
// 取得所有 forge dbid
const getAllDbIds = (model) => {
const instanceTree = model.getInstanceTree();
const allDbIdsStr = Object.keys(instanceTree.nodeAccess.dbIdToIndex);
return allDbIdsStr.map(id => parseInt(id));
}
useEffect(() => {
if (model && selectedDeviceList.length !== 0) {
console.log(model)
const allDbIds = getAllDbIds(model)
viewer.hide(allDbIds)
const showDbIds = selectedDeviceList.map((d) => parseInt(d.forge_dbid))
let showNodeDbId = [];
selectedDeviceList.forEach(({ device_nodes }) => {
showNodeDbId = [...showNodeDbId, ...device_nodes.map(({ forge_dbid }) => forge_dbid)]
})
viewer.show([...showDbIds, ...showNodeDbId])
}
}, [model, selectedDeviceList])
return ( return (
<> <>
<Container <Container
@ -60,12 +83,13 @@ function Monitor() {
<Col md={1}> <Col md={1}>
<Button className="px-4 py-2 text-white">{floor_tag}</Button> <Button className="px-4 py-2 text-white">{floor_tag}</Button>
</Col> </Col>
<Col className="d-flex justify-content-evenly align-items-center flex-wrap"> <Col className="d-flex justify-content-start align-items-center flex-wrap">
{selectedDeviceList.map(({ device_guid, full_name, forge_dbid }) => ( {selectedDeviceList.map(({ device_guid, full_name, forge_dbid, device_floor }) => (
<Card device_floor === floor_tag ?
<Card
bg="dark" bg="dark"
key={device_guid} key={device_guid}
className="mb-3" className="mb-3 ms-4"
style={{ maxWidth: "45%" }} style={{ maxWidth: "45%" }}
> >
<Card.Body> <Card.Body>
@ -77,13 +101,14 @@ function Monitor() {
<span className="text-secondary me-4">功率 kW</span> <span className="text-secondary me-4">功率 kW</span>
<Card.Link <Card.Link
className="text-white text-decoration-none" className="text-white text-decoration-none"
data-forgeId={forge_dbid} data-forgeid={forge_dbid}
> >
詳細內容 詳細內容
</Card.Link> </Card.Link>
</Card.Text> </Card.Text>
</Card.Body> </Card.Body>
</Card> </Card> :
<></>
))} ))}
</Col> </Col>
</Row> </Row>
@ -91,7 +116,7 @@ function Monitor() {
)} )}
</Col> </Col>
<Col md={6}> <Col md={6}>
<ForgeModel forgeHeight="90vh" sprites={selectedDeviceList} /> <ForgeModel forgeHeight="90vh" deviceList={ selectedDeviceList } />
</Col> </Col>
</Row> </Row>
</Container> </Container>

View File

@ -1,13 +0,0 @@
const reportWebVitals = onPerfEntry => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View File

@ -20,8 +20,8 @@ const routes = [
/(?:(?:^|.*;\s*)JWT-Authorization\s*\=\s*([^;]*).*$)|^.*$/, /(?:(?:^|.*;\s*)JWT-Authorization\s*\=\s*([^;]*).*$)|^.*$/,
"$1", "$1",
); );
if (window.location.href.includes("localhost:3000") && !JWT_Authorization) {
console.log(JWT_Authorization); console.log(JWT_Authorization);
if (window.location.href.includes("localhost:3000") && !JWT_Authorization) {
return redirect("/login"); return redirect("/login");
} else if (window.location.href.includes("http://220.132.206.5") && !JWT_Authorization) { } else if (window.location.href.includes("http://220.132.206.5") && !JWT_Authorization) {
const account = await setUserAccountByBaja(); const account = await setUserAccountByBaja();

View File

@ -1,5 +0,0 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

View File

@ -16,7 +16,7 @@ const buildingSlice = createSlice({
buildingList: ["中凌大樓"], buildingList: ["中凌大樓"],
urn_3D: "", urn_3D: "",
selectedBuiArea: "TPE", selectedBuiArea: "TPE",
selectedBuiTag: "", selectedBuiTag: "B1",
selectedBuiFullName: "", selectedBuiFullName: "",
errMsg: "", errMsg: "",
}, },

View File

@ -3,6 +3,7 @@ import axios from "axios";
import { deviceBuiMenuBaseUrl, deviceListBaseUrl, deviceFloorBaseUrl } from "@CON"; import { deviceBuiMenuBaseUrl, deviceListBaseUrl, deviceFloorBaseUrl } from "@CON";
import { ajaxRes } from "@UTIL"; import { ajaxRes } from "@UTIL";
// 獲取小類中總覽資料
export const fetchSelectedDeviceMenu = createAsyncThunk( export const fetchSelectedDeviceMenu = createAsyncThunk(
"deviceList/fetchSelectedDeviceMenu", "deviceList/fetchSelectedDeviceMenu",
async ({ main_system_tag, sub_system_tag }, thunkAPI) => { async ({ main_system_tag, sub_system_tag }, thunkAPI) => {
@ -29,14 +30,12 @@ export const fetchSelectedDeviceList = createAsyncThunk(
if (code !== "0000" || !data) { if (code !== "0000" || !data) {
return rejectWithValue(msg); return rejectWithValue(msg);
} else { } else {
console.log(data)
let results=[]; let results=[];
data.forEach((p) => { data.forEach((p) => {
p.device_list.forEach((d) => { p.device_list.forEach((d) => {
results.push({ ...d, device_floor: p.full_name }); results.push({ ...d, device_floor: p.full_name });
}); });
}); });
console.log("v", [...results]);
return fulfillWithValue([...results]); return fulfillWithValue([...results]);
} }
}, },
@ -66,16 +65,30 @@ const deviceListSlice = createSlice({
selectedDeviceMaster: "", // BANK1 selectedDeviceMaster: "", // BANK1
selectedDeviceLastName: "", // ELEV selectedDeviceLastName: "", // ELEV
selectedDeviceSerialTag: "", // N1 selectedDeviceSerialTag: "", // N1
tempsensorDevList: [],
}, },
reducers: { reducers: {
getAllDevice: (state, action) => {}, getAllDevice: (state, action) => { },
getCurDeviceTemp: (state, { payload }) => {
const { device_number, temp } = payload;
state.tempsensorDevList = state.tempsensorDevList.map((sensor) => {
if (sensor.some(s => s.device_number == device_number)) {
return { ...sensor, temp }
}
return sensor
})
},
changeMainSubSys: (state, { payload }) => {
const { main_system_tag, sub_system_tag } = payload;
state.selectedDeviceSysTag = main_system_tag;
state.selectedDeviceNameTag = sub_system_tag;
}
}, },
extraReducers: (builder) => { extraReducers: (builder) => {
builder.addCase(fetchSelectedDeviceMenu.fulfilled, (state, { payload }) => { builder.addCase(fetchSelectedDeviceMenu.fulfilled, (state, { payload }) => {
state.selectedDeviceMenu = payload; state.selectedDeviceMenu = payload;
}); });
builder.addCase(fetchSelectedDeviceList.fulfilled, (state, { payload }) => { builder.addCase(fetchSelectedDeviceList.fulfilled, (state, { payload }) => {
console.log("de", payload);
state.selectedDeviceList = payload; state.selectedDeviceList = payload;
}); });
@ -88,5 +101,5 @@ const deviceListSlice = createSlice({
}); });
const { reducer, actions } = deviceListSlice; const { reducer, actions } = deviceListSlice;
export const { getAllDevice } = actions; export const { getCurDeviceTemp, changeMainSubSys } = actions;
export default reducer; export default reducer;

View File

@ -6,7 +6,7 @@ export const fetchForge = createAsyncThunk(
async ({ viewerEl, urn }, { dispatch, fulfillWithValue, rejectWithValue }) => { async ({ viewerEl, urn }, { dispatch, fulfillWithValue, rejectWithValue }) => {
const res = await forgeInit(viewerEl); const res = await forgeInit(viewerEl);
if (res.ok) { if (res.ok) {
modelLoad(res.viewer, urn, dispatch); await modelLoad(res.viewer, urn, dispatch);
return fulfillWithValue(res.viewer); return fulfillWithValue(res.viewer);
} else { } else {
return rejectWithValue(res.errCode); return rejectWithValue(res.errCode);
@ -18,8 +18,10 @@ const forgeSlice = createSlice({
name: "forge", name: "forge",
initialState: { initialState: {
viewer: null, viewer: null,
model: null,
dataVizExtn: null, dataVizExtn: null,
DataVizCore: null, DataVizCore: null,
structureInfo: null,
errCode: 0, errCode: 0,
urn_3D: "", urn_3D: "",
}, },
@ -27,6 +29,14 @@ const forgeSlice = createSlice({
loadDataVizExtn: (state, { payload }) => { loadDataVizExtn: (state, { payload }) => {
state.dataVizExtn = payload; state.dataVizExtn = payload;
state.DataVizCore = window.Autodesk.DataVisualization.Core; state.DataVizCore = window.Autodesk.DataVisualization.Core;
// heatmap
state.structureInfo = new window.Autodesk.DataVisualization.Core.ModelStructureInfo(state.model);
},
loadStructureInfo: (state, { payload }) => {
state.structureInfo = payload
},
loadModel: (state, { payload }) => {
state.model = payload
}, },
shutdownForge: (state, action) => { shutdownForge: (state, action) => {
state.viewer?.finish(); state.viewer?.finish();
@ -46,5 +56,5 @@ const forgeSlice = createSlice({
}); });
const { reducer, actions } = forgeSlice; const { reducer, actions } = forgeSlice;
export const { shutdownForge, loadDataVizExtn } = actions; export const { shutdownForge, loadDataVizExtn, loadModel } = actions;
export default reducer; export default reducer;

View File

@ -5,8 +5,10 @@ import device, {
fetchSelectedDeviceList, fetchSelectedDeviceList,
fetchSelectedDeviceMenu, fetchSelectedDeviceMenu,
fetchSelectedDevFlTags, fetchSelectedDevFlTags,
getCurDeviceTemp,
changeMainSubSys,
} from "./deviceListSlice"; } from "./deviceListSlice";
import forgeViewer, { fetchForge, loadDataVizExtn, shutdownForge } from "./forgeSlice"; import forgeViewer, { fetchForge, loadDataVizExtn, loadModel, shutdownForge } from "./forgeSlice";
import system, { fetchSysMainSub } from "./systemSlice"; import system, { fetchSysMainSub } from "./systemSlice";
import user, { fetchUserInfo, fetchUserAuthPages } from "./userSlice"; import user, { fetchUserInfo, fetchUserAuthPages } from "./userSlice";
import alarm, { fetchBuiAlarmStateByBaja } from "./alarmSlice"; import alarm, { fetchBuiAlarmStateByBaja } from "./alarmSlice";
@ -40,16 +42,25 @@ export default store;
export { export {
fetchBuiList, fetchBuiList,
changeBuilding, changeBuilding,
fetchSelectedDeviceList, fetchSelectedDeviceList,
fetchSelectedDeviceMenu, fetchSelectedDeviceMenu,
fetchSelectedDevFlTags, fetchSelectedDevFlTags,
getCurDeviceTemp,
changeMainSubSys,
fetchForge, fetchForge,
loadDataVizExtn, loadDataVizExtn,
loadModel,
shutdownForge, shutdownForge,
fetchSysMainSub, fetchSysMainSub,
fetchUserInfo, fetchUserInfo,
fetchUserAuthPages, fetchUserAuthPages,
fetchBuiAlarmStateByBaja, fetchBuiAlarmStateByBaja,
fetchInitElecMeterByBaja, fetchInitElecMeterByBaja,
getElectricMeter, getElectricMeter,
getHourElectricMeter, getHourElectricMeter,

View File

@ -14,7 +14,8 @@ export async function getBuiAlarmStateByBaja(area_tag, building_tag) {
const { msgText, sourceName } = this.get("alarmData").$map.$map; const { msgText, sourceName } = this.get("alarmData").$map.$map;
const { $enc: ackState } = this.get("ackState").getType(); const { $enc: ackState } = this.get("ackState").getType();
const { $enc: sourceState } = this.get("sourceState").getType(); const { $enc: sourceState } = this.get("sourceState").getType();
if (ackState !== "acked" && sourceState !== "normal") { // 在選單上的顯示警告,只須出現在緊急的 offnormal 設備
if (sourceState !== "normal") {
result.push({ result.push({
msgText, msgText,
sourceName, sourceName,

View File

@ -0,0 +1,12 @@
export function PointSubscribe(baja, sub, ordPath, pointName) {
// ord 為要訂閱的點位
baja.Ord.make(`local:|foxs:|station:|slot:/${ordPath}`)
.get()
.then(folder => {
folder.getSlots().is("control:NumericWritable").eachValue((point) => {
if (point.getDisplayName() === pointName) {
baja.Ord.make(`local:|foxs:|station:|slot:/${ordPath}/${pointName}`).get({ subscriber: sub })
}
})
})
}

View File

@ -1,26 +1,35 @@
import { getCurDeviceTemp } from "@STORE"
import { roundDecimal } from "@UTIL";
// 訂閱設備 // 訂閱設備
// 針對數值的點位 // 針對數值的點位
export function SubscribeDeviceByBaja(ord) { export function SubscribeDeviceTempByBaja(ordPath, dispatch) {
window.require && window.require &&
window.requirejs(["baja!"], (baja) => { window.requirejs(["baja!"], (baja) => {
console.log("進入 bajaSubscriber 準備執行BQL訂閱"); console.log("進入 bajaSubscriber 準備執行BQL訂閱");
const sub = new baja.subscriber(); const sub = new baja.Subscriber();
sub.attach("changed", (prop, cx) => { function passValueToFront(temp) {
console.log(prop, cx); dispatch(getCurDeviceTemp({ device_number: ordPath, temp }))
}); }
sub.attach("changed", (prop) => {
if (prop && prop.$displayName === "Out") {
passValueToFront(prop.$getValue().getValueDisplay())
}
})
sub.attach("subscribed", (prop) => {
if (prop && prop.$displayName === "Out") {
passValueToFront(prop.$getValue().getValueDisplay())
}
})
// ord 為要訂閱的點位 // ord 為要訂閱的點位
baja.Ord.make(ord) // ord 為要訂閱的點位
.get({ baja.Ord.make(`local:|foxs:|station:|slot:/${ordPath}`)
subscriber: sub, .get()
// cursor 對返回的數據做處理 .then(folder => {
cursor: { folder.getSlots().is("control:NumericWritable").eachValue((point) => {
before: function () {}, if (point.getDisplayName() === "Temp" || point.getDisplayName() === "TEMP") {
each: function () {}, baja.Ord.make(`local:|foxs:|station:|slot:/${ordPath}/${point.getDisplayName()}`).get({ subscriber: sub })
after: function () {}, }
}, })
}) })
.then((point) => { })
console.log(point);
});
});
} }

View File

@ -89,30 +89,34 @@ export async function getCurPower(ordPath, dispatch) {
window.require && window.require &&
window.require(["baja!"], function (baja) { window.require(["baja!"], function (baja) {
const sub = new baja.Subscriber(); const sub = new baja.Subscriber();
sub.attach("changed", function (prop) { function passValueToFront(value) {
const value = roundDecimal(this.get("out").getValue()); const newValue = roundDecimal(value);
dispatch( dispatch(
getCurElectricity([ getCurElectricity([
{ data: value, text: "即時功率 " }, { data: newValue, text: "即時功率 " },
{ data: roundDecimal(value / 4), text: "即時契約容量占比 " }, { data: roundDecimal(newValue / 4), text: "即時契約容量占比 " },
]), ]),
); );
}
sub.attach("changed", function (prop) {
if (prop && prop.$displayName === "Out") {
passValueToFront(prop.$getValue().getValueDisplay())
}
})
sub.attach("subscribed", function (prop) {
if (prop && prop.$displayName === "Out") {
passValueToFront(prop.$getValue().getValueDisplay())
}
}); });
// ord 為要訂閱的點位
baja.Ord.make(`local:|foxs:|station:|slot:/${ordPath}`) baja.Ord.make(`local:|foxs:|station:|slot:/${ordPath}`)
.get() .get()
.then((folder) => { .then(folder => {
folder folder.getSlots().is("control:NumericWritable").eachValue((point) => {
.getSlots() if (point.getDisplayName() === "P") {
.is("control:NumericWritable") baja.Ord.make(`local:|foxs:|station:|slot:/${ordPath}/${point.getDisplayName() }`).get({ subscriber: sub })
.eachValue((point) => { }
if (point.getDisplayName() === "P") { })
baja.Ord.make( })
`local:|foxs:|station:|slot:/TPE/B1/EE/E4/R2F/NA/WHT/N1/${point.getDisplayName()}`,
).get({
subscriber: sub,
});
}
});
});
}); });
} }

View File

@ -1,5 +1,5 @@
import { getBuiAlarmStateByBaja, getDeviceAlarmByBaja } from "./alarmBaja"; import { getBuiAlarmStateByBaja, getDeviceAlarmByBaja } from "./alarmBaja";
import { SubscribeDeviceByBaja } from "./deviceBaja"; import { SubscribeDeviceTempByBaja } from "./deviceBaja";
import { getTotalElectricByBaja, getCurPower } from "./electricityBaja"; import { getTotalElectricByBaja, getCurPower } from "./electricityBaja";
// 下載 N4 內置requireJS // 下載 N4 內置requireJS
function loadRequireJS() { function loadRequireJS() {
@ -25,10 +25,14 @@ function setUserAccountByBaja(callBackFunc = null) {
export { export {
loadRequireJS, loadRequireJS,
// 使用者
setUserAccountByBaja, setUserAccountByBaja,
// alarm
getBuiAlarmStateByBaja, getBuiAlarmStateByBaja,
getDeviceAlarmByBaja, getDeviceAlarmByBaja,
SubscribeDeviceByBaja, // device
SubscribeDeviceTempByBaja,
// eletricity
getTotalElectricByBaja, getTotalElectricByBaja,
getCurPower, getCurPower,
}; };

View File

@ -1,5 +1,5 @@
import { forgeTokenBaseUrl } from "@CON"; import { forgeTokenBaseUrl } from "@CON";
import { loadDataVizExtn } from "@STORE"; import { loadDataVizExtn, loadModel } from "@STORE";
// 載入 forgeCss 樣式 // 載入 forgeCss 樣式
function loadForgeCss(src) { function loadForgeCss(src) {
const link = document.createElement("link"); const link = document.createElement("link");
@ -72,15 +72,19 @@ export function modelLoad(viewer, urn, dispatch) {
const documentId = `urn:${urn}`; const documentId = `urn:${urn}`;
window.Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure); window.Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
function onDocumentLoadSuccess(viewerDocument) { async function onDocumentLoadSuccess(viewerDocument) {
var defaultModel = viewerDocument.getRoot().getDefaultGeometry(); var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(viewerDocument, defaultModel); viewer.loadDocumentNode(viewerDocument, defaultModel);
viewer.addEventListener(window.Autodesk.Viewing.GEOMETRY_LOADED_EVENT, async function () { viewer.addEventListener(window.Autodesk.Viewing.GEOMETRY_LOADED_EVENT, async ()=> {
// 取得所有 forge dbid console.log(viewer.model)
const allDbIds = getAllDbIds(this); dispatch(loadModel(viewer.model))
const dataVizExtn = await viewer.loadExtension("Autodesk.DataVisualization"); // sprites
dispatch(loadDataVizExtn(dataVizExtn)); const dataVizExtn = await viewer.loadExtension("Autodesk.DataVisualization");
dispatch(loadDataVizExtn(dataVizExtn));
// heatmap
//const structureInfo = new window.Autodesk.DataVisualization.Core.ModelStructureInfo(viewer.model);
//dispatch(loadStructureInfo(structureInfo));
}); });
} }
@ -89,13 +93,4 @@ export function modelLoad(viewer, urn, dispatch) {
} }
} }
// 取得 forge dbid
function getAllDbIds(viewer) {
var instanceTree = viewer.model?.getData().instanceTree;
var allDbIdsStr = Object.keys(instanceTree.nodeAccess.dbIdToIndex);
return allDbIdsStr.map(function (id) {
return parseInt(id);
});
}

View File

@ -1,9 +1,13 @@
import { import {
loadRequireJS, loadRequireJS,
// 使用者
setUserAccountByBaja, setUserAccountByBaja,
// alarm
getBuiAlarmStateByBaja, getBuiAlarmStateByBaja,
getDeviceAlarmByBaja, getDeviceAlarmByBaja,
SubscribeDeviceByBaja, // device
SubscribeDeviceTempByBaja,
// eletricity
getTotalElectricByBaja, getTotalElectricByBaja,
getCurPower, getCurPower,
} from "./baja/index"; } from "./baja/index";
@ -14,10 +18,14 @@ import { userLogin } from "./login";
import { roundDecimal } from "./math"; import { roundDecimal } from "./math";
export { export {
loadRequireJS, loadRequireJS,
// 使用者
setUserAccountByBaja, setUserAccountByBaja,
// alarm
getBuiAlarmStateByBaja, getBuiAlarmStateByBaja,
getDeviceAlarmByBaja, getDeviceAlarmByBaja,
SubscribeDeviceByBaja, // device
SubscribeDeviceTempByBaja,
// eletricity
getTotalElectricByBaja, getTotalElectricByBaja,
getCurPower, getCurPower,
forgeInit, forgeInit,