Exemple #1
0
        public async Task Drop_New_Messages_On_Full_Queue()
        {
            var factory       = new MqttFactory();
            var managedClient = factory.CreateManagedMqttClient();

            try
            {
                var clientOptions = new ManagedMqttClientOptionsBuilder()
                                    .WithMaxPendingMessages(5)
                                    .WithPendingMessagesOverflowStrategy(MqttPendingMessagesOverflowStrategy.DropNewMessage);

                clientOptions.WithClientOptions(o => o.WithTcpServer("localhost"));

                await managedClient.StartAsync(clientOptions.Build());

                await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "1" });

                await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "2" });

                await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "3" });

                await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "4" });

                await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "5" });

                await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "6" });

                await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "7" });

                await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "8" });

                Assert.AreEqual(5, managedClient.PendingApplicationMessagesCount);
            }
            finally
            {
                await managedClient.StopAsync();
            }
        }
        private static void Iniciar()
        {
            try
            {
                //clientId = string.Format("{0}-{1}", NetworkUtils.GetLocalIPAddress(), Guid.NewGuid().ToString());
                MqttClientOptionsBuilder builder = new MqttClientOptionsBuilder()
                                                   .WithClientId(clientId)
                                                   .WithTcpServer(ipAddress, 1883);

                // Create client options objects
                ManagedMqttClientOptions options = new ManagedMqttClientOptionsBuilder()
                                                   .WithAutoReconnectDelay(TimeSpan.FromSeconds(10))
                                                   .WithClientOptions(builder.Build())
                                                   .Build();

                // Creates the client object
                client = new MqttFactory().CreateManagedMqttClient();

                // Set up handlers
                client.ConnectedHandler                   = new MqttClientConnectedHandlerDelegate(OnConnected);
                client.DisconnectedHandler                = new MqttClientDisconnectedHandlerDelegate(OnDisconnected);
                client.ConnectingFailedHandler            = new ConnectingFailedHandlerDelegate(OnConnectingFailed);
                client.ApplicationMessageProcessedHandler = new ApplicationMessageProcessedHandlerDelegate(OnMensajeProcesado);
                client.ApplicationMessageReceivedHandler  = new MqttApplicationMessageReceivedHandlerDelegate(OnMensajeRecibido);

                client.StartAsync(options).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
            }



            /*client = new MqttClient(ipAddress);
             * client.Connect(clientId, "", "", true, 10);
             * client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived; ;
             * client.ConnectionClosed += Client_ConnectionClosed;*/
        }
Exemple #3
0
        public MqttService(IHubContext <DevicesHub> hubContext)
        {
            _hubContext = hubContext;
            var messageBuilder = new MqttClientOptionsBuilder().WithClientId(clientId) /*.WithCredentials(mqttUser, mqttPassword)*/.WithTcpServer(mqttURI, mqttPort).WithCleanSession();

            var options = mqttSecure
              ? messageBuilder
                          .WithTls()
                          .Build()
              : messageBuilder
                          .Build();

            var managedOptions = new ManagedMqttClientOptionsBuilder().WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                 .WithClientOptions(options)
                                 .Build();

            client = new MqttFactory().CreateManagedMqttClient();
            client.StartAsync(managedOptions);

            client.UseConnectedHandler(ClientConnectedHandler);
            client.UseDisconnectedHandler(ClientDisconnectedHandler);
            client.UseApplicationMessageReceivedHandler(ClientMessageReceivedHandler);
        }
Exemple #4
0
        public async void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            string mqttServer = _configuration.GetValue <string>(MQTT_SERVER_KEY_NAME, String.Empty);

            if (String.IsNullOrEmpty(mqttServer))
            {
                _logger.LogCritical(JsonConvert.SerializeObject(
                                        new
                {
                    error = "MQTT Server is not set!"
                }
                                        ));
            }

            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithWebSocketServer(mqttServer)
                                             .WithTls().Build())
                          .Build();

            IManagedMqttClient mqttClient = new MqttFactory().CreateManagedMqttClient();

            List <Message> logMessages = new List <Message>();
            MqttManager    mqttManager = new MqttManager(_logger, logMessages);

            mqttClient.UseApplicationMessageReceivedHandler((e) => {
                mqttManager.MessageReceived(e);
            });

            await mqttClient.StartAsync(options);

            services.AddSingleton(mqttClient);
            services.AddSingleton(logMessages);
        }
        private async Task ConnectAsync(String server, ushort port, String username, SecureString password, String clientID = null)
        {
            if (MqttClient.IsConnected)
            {
                Debug("Already connected...", 1);
                return;
            }

            if (clientID == null)
            {
                clientID = Guid.NewGuid().ToString();
            }

            var options = new MqttClientOptionsBuilder()
                          .WithClientId(clientID)
                          .WithTcpServer(server, port)
                          .WithCleanSession(true) // must be true for Managed Client, easier reconnects
            ;

            //.Build();

            // Only use authentication when a username or password is specified
            if (username != "" || SecureStringToString(password) != "")
            {
                options = options.WithCredentials(username, SecureStringToString(password));
            }


            var managedClientOptions = new ManagedMqttClientOptionsBuilder()
                                       .WithAutoReconnectDelay(TimeSpan.FromSeconds(RetryInterval))
                                       .WithClientOptions(options.Build())
                                       .Build();

            Debug("Connecting...", 1);
            //await MqttClient.ConnectAsync(options, CancellationToken.None);
            await MqttClient.StartAsync(managedClientOptions);
        }
Exemple #6
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(
                new MqttClientOptionsBuilder()
                .WithClientId("device1")
                .WithCleanSession()
                .WithKeepAlivePeriod(TimeSpan.FromHours(24))
                .WithKeepAliveSendInterval(TimeSpan.FromSeconds(5))
                .WithTcpServer("localhost", 1833)
                .Build()
                )
                          .Build();

            Client               = new MqttFactory().CreateManagedMqttClient();
            Client.Connected    += (s, e) => Console.WriteLine("Connected");
            Client.Disconnected += (s, e) => Console.WriteLine("Disconnected.");
            Client.ApplicationMessageReceived += (s, e) =>
            {
                switch (e.ApplicationMessage.Topic)
                {
                case "device1/ping":
                    Console.WriteLine("Received Ping Request.");
                    break;
                }
            };

            await Client.SubscribeAsync(FILTERS);

            await Client.StartAsync(options);

            Console.WriteLine("Press enter to end program.");
            Console.ReadLine();
        }
Exemple #7
0
        private static async System.Threading.Tasks.Task Main(string[] args)
        {
            // Setup and start a managed MQTT client.
            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithClientId("Client1")
                                             .WithWebSocketServer("localhost:50482/mqtt")
                                             .Build())
                          .Build();

            var mqttClient = new MqttFactory().CreateManagedMqttClient();
            await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("MqttWeatherForecast/90210/temperature").Build());

            mqttClient.UseConnectedHandler(e =>
            {
                Console.WriteLine($"Connection Result: {e.AuthenticateResult.ResultCode}");
            });

            mqttClient.UseApplicationMessageReceivedHandler(e =>
            {
                Console.WriteLine($"Message from {e.ClientId}: {e.ApplicationMessage.Payload.Length} bytes.");
            });

            await mqttClient.StartAsync(options);

            await mqttClient.PublishAsync(new ManagedMqttApplicationMessageBuilder().WithApplicationMessage(msg =>
            {
                msg.WithAtLeastOnceQoS();
                msg.WithPayload(BitConverter.GetBytes(98.6d));
                msg.WithTopic("MqttWeatherForecast/90210/temperature");
            }).Build());

            // StartAsync returns immediately, as it starts a new thread using Task.Run, and so the calling thread needs
            // to wait.
            Console.ReadLine();
        }
