public IMqttChannelAdapter CreateClientAdapter(MqttClientOptions options, MqttPacketInspector packetInspector, IMqttNetLogger logger)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            switch (options.ChannelOptions)
            {
            case MqttClientTcpOptions _:
            {
                return(new MqttChannelAdapter(
                           new MqttTcpChannel(options),
                           new MqttPacketFormatterAdapter(options.ProtocolVersion, new MqttBufferWriter(4096, 65535)),
                           packetInspector,
                           logger));
            }

            case MqttClientWebSocketOptions webSocketOptions:
            {
                return(new MqttChannelAdapter(
                           new WebSocket4NetMqttChannel(options, webSocketOptions),
                           new MqttPacketFormatterAdapter(options.ProtocolVersion, new MqttBufferWriter(4068, 65535)),
                           packetInspector,
                           logger));
            }

            default:
            {
                throw new NotSupportedException();
            }
            }
        }
Example #2
0
        static async Task Main(string[] args)
        {
            var mqttFactory = new MqttFactory();

            var tlsOptions = new MqttClientTlsOptions
            {
                UseTls = false,
                IgnoreCertificateChainErrors      = true,
                IgnoreCertificateRevocationErrors = true,
                AllowUntrustedCertificates        = true
            };

            var options = new MqttClientOptions
            {
                ClientId        = "Note",
                ProtocolVersion = MqttProtocolVersion.V311,
                ChannelOptions  = new MqttClientTcpOptions
                {
                    Server     = "xx.xx.xx.xx",
                    Port       = 1883,
                    TlsOptions = tlsOptions
                }
            };

            if (options.ChannelOptions == null)
            {
                throw new InvalidOperationException();
            }

            options.Credentials = new MqttClientCredentials
            {
                Username = "******",
                Password = Encoding.UTF8.GetBytes("123456")
            };

            var topicFilter = new MqttTopicFilter {
                Topic = "esp32/dht/temperature"
            };


            options.CleanSession    = true;
            options.KeepAlivePeriod = TimeSpan.FromSeconds(5);

            managedMqttClientSubscriber = mqttFactory.CreateManagedMqttClient();
            managedMqttClientSubscriber.ConnectedHandler    = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected);
            managedMqttClientSubscriber.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected);
            managedMqttClientSubscriber.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived);

            await managedMqttClientSubscriber.SubscribeAsync(topicFilter);

            await managedMqttClientSubscriber.StartAsync(
                new ManagedMqttClientOptions
            {
                ClientOptions = options
            });

            while (true)
            {
            }
        }
Example #3
0
        /// <summary>
        /// 登陆连接
        /// </summary>
        /// <param name="host">主机</param>
        /// <param name="port">端口</param>
        /// <param name="userId">用户Id</param>
        /// <param name="userName">用户名</param>
        /// <param name="userPad">用户密码</param>
        public void Connect(string host, int port, int userId, string userName, string userPad)
        {
            this.host   = host;
            this.port   = port;
            this.userId = userId;
            if (LoginEvent != null)
            {
                Tuple <bool, string, string> tuple = LoginEvent?.Invoke();
                if (!tuple.Item1)
                {
                    return;
                }
                userName = tuple.Item2;
                userPad  = tuple.Item3;
            }
            var options = new MqttClientOptions
            {
                ClientId       = this.ClientId,
                ChannelOptions = new MqttClientTcpOptions()
                {
                    Server = host,
                    Port   = port
                },
                Credentials = new MqttClientCredentials()
                {
                    Username = userId > 0 ? userId + "" : userName,
                    Password = userId > 0 ? null : userPad,
                },
                CleanSession = true,
            };

            options.KeepAlivePeriod = TimeSpan.FromSeconds(this.keepAlivePeriod);
            //options.KeepAliveSendInterval = TimeSpan.FromSeconds(15);
            mqttClient.ConnectAsync(options);
        }
