Ejemplo n.º 1
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.º 2
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.º 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
        private async Task OpenWebSocketAsync()
        {
            connection = null;

            connection          = new WebSocketConnection(config, logger);
            connection.OnError += WebSocket_OnError;
            connection.OnClose += WebSocket_OnClose;
            ConnectAckCode code = await connection.OpenAsync();

            restarting = false;
            this.logger?.LogDebug($"VRTU web socket client opened with code '{code}'");

            if (code != ConnectAckCode.ConnectionAccepted)
            {
                OnError?.Invoke(this, new AdapterErrorEventArgs(Id, new Exception($"SCADA adapter failed to open web socket with code = {code}")));
            }
        }
Ejemplo n.º 6
0
        internal override MqttMessage Decode(byte[] message)
        {
            ConnectAckMessage connackMessage = new ConnectAckMessage();

            int  index       = 0;
            byte fixedHeader = message[index];

            base.DecodeFixedHeader(fixedHeader);

            int remainingLength = base.DecodeRemainingLength(message);

            int temp = remainingLength; //increase the fixed header size

            do
            {
                index++;
                temp = temp / 128;
            } while (temp > 0);

            index++;

            byte[] buffer = new byte[remainingLength];
            Buffer.BlockCopy(message, index, buffer, 0, buffer.Length);

            //base.VariableHeader = new ConnackVariableHeader();

            //index = base.VariableHeader.Decode(buffer);

            index = 0;
            byte reserved = buffer[index++];

            if (reserved != 0x00)
            {
                this.SessionPresent = Convert.ToBoolean(reserved);
            }

            byte code = buffer[index++];

            this.ReturnCode = (ConnectAckCode)code;


            return(connackMessage);
        }
Ejemplo n.º 7
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.º 8
0
        static async Task StartMqttClientAsync(string token)
        {
            ConnectAckCode code = await MqttConnectAsync(token);

            if (code != ConnectAckCode.ConnectionAccepted)
            {
                return;
            }

            string observableEvent = role == "A" ? "http://www.skunklab.io/resource-b" : "http://www.skunklab.io/resource-a";

            try
            {
                await mqttClient.SubscribeAsync(observableEvent, QualityOfServiceLevelType.AtLeastOnce, ObserveEvent).ContinueWith(SendMessages);
            }
            catch (Exception ex)
            {
                PrintMessage("Error", ConsoleColor.Red, true);
                PrintMessage(ex.Message, ConsoleColor.Red);
                Console.ReadKey();
            }
        }
Ejemplo n.º 9
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.º 10
0
        static async Task StartMqttClientAsync(string token)
        {
            ConnectAckCode code = await MqttConnectAsync(token);

            if (code != ConnectAckCode.ConnectionAccepted)
            {
                return;
            }

            string observableEvent = !string.IsNullOrEmpty(pubResource) ? subResource : role == "A" ? resourceB : resourceA;

            //string observableEvent = role == "A" ? resourceB : resourceA;

            try
            {
                await mqttClient.SubscribeAsync(observableEvent, QualityOfServiceLevelType.AtLeastOnce, ObserveEvent).ContinueWith(SendMessages);
            }
            catch (Exception ex)
            {
                PrintMessage("Error", ConsoleColor.Red, true);
                PrintMessage(ex.Message, ConsoleColor.Red);
                Console.ReadKey();
            }
        }
Ejemplo n.º 11
0
 public ConnectAckMessage(bool sessionPresent, ConnectAckCode returnCode)
 {
     SessionPresent = sessionPresent;
     ReturnCode     = returnCode;
 }
Ejemplo n.º 12
0
 public MqttConnectionArgs(ConnectAckCode code)
 {
     Code = code;
 }
Ejemplo n.º 13
0
 internal void Connect(ConnectAckCode code)
 {
     ConnectResult = code;
     OnConnect?.Invoke(this, new MqttConnectionArgs(code));
 }
Ejemplo n.º 14
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.");
            }
        }