Exemple #8
0
        public async Task SetupClientAsync(CancellationToken cancellationToken)
        {
            // Setup and start a managed MQTT client.
            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithClientId("Server")
                                             //.WithWebSocketServer("localhost:50482/mqtt")
                                             .Build())
                          .Build();

            _mqttClient = new MqttFactory().CreateManagedMqttClient();

            await _mqttClient.StartAsync(options);


            await _mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("MqttWeatherForecast/90210/temperature").Build());

            _mqttClient.UseConnectedHandler(e =>
            {
                //Console.WriteLine($"Connection Result: {e.AuthenticateResult.ResultCode}");
            });

            _mqttClient.UseApplicationMessageReceivedHandler(e =>
            {
                //Console.WriteLine($"Message from {e.ClientId}: {e.ApplicationMessage.Payload.Length} bytes.");
            });

            await _mqttClient.StartAsync(options);

            await _mqttClient.PublishAsync(new ManagedMqttApplicationMessageBuilder().WithApplicationMessage(msg =>
            {
                msg.WithAtLeastOnceQoS();
                msg.WithPayload(BitConverter.GetBytes(98.6d));
                msg.WithTopic("inTopic");
            }).Build());
        }
        private async Task <IManagedMqttClient> ConnectAsync(string clientId, string mqttServerAddress, int port, string username, string password, bool useTLS, CancellationToken token)
        {
            var mqttClientFactory = new MqttFactory();
            var builder           = new MqttClientOptionsBuilder();

            builder.WithTcpServer(mqttServerAddress, port);
            if (!string.IsNullOrWhiteSpace(clientId))
            {
                builder.WithClientId(clientId);
            }

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                builder.WithCredentials(username, password);
            }

            if (useTLS)
            {
                builder.WithTls();
            }

            var options = builder.Build();


            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                 .WithClientOptions(options)
                                 .Build();

            //todo add a logger provided to the function CreateMqttClient
            var client = mqttClientFactory.CreateManagedMqttClient(new MqttNetLogger(logger));
            await client.StartAsync(managedOptions);

            await client.WaitForConnectAsync(2000, token);

            return(client);
        }
Exemple #10
0
        private void CreateMQTTClient(ConnectionDetails connectionDetails)
        {
            var factory    = new MqttFactory();
            var mqttClient = factory.CreateManagedMqttClient();

            var options = new ManagedMqttClientOptionsBuilder().WithAutoReconnectDelay(TimeSpan.FromSeconds(connectionDetails.AutoReconnectTime))
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithClientId(connectionDetails.ClientId)
                                             .WithTcpServer(connectionDetails.Server)
                                             .WithCredentials(connectionDetails.Username, connectionDetails.Password)
                                             .WithTls()
                                             .WithCleanSession()
                                             .Build())
                          .Build();

            //mqttClient.PublishAsync()
            //mqttClient.ConnectAsync(options).Wait();
            //mqttClient.Disconnected += async (s, e) =>
            //{

            //    this.IsConnected = false;

            //    log.Warn("### DISCONNECTED FROM SERVER ###");
            //    await Task.Delay(TimeSpan.FromSeconds(2));

            //    try
            //    {
            //        await mqttClient.ConnectAsync(options);
            //        this.IsConnected = true;
            //    }
            //    catch
            //    {
            //        log.Error("### RECONNECTING FAILED ###");
            //    }
            //};
            msgClient = mqttClient;
        }
Exemple #11
0
 public static async Task <bool> ConnectMQTT()
 {
     if (mqttClient != null)
     {
         await mqttClient.StopAsync();
     }
     Debug.Write("Connecting to MQTT...");
     mqttClient = (ManagedMqttClient) new MqttFactory().CreateManagedMqttClient();
     try
     {
         var options = new MqttClientOptionsBuilder()
                       .WithClientId(Preferences.Get("deviceName", ""))                                               //client name
                       .WithTcpServer(Preferences.Get("brokerIp", ""))                                                //mqtt server
                       .WithCredentials(Preferences.Get("brokerUsername", ""), Preferences.Get("brokerPassword", "")) //username, password
                       .Build();
         var managedOptions = new ManagedMqttClientOptionsBuilder()
                              .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                              .WithClientOptions(options)
                              .Build();
         await mqttClient.StartAsync(managedOptions);
     }
     catch (Exception e)
     {
         Debug.WriteLine("error while connecting: " + e.Message);
     };
     //            if (!mqttClient.IsConnected)
     //            {
     //#if !DEBUG
     //                if (await App.Current.MainPage.DisplayAlert("MQTT connection failed", "do you want to enter settings?", "yes", "no"))
     //                    await App.Current.MainPage.Navigation.PushAsync(new SettingsPassword( new SettingsPage()), true);
     //#endif
     //                Debug.WriteLine("connecting failed");
     //                return false;
     //            }
     //Debug.WriteLine("connected");
     return(true);
 }
Exemple #12
0
        private async Task ConsumeAsync()
        {
            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithClientId("Ali_Fleck_Consumer")
                                             .WithCredentials("testuser", "testpass")
                                             .WithTcpServer("www.baltavista.com", 8883)
                                             .WithCleanSession(true)
                                             .Build())
                          .Build();

            _mqttClient = new MqttFactory().CreateManagedMqttClient();
            await _mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("test1").Build());

            await _mqttClient.StartAsync(options);

            _mqttClient.UseApplicationMessageReceivedHandler(e =>
            {
                var message = $"({DateTime.Now}):{Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}";
                _allSockets.ForEach(s => s.Send(message));
                Console.WriteLine($"FLECK SERVED : {message}");
            });
        }
        public async void Options()
        {
            using var mock = AutoMock.GetLoose();

            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithClientId("Client1")
                                             .WithTcpServer("broker.hivemq.com")
                                             .WithTls().Build())
                          .Build();

            mock.Mock <IManagedMqttClient>()
            .Setup(x => x.Options)
            .Returns(options);
            var rxMqttClinet = mock.Create <RxMqttClient>();

            // act
            await rxMqttClinet.StartAsync(options);

            // test
            mock.Mock <IManagedMqttClient>().Verify(x => x.StartAsync(options));
            Assert.Equal(options, rxMqttClinet.Options);
        }