Example #4
0
        public async Task ConnectAsync(MqttClientOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (_socket == null)
            {
                _socket = new StreamSocket();
            }

            if (!options.TlsOptions.UseTls)
            {
                await _socket.ConnectAsync(new HostName(options.Server), options.GetPort().ToString());
            }
            else
            {
                _socket.Control.ClientCertificate = LoadCertificate(options);

                if (!options.TlsOptions.CheckCertificateRevocation)
                {
                    _socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.IncompleteChain);
                    _socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.RevocationInformationMissing);
                }

                await _socket.ConnectAsync(new HostName(options.Server), options.GetPort().ToString(), SocketProtectionLevel.Tls12);
            }

            SendStream       = _socket.OutputStream.AsStreamForWrite();
            ReceiveStream    = _socket.InputStream.AsStreamForRead();
            RawReceiveStream = ReceiveStream;
        }
Example #5
0
        public static async void MqttclientConnect()
        {
            try
            {
                var clientoptions = new MqttClientOptions();
                clientoptions.ChannelOptions = new MqttClientTcpOptions()
                {
                    Server = "192.168.137.1",
                    Port   = 1883
                };
                clientoptions.Credentials = new MqttClientCredentials()
                {
                    Username = "******",
                    Password = "******"
                };
                clientoptions.CleanSession          = true;
                clientoptions.KeepAlivePeriod       = TimeSpan.FromSeconds(100.0);
                clientoptions.KeepAliveSendInterval = TimeSpan.FromSeconds(20000);

                var mqttclient = new MqttFactory().CreateMqttClient();

                await mqttclient.ConnectAsync(clientoptions);
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #6
0
        public async Task ConnectAsync(MqttClientOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            try
            {
                if (!options.TlsOptions.UseTls)
                {
                    await _socket.ConnectAsync(new HostName(options.Server), options.GetPort().ToString());
                }
                else
                {
                    _socket.Control.ClientCertificate = LoadCertificate(options);

                    if (!options.TlsOptions.CheckCertificateRevocation)
                    {
                        _socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.IncompleteChain);
                        _socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.RevocationInformationMissing);
                    }

                    await _socket.ConnectAsync(new HostName(options.Server), options.GetPort().ToString(), SocketProtectionLevel.Tls12);
                }
            }
            catch (SocketException exception)
            {
                throw new MqttCommunicationException(exception);
            }
        }
        public MqttClient(string clientId = "")
        {
            if (clientId == string.Empty)
            {
                clientId = Guid.NewGuid().ToString();
            }

            this._clientOption = new MqttClientOptions()
            {
                ClientId = clientId
            };
            this._clientOption.CleanSession         = false;
            this._clientOption.KeepAlivePeriod      = TimeSpan.FromSeconds(90);
            this._clientOption.CommunicationTimeout = TimeSpan.FromSeconds(10);
            // 遗嘱信息
            this._clientOption.WillMessage = new MqttApplicationMessage()
            {
                Topic   = "Test",
                Payload = Encoding.UTF8.GetBytes("异常中断"),
                QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce
            };

            this._clientOption.ProtocolVersion = MQTTnet.Serializer.MqttProtocolVersion.V310;

            this._mqttClient = new MqttFactory().CreateMqttClient();
        }
Example #8
0
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="id"></param>
        /// <param name="url"></param>
        /// <param name="port"></param>
        private static void InitClient(string id, string url = "127.0.0.1", int port = 1883)
        {
            var options = new MqttClientOptions()
            {
                ClientId = id
            };

            options.ChannelOptions = new MqttClientTcpOptions()
            {
                Server = url,
                Port   = port
            };
            options.Credentials = new MqttClientCredentials()
            {
                Username = _myMqtt.UserName,
                Password = _myMqtt.Password
            };
            options.CleanSession          = true;
            options.KeepAlivePeriod       = TimeSpan.FromSeconds(100);
            options.KeepAliveSendInterval = TimeSpan.FromSeconds(10000);
            if (_client != null)
            {
                if (_myMqtt.IsConnected == true)
                {
                    _client.DisconnectAsync();
                }
                _client = null;
            }
            _client = new MQTTnet.MqttFactory().CreateMqttClient();
            _client.ApplicationMessageReceived += _client_ApplicationMessageReceived;
            _client.Connected    += _client_Connected;
            _client.Disconnected += _client_Disconnected;
            _client.ConnectAsync(options);
        }
