updated frontend-backend

This commit is contained in:
Noe 2025-01-14 13:56:12 +01:00
parent 546192cbab
commit 7045648622
15 changed files with 79 additions and 76 deletions

View File

@ -67,6 +67,7 @@ public class Controller : ControllerBase
[HttpGet(nameof(CreateWebSocket))]
public async Task CreateWebSocket(Token authToken)
{
//Everytime a user logs in, this function is called
var session = Db.GetSession(authToken)?.User;
if (session is null)
@ -85,6 +86,8 @@ public class Controller : ControllerBase
return;
}
//Create a websocket and pass its descriptor to the HandleWebSocketConnection method.
//This descriptor is returned to the frontend on the background
var webSocketContext = await HttpContext.WebSockets.AcceptWebSocketAsync();
var webSocket = webSocketContext;
@ -179,7 +182,7 @@ public class Controller : ControllerBase
Int64 startTimestamp = Int64.Parse(start.ToString().Substring(0,5));
Int64 endTimestamp = Int64.Parse(end.ToString().Substring(0,5));
if (installation.Product == 1)
if (installation.Product == (int)ProductType.Salidomo)
{
start = Int32.Parse(start.ToString().Substring(0, start.ToString().Length - 2));
@ -190,7 +193,7 @@ public class Controller : ControllerBase
while (startTimestamp <= endTimestamp)
{
string bucketPath = installation.Product==0? "s3://"+installation.S3BucketId + "-3e5b3069-214a-43ee-8d85-57d72000c19d/"+startTimestamp :
string bucketPath = installation.Product==(int)ProductType.Salimax? "s3://"+installation.S3BucketId + "-3e5b3069-214a-43ee-8d85-57d72000c19d/"+startTimestamp :
"s3://"+installation.S3BucketId + "-c0436b6a-d276-4cd8-9c44-1eae86cf5d0e/"+startTimestamp;
Console.WriteLine("Fetching data for "+startTimestamp);
@ -447,7 +450,7 @@ public class Controller : ControllerBase
return Unauthorized();
return user
.AccessibleInstallations(product:0)
.AccessibleInstallations(product:(int)ProductType.Salimax)
.Select(i => i.FillOrderNumbers().HideParentIfUserHasNoAccessToParent(user).HideWriteKeyIfUserIsNotAdmin(user.UserType))
.ToList();
}
@ -461,7 +464,7 @@ public class Controller : ControllerBase
return Unauthorized();
return user
.AccessibleInstallations(product:1)
.AccessibleInstallations(product:(int)ProductType.Salidomo)
.ToList();
}
@ -634,7 +637,7 @@ public class Controller : ControllerBase
if (!session.Update(installation))
return Unauthorized();
if (installation.Product == 0)
if (installation.Product == (int)ProductType.Salimax)
{
return installation.FillOrderNumbers().HideParentIfUserHasNoAccessToParent(session!.User).HideWriteKeyIfUserIsNotAdmin(session.User.UserType);
}

View File

