public static async Task HandleMQTTMessage() { var options = new MqttClientOptionsBuilder() .WithClientId("narojay-recever") .WithTcpServer("106.14.142.74", 1883) .WithCredentials("admin", "123456") .WithCleanSession() .Build(); MqttClient mqttclient = new MqttFactory().CreateMqttClient() as MqttClient; if (null == mqttclient) { throw new Exception("mqttclient为空"); } await mqttclient.ConnectAsync(options); await mqttclient.SubscribeAsync(new TopicFilterBuilder().WithTopic("topic/narojay").Build()); mqttclient.UseApplicationMessageReceivedHandler(e => { Console.WriteLine(Encoding.UTF8.GetString(e.ApplicationMessage.Payload)); }); Console.ReadKey(); }
public async Task Subscribe() { using (var testEnvironment = new TestEnvironment(TestContext)) { var server = await testEnvironment.StartServerAsync(); var factory = new MqttFactory(); var lowLevelClient = factory.CreateLowLevelMqttClient(); await lowLevelClient.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", testEnvironment.ServerPort).Build(), CancellationToken.None); await Authenticate(lowLevelClient).ConfigureAwait(false); var receivedPacket = await Subscribe(lowLevelClient, "a").ConfigureAwait(false); await lowLevelClient.DisconnectAsync(CancellationToken.None).ConfigureAwait(false); Assert.IsNotNull(receivedPacket); Assert.AreEqual(MqttSubscribeReturnCode.SuccessMaximumQoS0, receivedPacket.ReturnCodes[0]); } }
public static async Task Connect_Client_Using_WebSockets() { /* * This sample creates a simple MQTT client and connects to a public broker using a WebSocket connection. * * This is a modified version of the sample _Connect_Client_! See other sample for more details. */ var mqttFactory = new MqttFactory(); using (var mqttClient = mqttFactory.CreateMqttClient()) { var mqttClientOptions = new MqttClientOptionsBuilder().WithWebSocketServer("broker.hivemq.com:8000/mqtt").Build(); var response = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None); Console.WriteLine("The MQTT client is connected."); response.DumpToConsole(); } }
public async Task ConnectAsync() { var mqttClient = new MqttFactory().CreateMqttClient(); mqttClient.UseApplicationMessageReceivedHandler(e => { HandleMessage(e.ApplicationMessage); }); mqttClient.UseDisconnectedHandler(e => { HandleDisconnect(e.AuthenticateResult); }); var topicFilter = new MqttTopicFilter { Topic = _mqttTopic }; var options = new MqttClientOptionsBuilder() .WithClientId(_clientId) .WithTcpServer(_mqttServer, 1883) .WithCredentials(_mqttUser, _mqttPassword) .WithCleanSession() .Build(); mqttClient.ConnectAsync(options, CancellationToken.None).Wait(); await mqttClient.SubscribeAsync(topicFilter); }
public static void SendToOutput(string message) { // Create a new MQTT client. var factory = new MqttFactory(); mqttClient = factory.CreateMqttClient(); var msg = new MqttApplicationMessageBuilder() .WithTopic("testtopic/1") .WithPayload(message) .WithExactlyOnceQoS() .WithRetainFlag() .Build(); var options = new MqttClientOptionsBuilder().WithTcpServer("broker.hivemq.com", 1883).Build(); mqttClient.UseDisconnectedHandler(new MqttClientDisconnectedHandlerDelegate(e => MqttClient_Disconnected(e))); mqttClient.UseConnectedHandler(new MqttClientConnectedHandlerDelegate(e => MqttClient_Connected(e))); mqttClient.UseApplicationMessageReceivedHandler(new MqttApplicationMessageReceivedHandlerDelegate(e => MqttClient_ApplicationMessageReceived(e))); mqttClient.ConnectAsync(options).Wait(); //try { // var options = new MqttClientOptionsBuilder().WithTcpServer("broker.hivemq.com", 1883).Build(); // MQTTnet.Client.Connecting.MqttClientAuthenticateResult conn = mqttClient.ConnectAsync(options, CancellationToken.None).Result; // mqttClient.PublishAsync(msg, CancellationToken.None); // mqttClient.UseConnectedHandler(async e => // { // Console.WriteLine("### CONNECTED WITH SERVER ###"); // // Subscribe to a topic // await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("testtopic/1").Build()); // Console.WriteLine("### SUBSCRIBED ###"); // }); //} catch (Exception ex) { // Console.WriteLine(ex.Message); //} Console.ReadLine(); }
public static void RunClientOnly() { try { var options = new MqttClientOptions { ChannelOptions = new MqttClientTcpOptions { Server = "127.0.0.1" }, CleanSession = true }; var client = new MqttFactory().CreateMqttClient(); client.ConnectAsync(options).GetAwaiter().GetResult(); var message = CreateMessage(); var stopwatch = new Stopwatch(); for (var i = 0; i < 10; i++) { var sentMessagesCount = 0; stopwatch.Restart(); while (stopwatch.ElapsedMilliseconds < 1000) { client.PublishAsync(message).GetAwaiter().GetResult(); sentMessagesCount++; } Console.WriteLine($"Sending {sentMessagesCount} messages per second. #" + (i + 1)); GC.Collect(); } } catch (Exception exception) { Console.WriteLine(exception); } }
public async Task StartAsync() { // Create a new MQTT client. var factory = new MqttFactory(); client = factory.CreateMqttClient(); // Create TCP based options using the builder. var options = new MqttClientOptionsBuilder() .WithClientId("iGrill") .WithTcpServer(Settings.MqttHost, Settings.MqttPort) .WithCleanSession() .Build(); client.Disconnected += async(s, e) => { await Task.Delay(TimeSpan.FromSeconds(5)); try { var result = await client.ConnectAsync(options); } catch (MQTTnet.Exceptions.MqttCommunicationException ex) { Console.WriteLine("Mqtt reconnect failed: " + ex.Message); } }; try { var result = await client.ConnectAsync(options); } catch (MQTTnet.Exceptions.MqttCommunicationException ex) { Console.WriteLine("### CONNECTING FAILED ###" + ex.Message); } catch (Exception ex) { Console.WriteLine("### CONNECTING FAILED ###" + ex.Message); } }
async void Handle_Clicked(object sender, System.EventArgs e) { Debug.WriteLine("Client"); var factory = new MqttFactory(); var client = factory.CreateMqttClient(); client.UseConnectedHandler(async(arg) => { Debug.WriteLine("Connected with server"); //await client.SubscribeAsync(new MqttClientSubscribeOptions() //{ // TopicFilters = new System.Collections.Generic.List<MQTTnet.TopicFilter> // { // new TopicFilterBuilder().WithTopic("HotReloading").WithExactlyOnceQoS().Build() // } //}, CancellationToken.None); }); client.UseApplicationMessageReceivedHandler((arg) => { Debug.WriteLine("Data Received: " + arg.ApplicationMessage.ConvertPayloadToString()); }); var clientOptions = new MqttClientOptionsBuilder() .WithTcpServer("192.168.1.155", 8076) .Build(); await client.ConnectAsync(clientOptions); var message = new MqttApplicationMessageBuilder() .WithTopic("HotReloading") .WithExactlyOnceQoS() .WithPayload("Test data") .Build(); await client.PublishAsync(message); Debug.WriteLine("Press any key to close app"); await client.DisconnectAsync(); }
private static async void testi() { var factory = new MqttFactory(); var mqttClient = factory.CreateMqttClient(); //var mqttClient = new MqttClientFactory().CreateMqttClient(); var _mqttOptions = new MqttClientTcpOptions(); _mqttOptions.CleanSession = true; _mqttOptions.ClientId = "TEST"; _mqttOptions.DefaultCommunicationTimeout = TimeSpan.FromSeconds(20); _mqttOptions.KeepAlivePeriod = TimeSpan.FromSeconds(31); _mqttOptions.Server = "127.0.0.1"; _mqttOptions.UserName = "******"; _mqttOptions.Port = 8883; _mqttOptions.TlsOptions = new MqttClientTlsOptions { UseTls = true, AllowUntrustedCertificates = true, IgnoreCertificateChainErrors = true, IgnoreCertificateRevocationErrors = true }; MqttTcpChannel.CustomCertificateValidationCallback = remoteValidation; await mqttClient.ConnectAsync(_mqttOptions); mqttClient.Disconnected += async(s, e) => { Console.WriteLine("### DISCONNECTED FROM SERVER ###"); await Task.Delay(TimeSpan.FromSeconds(5)); try { await mqttClient.ConnectAsync(_mqttOptions); } catch { Console.WriteLine("### RECONNECTING FAILED ###"); } }; }
static async System.Threading.Tasks.Task Main() { /************************************************************* * User Configuration * *************************************************************/ var user = "******"; var password = "******"; // Setup client validator !!! chua ket hop option builder nay vo dc var optionsBuilder = new MqttServerOptionsBuilder() .WithConnectionBacklog(99) .WithDefaultEndpointPort(1884); // Setup client validator var options = new MqttServerOptions(); options.ConnectionValidator = new MqttServerConnectionValidatorDelegate(c => { if (c.Username != user) { c.ReturnCode = MQTTnet.Protocol.MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword; return; } if (c.Password != password) { c.ReturnCode = MQTTnet.Protocol.MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword; return; } c.ReturnCode = MQTTnet.Protocol.MqttConnectReturnCode.ConnectionAccepted; }); // Start Server var mqttServer = new MqttFactory().CreateMqttServer(); await mqttServer.StartAsync(options); Console.WriteLine("Server is running... \r\n\nPress Enter to exit."); Console.ReadLine(); await mqttServer.StopAsync(); }
public void Start() { _storageService.TryReadOrCreate(out _options, DefaultDirectoryNames.Configuration, MqttServiceOptions.Filename); var mqttFactory = new MqttFactory(); IsLowLevelMqttLoggingEnabled = _options.EnableLogging; if (IsLowLevelMqttLoggingEnabled) { _mqttServer = mqttFactory.CreateMqttServer(new LoggerAdapter(_logger)); } else { _mqttServer = mqttFactory.CreateMqttServer(); } _mqttServer.UseApplicationMessageReceivedHandler(new MqttApplicationMessageReceivedHandlerDelegate(e => OnApplicationMessageReceived(e))); var serverOptions = new MqttServerOptionsBuilder() .WithDefaultEndpointPort(_options.ServerPort) .WithConnectionValidator(ValidateClientConnection) .WithPersistentSessions(); if (_options.PersistRetainedMessages) { var storage = new MqttServerStorage(_storageService, _logger); storage.Start(); serverOptions.WithStorage(storage); } _mqttServer.StartAsync(serverOptions.Build()).GetAwaiter().GetResult(); _workerThread = new Thread(ProcessIncomingMqttMessages) { Name = nameof(MqttService), IsBackground = true }; _workerThread.Start(); }
public async Task PublishRemoveIDMCommand(Guid moduleId) { var mqttOptions = new MqttClientOptionsBuilder() .WithClientId("LiveboltServer") .WithTcpServer("localhost") .WithCredentials("livebolt", "livebolt") .Build(); var mqttClient = new MqttFactory().CreateMqttClient(); await mqttClient.ConnectAsync(mqttOptions); var message = new MqttApplicationMessageBuilder() .WithTopic($"idm/remove/{moduleId}") .WithPayload(1.ToString()) .WithExactlyOnceQoS() .Build(); await mqttClient.PublishAsync(message); await mqttClient.DisconnectAsync(); }
public async Task invioAsync(string sq) { var factory = new MqttFactory(); var mqttClient = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithTcpServer("192.168.101.49", 1883) // Port is optional .Build(); await mqttClient.ConnectAsync(options, CancellationToken.None); var message = new MqttApplicationMessageBuilder() .WithTopic("") .WithPayload(sq) .WithExactlyOnceQoS() .WithRetainFlag() .Build(); await mqttClient.PublishAsync(message); /* * HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://192.168.102.11:8011/tables/AB123"); * httpWebRequest.ContentType = "text/json"; * httpWebRequest.Method = "POST"; * * using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) * { * streamWriter.Write(sq); * } * * var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); * * Console.Out.WriteLine(httpResponse.StatusCode); * * httpResponse.Close(); * * System.Threading.Thread.Sleep(1000);*/ }
public static async Task <MqttServerInstance> StartServer(MqttServerConfiguration serverConfiguration) { logger.Info($"Starting Mqtt Server"); string storagefile = Path.Combine(PlugInData.HomeSeerDirectory, "data", PlugInData.PlugInId, "mqtt", "retained.json"); // Configure MQTT server. var optionsBuilder = new MqttServerOptionsBuilder() .WithConnectionBacklog(512) .WithStorage(new MqttStorage(storagefile)) .WithDefaultEndpointPort(serverConfiguration.Port); if (serverConfiguration.BoundIPAddress != null) { optionsBuilder = optionsBuilder.WithDefaultEndpointBoundIPAddress(serverConfiguration.BoundIPAddress); } optionsBuilder = optionsBuilder.WithDefaultEndpointBoundIPV6Address(IPAddress.None); var mqttServer = new MqttFactory(new MqttNetLogger()).CreateMqttServer(); await mqttServer.StartAsync(optionsBuilder.Build()).ConfigureAwait(false); return(new MqttServerInstance(mqttServer, serverConfiguration)); }
private static async Task TestPublishAsync( string topic, MqttQualityOfServiceLevel qualityOfServiceLevel, string topicFilter, MqttQualityOfServiceLevel filterQualityOfServiceLevel, int expectedReceivedMessagesCount) { var serverAdapter = new TestMqttServerAdapter(); var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger()); var receivedMessagesCount = 0; try { await s.StartAsync(new MqttServerOptions()); var c1 = await serverAdapter.ConnectTestClient(s, "c1"); var c2 = await serverAdapter.ConnectTestClient(s, "c2"); c1.ApplicationMessageReceived += (_, __) => receivedMessagesCount++; await c1.SubscribeAsync(new TopicFilterBuilder().WithTopic(topicFilter).WithQualityOfServiceLevel(filterQualityOfServiceLevel).Build()); await c2.PublishAsync(new MqttApplicationMessageBuilder().WithTopic(topic).WithPayload(new byte[0]).WithQualityOfServiceLevel(qualityOfServiceLevel).Build()); await Task.Delay(500); await c1.UnsubscribeAsync(topicFilter); await Task.Delay(500); } finally { await s.StopAsync(); } Assert.AreEqual(expectedReceivedMessagesCount, receivedMessagesCount); }
public async Task StartAsync(CancellationToken cancellationToken) { NotificationHub notificationHub = null; var deviceTopics = new List <DeviceMqttTopic>(); using (var scope = _serviceScopeFactory.CreateScope()) { var topicRepository = scope.ServiceProvider.GetRequiredService <IDeviceMqttTopicRepository>(); notificationHub = scope.ServiceProvider.GetRequiredService <NotificationHub>(); deviceTopics = topicRepository.GetAllWithBrokerInfo(); } foreach (var deviceTopic in deviceTopics.Where(x => x.TopicType == MqttTopicTypeEnum.Subscribe)) { var options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(AUTO_RECONNECT_DELAY)) .WithClientOptions( new MqttClientOptionsBuilder() .WithClientId(MQTT_CLIENT_ID + deviceTopic.Id) .WithTcpServer(deviceTopic.MqttBroker.Address, MQTT_SERVER_PORT) .Build()) .Build(); var subscriber = new MqttFactory().CreateManagedMqttClient(); subscriber.UseApplicationMessageReceivedHandler(message => notificationHub.NotifyDevice( deviceTopic.Id, message.ApplicationMessage.ConvertPayloadToString())); await subscriber.SubscribeAsync(new MqttTopicFilterBuilder() .WithTopic(deviceTopic.Topic) .Build()); await subscriber.StartAsync(options); } await Task.CompletedTask; }
public MqttPusher(ILogger <MqttPusher> logger, IHostApplicationLifetime hostApplicationLifetime) { this.logger = logger; this.hostApplicationLifetime = hostApplicationLifetime; mqttClientOptions = new MqttClientOptions { ChannelOptions = new MqttClientTcpOptions { Server = Environment.GetEnvironmentVariable("MQTT_HOST"), Port = int.Parse(Environment.GetEnvironmentVariable("MQTT_PORT")) } }; var factory = new MqttFactory(); client = factory.CreateMqttClient(); client.DisconnectedHandler = this; client.ConnectedHandler = this; Task t = this.ConnectingMqtt(hostApplicationLifetime.ApplicationStopping); t.Wait(); }
public async Task Initialize() { var factory = new MqttFactory(); mqttClient = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithTcpServer(url, 1883) .Build(); mqttClient.UseConnectedHandler(async e => { var topicFilters = new TopicFilterBuilder() .WithTopic("FX/FromNode") .WithTopic("FX/FromPython") .Build(); await mqttClient.SubscribeAsync(topicFilters); }); await mqttClient.ConnectAsync(options, CancellationToken.None); }
public static async Task Handle_Received_Application_Message() { /* * This sample subscribes to a topic and processes the received message. */ var mqttFactory = new MqttFactory(); using (var mqttClient = mqttFactory.CreateMqttClient()) { var mqttClientOptions = new MqttClientOptionsBuilder() .WithTcpServer("broker.hivemq.com") .Build(); // Setup message handling before connecting so that queued messages // are also handled properly. When there is no event handler attached all // received messages get lost. mqttClient.ApplicationMessageReceivedAsync += e => { Console.WriteLine("Received application message."); e.DumpToConsole(); return(Task.CompletedTask); }; await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None); var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder() .WithTopicFilter(f => { f.WithTopic("mqttnet/samples/topic/2"); }) .Build(); await mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None); Console.WriteLine("MQTT client subscribed to topic."); Console.WriteLine("Press enter to exit."); Console.ReadLine(); } }
protected override Task ExecuteAsync(CancellationToken stoppingToken) { var ClientOptions = new MqttClientOptions { ClientId = mqttOptions.ClientId, ChannelOptions = new MqttClientTcpOptions { Server = mqttOptions.BindAddress, Port = mqttOptions.Port } }; var managedClient = new MqttFactory().CreateMqttClient(); managedClient.ApplicationMessageReceived += ManagedClient_ApplicationMessageReceived; managedClient.Connected += ManagedClient_Connected; while (!stoppingToken.IsCancellationRequested) { //managedClient.sub } throw new NotImplementedException(); }
public void Init(string clientId, string server, int?port, string userName, string password) { try { mqttClientOptions = new MqttClientOptions { ClientId = clientId, CleanSession = true, ChannelOptions = new MqttClientTcpOptions { Server = server, Port = port }, Credentials = new MqttClientCredentials { Username = userName, Password = Encoding.UTF8.GetBytes(password) } }; 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) { } }
IMqttClient ProvideMQTTClient() { var configuration = _getContainer().Get <Configuration>(); _logger.Information($"Connecting to MQTT broker '{configuration.Connection.Host}:{configuration.Connection.Port}'"); var optionsBuilder = new MqttClientOptionsBuilder() .WithClientId(configuration.Connection.ClientId) .WithTcpServer(configuration.Connection.Host, configuration.Connection.Port); if (configuration.Connection.UseTls) { optionsBuilder = optionsBuilder.WithTls(); } var options = optionsBuilder.Build(); _mqttOptions = options; var factory = new MqttFactory(); var mqttClient = factory.CreateMqttClient(); mqttClient.UseDisconnectedHandler(async e => { await Task.Delay(TimeSpan.FromSeconds(5)); try { await mqttClient.ConnectAsync(options, CancellationToken.None); } catch (Exception ex) { _logger.Error(ex, "Couldn't reconnect MQTT client"); } }); _logger.Information($"Connect to MQTT broker"); return(mqttClient); }
public async Task Publish_QoS_2() { var server = new MqttFactory().CreateMqttServer(); var client = new MqttFactory().CreateMqttClient(); try { await server.StartAsync(new MqttServerOptions()); await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").WithProtocolVersion(MqttProtocolVersion.V500).Build()); var result = await client.PublishAsync("a", "b", MqttQualityOfServiceLevel.ExactlyOnce); await client.DisconnectAsync(); Assert.AreEqual(MqttClientPublishReasonCode.Success, result.ReasonCode); } finally { await server.StopAsync(); } }
static async Task Run(TraceLevel trace, int port) { var optionsBuilder = new MqttServerOptionsBuilder() .WithConnectionBacklog(100) .WithDefaultEndpointPort(port); var mqttServer = new MqttFactory().CreateMqttServer(); await mqttServer.StartAsync(optionsBuilder.Build()); mqttServer.UseApplicationMessageReceivedHandler(t => { if (t.ClientId != null) { if (trace == TraceLevel.Verbose) { Console.WriteLine("### Received message ###"); Console.WriteLine($"+ Topic = {t.ApplicationMessage.Topic}"); Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(t.ApplicationMessage.Payload)}"); } } }); }
public async Task ClientDisconnectException() { var factory = new MqttFactory(); var client = factory.CreateMqttClient(); var exceptionIsCorrect = false; client.Disconnected += (s, e) => { exceptionIsCorrect = e.Exception is MqttCommunicationException c && c.InnerException is SocketException; }; try { await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("wrong-server").Build()); } catch { } Assert.IsTrue(exceptionIsCorrect); }
private static async Task <IMqttServer> CreateMqttServerAsync() { var appsettings = ReadAppSettingsConfiguration(); // Configure MQTT server. var optionsBuilder = new MqttServerOptionsBuilder() .WithConnectionBacklog(100) .WithDefaultEndpointPort(appsettings.Port); var mqttServer = new MqttFactory().CreateMqttServer(); mqttServer.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(e => { MyConsole.Disconnected($"Client {e.ClientId} disconnected event fired."); }); mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(e => { MyConsole.Connected($"Client {e.ClientId} connected event fired."); }); await mqttServer.StartAsync(optionsBuilder.Build()); return(mqttServer); }
public MqttWorker(EvoHomeSettings evoHomeSettings, ILogger <MqttWorker> logger) { _settings = evoHomeSettings; _logger = logger; if (evoHomeSettings.DisableMqtt) { _logger.LogInformation("Mqtt Disabled"); return; } var builder = new MqttClientOptionsBuilder() .WithClientId(evoHomeSettings.MqttClientName); if (!string.IsNullOrWhiteSpace(evoHomeSettings.MqttUser)) { builder.WithCredentials(evoHomeSettings.MqttUser, evoHomeSettings.MqttPassword); } if (evoHomeSettings.MqttWebSockets) { builder.WithWebSocketServer($"{evoHomeSettings.MqttConnection}:{evoHomeSettings.MqttPort}"); } else { builder.WithTcpServer(evoHomeSettings.MqttConnection, evoHomeSettings.MqttPort); } var options = builder.Build(); _managedOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(options) .Build(); var factory = new MqttFactory(); _mqttClient = factory.CreateManagedMqttClient(); }
public async Task MqttServer_ClearRetainedMessage() { var serverAdapter = new TestMqttServerAdapter(); var services = new ServiceCollection() .AddLogging() .AddMqttServer() .AddSingleton <IMqttServerAdapter>(serverAdapter) .BuildServiceProvider(); var s = new MqttFactory(services).CreateMqttServer(); var receivedMessagesCount = 0; try { await s.StartAsync(); var c1 = await serverAdapter.ConnectTestClient(s, "c1"); await c1.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[3]).WithRetainFlag().Build()); await c1.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[0]).WithRetainFlag().Build()); await c1.DisconnectAsync(); var c2 = await serverAdapter.ConnectTestClient(s, "c2"); c2.ApplicationMessageReceived += (_, __) => receivedMessagesCount++; await c2.SubscribeAsync(new TopicFilter("retained", MqttQualityOfServiceLevel.AtMostOnce)); await Task.Delay(500); } finally { await s.StopAsync(); } Assert.AreEqual(0, receivedMessagesCount); }
static void Main(string[] args) { double treshold = 0; string postUrl = ""; if (args.Length < 2) { return; } if (args[0].Length <= 0 || !double.TryParse(args[0], out treshold)) { return; } if (args[1].Length <= 0) { return; } postUrl = args[1]; poster = new SensorValuePoster(postUrl); var MQTTClientFactory = new MqttFactory(); var sensor = new MQTTSensor(MQTTClientFactory.CreateMqttClient(), "b82399dacdbc4dc6bec4c2bda55d38cc", "test.mosquitto.org", "sensors/lyse-test-01"); sensor.SensorValueThreshold = treshold; sensor.SensorThresholdExceeded += sensor_SensorThresholdExceeded; while (true) { Console.ReadKey(); if (sensor.CurrentValue != null) { Console.WriteLine($"CurrentValue: {sensor.CurrentValue.Value}"); Console.WriteLine($"TimeStamp: {sensor.CurrentValue.TimeStamp}"); } } }
public MqttPublisher( ILogger <MqttPublisher> logger, DeviceConfigModel deviceConfigModel, IConfigurationService configurationService) { this.Subscribers = new List <AbstractCommand>(); this._logger = logger; this.DeviceConfigModel = deviceConfigModel; this._configurationService = configurationService; var options = _configurationService.GetMqttClientOptionsAsync().Result; _configurationService.MqqtConfigChangedHandler = this.ReplaceMqttClient; var factory = new MqttFactory(); this._mqttClient = factory.CreateManagedMqttClient(); if (options != null) { this._mqttClient.StartAsync(options); this._mqttClientMessage = "Connecting..."; } else { this._mqttClientMessage = "Not configured"; } this._mqttClient.UseConnectedHandler(e => { this._mqttClientMessage = "All good"; }); this._mqttClient.UseApplicationMessageReceivedHandler(e => this.HandleMessageReceived(e.ApplicationMessage)); // configure what happens on disconnect this._mqttClient.UseDisconnectedHandler(e => { this._mqttClientMessage = e.ReasonCode.ToString(); }); }