Example #9
0
        public async Task ConnectAsync(MqttClientOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (_socket == null)
            {
                _socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            }

            await _socket.ConnectAsync(options.Server, options.GetPort()).ConfigureAwait(false);

            if (options.TlsOptions.UseTls)
            {
                _sslStream    = new SslStream(new NetworkStream(_socket, true));
                ReceiveStream = _sslStream;
                await _sslStream.AuthenticateAsClientAsync(options.Server, LoadCertificates(options), SslProtocols.Tls12, options.TlsOptions.CheckCertificateRevocation).ConfigureAwait(false);
            }
            else
            {
                ReceiveStream = new NetworkStream(_socket);
            }
        }
Example #10
0
        private void CreateMQTTClient()
        {
            var clientOptions = new MqttClientOptions()
            {
                ClientId        = _config.RobotName,
                ProtocolVersion = MqttProtocolVersion.V500,
                ChannelOptions  = new MqttClientTcpOptions()
                {
                    Server     = $"{_brokerIP}",
                    Port       = _brokerPort,
                    TlsOptions = _config.TLSOptions
                },
                KeepAlivePeriod = _config.KeepalivePeriod,
                CleanSession    = _config.CleanSession
            };

            _mqttClient = new MqttFactory().CreateManagedMqttClient();
            _mqttClient.ConnectedHandler    = new MqttClientConnectedHandlerDelegate(OnConnected);
            _mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnDisconnected);
            _mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnMessageReceived);

            _mqttClient.StartAsync(new ManagedMqttClientOptions()
            {
                ClientOptions = clientOptions
            }).Wait();
        }
Example #11
0
        private async void StartSubscribe()
        {
            var ClientOptions = new MqttClientOptions
            {
                ClientId       = mqttOptions.ClientId,
                ChannelOptions = new MqttClientTcpOptions
                {
                    Server = mqttOptions.BindAddress,
                    Port   = mqttOptions.Port
                },
            };

            client = new MqttFactory().CreateMqttClient();
            client.ApplicationMessageReceived += ManagedClient_ApplicationMessageReceived;
            client.Connected    += ManagedClient_Connected;
            client.Disconnected += Client_Disconnected;

            try
            {
                var result = await client.ConnectAsync(ClientOptions);
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "### CONNECTING FAILED ###" + Environment.NewLine + exception);
            }
        }
        public async Task ConnectAsync(MqttClientOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            try
            {
                if (_socket == null)
                {
                    _socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
                }

                await _socket.ConnectAsync(options.Server, options.GetPort());

                if (options.TlsOptions.UseTls)
                {
                    _sslStream = new SslStream(new NetworkStream(_socket, true), true, (sender, certificate, chain, errors) => true);
                    //await _sslStream.AuthenticateAsClientAsync(options.Server, LoadCertificates(options), SslProtocols.Tls11, options.TlsOptions.CheckCertificateRevocation);
                    await _sslStream.AuthenticateAsClientAsync(options.Server, _certificateCollection, SslProtocols.Tls11, options.TlsOptions.CheckCertificateRevocation);
                }
            }
            catch (SocketException exception)
            {
                throw new MqttCommunicationException(exception);
            }
        }