Exemple #14
0
        private async Task Connect()
        {
            Disconnect();

            _logger.LogInformation("Starting MqttConnectionService...");
            await Task.Yield();

            var settings = _settings.CurrentSettings;

            var options = new MqttClientOptionsBuilder()
                          .WithTcpServer(settings.MqttServer, settings.MqttPort)
                          .WithTls(x => x.UseTls = settings.MqttSecure)
                          .WithCredentials(settings.MqttUsername, settings.MqttPassword)
                          .Build();

            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithClientOptions(options)
                                 .WithAutoReconnectDelay(TimeSpan.FromSeconds(10))
                                 .Build();

            _client = _mqttFactory.CreateManagedMqttClient();

            _client.ConnectedHandler    = this;
            _client.DisconnectedHandler = this;
            _client.ApplicationMessageReceivedHandler = this;
            await _client.StartAsync(managedOptions);

            _connection.Disposable = Disposable.Create(() =>
            {
                _logger.LogInformation("Disconnection from MQTT server...");
                _client.Dispose();
            });

            _logger.LogInformation("Subscribing to MQTT topics...");
            await Subscribe();
        }
        public async Task ConnectAsync()
        {
            var messageBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId(_MQTTSettings.Value.ClientId)
                                 .WithCredentials(_MQTTSettings.Value.Username, _MQTTSettings.Value.Password)
                                 .WithTcpServer(_MQTTSettings.Value.Server, _MQTTSettings.Value.Port)
                                 .WithCleanSession();

            var options = _MQTTSettings.Value.MqttSecure ?
                          messageBuilder
                          .WithTls()
                          .Build() :
                          messageBuilder
                          .Build();

            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(System.TimeSpan.FromSeconds(5))
                                 .WithClientOptions(options)
                                 .Build();

            _client = new MqttFactory().CreateManagedMqttClient();

            await _client.StartAsync(managedOptions);
        }
Exemple #16
0
        private MqttIpcClient(MqttIpcClientConfiguration conf, IIpcPacketRouter router, IIpcSerializer serializer)
        {
            _router          = router;
            _serializer      = serializer;
            _endPoint        = conf.EndPoint;
            _name            = conf.ClientName;
            _responsesQueues = new HashSet <string>();
            _pendingRequests = new ConcurrentDictionary <Guid, PendingRequest>();
            _packetFactory   = new PacketContainerFactory();
            _requestFactory  = new PendingRequestFactory();
            _client          = new MqttFactory().CreateManagedMqttClient(new MqttNetLogger(conf.ClientName));
            ManagedMqttClientOptions options = new ManagedMqttClientOptionsBuilder()
                                               .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                               .WithClientOptions(new MqttClientOptionsBuilder()
                                                                  .WithClientId(_name)
                                                                  .WithTcpServer(_endPoint)
                                                                  .Build())
                                               .Build();

            _client.Connected += (sender, args) =>
                                 _log.Info($"[CONNECTED] {_name} is connected on MQTT Broker {_endPoint}");
            _client.ApplicationMessageReceived += (sender, args) => OnMessage(args.ClientId, args.ApplicationMessage);
            _client.StartAsync(options).ConfigureAwait(false).GetAwaiter().GetResult();
        }
Exemple #17
0
    public static async Task Connect_Client()
    {
        /*
         * This sample creates a simple managed MQTT client and connects to a public broker.
         *
         * The managed client extends the existing _MqttClient_. It adds the following features.
         * - Reconnecting when connection is lost.
         * - Storing pending messages in an internal queue so that an enqueue is possible while the client remains not connected.
         */

        var mqttFactory = new MqttFactory();

        using (var managedMqttClient = mqttFactory.CreateManagedMqttClient())
        {
            var mqttClientOptions = new MqttClientOptionsBuilder()
                                    .WithTcpServer("broker.hivemq.com")
                                    .Build();

            var managedMqttClientOptions = new ManagedMqttClientOptionsBuilder()
                                           .WithClientOptions(mqttClientOptions)
                                           .Build();

            await managedMqttClient.StartAsync(managedMqttClientOptions);

            // The application message is not sent. It is stored in an internal queue and
            // will be sent when the client is connected.
            await managedMqttClient.EnqueueAsync("Topic", "Payload");

            Console.WriteLine("The managed MQTT client is connected.");

            // Wait until the queue is fully processed.
            SpinWait.SpinUntil(() => managedMqttClient.PendingApplicationMessagesCount == 0, 10000);

            Console.WriteLine($"Pending messages = {managedMqttClient.PendingApplicationMessagesCount}");
        }
    }
Exemple #18
0
        private MqttConfiguration GetConfigurationViaAttributeValues()
        {
            var port = _connectionString.TryGetValue(ConnectionStringForPort, out var portAsString) &&
                       int.TryParse(portAsString as string, out var portAsInt)
                    ? portAsInt
                    : DetaultMqttPort;

            var clientId = _connectionString.TryGetValue(ConnectionStringForClientId, out var clientIdValue) && !string.IsNullOrEmpty(clientIdValue as string)
                ? clientIdValue.ToString()
                : Guid.NewGuid().ToString();

            var server = _connectionString.TryGetValue(ConnectionStringForServer, out var serverValue)
                ? serverValue.ToString()
                : throw new Exception("No server hostname configured, please set the server via the MqttTriggerAttribute, using the application settings via the Azure Portal or using the local.settings.json");;

            var username = _connectionString.TryGetValue(ConnectionStringForUsername, out var userNameValue)
                ? userNameValue.ToString()
                : null;

            var password = _connectionString.TryGetValue(ConnectionStringForPassword, out var passwordValue)
                ? passwordValue.ToString()
                : null;

            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(_detaultReconnectTime)
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithClientId(clientId)
                                             .WithTcpServer(server, port)
                                             .WithCredentials(username, password)
                                             .Build())
                          .Build();

            var topics = _mqttTriggerAttribute.Topics.Select(t => new TopicFilter(t, MqttQualityOfServiceLevel.AtLeastOnce));

            return(new MqttConfiguration(options, topics));
        }
Exemple #19
0
        public static async Task <IManagedMqttClient> RunAsync(string Username, string Password, string Server)
        {
            var options = new ManagedMqttClientOptionsBuilder()
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithClientId("TestManagedClient")
                                             .WithCredentials("ChatByKey", "DellaSwag123")
                                             .WithTcpServer("localhost", 1883)
                                             .Build())
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(1))
                          .WithStorage(new MqttStorage())
                          .Build();
            var managedClient = new MqttFactory().CreateManagedMqttClient();

            managedClient.UseApplicationMessageReceivedHandler(h =>
            {
                Console.WriteLine(h.ClientId + ": " + h.ApplicationMessage.Payload);
            });
            await managedClient.StartAsync(options);

            await managedClient.PublishAsync(builder => builder.WithExactlyOnceQoS().WithPayload("swag").WithTopic("xyz"));

            Console.ReadLine();
            return(managedClient);
        }
