Compare commits

..

No commits in common. "f87f7bb2aa1c657dfffc39c286fa238a51abcb22" and "1a7c06b6b36e2e5a61e2cc075a36006f6cc43f7a" have entirely different histories.

14 changed files with 104 additions and 95 deletions

View File

@ -793,7 +793,7 @@ public class Controller : ControllerBase
public async Task<ActionResult<IEnumerable<Object>>> InsertNewAction([FromBody] UserAction action, Token authToken)
{
var session = Db.GetSession(authToken);
var actionSuccess = await session.InsertUserAction(action);
var actionSuccess = await session.RecordUserAction(action);
return actionSuccess ? Ok() : Unauthorized();
}
@ -835,7 +835,7 @@ public class Controller : ControllerBase
Description = config.GetConfigurationString()
};
var actionSuccess = await session.InsertUserAction(action);
var actionSuccess = await session.RecordUserAction(action);
return actionSuccess?Ok():Unauthorized();
}

View File

@ -19,7 +19,6 @@ public class Installation : TreeNode
public int S3BucketId { get; set; } = 0;
public String ReadRoleId { get; set; } = "";
public String WriteRoleId { get; set; } = "";
public Boolean TestingMode { get; set; } = false;
public int Product { get; set; } = 0;
public int Device { get; set; } = 0;

View File

@ -1,7 +1,6 @@
using System.Diagnostics;
using InnovEnergy.App.Backend.Database;
using InnovEnergy.App.Backend.Relations;
using InnovEnergy.App.Backend.Websockets;
using InnovEnergy.Lib.Utils;
using Org.BouncyCastle.Asn1.X509;
@ -132,17 +131,14 @@ public static class SessionMethods
&& await installation.SendConfig(configuration);
}
public static async Task<Boolean> InsertUserAction(this Session? session, UserAction action)
public static async Task<Boolean> RecordUserAction(this Session? session, UserAction action)
{
var user = session?.User;
if (user is null || user.UserType == 0)
return false;
var installation = Db.GetInstallationById(action.InstallationId);
installation.TestingMode = action.TestingMode;
installation.Apply(Db.Update);
WebsocketManager.InformWebsocketsForInstallation(action.InstallationId);
action.UserName = user.Name;
// Save the configuration change to the database
Db.HandleAction(action);
@ -156,14 +152,6 @@ public static class SessionMethods
if (user is null || user.UserType == 0)
return false;
var installation = Db.GetInstallationById(action.InstallationId);
if (installation.TestingMode != action.TestingMode)
{
installation.TestingMode = action.TestingMode;
installation.Apply(Db.Update);
WebsocketManager.InformWebsocketsForInstallation(action.InstallationId);
}
Db.UpdateAction(action);
return true;
}

View File

@ -12,8 +12,6 @@ public class UserAction
public Int64 InstallationId { get; set; } // Installation ID where the configuration change is made
public Boolean TestingMode { get; set; }
public DateTime Timestamp { get; set; } // Timestamp of the configuration change
public String Description { get; set; } = null!;// Serialized string representing the new configuration

View File

@ -111,14 +111,11 @@ public static partial class Db
public static void UpdateAction(UserAction updatedAction)
{
var existingAction = UserActions.FirstOrDefault(action => action.Id == updatedAction.Id);
if (existingAction != null)
{
//existingAction.Description = updatedAction.Description;
//existingAction.Timestamp = updatedAction.Timestamp;
//existingAction.TestingMode = updatedAction.TestingMode;
Update(updatedAction);
existingAction.Description = updatedAction.Description;
existingAction.Timestamp = updatedAction.Timestamp;
Update(existingAction);
Console.WriteLine("---------------Updated the Action in the database-----------------");
}
}

View File