Example #13
0
        private async void Connect(object sender, RoutedEventArgs e)
        {
            var options = new MqttClientOptions
            {
                Server   = Server.Text,
                UserName = User.Text,
                Password = Password.Text,
                ClientId = ClientId.Text
            };

            options.TlsOptions.UseTls = UseTls.IsChecked == true;

            try
            {
                if (_mqttClient != null)
                {
                    await _mqttClient.DisconnectAsync();
                }

                var factory = new MqttClientFactory();
                _mqttClient = factory.CreateMqttClient(options);
                await _mqttClient.ConnectAsync();
            }
            catch (Exception exception)
            {
                Trace.Text += exception + Environment.NewLine;
            }
        }
Example #14
0
        public void Get(string topic)
        {
            var factory       = new MqttFactory();
            var client        = factory.CreateMqttClient();
            var clientOptions = new MqttClientOptions
            {
                ChannelOptions = new MqttClientTcpOptions
                {
                    Server = "127.0.0.1"
                }
            };

            client.ConnectAsync(clientOptions);
            client.SubscribeAsync(new MqttTopicFilter {
                Topic = topic
            });

            client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
            {
                //var messaggio = string.Empty;
                Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                Console.WriteLine();
                var messaggio   = (Encoding.UTF8.GetString(e.ApplicationMessage.Payload)).ToString();
                var deserialize = JsonSerializer.Deserialize <Command>(messaggio);
                Console.WriteLine(deserialize.ScooterId + " " + deserialize.MaxSpeed + " ");
            });
        }
Example #15
0
        public void Init(string clientId, string server, int?port)
        {
            try
            {
                mqttClientOptions = new MqttClientOptions
                {
                    ClientId       = clientId,
                    CleanSession   = false,
                    ChannelOptions = new MqttClientTcpOptions
                    {
                        Server = server,
                        Port   = port
                    }
                };

                var factory = new MqttFactory();
                _mqttClient = factory.CreateMqttClient();
                _mqttClient.ConnectedHandler = new MqttConnectedHandler(mqttClientConnectedEventArgs =>
                {
                    Connected?.Invoke(this, mqttClientConnectedEventArgs);
                });
                _mqttClient.DisconnectedHandler = new MqttDisconnectedHandler(disconnectEventArgs =>
                {
                    Disconnected?.Invoke(this, disconnectEventArgs);
                });
                _mqttClient.ApplicationMessageReceivedHandler = new MqttMessageReceivedHandler(messageReceivedArgs =>
                {
                    MessageReceived?.Invoke(this, messageReceivedArgs);
                });
            }
            catch (Exception ex)
            {
            }
        }
Example #16
0
        public MqttTcpChannel(MqttClientOptions clientOptions) : this()
        {
            _clientOptions = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions));
            _tcpOptions    = (MqttClientTcpOptions)clientOptions.ChannelOptions;

            IsSecureConnection = clientOptions.ChannelOptions?.TlsOptions?.UseTls == true;
        }
Example #17
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //var factory = new MqttFactory();
            var client        = _mqttFactory.CreateMqttClient();
            var clientOptions = new MqttClientOptions
            {
                ChannelOptions = new MqttClientTcpOptions
                {
                    Server = _mqttServer
                }
            };

            client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(MessageReceiver());

            client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(ClientConnect(client));

            client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(ClientDisconnect(client, clientOptions));

            try
            {
                await client.ConnectAsync(clientOptions);
            }
            catch (Exception exception)
            {
                _logger.LogInformation($"Connection Failed {exception?.Message}");
            }

            _logger.LogInformation("Waiting for messages.");

            while (!stoppingToken.IsCancellationRequested)
            {
                await Task.Delay(1000, stoppingToken);
            }
        }
