88 lines
2.9 KiB
C#
88 lines
2.9 KiB
C#
using System.Net;
|
|
using System.Net.NetworkInformation;
|
|
using System.Net.Sockets;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using InnovEnergy.App.SinexcelCommunication.DataTypes;
|
|
|
|
namespace InnovEnergy.App.SinexcelCommunication.MiddlewareClasses;
|
|
|
|
public static class MiddlewareAgent
|
|
{
|
|
private static UdpClient _udpListener = null!;
|
|
private static IPAddress? _controllerIpAddress;
|
|
private static EndPoint? _endPoint;
|
|
|
|
public static void InitializeCommunicationToMiddleware()
|
|
{
|
|
_controllerIpAddress = FindVpnIp();
|
|
if (Equals(IPAddress.None, _controllerIpAddress))
|
|
{
|
|
Console.WriteLine("There is no VPN interface, exiting...");
|
|
}
|
|
|
|
const Int32 udpPort = 9000;
|
|
_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);
|
|
|
|
var config = JsonSerializer.Deserialize<Configuration>(message);
|
|
|
|
if (config != null)
|
|
{
|
|
Console.WriteLine($"Received a configuration message: GridSetPoint is " + config.GridSetPoint +
|
|
", MinimumSoC is " + config.MinimumSoC + " and operating priorty is " );
|
|
|
|
// Send the reply to the sender's endpoint
|
|
_udpListener.Send(replyData, replyData.Length, serverEndpoint);
|
|
Console.WriteLine($"Replied to {serverEndpoint}: {replyMessage}");
|
|
return config;
|
|
}
|
|
}
|
|
|
|
if (_endPoint != null && !_endPoint.Equals(_udpListener.Client.LocalEndPoint as IPEndPoint))
|
|
{
|
|
Console.WriteLine("UDP address has changed, rebinding...");
|
|
InitializeCommunicationToMiddleware();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
} |