更新历史数据面板显示和设计;更新scada数据全部清洗api数据格式;更新scada数据显示模拟数据;更新scada数据面板,非清洗状态下能显示两条数据;新增注释,未来准备修复矢量瓦片样式更新时闪烁的问题;

This commit is contained in:
JIANG
2025-12-15 17:40:05 +08:00
parent 2fc9075cce
commit fd064f3aa9
5 changed files with 437 additions and 413 deletions

View File

@@ -7,41 +7,29 @@ import {
Chip,
CircularProgress,
Divider,
IconButton,
Stack,
Tab,
Tabs,
Tooltip,
Typography,
Drawer,
Slider,
} from "@mui/material";
import {
Refresh,
ShowChart,
TableChart,
ChevronLeft,
ChevronRight,
} from "@mui/icons-material";
import { Refresh, ShowChart, TableChart } from "@mui/icons-material";
import { DataGrid, GridColDef } from "@mui/x-data-grid";
import { LineChart } from "@mui/x-charts";
import ReactECharts from "echarts-for-react";
import * as echarts from "echarts";
import "dayjs/locale/zh-cn"; // 引入中文包
import dayjs, { Dayjs } from "dayjs";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { DateTimePicker, LocalizationProvider } from "@mui/x-date-pickers";
import config, { NETWORK_NAME } from "@/config/config";
import config from "@/config/config";
import { GeoJSON } from "ol/format";
dayjs.extend(utc);
dayjs.extend(timezone);
type IUser = {
id: number;
name: string;
};
export interface TimeSeriesPoint {
/** ISO8601 时间戳 */
timestamp: string;
@@ -49,23 +37,14 @@ export interface TimeSeriesPoint {
values: Record<string, number | null | undefined>;
}
export interface HistoryDataPanelProps {
/** 选中的设备 ID 列表(使用 `ids` 代替,组件不再接收 `deviceIds` */
/** 设备列表:每项包含 id 与可选的 type例如 'scada' / 'simulation' */
devices?: { id: string; type?: string }[];
/** 可选:外部传入的开始时间(若传入会作为默认值) */
starttime?: string | Date;
/** 可选:外部传入的结束时间(若传入会作为默认值) */
endtime?: string | Date;
/** 可选:方案名(用于 scheme 类型的查询) */
schemeName?: string;
export interface SCADADataPanelProps {
/** 选中的设备 ID 列表 */
deviceIds: string[];
/** 自定义数据获取器,默认使用后端 API */
fetchTimeSeriesData?: (
deviceIds: string[],
range: { from: Date; to: Date }
) => Promise<TimeSeriesPoint[]>;
/** 可选:控制浮窗显示 */
visible?: boolean;
/** 默认展示的选项卡 */
defaultTab?: "chart" | "table";
/** Y 轴数值的小数位数 */
@@ -87,30 +66,53 @@ const fetchFromBackend = async (
return [];
}
const ids = deviceIds.join(",");
const starttime = dayjs(range.from).format("YYYY-MM-DD HH:mm:ss");
const endtime = dayjs(range.to).format("YYYY-MM-DD HH:mm:ss");
// 原始数据接口(清洗功能已移除)
const rawSCADAUrl = `${config.BACKEND_URL}/queryscadadatabydeviceidandtimerange/?ids=${ids}&starttime=${starttime}&endtime=${endtime}`;
// 模拟数据接口(备用)
const simulationSCADAUrl = `${config.BACKEND_URL}/querysimulationscadadatabydeviceidandtimerange/?ids=${ids}&starttime=${starttime}&endtime=${endtime}`;
const device_ids = deviceIds.join(",");
const start_time = dayjs(range.from).toISOString();
const end_time = dayjs(range.to).toISOString();
// 清洗数据接口
const cleaningDataUrl = `${config.BACKEND_URL}/timescaledb/scada/by-ids-field-time-range?device_ids=${device_ids}&field=cleaned_value&start_time=${start_time}&end_time=${end_time}`;
// 原始数据
const rawDataUrl = `${config.BACKEND_URL}/timescaledb/scada/by-ids-field-time-range?device_ids=${device_ids}&field=monitored_value&start_time=${start_time}&end_time=${end_time}`;
// 模拟数据接口
const simulationDataUrl = `${config.BACKEND_URL}/timescaledb/composite/scada-simulation?device_ids=${device_ids}&start_time=${start_time}&end_time=${end_time}`;
try {
// 先使用原始数据接口
let response = await fetch(rawSCADAUrl);
if (!response.ok) {
console.warn(
`[SCADADataPanel] 原始数据接口返回非 OK${response.status}, 尝试模拟接口`
// 优先查询清洗数据和模拟数据
const [cleaningRes, simulationRes] = await Promise.all([
fetch(cleaningDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null),
fetch(simulationDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null),
]);
const cleaningData = transformBackendData(cleaningRes, deviceIds);
const simulationData = transformBackendData(simulationRes, deviceIds);
// 如果清洗数据有数据,返回清洗和模拟数据
if (cleaningData.length > 0) {
return mergeTimeSeriesData(
cleaningData,
simulationData,
deviceIds,
"clean",
"sim"
);
} else {
// 如果清洗数据没有数据,查询原始数据,返回模拟和原始数据
const rawRes = await fetch(rawDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null);
const rawData = transformBackendData(rawRes, deviceIds);
return mergeTimeSeriesData(
simulationData,
rawData,
deviceIds,
"sim",
"raw"
);
// 尝试模拟接口
response = await fetch(simulationSCADAUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
}
const data = await response.json();
const transformedData = transformBackendData(data, deviceIds);
return transformedData;
} catch (error) {
console.error("[SCADADataPanel] 从后端获取数据失败:", error);
throw error;
@@ -172,6 +174,48 @@ const transformBackendData = (
return [];
};
/**
* 合并两个时间序列数据,为每个设备添加后缀
*/
const mergeTimeSeriesData = (
data1: TimeSeriesPoint[],
data2: TimeSeriesPoint[],
deviceIds: string[],
suffix1: string,
suffix2: string
): TimeSeriesPoint[] => {
const timeMap = new Map<string, Record<string, number | null>>();
const processData = (data: TimeSeriesPoint[], suffix: string) => {
data.forEach((point) => {
if (!timeMap.has(point.timestamp)) {
timeMap.set(point.timestamp, {});
}
const values = timeMap.get(point.timestamp)!;
deviceIds.forEach((deviceId) => {
const value = point.values[deviceId];
if (value !== undefined) {
values[`${deviceId}_${suffix}`] = value;
}
});
});
};
processData(data1, suffix1);
processData(data2, suffix2);
const result = Array.from(timeMap.entries()).map(([timestamp, values]) => ({
timestamp,
values,
}));
result.sort(
(a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
);
return result;
};
const defaultFetcher = fetchFromBackend;
const formatTimestamp = (timestamp: string) =>
@@ -199,13 +243,18 @@ const buildDataset = (
};
deviceIds.forEach((id) => {
const value = point.values[id];
entry[id] =
typeof value === "number"
? Number.isFinite(value)
? parseFloat(value.toFixed(fractionDigits))
: null
: value ?? null;
["raw", "clean", "sim"].forEach((suffix) => {
const key = `${id}_${suffix}`;
const value = point.values[key];
if (value !== undefined && value !== null) {
entry[key] =
typeof value === "number"
? Number.isFinite(value)
? parseFloat(value.toFixed(fractionDigits))
: null
: value ?? null;
}
});
});
return entry;
@@ -226,38 +275,26 @@ const emptyStateMessages: Record<
},
};
const HistoryDataPanel: React.FC<HistoryDataPanelProps> = ({
devices = [],
starttime,
endtime,
schemeName,
const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
deviceIds,
fetchTimeSeriesData = defaultFetcher,
visible = true,
defaultTab = "chart",
fractionDigits = 3,
fractionDigits = 2,
}) => {
// 从 devices 中提取 id 列表用于渲染与查询
const deviceIds = devices?.map((d) => d.id) ?? [];
const customFetcher = useMemo(() => {
return fetchTimeSeriesData;
}, [fetchTimeSeriesData]);
// 清洗功能已移除,直接使用传入的 fetcher
const customFetcher = fetchTimeSeriesData;
const [from, setFrom] = useState<Dayjs>(() =>
starttime ? dayjs(starttime) : dayjs().subtract(1, "day")
);
const [to, setTo] = useState<Dayjs>(() =>
endtime ? dayjs(endtime) : dayjs()
);
const [from, setFrom] = useState<Dayjs>(() => dayjs().subtract(1, "day"));
const [to, setTo] = useState<Dayjs>(() => dayjs());
const [activeTab, setActiveTab] = useState<PanelTab>(defaultTab);
const [timeSeries, setTimeSeries] = useState<TimeSeriesPoint[]>([]);
const [loadingState, setLoadingState] = useState<LoadingState>("idle");
const [error, setError] = useState<string | null>(null);
const [isExpanded, setIsExpanded] = useState<boolean>(true);
const [deviceLabels, setDeviceLabels] = useState<Record<string, string>>({});
// 清洗相关状态移除
// 滑块状态:用于图表缩放
const [zoomRange, setZoomRange] = useState<[number, number]>([0, 100]);
const [selectedSource, setSelectedSource] = useState<
"raw" | "clean" | "sim" | "all"
>(() => (deviceIds.length === 1 ? "all" : "clean"));
// 获取 SCADA 设备信息,生成 deviceLabels
useEffect(() => {
@@ -303,21 +340,6 @@ const HistoryDataPanel: React.FC<HistoryDataPanelProps> = ({
[timeSeries, deviceIds, fractionDigits]
);
// 根据滑块范围过滤数据集
const filteredDataset = useMemo(() => {
if (dataset.length === 0) return dataset;
const startIndex = Math.floor((zoomRange[0] / 100) * dataset.length);
const endIndex = Math.ceil((zoomRange[1] / 100) * dataset.length);
return dataset.slice(startIndex, endIndex);
}, [dataset, zoomRange]);
// 重置滑块范围当数据变化时
useEffect(() => {
setZoomRange([0, 100]);
}, [timeSeries]);
const handleFetch = useCallback(
async (reason: string) => {
if (!hasDevices) {
@@ -354,6 +376,13 @@ const HistoryDataPanel: React.FC<HistoryDataPanelProps> = ({
}
}, [deviceIds.join(",")]);
// 当设备数量变化时,调整数据源选择
useEffect(() => {
if (deviceIds.length > 1 && selectedSource === "all") {
setSelectedSource("clean");
}
}, [deviceIds.length, selectedSource]);
const columns: GridColDef[] = useMemo(() => {
const base: GridColDef[] = [
{
@@ -364,22 +393,24 @@ const HistoryDataPanel: React.FC<HistoryDataPanelProps> = ({
},
];
const dynamic = deviceIds.map<GridColDef>((id) => ({
field: id,
headerName: deviceLabels?.[id] ?? id,
minWidth: 140,
flex: 1,
valueFormatter: (value: any) => {
if (value === null || value === undefined) return "--";
if (Number.isFinite(Number(value))) {
return Number(value).toFixed(fractionDigits);
}
return String(value);
},
}));
const dynamic = (() => {
return deviceIds.map<GridColDef>((id) => ({
field: id,
headerName: deviceLabels?.[id] ?? id,
minWidth: 140,
flex: 1,
valueFormatter: (value: any) => {
if (value === null || value === undefined) return "--";
if (Number.isFinite(Number(value))) {
return Number(value).toFixed(fractionDigits);
}
return String(value);
},
}));
})();
return [...base, ...dynamic];
}, [deviceIds, deviceLabels, fractionDigits]);
}, [deviceIds, deviceLabels, fractionDigits, selectedSource]);
const rows = useMemo(
() =>
@@ -435,17 +466,120 @@ const HistoryDataPanel: React.FC<HistoryDataPanelProps> = ({
"#3f51b5", // 靛蓝色
];
// 获取当前显示范围的时间边界
const getTimeRangeLabel = () => {
if (filteredDataset.length === 0) return "";
const firstTime = filteredDataset[0].time;
const lastTime = filteredDataset[filteredDataset.length - 1].time;
if (firstTime instanceof Date && lastTime instanceof Date) {
return `${dayjs(firstTime).format("MM-DD HH:mm")} ~ ${dayjs(
lastTime
).format("MM-DD HH:mm")}`;
}
return "";
const xData = dataset.map((item) => item.label);
const getSeries = () => {
return deviceIds.flatMap((id, index) => {
const series = [];
["raw", "clean", "sim"].forEach((suffix, sIndex) => {
const key = `${id}_${suffix}`;
const hasData = dataset.some(
(item) => item[key] !== null && item[key] !== undefined
);
if (hasData) {
series.push({
name: `${deviceLabels?.[id] ?? id} (${
suffix === "raw" ? "原始" : suffix === "clean" ? "清洗" : "模拟"
})`,
type: "line",
symbol: "none",
sampling: "lttb",
itemStyle: {
color: colors[(index * 3 + sIndex) % colors.length],
},
data: dataset.map((item) => item[key]),
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{
offset: 0,
color: colors[(index * 3 + sIndex) % colors.length],
},
{
offset: 1,
color: "rgba(255, 255, 255, 0)",
},
]),
opacity: 0.3,
},
});
}
});
// 如果没有clean/raw/sim数据则使用fallback
if (series.length === 0) {
series.push({
name: deviceLabels?.[id] ?? id,
type: "line",
symbol: "none",
sampling: "lttb",
itemStyle: { color: colors[index % colors.length] },
data: dataset.map((item) => item[id]),
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{
offset: 0,
color: colors[index % colors.length],
},
{
offset: 1,
color: "rgba(255, 255, 255, 0)",
},
]),
opacity: 0.3,
},
});
}
return series;
});
};
const option = {
// animation: false,
animationDuration: 500,
tooltip: {
trigger: "axis",
confine: true,
position: function (pt: any[]) {
return [pt[0], "10%"];
},
},
legend: {
top: "top",
},
grid: {
left: "5%",
right: "5%",
bottom: "11%",
containLabel: true,
},
toolbox: {
feature: {
dataZoom: {
yAxisIndex: "none",
},
restore: {},
saveAsImage: {},
},
},
xAxis: {
type: "category",
boundaryGap: false,
data: xData,
},
yAxis: {
type: "value",
scale: true,
},
dataZoom: [
{
type: "inside",
start: 0,
end: 100,
},
{
start: 0,
end: 100,
},
],
series: getSeries(),
};
return (
@@ -455,181 +589,15 @@ const HistoryDataPanel: React.FC<HistoryDataPanelProps> = ({
height: "100%",
display: "flex",
flexDirection: "column",
overflow: "hidden",
}}
>
<Box sx={{ flex: 1 }}>
<LineChart
dataset={filteredDataset}
height={480}
margin={{ left: 70, right: 40, top: 30, bottom: 90 }}
xAxis={[
{
dataKey: "time",
scaleType: "time",
valueFormatter: (value) =>
value instanceof Date
? dayjs(value).format("MM-DD HH:mm")
: String(value),
tickLabelStyle: {
angle: -45,
textAnchor: "end",
fontSize: 11,
fill: "#666",
},
},
]}
yAxis={[
{
label: "压力/流量值",
labelStyle: {
fontSize: 13,
fill: "#333",
fontWeight: 500,
},
tickLabelStyle: {
fontSize: 11,
fill: "#666",
},
},
]}
series={deviceIds.map((id, index) => ({
dataKey: id,
label: deviceLabels?.[id] ?? id,
showMark: dataset.length < 50,
curve: "catmullRom",
color: colors[index % colors.length],
valueFormatter: (value: number | null) =>
value !== null ? value.toFixed(fractionDigits) : "--",
area: false,
stack: undefined,
}))}
grid={{ vertical: true, horizontal: true }}
sx={{
"& .MuiLineElement-root": {
strokeWidth: 2.5,
strokeLinecap: "round",
strokeLinejoin: "round",
},
"& .MuiMarkElement-root": {
scale: "0.8",
strokeWidth: 2,
},
"& .MuiChartsAxis-line": {
stroke: "#e0e0e0",
strokeWidth: 1,
},
"& .MuiChartsAxis-tick": {
stroke: "#e0e0e0",
strokeWidth: 1,
},
"& .MuiChartsGrid-line": {
stroke: "#d0d0d0",
strokeWidth: 0.8,
strokeDasharray: "4 4",
},
}}
slotProps={{
legend: {
direction: "row",
position: { horizontal: "middle", vertical: "bottom" },
padding: { bottom: 2, left: 0, right: 0 },
itemMarkWidth: 16,
itemMarkHeight: 3,
markGap: 8,
itemGap: 16,
labelStyle: {
fontSize: 12,
fill: "#333",
fontWeight: 500,
},
},
loadingOverlay: {
style: { backgroundColor: "rgba(255, 255, 255, 0.7)" },
},
}}
tooltip={{
trigger: "axis",
}}
/>
</Box>
{/* 时间范围滑块 */}
<Box sx={{ px: 3, pb: 2, pt: 1 }}>
<Stack direction="row" spacing={2} alignItems="center">
<Typography
variant="body2"
sx={{ minWidth: 60, color: "text.secondary", fontSize: "0.8rem" }}
>
</Typography>
<Slider
value={zoomRange}
onChange={(_, newValue) =>
setZoomRange(newValue as [number, number])
}
valueLabelDisplay="auto"
valueLabelFormat={(value) => {
const index = Math.floor((value / 100) * dataset.length);
if (dataset[index] && dataset[index].time instanceof Date) {
return dayjs(dataset[index].time).format("MM-DD HH:mm");
}
return `${value}%`;
}}
marks={[
{
value: 0,
label:
dataset.length > 0 && dataset[0].time instanceof Date
? dayjs(dataset[0].time).format("MM-DD HH:mm")
: "起始",
},
{
value: 100,
label:
dataset.length > 0 &&
dataset[dataset.length - 1].time instanceof Date
? dayjs(dataset[dataset.length - 1].time).format(
"MM-DD HH:mm"
)
: "结束",
},
]}
sx={{
flex: 1,
"& .MuiSlider-thumb": {
width: 16,
height: 16,
},
"& .MuiSlider-markLabel": {
fontSize: "0.7rem",
color: "text.secondary",
},
}}
/>
<Button
size="small"
variant="outlined"
onClick={() => setZoomRange([0, 100])}
sx={{ minWidth: 60, fontSize: "0.75rem" }}
>
</Button>
</Stack>
{getTimeRangeLabel() && (
<Typography
variant="caption"
sx={{
color: "primary.main",
display: "block",
textAlign: "center",
mt: 0.5,
}}
>
: {getTimeRangeLabel()} ( {filteredDataset.length}{" "}
)
</Typography>
)}
</Box>
<ReactECharts
option={option}
style={{ height: "100%", width: "100%" }}
notMerge={true}
lazyUpdate={true}
/>
</Box>
);
};
@@ -680,31 +648,9 @@ const HistoryDataPanel: React.FC<HistoryDataPanelProps> = ({
return (
<>
{/* 收起时的触发按钮 */}
{!isExpanded && hasDevices && (
<Box
className="absolute top-20 right-4 bg-white shadow-2xl rounded-lg cursor-pointer hover:shadow-xl transition-all duration-300 opacity-95 hover:opacity-100"
onClick={() => setIsExpanded(true)}
sx={{ zIndex: 1300 }}
>
<Box className="flex flex-col items-center py-3 px-3 gap-1">
<ShowChart className="text-[#257DD4] w-5 h-5" />
<Typography
variant="caption"
className="text-gray-700 font-semibold my-1 text-xs"
style={{ writingMode: "vertical-rl" }}
>
</Typography>
<ChevronLeft className="text-gray-600 w-4 h-4" />
</Box>
</Box>
)}
{/* 主面板 */}
<Drawer
anchor="right"
open={isExpanded && visible}
variant="persistent"
hideBackdrop
sx={{
@@ -749,7 +695,7 @@ const HistoryDataPanel: React.FC<HistoryDataPanelProps> = ({
<Stack direction="row" spacing={1} alignItems="center">
<ShowChart fontSize="small" />
<Typography variant="h6" sx={{ fontWeight: "bold" }}>
SCADA
</Typography>
<Chip
size="small"
@@ -761,17 +707,6 @@ const HistoryDataPanel: React.FC<HistoryDataPanelProps> = ({
}}
/>
</Stack>
<Stack direction="row" spacing={1}>
<Tooltip title="收起">
<IconButton
size="small"
onClick={() => setIsExpanded(false)}
sx={{ color: "primary.contrastText" }}
>
<ChevronRight fontSize="small" />
</IconButton>
</Tooltip>
</Stack>
</Stack>
</Box>
@@ -786,11 +721,18 @@ const HistoryDataPanel: React.FC<HistoryDataPanelProps> = ({
<DateTimePicker
label="开始时间"
value={from}
onChange={(value) =>
value && dayjs.isDayjs(value) && setFrom(value)
}
onChange={(value) => {
if (value && dayjs.isDayjs(value) && value.isValid()) {
setFrom(value);
}
}}
onAccept={(value) => {
if (value && dayjs.isDayjs(value) && hasDevices) {
if (
value &&
dayjs.isDayjs(value) &&
value.isValid() &&
hasDevices
) {
handleFetch("date-change");
}
}}
@@ -802,11 +744,18 @@ const HistoryDataPanel: React.FC<HistoryDataPanelProps> = ({
<DateTimePicker
label="结束时间"
value={to}
onChange={(value) =>
value && dayjs.isDayjs(value) && setTo(value)
}
onChange={(value) => {
if (value && dayjs.isDayjs(value) && value.isValid()) {
setTo(value);
}
}}
onAccept={(value) => {
if (value && dayjs.isDayjs(value) && hasDevices) {
if (
value &&
dayjs.isDayjs(value) &&
value.isValid() &&
hasDevices
) {
handleFetch("date-change");
}
}}
@@ -857,7 +806,6 @@ const HistoryDataPanel: React.FC<HistoryDataPanelProps> = ({
</Tooltip>
</Stack>
</Stack>
{/* 清洗功能已移除,数据源选择请通过后端或外部参数控制 */}
</Stack>
</LocalizationProvider>
@@ -909,4 +857,4 @@ const HistoryDataPanel: React.FC<HistoryDataPanelProps> = ({
);
};
export default HistoryDataPanel;
export default SCADADataPanel;

View File

@@ -814,6 +814,8 @@ const StyleEditorPanel: React.FC<StyleEditorPanelProps> = ({
const junctionStyleConfigState = layerStyleStates.find(
(s) => s.layerId === "junctions"
);
// setStyle() 会清除渲染器缓存,这是闪烁的主要原因 WebGLVectorTile.js:114-118
// 尝试考虑使用 updateStyleVariables() 更新
applyClassificationStyle(
"junctions",
junctionStyleConfigState?.styleConfig