Example #18
0
        public MqttConnection(string server, int port, string clientID, string userName, string password, List <string> topics)
        {
            Server   = server;
            Port     = port;
            ClientID = clientID;
            Username = userName;
            Password = password;
            Topics   = topics;

            MqttClientOptions = new MqttClientOptions
            {
                ClientId       = ClientID,
                CleanSession   = true,
                ChannelOptions = new MqttClientTcpOptions
                {
                    Server = Server,
                    Port   = Port
                },
                Credentials = new MqttClientCredentials
                {
                    Username = Username,
                    Password = Encoding.UTF8.GetBytes(Password)
                }
            };
        }
Example #19
0
        public IMqttChannelAdapter CreateClientAdapter(MqttClientOptions options, MqttPacketInspector packetInspector, IMqttNetLogger logger)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            IMqttChannel channel;

            switch (options.ChannelOptions)
            {
            case MqttClientTcpOptions _:
            {
                channel = new MqttTcpChannel(options);
                break;
            }

            case MqttClientWebSocketOptions webSocketOptions:
            {
                channel = new MqttWebSocketChannel(webSocketOptions);
                break;
            }

            default:
            {
                throw new NotSupportedException();
            }
            }

            var bufferWriter           = new MqttBufferWriter(options.WriterBufferSize, options.WriterBufferSizeMax);
            var packetFormatterAdapter = new MqttPacketFormatterAdapter(options.ProtocolVersion, bufferWriter);

            return(new MqttChannelAdapter(channel, packetFormatterAdapter, packetInspector, logger));
        }
Example #20
0
        public async Task mqttClientConnectAsync()
        {
            QMLog qMLog = new QMLog();

            var options = new MqttClientOptions
            {
                ClientId    = ClientId,
                Credentials = new MqttClientCredentials
                {
                    Username = Username,
                    Password = Password
                },
                ChannelOptions = new MqttClientTcpOptions
                {
                    Server = MqttServer,
                    Port   = MqttPort
                }
            };

            qMLog.WriteLogToFile("创建", JsonConvert.SerializeObject(options), 0);
            // qMLog.WriteLogToFile("MqttClientConnectAsync", JsonConvert.SerializeObject(options),0);
            try
            {
                await mqttClient.ConnectAsync(options);
            }
            catch (Exception e)
            {
                qMLog.WriteLogToFile("连接", e.ToString(), 0);
            }
        }
Example #21
0
        private async Task ConnectMqttServerAsync()
        {
            if (_mqttClient == null)
            {
                _mqttClient = (new MqttFactory()).CreateMqttClient();
                _mqttClient.ApplicationMessageReceived += _mqttClient_ApplicationMessageReceived;
                _mqttClient.Connected    += _mqttClient_Connected;
                _mqttClient.Disconnected += _mqttClient_Disconnected;
            }

            try
            {
                var keep    = int.Parse(cfg.AppSettings["EmqKeepAlive"]);
                var options = new MqttClientOptions()
                {
                    ClientId        = cfg.AppSettings["MqttClientId"],
                    ProtocolVersion = MQTTnet.Serializer.MqttProtocolVersion.V311,
                    ChannelOptions  = new MqttClientTcpOptions
                    {
                        Server = cfg.AppSettings["EmqIp"],
                        Port   = int.Parse(cfg.AppSettings["EmqPort"]),
                    },
                    KeepAlivePeriod       = new TimeSpan(0, 0, keep * 2),
                    KeepAliveSendInterval = new TimeSpan(0, 0, keep),
                };

                await _mqttClient.ConnectAsync(options);
            }
            catch (Exception ex)
            {
                LogHelper.Error($"connect mqtt failed!=> {ex.Message}");
            }
        }
