Ejemplo n.º 1
0
        private void CreateWebSocketClient()
        {
            try
            {
                Uri uri = new Uri(String.Format($"wss://{config.Hostname}/ws/connect"));
                cts              = new CancellationTokenSource();
                channel          = new WebSocketClientChannel(uri, "mqtt", new WebSocketConfig(), cts.Token);
                channel.OnClose += Channel_OnClose;
                pclient          = new PiraeusMqttClient(new MqttConfig(180), channel);

                ConnectAckCode code = pclient.ConnectAsync(clientId, "JWT", config.SecurityToken, 90).GetAwaiter().GetResult();
                Console.WriteLine($"MQTT client connection code = {code}");
                if (code != ConnectAckCode.ConnectionAccepted)
                {
                    throw new Exception("MQTT connection failed.");
                }

                pclient.OnChannelError += Pclient_OnChannelError;

                pclient.SubscribeAsync(config.RtuInputPiSystem, QualityOfServiceLevelType.AtLeastOnce, RtuInput).GetAwaiter();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception creating web socket client - {ex.Message}");
                SetDelay();
                CreateWebSocketClient();
            }
        }
Ejemplo n.º 2
0
        private PiraeusMqttClient AddClient()
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            //string uriString = String.Format("wss://{0}/ws/api/connect", hostname);

            Uri      uri     = new Uri(endpoint);
            IChannel channel = ChannelFactory.Create(uri, securityToken, "mqtt", new WebSocketConfig(), cts.Token);



            //IChannel channel = new WebSocketClientChannel(new Uri(endpoint), "mqtt", new WebSocketConfig(), cts.Token);
            //IChannel channel = ChannelFactory.Create(new Uri(endpoint), securityToken, "mqtt", new WebSocketConfig(), cts.Token);
            PiraeusMqttClient client = new PiraeusMqttClient(new MqttConfig(90), channel);

            try
            {
                ConnectAckCode code = client.ConnectAsync(Guid.NewGuid().ToString(), "JWT", securityToken, 90).GetAwaiter().GetResult();
                if (code != ConnectAckCode.ConnectionAccepted)
                {
                    //Houston, we have a problem
                }
                else
                {
                    clients.Add(channel.Id, client);
                    sources.Add(channel.Id, cts);
                    channels.Add(channel.Id, channel);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Connnect pool failed to add client with - {ex.Message}");
            }

            return(client);
        }
Ejemplo n.º 3
0
        private static void Main(string[] args)
        {
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            cts = new CancellationTokenSource();

            if (args == null || args.Length == 0)
            {
                UseUserInput();
            }
            else
            {
                Console.WriteLine("Invalid user input");
                Console.ReadKey();
                return;
            }

            string token = GetSecurityToken(name, role);

            channel = CreateChannel(token, cts);

            channel.OnClose += Channel_OnClose;
            channel.OnError += Channel_OnError;
            channel.OnOpen  += Channel_OnOpen;

            mqttClient = new PiraeusMqttClient(new MqttConfig(180.0), channel);

            Task task = StartMqttClientAsync(token);

            Task.WaitAll(task);

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
            cts.Cancel();
        }