Exemple #20
0
        public static IServiceCollection AddManagedMqttServices <TMqttSettings>(this IServiceCollection services, IConfiguration mqttConfiguration)
            where TMqttSettings : ManagedMqttSettings, new()
        {
            services.AddMqttServices <TMqttSettings>(mqttConfiguration);

            services.AddSingleton <IManagedMqttClientOptions>(sp =>
            {
                var managedMqttClientStorage = sp.GetService <IManagedMqttClientStorage>();
                var mqttManagedSettings      = sp.GetRequiredService <IOptions <TMqttSettings> >().Value;
                var mqttClientOptions        = sp.GetRequiredService <IMqttClientOptions>();

                var managedMqttClientOptionsBuilder = new ManagedMqttClientOptionsBuilder()
                                                      .WithClientOptions(mqttClientOptions)
                                                      .WithPendingMessagesOverflowStrategy(mqttManagedSettings.PendingMessagesOverflowStrategy ?? MqttPendingMessagesOverflowStrategy.DropNewMessage)
                                                      .WithAutoReconnectDelay(mqttManagedSettings.AutoReconnectDelay ?? TimeSpan.FromSeconds(5.0))
                                                      .WithMaxPendingMessages(mqttManagedSettings.MaxPendingMessages ?? int.MaxValue);

                if (managedMqttClientStorage != null)
                {
                    managedMqttClientOptionsBuilder = managedMqttClientOptionsBuilder.WithStorage(managedMqttClientStorage);
                }

                var managedMqttClientOptions = managedMqttClientOptionsBuilder.Build();

                return(managedMqttClientOptions);
            });

            services.AddSingleton(sp =>
            {
                var factory    = sp.GetRequiredService <IMqttFactory>();
                var mqttClient = factory.CreateManagedMqttClient();
                return(mqttClient);
            });

            return(services);
        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureHostConfiguration(config =>
        {
            config.AddInMemoryCollection(new KeyValuePair <string, string>[]
            {
                new KeyValuePair <string, string>("LOGGING_LEVEL", "Debug")
            });
        })
        .ConfigureBCTLogging()
        .ConfigureServices(services =>
        {
            // *** APP Component ***
            services.AddSingleton(p =>
            {
                var appName   = "application";
                var clientId  = $"{appName}-{Guid.NewGuid()}";
                Console.Title = $"Application: {clientId}";
                return(new BctMqttClientConfiguration()
                {
                    ClientId = clientId,
                });
            });

            // *** Mediator Component ***
            services.AddSingleton <IManagedMqttClient>(p =>
            {
                var mqttClientConfiguration = p.GetService <BctMqttClientConfiguration>();
                var options = new ManagedMqttClientOptionsBuilder()

                              .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                              .WithClientOptions(new MqttClientOptionsBuilder()
                                                 .WithClientId(mqttClientConfiguration.ClientId)
                                                 .WithProtocolVersion(MqttProtocolVersion.V500)
                                                 .WithTcpServer("192.168.1.98", 1883)
                                                 //.WithTls()
                                                 .Build()
                                                 )

                              .Build();
                var mqttClient = new MqttFactory().CreateManagedMqttClient();

                mqttClient.StartAsync(options).Wait();
                return(mqttClient);
            });

            // *** Mediator Component ***
            services.AddMediatR(new[] { typeof(Program).Assembly });

            // *** Messages Component ***
            // add all known messages from assemblyies using known message type
            services.RegisterAssemblyPublicNonGenericClasses(new[] { Assembly.GetAssembly(typeof(DeviceStatus)) })
            .Where(c => c.BaseType == typeof(BaseAggregate))
            .AsPublicImplementedInterfaces();

            // *** Mediator Component ***
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(MetricsPipelineBehavior <,>));
            //services.AddScoped(typeof(IPipelineBehavior<,>), typeof(DistributedTracingBehavior<,>));

            // *** Metrics Component *** (already exists)
            services.AddHostedService(provider => new MetricsHost("localhost", 1200));
            // *** Traceing componetnt *** (already exists)
            //services.AddHostedService(provider => new DistributedTracingHost(provider.GetService<ILoggerFactory>(), provider.GetService<IConfiguration>()));

            // *** MQTT Component ***
            services.AddHostedService <MqttProcessorHost>();

            // *** APP Component ***
            services.AddHostedService <StatusSender>();
        });
Exemple #22
0
        static void Main()
        {
            Thread publisher = new Thread(async() =>
            {
                // Setup and start a managed MQTT client.
                var options = new ManagedMqttClientOptionsBuilder()
                              .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                              .WithClientOptions(new MqttClientOptionsBuilder()
                                                 .WithClientId("Source")
                                                 .WithTcpServer("127.0.0.1")
                                                 .Build())
                              .Build();

                var factory = new MqttFactory();

                var mqttPublisherClient = factory.CreateManagedMqttClient(new MqttNetLogger("MyCustomID"));
                MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
                {
                    var trace = $">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}";
                    if (e.TraceMessage.Exception != null)
                    {
                        trace += Environment.NewLine + e.TraceMessage.Exception.ToString();
                    }

                    Debug.WriteLine('\x2' + trace);
                };

                await mqttPublisherClient.StartAsync(options);
                Console.WriteLine("Source started\n");

                while (true)
                {
                    Console.WriteLine("Press 'P' to publish, 'X' to exit.");
                    var c = Console.ReadKey().KeyChar;
                    Console.WriteLine();
                    if (c == 'P' || c == 'p')
                    {
                        for (int i = 0; i < 10; ++i)
                        {
                            // 2018-03-18 KSM moving the message creation into the for-loop eliminates the need to
                            // have a delay inthe loop
                            var msg = new MqttApplicationMessage
                            {
                                Topic = $"source/property/i{i}",
                                QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce,
                                Retain  = true,
                                Payload = new byte[] { 30 }
                            };
                            await mqttPublisherClient.PublishAsync(msg);
                            Console.WriteLine($"Published topic: {msg.Topic}");


                            //2018-03-18 KSM delay no longer needed when a new message within the above for-loop
                            //***************************************************************
                            //adjust this value to stop published messages from being dropped
                            //Thread.Sleep(0);
                            //***************************************************************
                        }
                    }
                    else if (c == 'X' || c == 'x')
                    {
                        break;
                    }
                }

                await mqttPublisherClient.StopAsync();
            });

            publisher.Start();
        }
