using System.Diagnostics.CodeAnalysis; using System.Text; using System.Text.Json; using InnovEnergy.App.SinexcelCommunication.DataTypes; using RabbitMQ.Client; namespace InnovEnergy.App.SinexcelCommunication.MiddlewareClasses; public static class RabbitMqManager { private static ConnectionFactory? _factory ; private static IConnection ? _connection; private static IModel? _channel; public static Boolean SubscribeToQueue(StatusMessage currentSalimaxState, String? s3Bucket,String VpnServerIp) { try { //_factory = new ConnectionFactory { HostName = VpnServerIp }; _factory = new ConnectionFactory { HostName = VpnServerIp, Port = 5672, VirtualHost = "/", UserName = "producer", Password = "b187ceaddb54d5485063ddc1d41af66f", AutomaticRecoveryEnabled = true, NetworkRecoveryInterval = TimeSpan.FromSeconds(10), RequestedHeartbeat = TimeSpan.FromSeconds(30) }; _connection = _factory.CreateConnection(); _channel = _connection.CreateModel(); _channel.QueueDeclare(queue: "statusQueue", durable: true, exclusive: false, autoDelete: false, arguments: null); Console.WriteLine("The controller sends its status to the middleware for the first time"); if (s3Bucket != null) InformMiddleware(currentSalimaxState); } catch (Exception ex) { Console.WriteLine("An error occurred while connecting to the RabbitMQ queue: " + ex.Message); return false; } return true; } public static void InformMiddleware(StatusMessage status) { var message = JsonSerializer.Serialize(status); var body = Encoding.UTF8.GetBytes(message); _channel.BasicPublish(exchange: string.Empty, routingKey: "statusQueue", basicProperties: null, body: body); Console.WriteLine($"Producer sent message: {message}"); } public static Boolean EnsureConnected(StatusMessage currentSalimaxState, string? s3Bucket, string vpnServerIp) { try { if (_connection == null || !_connection.IsOpen || _channel == null || _channel.IsClosed) { Console.WriteLine("⚠ RabbitMQ connection lost. Reconnecting..."); _connection?.Dispose(); _channel?.Dispose(); return SubscribeToQueue(currentSalimaxState, s3Bucket, vpnServerIp); } return true; } catch (Exception ex) { Console.WriteLine("❌ Error while ensuring RabbitMQ connection: " + ex); return false; } } }