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
        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.º 4
0
        static async Task <ConnectAckCode> MqttConnectAsync(string token)
        {
            PrintMessage("Trying to connect", ConsoleColor.Cyan, true);
            string         sessionId = Guid.NewGuid().ToString();
            ConnectAckCode code      = await mqttClient.ConnectAsync(sessionId, "JWT", token, 90);

            PrintMessage($"MQTT connection code {code}", code == ConnectAckCode.ConnectionAccepted ? ConsoleColor.Green : ConsoleColor.Red, false);

            return(code);
        }
Ejemplo n.º 5
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.º 6
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.º 7
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.");
            }
        }