Exemple #23
0
        public static async Task ConnectAsync()
        {
            string clientId       = Guid.NewGuid().ToString();
            string mqttURI        = "127.0.0.1";
            string mqttUser       = "******";
            string mqttPassword   = "******";
            int    mqttPort       = 1883;
            bool   mqttSecure     = false;
            var    messageBuilder = new MqttClientOptionsBuilder()
                                    .WithClientId(clientId)
                                    .WithCredentials(mqttUser, mqttPassword)
                                    .WithTcpServer(mqttURI, mqttPort)
                                    .WithProtocolVersion(MqttProtocolVersion.V500)
                                    //.WithTls()
                                    .WithCleanSession();

            var options        = mqttSecure ? messageBuilder.WithTls().Build() : messageBuilder.Build();
            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                 .WithClientOptions(options)

                                 .Build();

            client = new MqttFactory().CreateManagedMqttClient();
            await client.StartAsync(managedOptions);



            client.UseConnectedHandler(e =>
            {
                Console.WriteLine("Connected successfully with MQTT Brokers.");
            });


            await SubscribeAsync("+/+/+/+");

            //await SubscribeAsync("let/me/in/pep");

            Console.WriteLine(client.IsStarted + " " + client.IsConnected);

            client.UseDisconnectedHandler(e =>
            {
                Console.WriteLine("Disconnected from MQTT Brokers." + e.ClientWasConnected + " " + e?.AuthenticateResult?.ReasonString);
            });

            client.UseApplicationMessageReceivedHandler(e =>
            {
                try
                {
                    string topic = e.ApplicationMessage.Topic;
                    if (string.IsNullOrWhiteSpace(topic) == false)
                    {
                        string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                        Console.WriteLine($"Topic: {topic}. Message Received: {payload}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message, ex);
                }
            });
        }
        static async Task Main(string[] args)
        {
            // TODO refactor into proper app with DI
            var settingsConfiguration = new ConfigurationBuilder()
                                        .AddJsonFile("appsettings.json")
                                        .Build();

            settingsConfiguration.ConfigureBCTLogging();
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddLogging(configure => configure.AddBCTLogging());
            serviceCollection.Configure <LoggerFilterOptions>(options => options.MinLevel = LogLevel.Trace);
            IServiceProvider m_serviceProvider = serviceCollection.BuildServiceProvider();
            var logger = m_serviceProvider.GetService <ILogger <BaseAggregate> >();

            BaseAggregate.SetLogger(logger);


            logger.WithInformation("Logging initialized").Log();
            logger.WithError("error").Log();

            var running = true;
            var are     = new AutoResetEvent(false);

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                running          = false;
                eventArgs.Cancel = true;
                are.Set();
            };

            var deviceType     = "device-type-1";
            var deviceUniqueId = Guid.NewGuid();
            //var deviceUniqueId = "a";
            var deviceId = $"{deviceType}-{deviceUniqueId}";

            Console.Title = $"Device: {deviceId}";

            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithPendingMessagesOverflowStrategy(MqttPendingMessagesOverflowStrategy.DropOldestQueuedMessage)
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithCommunicationTimeout(TimeSpan.FromSeconds(15))
                                             .WithProtocolVersion(MqttProtocolVersion.V500)
                                             .WithClientId(deviceId)
                                             .WithTcpServer("192.168.1.98", 1883)
                                             //.WithTls()
                                             .Build()
                                             )
                          .Build();


            using (var cancellationTokenSource = new CancellationTokenSource())
                using (var mqttClient = new MqttFactory().CreateManagedMqttClient())
                {
                    await mqttClient.SubscribeAsync(
                        new TopicFilterBuilder().WithTopic("bct/app/status").Build(),
                        new TopicFilterBuilder().WithTopic($"bct/{deviceType}/{deviceId}/response").Build(),
                        new TopicFilterBuilder().WithTopic($"bct/{deviceType}/{deviceId}/in").Build());

                    mqttClient.ApplicationMessageReceivedHandler =
                        new MqttApplicationMessageReceivedHandlerDelegate(OnMessageReceived);
                    await mqttClient.StartAsync(options);

                    var initializeMessage = new InitializeConnection();
                    initializeMessage.DeviceId.Value = deviceId;
                    var payload = Encoding.UTF8.GetBytes(initializeMessage.Serialize());
                    _correlation = Guid.NewGuid().ToByteArray();

                    await mqttClient.PublishAsync(builder =>
                                                  builder
                                                  .WithTopic($"bct/{deviceType}/{deviceId}/out")
                                                  .WithResponseTopic($"bct/{deviceType}/{deviceId}/response")
                                                  .WithCorrelationData(_correlation)
                                                  .WithUserProperty("messageType", nameof(InitializeConnection))
                                                  .WithUserProperty("responseType", nameof(InitializeConnectionResponse))
                                                  .WithPayload(payload)
                                                  , cancellationTokenSource.Token);

                    Console.WriteLine($"Publishing InitializeConnection Message");

                    await Task.Run(async() =>
                    {
                        while (running)
                        {
                            var messageId             = Guid.NewGuid();
                            var devStatus             = new DeviceStatus();
                            devStatus.Condition.Value = StatusEnum.Connected;
                            devStatus.DeviceId.Value  = deviceId;
                            devStatus.MessageId.Value = messageId.ToString();
                            devStatus.When.Value      = Convert.ToDouble(DateTime.UtcNow.Ticks);
                            var payload = Encoding.UTF8.GetBytes(devStatus.Serialize());
                            await mqttClient.PublishAsync(builder =>
                                                          builder
                                                          .WithTopic($"bct/{deviceType}/{deviceId}/status")
                                                          // KWC HOW IS THIS DIFFERENT .WithMessage<DeviceStatus>(devStatus)
                                                          .WithUserProperty("messageType", nameof(DeviceStatus))
                                                          .WithPayload(payload)
                                                          .WithContentType("application/json")
                                                          , cancellationTokenSource.Token);

                            await Task.Delay(5000, cancellationTokenSource.Token);
                        }
                    }, cancellationTokenSource.Token);

                    are.WaitOne();
                    await mqttClient.StopAsync();
                }
        }
Exemple #25
0
#pragma warning disable IDE0051 // Remove unused private members
        private async Task WikiCode()