@ -2,6 +2,20 @@ using SQLite;
namespace InnovEnergy.App.Backend.DataTypes;
public enum ProductType
{
Salimax = 0,
Salidomo = 1
}
public enum StatusType
{
Offline = -1,
Green = 0,
Warning = 1,
Alarm = 2
}
public class Installation : TreeNode
{
//Each installation has 2 roles, a read role and a write role.
@ -24,7 +38,7 @@ public class Installation : TreeNode
public String WriteRoleId { get; set; } = "";
public Boolean TestingMode { get; set; } = false;
public int Status { get; set; } = -1;
public int Product { get; set; } = 0;
public int Product { get; set; } = (int)ProductType.Salimax;
public int Device { get; set; } = 0;
[Ignore]

View File

@ -143,7 +143,7 @@ public static class ExoCmd
{
const String url = "https://api-ch-dk-2.exoscale.com/v2/iam-role";
const String method = "iam-role";
String rolename = installation.Product==0?Db.Installations.Count(f => f.Product == 0) + installation.Name:Db.Installations.Count(f => f.Product == 1) + installation.Name;
String rolename = installation.Product==(int)ProductType.Salimax?Db.Installations.Count(f => f.Product == (int)ProductType.Salimax) + installation.Name:Db.Installations.Count(f => f.Product == (int)ProductType.Salidomo) + installation.Name;
var contentString = $$"""
@ -316,7 +316,7 @@ public static class ExoCmd
{
const String url = "https://api-ch-dk-2.exoscale.com/v2/iam-role";
const String method = "iam-role";
String rolename = installation.Product==0?Db.Installations.Count(f => f.Product == 0) + installation.Name:Db.Installations.Count(f => f.Product == 1) + installation.Name;
String rolename = installation.Product==(int)ProductType.Salimax?Db.Installations.Count(f => f.Product == (int)ProductType.Salimax) + installation.Name:Db.Installations.Count(f => f.Product == (int)ProductType.Salidomo) + installation.Name;
var contentString = $$"""
{

View File

@ -16,7 +16,7 @@ public static class InstallationMethods
public static String BucketName(this Installation installation)
{
if (installation.Product == 0)
if (installation.Product == (int)ProductType.Salimax)
{
return $"{installation.S3BucketId}-{BucketNameSalt}";
}

View File

@ -72,7 +72,7 @@ public static class SessionMethods
public static async Task RunScriptInBackground(this Session? session, String vpnIp, Int64 batteryNode,String version,Int64 product)
{
Console.WriteLine("-----------------------------------Start updating firmware-----------------------------------");
string scriptPath = (product == 0)
string scriptPath = (product == (int)ProductType.Salimax)
? "/home/ubuntu/backend/uploadBatteryFw/update_firmware_Salimax.sh"
: "/home/ubuntu/backend/uploadBatteryFw/update_firmware_Salidomo.sh";
@ -95,7 +95,7 @@ public static class SessionMethods
public static async Task RunDownloadLogScript(this Session? session, String vpnIp, Int64 batteryNode,Int64 product)
{
Console.WriteLine("-----------------------------------Start downloading battery log-----------------------------------");
string scriptPath = (product == 0)
string scriptPath = (product == (int)ProductType.Salimax)
? "/home/ubuntu/backend/downloadBatteryLog/download_bms_log_Salimax.sh"
: "/home/ubuntu/backend/downloadBatteryLog/download_bms_log_Salidomo.sh";
@ -210,7 +210,7 @@ public static class SessionMethods
//Salimax installation
if (installation.Product == 0)
if (installation.Product == (int)ProductType.Salimax)
{
return user is not null
&& user.UserType != 0
@ -223,7 +223,7 @@ public static class SessionMethods
}
if (installation.Product == 1)
if (installation.Product == (int)ProductType.Salidomo)
{
return user is not null
&& user.UserType != 0
@ -242,7 +242,7 @@ public static class SessionMethods
var original = Db.GetInstallationById(installation?.Id);
//Salimax installation
if (installation.Product == 0)
if (installation.Product == (int)ProductType.Salimax)
{
return user is not null
@ -256,7 +256,7 @@ public static class SessionMethods
.Apply(Db.Update);
}
if (installation.Product==1)
if (installation.Product==(int)ProductType.Salidomo)
{
return user is not null
&& installation is not null

View File

@ -100,7 +100,7 @@ public static partial class Db
Boolean DeleteInstallationAndItsDependencies()
{
InstallationAccess.Delete(i => i.InstallationId == installation.Id);
if (installation.Product == 0)
if (installation.Product == (int)ProductType.Salimax)
{
//For Salimax, delete the OrderNumber2Installation entries associated with this installation id.
OrderNumber2Installation.Delete(i => i.InstallationId == installation.Id);

View File

@ -25,12 +25,11 @@ public static class Program
Db.Init();
var builder = WebApplication.CreateBuilder(args);
RabbitMqManager.InitializeEnvironment();
RabbitMqManager.StartRabbitMqConsumer().SupressAwaitWarning();
//RabbitMqManager.InitializeEnvironment();
//RabbitMqManager.StartRabbitMqConsumer().SupressAwaitWarning();
WebsocketManager.MonitorSalimaxInstallationTable().SupressAwaitWarning();
WebsocketManager.MonitorSalidomoInstallationTable().SupressAwaitWarning();
builder.Services.AddControllers();
builder.Services.AddProblemDetails(setup =>
{

View File

@ -43,8 +43,8 @@ public class Session : Relation<String, Int64>
Token = CreateToken();
UserId = user.Id;
LastSeen = DateTime.Now;
AccessToSalimax = user.AccessibleInstallations(product: 0).ToList().Count > 0;
AccessToSalidomo = user.AccessibleInstallations(product: 1).ToList().Count > 0;
AccessToSalimax = user.AccessibleInstallations(product: (int)ProductType.Salimax).ToList().Count > 0;
AccessToSalidomo = user.AccessibleInstallations(product: (int)ProductType.Salidomo).ToList().Count > 0;
}
private static String CreateToken()

View File

@ -10,16 +10,13 @@ namespace InnovEnergy.App.Backend.Websockets;
public static class RabbitMqManager
{
public static ConnectionFactory Factory = null!;
public static IConnection Connection = null!;
public static IModel Channel = null!;
//This function will be called from the Backend/Program.cs
public static void InitializeEnvironment()
{
//string vpnServerIp = "194.182.190.208";
string vpnServerIp = "10.2.0.11";
//Subscribe to RabbitMq queue as a consumer
@ -57,24 +54,19 @@ public static class RabbitMqManager
{
Installation installation = Db.Installations.FirstOrDefault(f => f.Product == receivedStatusMessage.Product && f.S3BucketId == receivedStatusMessage.InstallationId);
int installationId = (int)installation.Id;
//Console.WriteLine("received a message from rabbitmq\n");
//This is a heartbit message, just update the timestamp for this installation.
//There is no need to notify the corresponding front-ends.
//Every 15 iterations(30 seconds), the installation sends a heartbit message to the queue
//Every 15 iterations(30 seconds), the installation sends a heartbit message to the queue.
if (receivedStatusMessage.Type == MessageType.Heartbit)
{
// if (installation.Product == 1 && installation.Device == 2)
// {
// Console.WriteLine("This is a heartbit message from installation: " + installationId + " Name of the file is " + receivedStatusMessage.Timestamp);
// }
//Do not do anything here, just for debugging purposes.
}
else
{
//Traverse the Warnings list, and store each of them to the database
if (receivedStatusMessage.Warnings != null)
{
foreach (var warning in receivedStatusMessage.Warnings)
{
Warning newWarning = new Warning
@ -98,7 +90,7 @@ public static class RabbitMqManager
{
string monitorLink;
if (installation.Product == 0)
if (installation.Product == (int)ProductType.Salimax)
{
monitorLink =
$"https://monitor.innov.energy/installations/list/installation/{installation.S3BucketId}/batteryview";
@ -149,9 +141,9 @@ public static class RabbitMqManager
}
}
var prevStatus = 0;
Int32 prevStatus;
//This installation id does not exist in our data structure, add it.
//This installation id does not exist in our in-memory data structure, add it.
if (!WebsocketManager.InstallationConnections.ContainsKey(installationId))
{
prevStatus = -2;
@ -168,11 +160,6 @@ public static class RabbitMqManager
prevStatus = WebsocketManager.InstallationConnections[installationId].Status;
WebsocketManager.InstallationConnections[installationId].Status = receivedStatusMessage.Status;
WebsocketManager.InstallationConnections[installationId].Timestamp = DateTime.Now;
// if (installationId == 130)
// {
// Console.WriteLine("prevStatus " + prevStatus + " , new status is: " + receivedStatusMessage.Status + " and status is: " + receivedStatusMessage.Status);
// }
}
installation.Status = receivedStatusMessage.Status;
@ -189,5 +176,4 @@ public static class RabbitMqManager
};
Channel.BasicConsume(queue: "statusQueue", autoAck: true, consumer: consumer);
}
}

View File

@ -13,8 +13,8 @@ public static class WebsocketManager
{
public static Dictionary<Int64, InstallationInfo> InstallationConnections = new Dictionary<Int64, 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.
//Every 1 minute, 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 Salimax installation unavailable.
public static async Task MonitorSalimaxInstallationTable()
{
while (true){
@ -22,15 +22,15 @@ public static class WebsocketManager
Console.WriteLine("MONITOR SALIMAX INSTALLATIONS\n");
foreach (var installationConnection in InstallationConnections){
if (installationConnection.Value.Product==0 && (DateTime.Now - installationConnection.Value.Timestamp) > TimeSpan.FromMinutes(2)){
if (installationConnection.Value.Product==(int)ProductType.Salimax && (DateTime.Now - installationConnection.Value.Timestamp) > TimeSpan.FromMinutes(2)){
Console.WriteLine("Installation ID is "+installationConnection.Key);
Console.WriteLine("installationConnection.Value.Timestamp is "+installationConnection.Value.Timestamp);
Console.WriteLine("diff is "+(DateTime.Now-installationConnection.Value.Timestamp));
// Console.WriteLine("Installation ID is "+installationConnection.Key);
// Console.WriteLine("installationConnection.Value.Timestamp is "+installationConnection.Value.Timestamp);
// Console.WriteLine("diff is "+(DateTime.Now-installationConnection.Value.Timestamp));
installationConnection.Value.Status = -1;
Installation installation = Db.Installations.FirstOrDefault(f => f.Product == 0 && f.Id == installationConnection.Key);
installation.Status = -1;
installationConnection.Value.Status = (int)StatusType.Offline;
Installation installation = Db.Installations.FirstOrDefault(f => f.Product == (int)ProductType.Salimax && f.Id == installationConnection.Key);
installation.Status = (int)StatusType.Offline;
installation.Apply(Db.Update);
if (installationConnection.Value.Connections.Count > 0){InformWebsocketsForInstallation(installationConnection.Key);}
}
@ -42,6 +42,8 @@ public static class WebsocketManager
}
}
//Every 1 minute, check the timestamp of the latest received message for every installation.
//If the difference between the two timestamps is more than 1 hour, we consider this Salidomo installation unavailable.
public static async Task MonitorSalidomoInstallationTable()
{
while (true){
@ -50,26 +52,17 @@ public static class WebsocketManager
Console.WriteLine("MONITOR SALIDOMO INSTALLATIONS\n");
foreach (var installationConnection in InstallationConnections){
Console.WriteLine("Installation ID is "+installationConnection.Key);
// if (installationConnection.Key == 104)
// {
// Console.WriteLine("installationConnection.Value.Timestamp is "+installationConnection.Value.Timestamp);
// Console.WriteLine("diff is "+(DateTime.Now-installationConnection.Value.Timestamp));
//
//
// }
if (installationConnection.Value.Product==1 && (DateTime.Now - installationConnection.Value.Timestamp) > TimeSpan.FromMinutes(30))
if (installationConnection.Value.Product==(int)ProductType.Salidomo && (DateTime.Now - installationConnection.Value.Timestamp) > TimeSpan.FromMinutes(60))
{
// Console.WriteLine("Installation ID is "+installationConnection.Key);
// Console.WriteLine("installationConnection.Value.Timestamp is "+installationConnection.Value.Timestamp);
// Console.WriteLine("diff is "+(DateTime.Now-installationConnection.Value.Timestamp));
Installation installation = Db.Installations.FirstOrDefault(f => f.Product == 1 && f.Id == installationConnection.Key);
installation.Status = -1;
Installation installation = Db.Installations.FirstOrDefault(f => f.Product == (int)ProductType.Salidomo && f.Id == installationConnection.Key);
installation.Status = (int)StatusType.Offline;
installation.Apply(Db.Update);
installationConnection.Value.Status = -1;
installationConnection.Value.Status = (int)StatusType.Offline;
if (installationConnection.Value.Connections.Count > 0){InformWebsocketsForInstallation(installationConnection.Key);}
}
}
@ -143,7 +136,8 @@ public static class WebsocketManager
continue;
}
//Console.WriteLine("Received a new message from websocket");
//Received a new message from this websocket.
//We have a HandleWebSocketConnection per connected frontend
lock (InstallationConnections)
{
List<WebsocketMessage> dataToSend = new List<WebsocketMessage>();
@ -153,14 +147,17 @@ 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)
{
//Console.WriteLine("New id is "+installationId);
var installation = Db.GetInstallationById(installationId);
if (!InstallationConnections.ContainsKey(installationId))
{
//Console.WriteLine("Create new empty list for installation id " + installationId);
//Since we keep all the changes to the database, in case that the backend reboots, we need to update the in-memory data structure.
//Thus, if the status is -1, we put an old timestamp, otherwise, we put the most recent timestamp.
//We store everything to the database, because when the backend reboots, we do not want to wait until all the installations send the heartbit messages.
//We want the in memory data structure to be up to date immediately.
InstallationConnections[installationId] = new InstallationInfo
{
Status = installation.Status,
Timestamp = installation.Status==(int)StatusType.Offline ? DateTime.Now.AddDays(-1) : DateTime.Now,
Product = installation.Product
};
}

View File

@ -1 +1,5 @@
#To deploy to the monitor server, uncomment the following line
dotnet publish Backend.csproj -c Release -r linux-x64 --self-contained true -p:PublishTrimmed=false && rsync -av bin/Release/net6.0/linux-x64/publish/ ubuntu@194.182.190.208:~/backend && ssh ubuntu@194.182.190.208 'sudo systemctl restart backend'
#To deploy to the stage server, uncomment the following line
#dotnet publish Backend.csproj -c Release -r linux-x64 --self-contained true -p:PublishTrimmed=false && rsync -av bin/Release/net6.0/linux-x64/publish/ ubuntu@91.92.154.141:~/backend && ssh ubuntu@91.92.154.141 'sudo systemctl restart backend'

View File

@ -66,5 +66,4 @@ ln -s "$vpn_service_path" "$vpn_symlink_path"
# EmuMeter_symlink_path="/service/EmuMeter"
# ln -s "$EmuMeter_service_path" "$EmuMeter_symlink_path"
exit 0

View File

@ -54,6 +54,6 @@ INNOVENERGY_PROTOCOL_VERSION = '48TL200V3'
# S3 Credentials
S3BUCKET = "627-c0436b6a-d276-4cd8-9c44-1eae86cf5d0e"
S3KEY = "EXOb7bcf7d1e53f2d46923144de"
S3SECRET = "-uUmMuAfx40LpTKTZgdbXswTw09o_qmE4gzkmQS8PTk"
S3BUCKET = "140-c0436b6a-d276-4cd8-9c44-1eae86cf5d0e"
S3KEY = "EXOa947c7fc5990a7a6f6c40860"
S3SECRET = "J1yOTLbYEO6cMxQ2wgIwe__ru9-_RH5BBtKzx_2JJHk"

View File

@ -533,7 +533,7 @@ function HistoryOfActions(props: HistoryProps) {
<IconButton
style={iconStyle}
onClick={() => HandleDelete(action)}
disabled={action.userName != currentUser.name}
// disabled={action.userName != currentUser.name}
>
<DeleteIcon />
</IconButton>

View File

@ -130,10 +130,11 @@ const FlatInstallationView = (props: FlatInstallationViewProps) => {
</TableHead>
<TableBody>
{sortedInstallations
.filter(
(installation) =>
installation.status === -1 && installation.device === 1
)
// .filter(
// (installation) =>
// installation.status === -1 &&
// installation.testingMode == false
// )
.map((installation) => {
const isInstallationSelected =
installation.s3BucketId === selectedInstallation;