Example #22
0
        public void Get(string topic)
        {
            var factory       = new MqttFactory();
            var client        = factory.CreateMqttClient();
            var clientOptions = new MqttClientOptions
            {
                ChannelOptions = new MqttClientTcpOptions
                {
                    Server = "127.0.0.1"
                }
            };

            client.ConnectAsync(clientOptions);
            client.SubscribeAsync(new MqttTopicFilter {
                Topic = "Test/#"
            });

            client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
            {
                Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                Console.WriteLine();
            });
        }
        public async Task <IMqttClient> ConnectTestClient(IMqttServer server, string clientId, MqttApplicationMessage willMessage = null)
        {
            var adapterA = new TestMqttCommunicationAdapter();
            var adapterB = new TestMqttCommunicationAdapter();

            adapterA.Partner = adapterB;
            adapterB.Partner = adapterA;

            var client = new MqttClient(
                new TestMqttCommunicationAdapterFactory(adapterA),
                new MqttNetLogger());

            var connected = WaitForClientToConnect(server, clientId);

            FireClientAcceptedEvent(adapterB);

            var options = new MqttClientOptions
            {
                ClientId       = clientId,
                WillMessage    = willMessage,
                ChannelOptions = new MqttClientTcpOptions()
            };

            await client.ConnectAsync(options);

            await connected;

            return(client);
        }
        public DeviceMessageBrokerService(ILogService logService)
        {
            if (logService == null)
            {
                throw new ArgumentNullException(nameof(logService));
            }

            _log = logService.CreatePublisher(nameof(DeviceMessageBrokerService));

            var channelA = new MqttCommunicationAdapter();

            _clientCommunicationAdapter         = new MqttCommunicationAdapter();
            channelA.Partner                    = _clientCommunicationAdapter;
            _clientCommunicationAdapter.Partner = channelA;

            var mqttClientOptions = new MqttClientOptions {
                ClientId = "HA4IoT.Loopback"
            };

            _client = new MqttClient(mqttClientOptions, channelA);
            _client.ApplicationMessageReceived += ProcessIncomingMessage;

            var mqttServerOptions = new MqttServerOptions();

            _server = new MqttServerFactory().CreateMqttServer(mqttServerOptions);
            _server.ClientConnected += (s, e) => _log.Info($"MQTT client '{e.Identifier}' connected.");
        }
Example #25
0
        public static async Task Connect(string clientId, string[] topics = null)
        {
            var options = new MqttClientOptions
            {
                ClientId        = clientId,
                ProtocolVersion = MqttProtocolVersion.V311,
                ChannelOptions  = new MqttClientTcpOptions
                {
                    Server     = Host,
                    Port       = Port,
                    TlsOptions = new MqttClientTlsOptions
                    {
                        UseTls = false,
                        IgnoreCertificateChainErrors      = true,
                        IgnoreCertificateRevocationErrors = true,
                        AllowUntrustedCertificates        = true
                    },
                    BufferSize = 2048
                },
                Credentials = new MqttClientCredentials
                {
                    Username = UserName,
                    Password = Encoding.UTF8.GetBytes(Password)
                },
                CleanSession         = true,
                KeepAlivePeriod      = TimeSpan.FromMinutes(2),
                CommunicationTimeout = TimeSpan.FromSeconds(60)
            };


            var client = Factory.CreateMqttClient();

            client.ConnectedHandler    = new MqttClientConnectedHandlerDelegate((args) => OnConnected(args, client));
            client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate((args) => OnDisconnected(args, clientId));
            try
            {
                //var st = new Stopwatch();
                //st.Start();
                await client.ConnectAsync(options);

                if (topics != null && topics.Length != 0)
                {
                    foreach (var topic in topics)
                    {
                        await client.SubscribeAsync(topic, MqttQualityOfServiceLevel.AtLeastOnce);
                    }
                }

                //st.Stop();
                //Console.WriteLine($"{DateTime.Now:g} - {client.Options.ClientId.PadRight(36)} Connected \t {st.ElapsedMilliseconds} ms");
                Console.WriteLine($"{DateTime.Now:g} - {client.Options.ClientId.PadRight(36)} Connected");
                //ConnectionTimes.Add((int) st.ElapsedMilliseconds);
            }
            catch (Exception exception)
            {
                Program.ConnectedClients--;
                LogExc(exception);
            }
        }