#pragma warning restore IDE0051 // Remove unused private members
        {
            {
                // Use a custom identifier for the trace messages.
                var clientOptions = new MqttClientOptionsBuilder()
                                    .Build();
            }

            {
                // Create a new MQTT client.
                var factory = new MqttFactory();
                var client  = factory.CreateMqttClient();

                // Create TCP based options using the builder.
                var options = new MqttClientOptionsBuilder()
                              .WithClientId("Client1")
                              .WithTcpServer("broker.hivemq.com")
                              .WithCredentials("bud", "%spencer%")
                              .WithTls()
                              .WithCleanSession()
                              .Build();

                await client.ConnectAsync(options);

                // Reconnecting

                client.UseDisconnectedHandler(async e =>
                {
                    Console.WriteLine("### DISCONNECTED FROM SERVER ###");
                    await Task.Delay(TimeSpan.FromSeconds(5));

                    try
                    {
                        await client.ConnectAsync(options);
                    }
                    catch
                    {
                        Console.WriteLine("### RECONNECTING FAILED ###");
                    }
                });

                // Consuming messages

                client.UseApplicationMessageReceivedHandler(e =>
                {
                    Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                    Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                    Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                    Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                    Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                    Console.WriteLine();
                });

                void Handler(MqttApplicationMessageReceivedEventArgs args)
                {
                    //...
                }

                client.UseApplicationMessageReceivedHandler(e => Handler(e));

                // Subscribe after connect

                client.UseConnectedHandler(async e =>
                {
                    Console.WriteLine("### CONNECTED WITH SERVER ###");

                    // Subscribe to a topic
                    await client.SubscribeAsync(new TopicFilterBuilder().WithTopic("my/topic").Build());

                    Console.WriteLine("### SUBSCRIBED ###");
                });

                // Subscribe to a topic
                await client.SubscribeAsync(new TopicFilterBuilder().WithTopic("my/topic").Build());

                // Unsubscribe from a topic
                await client.UnsubscribeAsync("my/topic");

                // Publish an application message
                var applicationMessage = new MqttApplicationMessageBuilder()
                                         .WithTopic("A/B/C")
                                         .WithPayload("Hello World")
                                         .WithAtLeastOnceQoS()
                                         .Build();

                await client.PublishAsync(applicationMessage);
            }

            {
                {
                    // Use TCP connection.
                    var options = new MqttClientOptionsBuilder()
                                  .WithTcpServer("broker.hivemq.com", 1883) // Port is optional
                                  .Build();
                }

                {
                    // Use secure TCP connection.
                    var options = new MqttClientOptionsBuilder()
                                  .WithTcpServer("broker.hivemq.com")
                                  .WithTls()
                                  .Build();
                }

                {
                    // Use WebSocket connection.
                    var options = new MqttClientOptionsBuilder()
                                  .WithWebSocketServer("broker.hivemq.com:8000/mqtt")
                                  .Build();
                }

                {
                    // Create TCP based options manually
                    var options = new MqttClientOptions
                    {
                        ClientId    = "Client1",
                        Credentials = new MqttClientCredentials
                        {
                            Username = "******",
                            Password = Encoding.UTF8.GetBytes("%spencer%")
                        },
                        ChannelOptions = new MqttClientTcpOptions
                        {
                            Server     = "broker.hivemq.org",
                            TlsOptions = new MqttClientTlsOptions
                            {
                                UseTls = true
                            }
                        },
                    };
                }
            }

            // ----------------------------------
            {
                var options = new MqttServerOptions
                {
                    ConnectionValidator = new MqttServerConnectionValidatorDelegate(c =>
                    {
                        if (c.ClientId.Length < 10)
                        {
                            c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
                            return;
                        }

                        if (c.Username != "mySecretUser")
                        {
                            c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                            return;
                        }

                        if (c.Password != "mySecretPassword")
                        {
                            c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                            return;
                        }

                        c.ReasonCode = MqttConnectReasonCode.Success;
                    })
                };

                var factory    = new MqttFactory();
                var mqttServer = factory.CreateMqttServer();
                await mqttServer.StartAsync(options);

                Console.WriteLine("Press any key to exit.");
                Console.ReadLine();

                await mqttServer.StopAsync();
            }

            // ----------------------------------

            // For UWP apps:
            MqttTcpChannel.CustomIgnorableServerCertificateErrorsResolver = o =>
            {
                if (o.Server == "server_with_revoked_cert")
                {
                    return(new[] { ChainValidationResult.Revoked });
                }

                return(Array.Empty <ChainValidationResult>());
            };

            {
                // Start a MQTT server.
                var mqttServer = new MqttFactory().CreateMqttServer();
                await mqttServer.StartAsync(new MqttServerOptions());

                Console.WriteLine("Press any key to exit.");
                Console.ReadLine();
                await mqttServer.StopAsync();
            }

            {
                // Configure MQTT server.
                var optionsBuilder = new MqttServerOptionsBuilder()
                                     .WithConnectionBacklog(100)
                                     .WithDefaultEndpointPort(1884);

                var options = new MqttServerOptions
                {
                };

                options.ConnectionValidator = new MqttServerConnectionValidatorDelegate(c =>
                {
                    if (c.ClientId != "Highlander")
                    {
                        c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
                        return;
                    }

                    c.ReasonCode = MqttConnectReasonCode.Success;
                });

                var mqttServer = new MqttFactory().CreateMqttServer();
                await mqttServer.StartAsync(optionsBuilder.Build());
            }

            {
                // Setup client validator.
                var options = new MqttServerOptions
                {
                    ConnectionValidator = new MqttServerConnectionValidatorDelegate(c =>
                    {
                        if (c.ClientId.Length < 10)
                        {
                            c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
                            return;
                        }

                        if (c.Username != "mySecretUser")
                        {
                            c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                            return;
                        }

                        if (c.Password != "mySecretPassword")
                        {
                            c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                            return;
                        }

                        c.ReasonCode = MqttConnectReasonCode.Success;
                    })
                };
            }

            {
                // Create a new MQTT server.
                var mqttServer = new MqttFactory().CreateMqttServer();
            }

            {
                // Setup application message interceptor.
                var options = new MqttServerOptionsBuilder()
                              .WithApplicationMessageInterceptor(context =>
                {
                    if (context.ApplicationMessage.Topic == "my/custom/topic")
                    {
                        context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes("The server injected payload.");
                    }

                    // It is also possible to read the payload and extend it. For example by adding a timestamp in a JSON document.
                    // This is useful when the IoT device has no own clock and the creation time of the message might be important.
                })
                              .Build();
            }

            {
                // Setup subscription interceptor.
                var options = new MqttServerOptionsBuilder()
                              .WithSubscriptionInterceptor(context =>
                {
                    if (context.TopicFilter.Topic.StartsWith("admin/foo/bar") && context.ClientId != "theAdmin")
                    {
                        context.AcceptSubscription = false;
                    }

                    if (context.TopicFilter.Topic.StartsWith("the/secret/stuff") && context.ClientId != "Imperator")
                    {
                        context.AcceptSubscription = false;
                        context.CloseConnection    = true;
                    }
                })
                              .Build();
            }

            {
                // Setup and start a managed MQTT client.
                var options = new ManagedMqttClientOptionsBuilder()
                              .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                              .WithClientOptions(new MqttClientOptionsBuilder()
                                                 .WithClientId("Client1")
                                                 .WithTcpServer("broker.hivemq.com")
                                                 .WithTls().Build())
                              .Build();

                var mqttClient = new MqttFactory().CreateManagedMqttClient();
                await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("my/topic").Build());

                await mqttClient.StartAsync(options);
            }

            {
                // Use a custom log ID for the logger.
                var factory = new MqttFactory();
                var client  = factory.CreateMqttClient(new MqttNetLogger("MyCustomId"));
            }

            {
                var client = new MqttFactory().CreateMqttClient();

                var message = new MqttApplicationMessageBuilder()
                              .WithTopic("MyTopic")
                              .WithPayload("Hello World")
                              .WithExactlyOnceQoS()
                              .WithRetainFlag()
                              .Build();

                await client.PublishAsync(message);
            }

            {
                // Write all trace messages to the console window.
                MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
                {
                    var trace = $">> [{e.LogMessage.Timestamp:O}] [{e.LogMessage.ThreadId}] [{e.LogMessage.Source}] [{e.LogMessage.Level}]: {e.LogMessage.Message}";
                    if (e.LogMessage.Exception != null)
                    {
                        trace += Environment.NewLine + e.LogMessage.Exception.ToString();
                    }

                    Console.WriteLine(trace);
                };
            }
        }
Exemple #26
0
        static void Main()
        {
            DotNetEnv.Env.Load();

            // configs, please filling your information accordingly
            var customClientId  = DotNetEnv.Env.GetString("CLIENT_ID"); // format suggested
            var loggerName      = DotNetEnv.Env.GetString("LOGGER_NAME");
            var mqttServAddress = DotNetEnv.Env.GetString("MQTT_ADDR"); //subject to change
            var username        = DotNetEnv.Env.GetString("USERNAME");  //subject to change
            var password        = DotNetEnv.Env.GetString("PASSWORD");  //subject to change
            var topic           = DotNetEnv.Env.GetString("TOPIC");
            var yourXML         = "<?xml version=\"1.0\"?>\r\n";        // a sample test xml in the format your are supposed to send

            Thread publisher = new Thread(async() =>
            {
                Console.WriteLine(mqttServAddress);
                // Setup and start a managed MQTT client.
                var options = new ManagedMqttClientOptionsBuilder()
                              .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                              .WithClientOptions(new MqttClientOptionsBuilder()
                                                 .WithClientId(customClientId)
                                                 .WithWebSocketServer(mqttServAddress)
                                                 //.WithTcpServer(mqttServAddress) // use this for local tcp connection
                                                 .WithCredentials(username, password)
                                                 .Build())
                              .Build();

                var factory = new MqttFactory();

                mqttPublisherClient = factory.CreateManagedMqttClient(new MqttNetLogger(loggerName));
                MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
                {
                    var trace = $">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}";
                    if (e.TraceMessage.Exception != null)
                    {
                        trace += Environment.NewLine + e.TraceMessage.Exception.ToString();
                    }

                    Debug.WriteLine('\x2' + trace);
                };


                Action send = async() =>
                {
                    var msg = new MqttApplicationMessage
                    {
                        Topic = topic,
                        QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
                        Retain  = true,
                        Payload = System.Text.Encoding.UTF8.GetBytes(
                            Newtonsoft.Json.JsonConvert.SerializeObject(new {
                            data = yourXML,                              //xml string needs to encoded and escaped utf-8
                            auth = new {
                                access_token = "",                       // subject to change later
                                secret_token = ""                        // subject to change later
                            }
                        })
                            )
                    };
                    await mqttPublisherClient.PublishAsync(msg);
                    Console.WriteLine($"Published topic: {msg.Topic}");
                };
                // * This is the place to publish mqtt message by calling send()
                for (var i = 1; i <= 1; i++)
                {
                    Console.WriteLine($"the number of message sent: {i}");
                    send(); // sending 1000 messages async
                }

                mqttPublisherClient.Disconnected += (s, e) =>
                {
                    Console.WriteLine("### DISCONNECTED FROM SERVER ###");
                };

                mqttPublisherClient.Connected += (s, e) =>
                {
                    Console.WriteLine("### CONNECTED WITH SERVER ###");
                };

                mqttPublisherClient.ApplicationMessageProcessed += (s, e) =>
                {
                    if (e.HasSucceeded)
                    {
                        Console.WriteLine("message successfully published!");
                    }
                    else
                    {
                        Console.WriteLine("message failed to publish!");
                    }
                };

                try {
                    await mqttPublisherClient.StartAsync(options);
                    Console.WriteLine("mqtt client started\n");
                } catch (Exception e) {
                    Console.WriteLine(e);
                }

                Shutdown.WaitOne();
                // await mqttPublisherClient.StopAsync();
            });

            publisher.Start();
            Console.WriteLine("testing dotnet mqtt client...");
        }