@ -9,7 +9,7 @@ namespace InnovEnergy.App.Backend.Websockets;
public static class WebsocketManager
{
public static Dictionary<Int64, InstallationInfo> InstallationConnections = new Dictionary<Int64, InstallationInfo>();
public static Dictionary<int, InstallationInfo> InstallationConnections = new Dictionary<int, InstallationInfo>();
//Every 2 minutes, check the timestamp of the latest received message for every installation.
//If the difference between the two timestamps is more than two minutes, we consider this installation unavailable.
@ -30,18 +30,15 @@ public static class WebsocketManager
}
//Inform all the connected websockets regarding installation "installationId"
public static void InformWebsocketsForInstallation(Int64 installationId)
public static void InformWebsocketsForInstallation(int installationId)
{
var installation = Db.GetInstallationById(installationId);
var installationConnection = InstallationConnections[installationId];
Console.WriteLine("Update all the connected websockets for installation " + installationId);
var jsonObject = new
{
id = installationId,
status = installationConnection.Status,
testingMode = installation.TestingMode
status = installationConnection.Status
};
string jsonString = JsonSerializer.Serialize(jsonObject);
@ -102,10 +99,9 @@ public static class WebsocketManager
//Then, report the status of each requested installation to the front-end that created the websocket connection
foreach (var installationId in installationIds)
{
var installation = Db.GetInstallationById(installationId);
if (!InstallationConnections.ContainsKey(installationId))
{
//Console.WriteLine("Create new empty list for installation id " + installationId);
Console.WriteLine("Create new empty list for installation id " + installationId);
InstallationConnections[installationId] = new InstallationInfo
{
Status = -1
@ -117,8 +113,7 @@ public static class WebsocketManager
var jsonObject = new
{
id = installationId,
status = InstallationConnections[installationId].Status,
testingMode = installation.TestingMode
status = InstallationConnections[installationId].Status
};
var jsonString = JsonSerializer.Serialize(jsonObject);

View File

@ -11,6 +11,8 @@ import fr from './lang/fr.json';
import SuspenseLoader from './components/SuspenseLoader';
import SidebarLayout from './layouts/SidebarLayout';
import { TokenContext } from './contexts/tokenContext';
import { TestModeProvider } from './contexts/TestModeContext';
import ResetPassword from './components/ResetPassword';
import InstallationTabs from './content/dashboards/Installations/index';
import routes from 'src/Resources/routes.json';
import './App.css';
@ -141,7 +143,9 @@ function App() {
element={
<AccessContextProvider>
<InstallationsContextProvider>
<TestModeProvider>
<InstallationTabs />
</TestModeProvider>
</InstallationsContextProvider>
</AccessContextProvider>
}

View File

@ -20,6 +20,7 @@ import { AxiosError, AxiosResponse } from 'axios/index';
import routes from '../../../Resources/routes.json';
import { useNavigate } from 'react-router-dom';
import { TokenContext } from '../../../contexts/tokenContext';
import { useTestMode } from '../../../contexts/TestModeContext';
import { Action } from '../../../interfaces/S3Types';
import Button from '@mui/material/Button';
import { DateTimePicker, LocalizationProvider } from '@mui/x-date-pickers';
@ -48,14 +49,19 @@ function HistoryOfActions(props: HistoryProps) {
const [newAction, setNewAction] = useState<Partial<Action>>({
installationId: props.id,
timestamp: actionDate.toDate(),
description: '',
testingMode: false
description: ''
});
const { testModeMap, setTestMode } = useTestMode();
const isTestMode = testModeMap[props.id] || false;
const context = useContext(UserContext);
const { currentUser, setUser } = context;
const [isRowHovered, setHoveredRow] = useState(-1);
const [selectedAction, setSelectedAction] = useState<number>(-1);
const [editMode, setEditMode] = useState(false);
const handleTestModeToggle = () => {
setTestMode(props.id, !isTestMode);
};
const handleDateChange = (newdate) => {
setActionDate(newdate);
setNewAction({
@ -65,10 +71,10 @@ function HistoryOfActions(props: HistoryProps) {
};
const handleChange = (e) => {
const { name, type, checked, value } = e.target;
const { name, value } = e.target;
setNewAction({
...newAction,
[name]: type === 'checkbox' ? checked : value
[name]: value
});
};
@ -77,8 +83,7 @@ function HistoryOfActions(props: HistoryProps) {
setActionDate(dayjs());
setNewAction({
...newAction,
['description']: '',
['timestamp']: dayjs().toDate()
['description']: ''
});
setEditMode(false);
};
@ -228,9 +233,8 @@ function HistoryOfActions(props: HistoryProps) {
<FormControlLabel
control={
<Switch
name="testingMode"
checked={newAction.testingMode}
onChange={handleChange}
checked={isTestMode}
onChange={handleTestModeToggle}
/>
}
label="Test Mode"

View File

@ -16,6 +16,7 @@ import { I_Installation } from 'src/interfaces/InstallationTypes';
import CancelIcon from '@mui/icons-material/Cancel';
import BuildIcon from '@mui/icons-material/Build';
import { WebSocketContext } from 'src/contexts/WebSocketContextProvider';
import { useTestMode } from 'src/contexts/TestModeContext';
import { FormattedMessage } from 'react-intl';
import { useLocation, useNavigate } from 'react-router-dom';
import routes from '../../../Resources/routes.json';
@ -27,10 +28,11 @@ interface FlatInstallationViewProps {
const FlatInstallationView = (props: FlatInstallationViewProps) => {
const [isRowHovered, setHoveredRow] = useState(-1);
const webSocketContext = useContext(WebSocketContext);
const { getStatus, getTestingMode } = webSocketContext;
const { getStatus } = webSocketContext;
const navigate = useNavigate();
const [selectedInstallation, setSelectedInstallation] = useState<number>(-1);
const currentLocation = useLocation();
const { testModeMap } = useTestMode();
const sortedInstallations = [...props.installations].sort((a, b) => {
// Compare the status field of each installation and sort them based on the status.
@ -244,7 +246,7 @@ const FlatInstallationView = (props: FlatInstallationViewProps) => {
}}
/>
{getTestingMode(installation.id) && (
{testModeMap[installation.id] && (
<BuildIcon
style={{
width: '23px',
@ -253,7 +255,7 @@ const FlatInstallationView = (props: FlatInstallationViewProps) => {
borderRadius: '50%',
position: 'relative',
zIndex: 1,
marginLeft: '15px'
marginLeft: status === -1 || status === -2 ? '-23px' : '2px',
}}
/>
)}

View File

@ -32,6 +32,7 @@ import BatteryView from '../BatteryView/BatteryView';
import { UserType } from '../../../interfaces/UserTypes';
import HistoryOfActions from '../History/History';
import PvView from '../PvView/PvView';
import { useTestMode } from '../../../contexts/TestModeContext';
interface singleInstallationProps {
current_installation?: I_Installation;
@ -45,12 +46,13 @@ function Installation(props: singleInstallationProps) {
const [fetchFunctionCalled, setFetchFunctionCalled] = useState(false);
const [errorLoadingS3Data, setErrorLoadingS3Data] = useState(false);
const webSocketsContext = useContext(WebSocketContext);
const { getStatus, getTestingMode } = webSocketsContext;
const { getStatus } = webSocketsContext;
const [currentTab, setCurrentTab] = useState<string>(undefined);
const [values, setValues] = useState<TopologyValues | null>(null);
const status = getStatus(props.current_installation.id);
const [connected, setConnected] = useState(true);
const [loading, setLoading] = useState(true);
const { testModeMap } = useTestMode();
if (props.current_installation == undefined) {
return null;
@ -360,7 +362,7 @@ function Installation(props: singleInstallationProps) {
}}
/>
{getTestingMode(props.current_installation.id) && (
{testModeMap[props.current_installation.id] && (
<BuildIcon
style={{
width: '23px',
@ -369,37 +371,34 @@ function Installation(props: singleInstallationProps) {
borderRadius: '50%',
position: 'relative',
zIndex: 1,
marginLeft: '15px'
marginLeft: status === -1 || status === -2 ? '-23px' : '2px'
}}
/>
)}
</div>
</div>
{loading &&
currentTab != 'information' &&
currentTab != 'history' &&
currentTab != 'log' && (
<Container
maxWidth="xl"
sx={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
height: '70vh'
}}
{loading && currentTab != 'information' && currentTab != 'history' && (
<Container
maxWidth="xl"
sx={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
height: '70vh'
}}
>
<CircularProgress size={60} style={{ color: '#ffc04d' }} />
<Typography
variant="body2"
style={{ color: 'black', fontWeight: 'bold' }}
mt={2}
>
<CircularProgress size={60} style={{ color: '#ffc04d' }} />
<Typography
variant="body2"
style={{ color: 'black', fontWeight: 'bold' }}
mt={2}
>
Connecting to the device...
</Typography>
</Container>
)}
Connecting to the device...
</Typography>
</Container>
)}
<Card variant="outlined">
<Grid

View File

@ -0,0 +1,30 @@
import React, { createContext, useContext, useState, ReactNode } from 'react';
interface TestModeContextProps {
testModeMap: { [key: number]: boolean };
setTestMode: (id: number, mode: boolean) => void;
}
const TestModeContext = createContext<TestModeContextProps | undefined>(undefined);
export const useTestMode = () => {
const context = useContext(TestModeContext);
if (!context) {
throw new Error('useTestMode must be used within a TestModeProvider');
}
return context;
};
export const TestModeProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const [testModeMap, setTestModeMap] = useState<{ [key: number]: boolean }>({});
const setTestMode = (id: number, mode: boolean) => {
setTestModeMap(prev => ({ ...prev, [id]: mode }));
};
return (
<TestModeContext.Provider value={{ testModeMap, setTestMode }}>
{children}
</TestModeContext.Provider>
);
};

View File

@ -7,7 +7,6 @@ interface WebSocketContextProviderProps {
openSocket: (installations: I_Installation[]) => void;
closeSocket: () => void;
getStatus: (installationId: number) => number;
getTestingMode: (installationId: number) => boolean;
}
// Create the context.
@ -19,10 +18,7 @@ const WebSocketContextProvider = ({ children }: { children: ReactNode }) => {
const [socket, setSocket] = useState<WebSocket>(null);
const [installations, setInstallations] = useState<I_Installation[]>(null);
const [installationStatus, setInstallationStatus] = useState<
Record<number, number>
>({});
const [installationMode, setInstallatioMode] = useState<
Record<number, boolean>
Record<number, number[]>
>({});
const BUFFER_LENGTH = 5;
@ -56,19 +52,23 @@ const WebSocketContextProvider = ({ children }: { children: ReactNode }) => {
if (message.id != -1) {
const installation_id = message.id;
const status = message.status;
//console.log('Message from server ', installation_id, status);
setInstallatioMode((prevMode) => {
// Create a new object by spreading the previous state
const newMode = { ...prevMode };
newMode[installation_id] = message.testingMode;
return newMode;
});
setInstallationStatus((prevStatus) => {
// Create a new object by spreading the previous state
const newStatus = { ...prevStatus };
newStatus[installation_id] = message.status;
if (!newStatus.hasOwnProperty(installation_id)) {
newStatus[installation_id] = [];
}
newStatus[installation_id].unshift(status);
newStatus[installation_id] = newStatus[installation_id].slice(
0,
BUFFER_LENGTH
);
return newStatus;
});
}
@ -90,23 +90,18 @@ const WebSocketContextProvider = ({ children }: { children: ReactNode }) => {
if (!installationStatus.hasOwnProperty(installationId)) {
status = -2;
} else {
status = installationStatus[installationId];
status = installationStatus[installationId][0];
}
return status;
};
const getTestingMode = (installationId: number) => {
return installationMode[installationId];
};
return (
<WebSocketContext.Provider
value={{
socket: socket,
openSocket: openSocket,
closeSocket: closeSocket,
getStatus: getStatus,
getTestingMode: getTestingMode
getStatus: getStatus
}}
>
{children}

View File

@ -18,7 +18,6 @@ export interface I_Installation extends I_S3Credentials {
s3WriteSecret: string;
product: number;
device: number;
testingMode: boolean;
}
export interface I_Folder {

View File

@ -29,5 +29,4 @@ export interface Action {
installationId: number;
timestamp: Date;
description: string;
testingMode: boolean;
}