Example #26
0
        private async void MqttClient()
        {
            try
            {
                var options = new MqttClientOptions()
                {
                    ClientId = Guid.NewGuid().ToString("D")
                };
                options.ChannelOptions = new MqttClientTcpOptions()
                {
                    Server = TxbServer.Text,
                    Port   = Convert.ToInt32(TxbPort.Text)
                };
                options.Credentials = new MqttClientCredentials()
                {
                    Username = "******",
                    Password = "******"
                };

                options.CleanSession          = true;
                options.KeepAlivePeriod       = TimeSpan.FromSeconds(100.5);
                options.KeepAliveSendInterval = TimeSpan.FromSeconds(20000);

                if (null != _mqttClient)
                {
                    await _mqttClient.DisconnectAsync();

                    _mqttClient = null;
                }
                _mqttClient = new MqttFactory().CreateMqttClient();

                _mqttClient.ApplicationMessageReceived += (sender, args) =>
                {
                    listBox1.BeginInvoke(
                        _updateListBoxAction,
                        $"ClientID:{args.ClientId} | TOPIC:{args.ApplicationMessage.Topic} | Payload:{Encoding.UTF8.GetString(args.ApplicationMessage.Payload)} | QoS:{args.ApplicationMessage.QualityOfServiceLevel} | Retain:{args.ApplicationMessage.Retain}"
                        );
                };

                _mqttClient.Connected += (sender, args) =>
                {
                    listBox1.BeginInvoke(_updateListBoxAction,
                                         $"Client is Connected:  IsSessionPresent:{args.IsSessionPresent}");
                };

                _mqttClient.Disconnected += (sender, args) =>
                {
                    listBox1.BeginInvoke(_updateListBoxAction,
                                         $"Client is DisConnected ClientWasConnected:{args.ClientWasConnected}");
                };

                await _mqttClient.ConnectAsync(options);
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #27
0
        public IMqttClient CreateMqttClient(MqttClientOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return(new MqttClient(options, new MqttChannelCommunicationAdapter(new MqttTcpChannel(), new MqttV311PacketSerializer())));
        }
Example #28
0
        public IMqttClient CreateMqttClient(MqttClientOptions options, X509CertificateCollection certificateCollection)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return(new MqttClient(options, new MqttChannelCommunicationAdapter(new CustomMqttTcpChannel(certificateCollection), new MqttPacketSerializer())));
        }
Example #29
0
        public async Task ConnectAsync(MqttClientOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            await _socket.ConnectAsync(new HostName(options.Server), options.Port.ToString());
        }
Example #30
0
        public async Task ConnectAsync()
        {
            _client = _factory.CreateMqttClient();

            var clientOptions = new MqttClientOptions
            {
                ChannelOptions = new MqttClientTcpOptions
                {
                    Server = _broker
                }
            };

            _client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(async e =>
            {
                Console.WriteLine("### RECEIVED MESSAGE FROM SHELLY 1PM ###");
                Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");

                var payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);

                Console.WriteLine($"+ Payload = {payload}");
                Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                Console.WriteLine();

                await Task.Delay(0);
            });

            _client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(async e =>
            {
                Console.WriteLine("### RELAY-CLIENT: CONNECTED WITH SERVER ###");
                await Task.Delay(0);
            });

            _client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(async e =>
            {
                Console.WriteLine("### RELAY-CLIENT: DISCONNECTED FROM SERVER ###");
                await Task.Delay(TimeSpan.FromSeconds(5));

                try
                {
                    await _client.ConnectAsync(clientOptions);
                }
                catch
                {
                    Console.WriteLine("### RELAY-CLIENT: RECONNECTING FAILED ###");
                }
            });

            try
            {
                await _client.ConnectAsync(clientOptions);
            }
            catch (Exception exception)
            {
                Console.WriteLine("### RELAY-CLIENT: CONNECTING FAILED ###" + Environment.NewLine + exception);
            }
        }