Exemple #27
0
        private static int _iLastUpdateThreshold      = 5;    // Minutes

        public static async void StartMQTT(string strMQTTServer, bool bMQTTTLS, string strClientId, string strUser, string strPassword, MessageHandler messageHandler)
        {
            IManagedMqttClientOptions             options;
            MqttClientOptionsBuilder              clientOptions;
            MqttClientOptionsBuilderTlsParameters optionsTLS;
            int iPort = 0;

            string[] strMQTTServerArray;
            string   strMQTTBroker;

            Logging.WriteDebugLog("MQTT.StartMQTT()");

            if (strMQTTServer == null || strMQTTServer == "")
            {
                return;
            }

            _timerMQTT = new Timer(Update, null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30));

            _strClientId    = strClientId;
            _messageHandler = messageHandler;

            if (strMQTTServer.Contains(":"))
            {
                strMQTTServerArray = strMQTTServer.Split(new char[] { ':' });
                if (strMQTTServerArray.Length != 2)
                {
                    Logging.WriteDebugLog("MQTT.StartMQTT() MQTTBroker field has incorrect syntax (host or host:port)");
                    return;
                }

                if (!int.TryParse(strMQTTServerArray[1], out iPort) || iPort == 0)
                {
                    Logging.WriteDebugLog("MQTT.StartMQTT() MQTTBroker field has incorrect syntax - port not non-zero numeric (host or host:port)");
                    return;
                }

                if (strMQTTServerArray[0].Length == 0)
                {
                    Logging.WriteDebugLog("MQTT.StartMQTT() MQTTBroker field has incorrect syntax - missing host (host or host:port)");
                    return;
                }

                strMQTTBroker = strMQTTServerArray[0];

                Logging.WriteDebugLog("MQTT.StartMQTT() Host: {0}, Port: {1}", strMQTTBroker, iPort);
            }
            else
            {
                strMQTTBroker = strMQTTServer;

                Logging.WriteDebugLog("MQTT.StartMQTT() Host: {0}", strMQTTBroker);
            }

            clientOptions = new MqttClientOptionsBuilder().WithClientId(_strClientId).WithTcpServer(strMQTTBroker, (iPort == 0 ? null : iPort));
            if (strUser != "")
            {
                clientOptions = clientOptions.WithCredentials(strUser, strPassword);
            }
            if (bMQTTTLS)
            {
                optionsTLS = new MqttClientOptionsBuilderTlsParameters
                {
                    IgnoreCertificateChainErrors = true,
                    UseTls = true,
                    IgnoreCertificateRevocationErrors = true,
                    AllowUntrustedCertificates        = true,
                    SslProtocol = System.Security.Authentication.SslProtocols.Tls12
                };

                clientOptions = clientOptions.WithTls(optionsTLS);
            }

            options = new ManagedMqttClientOptionsBuilder().WithAutoReconnectDelay(TimeSpan.FromSeconds(5)).WithClientOptions(clientOptions.Build()).Build();

            _mqtt = new MqttFactory().CreateManagedMqttClient();

            _mqtt.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(MessageProcessor);

            await _mqtt.StartAsync(options);
        }
        public async Task Create_Managed_Client_With_Logger()
        {
            var factory = new MqttFactory();

            //This test compares
            //1. correct logID
            string logId = "logId";
            bool   invalidLogIdOccured = false;

            //2. if the total log calls are the same for global and local
            int globalLogCount = 0;
            int localLogCount  = 0;

            MqttNetLogger logger = new MqttNetLogger(logId);

            //we have a theoretical bug here if a concurrent test is also logging
            var globalLog = new EventHandler <MqttNetLogMessagePublishedEventArgs>((s, e) =>
            {
                if (logId != e.TraceMessage.LogId)
                {
                    invalidLogIdOccured = true;
                }
                Interlocked.Increment(ref globalLogCount);
            });

            MqttNetGlobalLogger.LogMessagePublished += globalLog;

            logger.LogMessagePublished += (s, e) =>
            {
                if (logId != e.TraceMessage.LogId)
                {
                    invalidLogIdOccured = true;
                }
                Interlocked.Increment(ref localLogCount);
            };

            var managedClient = factory.CreateManagedMqttClient(logger);

            try
            {
                var clientOptions = new ManagedMqttClientOptionsBuilder();

                clientOptions.WithClientOptions(o => o.WithTcpServer("this_is_an_invalid_host").WithCommunicationTimeout(TimeSpan.FromSeconds(1)));

                //try connect to get some log entries
                await managedClient.StartAsync(clientOptions.Build());

                //wait at least connect timeout or we have some log messages
                var tcs = new TaskCompletionSource <object>();
                managedClient.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate(e => tcs.TrySetResult(null));
                await Task.WhenAny(Task.Delay(managedClient.Options.ClientOptions.CommunicationTimeout), tcs.Task);
            }
            finally
            {
                await managedClient.StopAsync();

                MqttNetGlobalLogger.LogMessagePublished -= globalLog;
            }

            Assert.IsFalse(invalidLogIdOccured);
            Assert.AreNotEqual(0, globalLogCount);
            Assert.AreEqual(globalLogCount, localLogCount);
        }
