upgraded the line charts

This commit is contained in:
2025-07-24 05:05:28 +03:00
parent e4d83e64de
commit 1f837dfdb0
5 changed files with 694 additions and 1802 deletions

View File

@@ -1,14 +1,13 @@
import { useState, useEffect } from 'react';
import { Box, Paper, Typography, Fade, useTheme, AppBar, Toolbar, Chip } from '@mui/material';
import Plot from 'react-plotly.js';
import { Layout, PlotData } from 'plotly.js';
import { LineChart } from '@mui/x-charts/LineChart';
import { config } from '../config/env';
interface DataItem {
now_timestamp: string;
future_timestamp: string;
power: string;
power_future_15min: string;
power_future_min: string;
positive_3p: string;
negative_3p: string;
positive_7p: string;
@@ -21,79 +20,27 @@ const API_BASE_URL = config.apiUrl;
const Maintenance = () => {
const theme = useTheme();
const [chartData, setChartData] = useState<Partial<PlotData>[]>([]);
const [data, setData] = useState<DataItem[]>([]);
const [currentFlag, setCurrentFlag] = useState<string>('');
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
const response = await fetch(`${API_BASE_URL}/prom/get_chart_data/maintenance/20`);
const result = await response.json();
if (result.data && result.data.length > 0) {
const last20Data = result.data.slice(-20);
setCurrentFlag(last20Data[last20Data.length - 1].flag);
const traces: Partial<PlotData>[] = [
{
x: last20Data.map((item: DataItem) => item.now_timestamp),
y: last20Data.map((item: DataItem) => parseFloat(item.power)),
type: 'scatter' as const,
mode: 'lines+markers' as const,
name: 'Current Power',
line: { color: '#2196f3', width: 2 },
marker: { size: 6, symbol: 'circle' }
},
{
x: last20Data.map((item: DataItem) => item.future_timestamp),
y: last20Data.map((item: DataItem) => parseFloat(item.power_future_15min)),
type: 'scatter' as const,
mode: 'lines+markers' as const,
name: 'Predicted (15min)',
line: { color: '#4caf50', width: 2, dash: 'dot' },
marker: { size: 6, symbol: 'circle' }
},
{
x: last20Data.map((item: DataItem) => item.future_timestamp),
y: last20Data.map((item: DataItem) => parseFloat(item.positive_3p)),
type: 'scatter' as const,
mode: 'lines' as const,
name: '+3% Positive',
line: { color: '#2ca02c', width: 1.5 },
showlegend: true,
},
{
x: last20Data.map((item: DataItem) => item.future_timestamp),
y: last20Data.map((item: DataItem) => parseFloat(item.negative_3p)),
type: 'scatter' as const,
mode: 'lines' as const,
name: '-3% Negative',
line: { color: '#d62728', width: 1.5 },
showlegend: true,
},
{
x: last20Data.map((item: DataItem) => item.future_timestamp),
y: last20Data.map((item: DataItem) => parseFloat(item.positive_7p)),
type: 'scatter' as const,
mode: 'lines' as const,
name: '+7% Positive',
line: { color: '#9467bd', width: 1.5 },
showlegend: true,
},
{
x: last20Data.map((item: DataItem) => item.future_timestamp),
y: last20Data.map((item: DataItem) => parseFloat(item.negative_7p)),
type: 'scatter' as const,
mode: 'lines' as const,
name: '-7% Negative',
line: { color: '#8c564b', width: 1.5 },
showlegend: true,
}
];
setChartData(traces);
setData(last20Data);
console.log('Fetched data:', last20Data);
}
} catch (error) {
console.error('Error fetching data:', error);
} finally {
setLoading(false);
}
};
@@ -102,58 +49,88 @@ const Maintenance = () => {
return () => clearInterval(interval);
}, []);
const layout: Partial<Layout> = {
xaxis: {
title: {
text: 'Time',
font: { size: 14, color: '#666', family: undefined }
},
type: 'date',
gridcolor: '#eee',
tickfont: { size: 12, family: undefined, color: '#666' },
showgrid: true,
gridwidth: 1,
rangeslider: { visible: true }
},
yaxis: {
title: {
text: 'Power (W)',
font: { size: 14, color: '#666', family: undefined }
},
gridcolor: '#eee',
tickfont: { size: 12, family: undefined, color: '#666' },
showgrid: true,
gridwidth: 1,
rangemode: 'tozero' as const,
fixedrange: false,
range: [0, Math.max(...chartData.flatMap(trace => trace.y as number[]).filter(Boolean)) * 1.1]
},
showlegend: true,
legend: {
orientation: 'h',
y: -0.2,
x: 0.5,
xanchor: 'center',
yanchor: 'top',
font: {
size: 12,
family: theme.typography.fontFamily,
color: theme.palette.text.secondary
},
bgcolor: 'rgba(255, 255, 255, 0)',
bordercolor: 'rgba(255, 255, 255, 0)'
},
margin: { t: 60, b: 100, l: 60, r: 20 },
plot_bgcolor: 'rgba(0,0,0,0)',
paper_bgcolor: 'rgba(0,0,0,0)',
hovermode: 'closest',
modebar: {
bgcolor: 'rgba(255, 255, 255, 0)',
color: theme.palette.text.secondary,
activecolor: theme.palette.primary.main
// Process data for charts
const prepareChartData = () => {
if (!data || data.length === 0) {
console.log('No data available, using fallback data');
// Fallback data for testing
const now = new Date();
const fallbackData = Array.from({ length: 10 }, (_, i) => ({
currentTimestamp: new Date(now.getTime() - (9 - i) * 60000), // 1 minute intervals
futureTimestamp: new Date(now.getTime() - (9 - i) * 60000 + 3 * 60000), // 3 minutes in the future
currentPower: 95 + Math.random() * 10,
predictedPower: 115 + Math.random() * 10,
positive3p: 118 + Math.random() * 5,
negative3p: 112 + Math.random() * 5,
positive7p: 123 + Math.random() * 5,
negative7p: 107 + Math.random() * 5,
}));
return fallbackData;
}
const processedData = data.map(item => {
const currentPower = parseFloat(item.power) || 0;
const predictedPower = parseFloat(item.power_future_min) || currentPower * 1.1; // Fallback to 10% higher than current
return {
currentTimestamp: new Date(item.now_timestamp),
futureTimestamp: new Date(item.future_timestamp),
currentPower: currentPower,
predictedPower: predictedPower,
positive3p: parseFloat(item.positive_3p) || predictedPower * 1.03,
negative3p: parseFloat(item.negative_3p) || predictedPower * 0.97,
positive7p: parseFloat(item.positive_7p) || predictedPower * 1.07,
negative7p: parseFloat(item.negative_7p) || predictedPower * 0.93,
};
});
console.log('Processed chart data:', processedData);
console.log('Data validation:', {
hasCurrentPower: processedData.some(d => d.currentPower > 0),
hasPredictedPower: processedData.some(d => d.predictedPower > 0),
currentPowerRange: [Math.min(...processedData.map(d => d.currentPower)), Math.max(...processedData.map(d => d.currentPower))],
predictedPowerRange: [Math.min(...processedData.map(d => d.predictedPower)), Math.max(...processedData.map(d => d.predictedPower))],
rawDataSample: data.slice(0, 2).map(item => ({
power: item.power,
power_future_min: item.power_future_min,
parsedCurrent: parseFloat(item.power),
parsedPredicted: parseFloat(item.power_future_min)
}))
});
return processedData;
};
const chartData = prepareChartData();
// Extract data arrays for charts
const currentTimestamps = chartData.map(item => item.currentTimestamp);
const futureTimestamps = chartData.map(item => item.futureTimestamp);
const currentPowerData = chartData.map(item => item.currentPower);
const predictedPowerData = chartData.map(item => item.predictedPower);
const positive3pData = chartData.map(item => item.positive3p);
const negative3pData = chartData.map(item => item.negative3p);
const positive7pData = chartData.map(item => item.positive7p);
const negative7pData = chartData.map(item => item.negative7p);
// Debug logging
console.log('Chart arrays:', {
currentTimestamps: currentTimestamps.length,
futureTimestamps: futureTimestamps.length,
currentPower: currentPowerData.length,
predictedPower: predictedPowerData.length,
positive3p: positive3pData.length,
negative3p: negative3pData.length,
positive7p: positive7pData.length,
negative7p: negative7pData.length,
});
console.log('Sample timestamps:', {
current: currentTimestamps.slice(0, 3),
future: futureTimestamps.slice(0, 3),
currentPower: currentPowerData.slice(0, 3),
predictedPower: predictedPowerData.slice(0, 3),
});
return (
<Box sx={{ flexGrow: 1, bgcolor: theme.palette.background.default }}>
<AppBar
@@ -221,23 +198,69 @@ const Maintenance = () => {
}}
>
<Box sx={{ height: 'calc(100vh - 200px)', minHeight: '500px' }}>
<Plot
data={chartData}
layout={layout}
config={{
responsive: true,
displayModeBar: true,
displaylogo: false,
modeBarButtonsToRemove: ['lasso2d', 'select2d'],
toImageButtonOptions: {
format: 'png',
filename: 'power_consumption_chart',
height: 1000,
width: 1500,
scale: 2
<LineChart
height={500}
skipAnimation={false}
series={[
{
data: currentPowerData,
label: 'Current Power',
color: '#028a4a', // B'GREEN brand color
showMark: true,
curve: 'linear'
},
{
data: predictedPowerData,
label: 'Predicted (3min)',
color: '#ff9800',
showMark: true,
curve: 'linear'
},
{
data: positive3pData,
label: '+3% Positive',
color: '#2ca02c',
showMark: false
},
{
data: negative3pData,
label: '-3% Negative',
color: '#d62728',
showMark: false
},
{
data: positive7pData,
label: '+7% Positive',
color: '#9467bd',
showMark: false
},
{
data: negative7pData,
label: '-7% Negative',
color: '#8c564b',
showMark: false
},
]}
xAxis={[
{
scaleType: 'time',
data: [...currentTimestamps, ...futureTimestamps],
valueFormatter: (value: Date) => value.toLocaleTimeString(),
},
]}
yAxis={[
{
width: 50,
valueFormatter: (value: number) => `${value} W`,
}
]}
margin={{ right: 24 }}
slotProps={{
legend: {
direction: 'horizontal',
position: { vertical: 'top', horizontal: 'center' },
},
}}
style={{ width: '100%', height: '100%' }}
/>
</Box>
</Paper>