using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text; using System.Text.Json; using InnovEnergy.App.SaliMax.DataTypes; using InnovEnergy.App.SaliMax.Ess; namespace InnovEnergy.App.SaliMax.MiddlewareClasses; public static class MiddlewareAgent { public static UdpClient UdpListener = null!; private static IPAddress? _controllerIpAddress; public static void InitializeCommunicationToMiddleware() { _controllerIpAddress = FindVpnIp(); if (Equals(IPAddress.None, _controllerIpAddress)) { Console.WriteLine("There is no VPN interface, exiting..."); } const Int32 udpPort = 9000; var endPoint = new IPEndPoint(_controllerIpAddress, udpPort); UdpListener = new UdpClient(); UdpListener.Client.Blocking = false; UdpListener.Client.Bind(endPoint); } private static IPAddress FindVpnIp() { const String interfaceName = "innovenergy"; var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (var networkInterface in networkInterfaces) { if (networkInterface.Name == interfaceName) { var ipProps = networkInterface.GetIPProperties(); var uniCastIPs = ipProps.UnicastAddresses; var controllerIpAddress = uniCastIPs[0].Address; Console.WriteLine("VPN IP is: "+ uniCastIPs[0].Address); return controllerIpAddress; } } return IPAddress.None; } public static Configuration? SetConfigurationFile() { if (UdpListener.Available > 0) { IPEndPoint? serverEndpoint = null; var replyMessage = "ACK"; var replyData = Encoding.UTF8.GetBytes(replyMessage); var udpMessage = UdpListener.Receive(ref serverEndpoint); var message = Encoding.UTF8.GetString(udpMessage); Configuration? config = JsonSerializer.Deserialize(message); Console.WriteLine($"Received a configuration message: GridSetPoint is " + config.GridSetPoint + ", MinimumSoC is " + config.MinimumSoC + " and ForceCalibrationCharge is " + config.ForceCalibrationCharge); // Send the reply to the sender's endpoint UdpListener.Send(replyData, replyData.Length, serverEndpoint); Console.WriteLine($"Replied to {serverEndpoint}: {replyMessage}"); return config; } return null; } }