Exemple #29
0
        // This code is for the Wiki at GitHub!
        // ReSharper disable once UnusedMember.Local
        private async Task WikiCode()
        {
            {
                // Write all trace messages to the console window.
                MqttNetGlobalLog.LogMessagePublished += (s, e) =>
                {
                    Console.WriteLine($">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}");
                    if (e.TraceMessage.Exception != null)
                    {
                        Console.WriteLine(e.TraceMessage.Exception);
                    }
                };
            }

            {
                // Use a custom identifier for the trace messages.
                var clientOptions = new MqttClientOptionsBuilder()
                                    .Build();
            }

            {
                // Create a new MQTT client.
                var factory    = new MqttFactory();
                var mqttClient = factory.CreateMqttClient();

                {
                    // Create TCP based options using the builder.
                    var options = new MqttClientOptionsBuilder()
                                  .WithClientId("Client1")
                                  .WithTcpServer("broker.hivemq.com")
                                  .WithCredentials("bud", "%spencer%")
                                  .WithTls()
                                  .WithCleanSession()
                                  .Build();

                    await mqttClient.ConnectAsync(options);
                }

                {
                    // Use TCP connection.
                    var options = new MqttClientOptionsBuilder()
                                  .WithTcpServer("broker.hivemq.com", 1883) // Port is optional
                                  .Build();
                }

                {
                    // Use secure TCP connection.
                    var options = new MqttClientOptionsBuilder()
                                  .WithTcpServer("broker.hivemq.com")
                                  .WithTls()
                                  .Build();
                }

                {
                    // Use WebSocket connection.
                    var options = new MqttClientOptionsBuilder()
                                  .WithWebSocketServer("broker.hivemq.com:8000/mqtt")
                                  .Build();

                    await mqttClient.ConnectAsync(options);
                }

                {
                    // Create TCP based options manually
                    var options = new MqttClientOptions
                    {
                        ClientId    = "Client1",
                        Credentials = new MqttClientCredentials
                        {
                            Username = "******",
                            Password = "******"
                        },
                        ChannelOptions = new MqttClientTcpOptions
                        {
                            Server     = "broker.hivemq.org",
                            TlsOptions = new MqttClientTlsOptions
                            {
                                UseTls = true
                            }
                        },
                    };
                }

                {
                    // Subscribe to a topic
                    await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("my/topic").Build());

                    // Unsubscribe from a topic
                    await mqttClient.UnsubscribeAsync("my/topic");

                    // Publish an application message
                    var applicationMessage = new MqttApplicationMessageBuilder()
                                             .WithTopic("A/B/C")
                                             .WithPayload("Hello World")
                                             .WithAtLeastOnceQoS()
                                             .Build();

                    await mqttClient.PublishAsync(applicationMessage);
                }
            }

            // ----------------------------------
            {
                var options = new MqttServerOptions();

                options.ConnectionValidator = c =>
                {
                    if (c.ClientId.Length < 10)
                    {
                        return(MqttConnectReturnCode.ConnectionRefusedIdentifierRejected);
                    }

                    if (c.Username != "mySecretUser")
                    {
                        return(MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword);
                    }

                    if (c.Password != "mySecretPassword")
                    {
                        return(MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword);
                    }

                    return(MqttConnectReturnCode.ConnectionAccepted);
                };

                var factory    = new MqttFactory();
                var mqttServer = factory.CreateMqttServer();
                await mqttServer.StartAsync(options);

                Console.WriteLine("Press any key to exit.");
                Console.ReadLine();

                await mqttServer.StopAsync();
            }

            // ----------------------------------

            // For UWP apps:
            MqttTcpChannel.CustomIgnorableServerCertificateErrorsResolver = o =>
            {
                if (o.Server == "server_with_revoked_cert")
                {
                    return(new[] { ChainValidationResult.Revoked });
                }

                return(new ChainValidationResult[0]);
            };

            {
                // Start a MQTT server.
                var mqttServer = new MqttFactory().CreateMqttServer();
                await mqttServer.StartAsync(new MqttServerOptions());

                Console.WriteLine("Press any key to exit.");
                Console.ReadLine();
                await mqttServer.StopAsync();
            }

            {
                // Configure MQTT server.
                var options = new MqttServerOptions
                {
                    ConnectionBacklog = 100
                };

                options.DefaultEndpointOptions.Port = 1884;
                options.ConnectionValidator         = packet =>
                {
                    if (packet.ClientId != "Highlander")
                    {
                        return(MqttConnectReturnCode.ConnectionRefusedIdentifierRejected);
                    }

                    return(MqttConnectReturnCode.ConnectionAccepted);
                };

                var mqttServer = new MqttFactory().CreateMqttServer();
                await mqttServer.StartAsync(options);
            }

            {
                // Setup client validator.
                var options = new MqttServerOptions
                {
                    ConnectionValidator = c =>
                    {
                        if (c.ClientId.Length < 10)
                        {
                            return(MqttConnectReturnCode.ConnectionRefusedIdentifierRejected);
                        }

                        if (c.Username != "mySecretUser")
                        {
                            return(MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword);
                        }

                        if (c.Password != "mySecretPassword")
                        {
                            return(MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword);
                        }

                        return(MqttConnectReturnCode.ConnectionAccepted);
                    }
                };
            }

            {
                // Create a new MQTT server.
                var mqttServer = new MqttFactory().CreateMqttServer();
            }

            {
                // Setup and start a managed MQTT client.
                var options = new ManagedMqttClientOptionsBuilder()
                              .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                              .WithClientOptions(new MqttClientOptionsBuilder()
                                                 .WithClientId("Client1")
                                                 .WithTcpServer("broker.hivemq.com")
                                                 .WithTls().Build())
                              .Build();

                var mqttClient = new MqttFactory().CreateManagedMqttClient();
                await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("my/topic").Build());

                await mqttClient.StartAsync(options);
            }
        }
Exemple #30
0
        private static async Task ConnectAsync()
        {
            const string mqttUri      = "localhost";
            var          mqttUser     = "******";
            var          mqttPassword = "******";
            var          mqttPort     = 1883;

            Console.WriteLine($"MQTT Server:{mqttUri} Username:{mqttUser} ClientID:{leadvehicle}");
            var messageBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId(leadvehicle)
                                 .WithCredentials(mqttUser, mqttPassword)
                                 .WithTcpServer(mqttUri, mqttPort)
                                 .WithKeepAlivePeriod(new TimeSpan(0, 0, 30))
                                 .WithCleanSession();

            var options = messageBuilder
                          .Build();

            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                 .WithClientOptions(options)
                                 .Build();

            await client.StartAsync(managedOptions);

            client.UseConnectedHandler(e => { Console.WriteLine("Connected successfully with MQTT Brokers."); });
            client.UseApplicationMessageReceivedHandler(e =>
            {
                Console.WriteLine("Connected UseApplicationMessageReceivedHandler with MQTT Brokers." + e.ApplicationMessage);
            });

            client.UseDisconnectedHandler(e =>
            {
                new MqttClientDisconnectedHandlerDelegate(e => MqttClient_Disconnected(e));
                Console.WriteLine("Disconnected from MQTT Brokers.Client Was Connected " + e.ClientWasConnected);
            });
            client.UseApplicationMessageReceivedHandler(e =>
            {
                try
                {
                    var topic = e.ApplicationMessage.Topic;

                    if (!string.IsNullOrWhiteSpace(topic))
                    {
                        var stringpayload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                        var bitArray      = new BitArray(e.ApplicationMessage.Payload);
                        var payload       = HelperFunctions.GetPayload(e.ApplicationMessage.Payload);
                        var py            = HelperFunctions.ToBitString(new BitArray(e.ApplicationMessage.Payload), 0, 61);
                        Console.WriteLine($"Topic: {topic}. Message Received: {py}");
                        var followingVehicle = topic.Replace("platooning/" + leadvehicle + "/", "");
                        if (payload.Maneuver == 1 && !string.IsNullOrWhiteSpace(followingVehicle))
                        {
                            payload.Maneuver = 2;
                            var message      = new BitArray(61);
                            message.Set(0, false);
                            message.Set(1, true);
                            message.Set(2, false);
                            _ = PublishAsync("platooning/" + followingVehicle + "/" + leadvehicle + "/" + platoonId, Encoding.ASCII.GetString(HelperFunctions.BitArrayToByteArray(message)));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message, ex);
                }
            });
        }