Ejemplo n.º 4
0
        public async Task OpenAsync()
        {
            await ExecuteRetryPolicy();

            subscriptions.Clear();

            if (channel != null)
            {
                try
                {
                    channel.Dispose();
                    channel = null;
                    client  = null;
                    logger?.LogDebug("Disposed internal channel.");
                }
                catch (Exception ex)
                {
                    logger?.LogError(ex, "Fault disposing internal channel.");
                }
            }

            try
            {
                channel = new WebSocketClientChannel(endpointUrl, securityToken, "mqtt", new WebSocketConfig(),
                                                     CancellationToken.None);
                client = new PiraeusMqttClient(new MqttConfig(180), channel);
                client.OnChannelError       += Client_OnChannelError;
                client.OnChannelStateChange += Client_OnChannelStateChange;

                string         sessionId = Guid.NewGuid().ToString();
                ConnectAckCode code      = await client.ConnectAsync(sessionId, "JWT", securityToken, 180);

                if (code != ConnectAckCode.ConnectionAccepted)
                {
                    logger?.LogWarning($"Vrtu channel connect return code = '{code}'.");
                    OnError.Invoke(this,
                                   new ChannelErrorEventArgs(channel.Id,
                                                             new Exception($"VRtu channel failed to open with code = {code}")));
                }
                else
                {
                    logger?.LogInformation("Vrtu channel connected.");
                    try
                    {
                        diag = new DiagnosticsChannel(config, client, logger);
                        diag.StartAsync().GetAwaiter();
                    }
                    catch (Exception ex)
                    {
                        diag = null;
                        logger?.LogError(ex, "Diagnostics on Vrtu channel faulted.");
                    }
                }
            }
            catch (Exception ex)
            {
                logger?.LogError(ex, "Fault opening MQTT client channel.");
            }
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            cts = new CancellationTokenSource();

            if (args == null || args.Length == 0)
            {
                UseUserInput();
            }
            else
            {
                Console.WriteLine("Invalid user input");
                Console.ReadKey();
                return;
            }

            //Console.Write("Change name and role [y/n] ? ");
            //if(Console.ReadLine().ToLowerInvariant() == "y")
            //{
            //    Console.Write("Enter name claim value ? ");
            //    name = Console.ReadLine();
            //    Console.Write("Enter role claim value ? ");
            //    role = Console.ReadLine();
            //}

            //Console.Write("Change resource A and B [y/n] ? ");
            //if (Console.ReadLine().ToLowerInvariant() == "y")
            //{
            //    Console.Write("Enter resource publish URI ? ");
            //    pubResource = Console.ReadLine();
            //    Console.Write("Enter resource subscribe URI ? ");
            //    subResource = Console.ReadLine();
            //}

            string token = GetSecurityToken(name, role);

            //create the channel
            channel = CreateChannel(token, cts);

            //add some channel events
            channel.OnClose += Channel_OnClose;
            channel.OnError += Channel_OnError;
            channel.OnOpen  += Channel_OnOpen;

            mqttClient = new PiraeusMqttClient(new SkunkLab.Protocols.Mqtt.MqttConfig(180.0), channel);

            Task task = StartMqttClientAsync(token);

            Task.WaitAll(task);

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
            cts.Cancel();
        }
Ejemplo n.º 6
0
 public DiagnosticsConnection(ModuleConfig config, PiraeusMqttClient mqttClient, ILogger logger = null)
 {
     this.name           = config.DeviceId;
     this.mqttClient     = mqttClient;
     this.logger         = logger;
     this.cache          = new LocalCache("diag");
     this.inputPiSystem  = UriGenerator.GetDeviceDiagnosticsPiSystem(config.Hostname, config.VirtualRtuId, config.DeviceId);
     this.outputPiSystem = UriGenerator.GetDeviceTelemetryPiSystem(config.Hostname, config.VirtualRtuId, config.DeviceId);
     if (!string.IsNullOrEmpty(config.InstrumentationKey))
     {
         tconfig = new TelemetryConfiguration(config.InstrumentationKey);
         tconfig.DisableTelemetry = true;
         tclient = new TelemetryClient(tconfig);
     }
 }
Ejemplo n.º 7
0
        public DiagnosticsChannel(VrtuConfig config, PiraeusMqttClient mqttClient, ILogger logger = null)
        {
            this.name       = config.VirtualRtuId;
            this.mqttClient = mqttClient;
            this.logger     = logger;
            this.cache      = new LocalCache(Guid.NewGuid().ToString());

            this.inputPiSystem  = UriGenerator.GetVirtualRtuDiagnosticsPiSystem(config.Hostname, config.VirtualRtuId);
            this.outputPiSystem = UriGenerator.GetVirtualRtuTelemetryPiSystem(config.Hostname, config.VirtualRtuId);

            if (!string.IsNullOrEmpty(config.InstrumentationKey))
            {
                tconfig = new TelemetryConfiguration(config.InstrumentationKey);
                tconfig.DisableTelemetry = true;
                tclient = new TelemetryClient(tconfig);
            }
        }
Ejemplo n.º 8
0
        public void Put(PiraeusMqttClient client)
        {
            string channelId = client.Channel.Id;

            if (sources.ContainsKey(channelId))
            {
                try
                {
                    sources[channelId].Cancel();
                }
                catch { }
            }

            if (sources.ContainsKey(channelId))
            {
                sources.Remove(channelId);
            }


            if (clients.ContainsKey(channelId))
            {
                clients.Remove(channelId);
            }

            if (channels.ContainsKey(channelId))
            {
                try
                {
                    IChannel channel = channels[channelId];
                    channel.Dispose();
                }
                catch { }
            }

            if (channels.ContainsKey(channelId))
            {
                channels.Remove(channelId);
            }

            if (channels.Count < Size)
            {
                AddClient();
            }
        }
Ejemplo n.º 9
0
 protected void Disposing(bool dispose)
 {
     if (dispose & !disposed)
     {
         disposed = true;
         try
         {
             if (client != null)
             {
                 client.Channel.Dispose();
                 client = null;
             }
         }
         catch (Exception ex)
         {
             logger?.LogError(ex, "Fault disposing module channel.");
         }
     }
 }
Ejemplo n.º 10
0
        protected ClientSingleton(string hostname, string symmetricKey)
        {
            this.hostname     = hostname;
            this.symmetricKey = symmetricKey;
            subscriptions     = new HashSet <string>();
            securityToken     = GetSecurityToken();
            uriString         = $"wss://{hostname}/ws/api/connect";
            Uri uri = new Uri(uriString);

            cts     = new CancellationTokenSource();
            channel = ChannelFactory.Create(uri, securityToken, "mqtt", new WebSocketConfig(), cts.Token);
            client  = new PiraeusMqttClient(new SkunkLab.Protocols.Mqtt.MqttConfig(180), channel);
            string         sessionId = Guid.NewGuid().ToString();
            ConnectAckCode code      = client.ConnectAsync(sessionId, "JWT", securityToken, 180).GetAwaiter().GetResult();

            if (code != ConnectAckCode.ConnectionAccepted)
            {
                throw new Exception("Invalid MQTT connection code.");
            }
        }
Ejemplo n.º 11
0
        public async Task CloseAsync()
        {
            if (client == null || !client.IsConnected)
            {
                logger?.LogWarning("MQTT client is not available to close.");
                return;
            }

            try
            {
                await client.DisconnectAsync();

                client = null;
                logger?.LogInformation("MQTT client channel disconnected/closed.");
            }
            catch (Exception ex)
            {
                logger?.LogError(ex, "Fault closing MQTT client channel.");
            }
        }
Ejemplo n.º 12
0
        public async Task <ConnectAckCode> OpenAsync()
        {
            string sessionId = Guid.NewGuid().ToString();
            Uri    uri       = new Uri(string.Format($"wss://{hostname}/ws/api/connect"));

            cts              = new CancellationTokenSource();
            channel          = ChannelFactory.Create(uri, securityToken, "mqtt", new WebSocketConfig(), cts.Token);
            channel.OnClose += Channel_OnClose;
            ConnectAckCode code = ConnectAckCode.ServerUnavailable;

            try
            {
                client = new PiraeusMqttClient(new MqttConfig(180), channel);
                client.OnChannelError += Client_OnChannelError;
                code = await client.ConnectAsync(sessionId, "JWT", securityToken, 90);
            }
            catch (Exception ex)
            {
                logger?.LogError(ex, "Web socket connection error.");
            }

            return(code);
        }
Ejemplo n.º 13
0
        public async Task OpenAsync()
        {
            await ExecuteRetryPolicy();

            subscriptions.Clear();

            if (channel != null)
            {
                try
                {
                    channel.Dispose();
                    channel = null;
                    client  = null;
                    logger?.LogDebug("Disposed internal channel.");
                }
                catch (Exception ex)
                {
                    logger?.LogError(ex, "Fault disposing internal channel.");
                }
            }

            try
            {
                channel = new WebSocketClientChannel(endpointUrl, securityToken, "mqtt", new WebSocketConfig(), CancellationToken.None);
                client  = new PiraeusMqttClient(new MqttConfig(180), channel);
                client.OnChannelError       += Client_OnChannelError;
                client.OnChannelStateChange += Client_OnChannelStateChange;

                string         sessionId = Guid.NewGuid().ToString();
                ConnectAckCode code      = await client.ConnectAsync(sessionId, "JWT", securityToken, 180);

                if (code != ConnectAckCode.ConnectionAccepted)
                {
                    logger?.LogWarning($"Module client connect return code = '{code}'.");
                    OnError?.Invoke(this, new ChannelErrorEventArgs(channel.Id, new Exception($"Module channel failed to open with code = {code}")));
                }
                else
                {
                    logger?.LogInformation("Module client connected.");
                    foreach (var slave in config.Slaves)
                    {
                        string inputPiSystem = UriGenerator.GetRtuPiSystem(config.Hostname, config.VirtualRtuId, config.DeviceId, slave.UnitId, true);
                        await client.SubscribeAsync(inputPiSystem, QualityOfServiceLevelType.AtMostOnce, ModuleReceived);

                        logger?.LogDebug($"Module client subscribed to '{inputPiSystem}'");
                    }

                    try
                    {
                        diag = new DiagnosticsChannel(config, client, logger);
                        diag.StartAsync().GetAwaiter();
                    }
                    catch (Exception ex)
                    {
                        diag = null;
                        logger?.LogError(ex, "Diagnostics channel faulted.");
                    }
                }
            }
            catch (Exception ex)
            {
                logger?.LogError(ex, "Fault opening module channel.");
            }
        }