private static async Task ConnectAsync() { // Setup and starts a managed MQTT client. var options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(new MqttClientOptionsBuilder() .WithClientId("Windows-MQTTtray") .WithTcpServer(server) //.WithTls() .Build()) .Build(); var mqttClient = new MqttFactory().CreateManagedMqttClient(); await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(topic).Build()); _ = mqttClient.UseApplicationMessageReceivedHandler(e => { //Debug.WriteLine("### RECEIVED APPLICATION MESSAGE ###"); //Debug.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}"); //Debug.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}"); //Debug.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}"); //Debug.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}"); var payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); var json = JObject.Parse(payload); var value = json.Value <int>(field); Debug.WriteLine($"{field}: {value}"); setIconText(value); }); await mqttClient.StartAsync(options); }
public async Task MqttServer_WillMessage() { var serverAdapter = new TestMqttServerAdapter(); var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger()); var receivedMessagesCount = 0; try { await s.StartAsync(new MqttServerOptions()); var willMessage = new MqttApplicationMessageBuilder().WithTopic("My/last/will").WithAtMostOnceQoS().Build(); var c1 = await serverAdapter.ConnectTestClient("c1"); var c2 = await serverAdapter.ConnectTestClient("c2", willMessage); c1.ApplicationMessageReceived += (_, __) => receivedMessagesCount++; await c1.SubscribeAsync(new TopicFilterBuilder().WithTopic("#").Build()); await c2.DisconnectAsync(); await Task.Delay(1000); await c1.DisconnectAsync(); } finally { await s.StopAsync(); } Assert.AreEqual(0, receivedMessagesCount); }
public static async Task <IMqttServer> StartServer() { var server = new MqttFactory().CreateMqttServer(); await server.StartAsync(new MqttServerOptions()); return(server); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); var currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() // ReSharper disable once AssignNullToNotNullAttribute .WriteTo.File(Path.Combine(currentPath, @"log\SimpleMqttServer_.txt"), rollingInterval: RollingInterval.Day) .WriteTo.Console() .CreateLogger(); var optionsBuilder = new MqttServerOptionsBuilder().WithDefaultEndpoint().WithApplicationMessageInterceptor( c => { c.AcceptPublish = true; LogMessage(c); }).WithSubscriptionInterceptor( c => { c.AcceptSubscription = true; LogMessage(c, true); }); var mqttServer = new MqttFactory().CreateMqttServer(); mqttServer.StartAsync(optionsBuilder.Build()); Console.ReadLine(); }
public async Task MqttServer_Publish() { 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("c1"); c1.ApplicationMessageReceived += (_, __) => receivedMessagesCount++; var message = new MqttApplicationMessageBuilder().WithTopic("a").WithAtLeastOnceQoS().Build(); await c1.SubscribeAsync(new TopicFilter("a", MqttQualityOfServiceLevel.AtLeastOnce)); await s.PublishAsync(message); await Task.Delay(500); } finally { await s.StopAsync(); } Assert.AreEqual(1, receivedMessagesCount); }
public async Task Unsubscribe() { 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()); await client.SubscribeAsync("a"); var result = await client.UnsubscribeAsync("a"); await client.DisconnectAsync(); Assert.AreEqual(1, result.Items.Count); Assert.AreEqual(MqttClientUnsubscribeResultCode.Success, result.Items[0].ReasonCode); } finally { await server.StopAsync(); } }
internal static async Task Main(string[] args) { Logger.Initialize(); // Setup and start a managed MQTT client. ManagedMqttClientOptions options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(new MqttClientOptionsBuilder() .WithClientId("Client1") .WithTcpServer("localhost") .Build()) .Build(); IManagedMqttClient mqttClient = new MqttFactory().CreateManagedMqttClient(); await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("families").Build()); await mqttClient.StartAsync(options); mqttClient.Connected += (sender, eventArgs) => { Log.Info("Connected !"); Task.Run(() => { Send(mqttClient).Wait(); }); }; mqttClient.ApplicationMessageReceived += (sender, eventArgs) => { Log.Info($"Message Received {eventArgs.ApplicationMessage.Topic} : {Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload)}"); }; mqttClient.ConnectingFailed += (sender, eventArgs) => { Log.Error("[CONNECTION_FAILED]", eventArgs.Exception); }; Console.ReadLine(); }
static void Main(string[] args) { var optionsBuilder = new MqttServerOptionsBuilder() .WithConnectionValidator(c => { Console.WriteLine($"{c.ClientId} connection validator for c.Endpoint: {c.Endpoint}"); c.ReasonCode = MqttConnectReasonCode.Success; }) .WithApplicationMessageInterceptor(context => { Console.WriteLine("WithApplicationMessageInterceptor block merging data"); var newData = Encoding.UTF8.GetBytes(DateTime.Now.ToString("O")); var oldData = context.ApplicationMessage.Payload; var mergedData = newData.Concat(oldData).ToArray(); context.ApplicationMessage.Payload = mergedData; }) .WithDefaultEndpointBoundIPAddress(IPAddress.Loopback) // Set IP address .WithConnectionBacklog(100) .WithDefaultEndpointPort(1884); //start server var mqttServer = new MqttFactory().CreateMqttServer(); mqttServer.StartAsync(optionsBuilder.Build()); Console.WriteLine($"Broker is Running: Host: {mqttServer.Options.DefaultEndpointOptions.BoundInterNetworkAddress} Port: {mqttServer.Options.DefaultEndpointOptions.Port}"); Console.WriteLine("Press any key to exit."); Console.ReadLine(); Task.Run(() => Thread.Sleep(Timeout.Infinite)).Wait(); mqttServer.StopAsync().Wait(); }
//static DeviceContext db = new DeviceContext(); public static void ConfigureAndStart() { DeviceContext db = new DeviceContext(); var optionsBuilder = new MqttServerOptionsBuilder() .WithDefaultEndpointPort(1884); var mqttServer = new MqttFactory().CreateMqttServer(); // mqttServer.UseApplicationMessageReceivedHandler(new MqttMessageReceivedHandler()); mqttServer.UseApplicationMessageReceivedHandler(e => { string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); //Console.WriteLine(payload); Device device = new Device { Temperature = payload }; db.devices.Add(device); db.SaveChanges(); //db.devices.Add(new Device { Id = 2, Temperature = payload }); //db.devices.Add(new Device {Id =4, Temperature= 3.ToString() }); }); mqttServer.StartAsync(optionsBuilder.Build()).GetAwaiter().GetResult(); }
static void Main(string[] args) { //Console.WriteLine("Hello World1!"); //configure options var optionsBuilder = new MqttServerOptionsBuilder() .WithConnectionValidator(c => { Console.WriteLine($"{c.ClientId} connection validator for c.Endpoint: {c.Endpoint}"); c.ReasonCode = MqttConnectReasonCode.Success; }) .WithConnectionBacklog(100) .WithDefaultEndpointPort(1884); //start server var mqttServer = new MqttFactory().CreateMqttServer(); mqttServer.StartAsync(optionsBuilder.Build()).Wait(); Console.WriteLine($"Broker is Running: Host: {mqttServer.Options.DefaultEndpointOptions.BoundInterNetworkAddress} Port: {mqttServer.Options.DefaultEndpointOptions.Port}"); Console.WriteLine("Press any key to exit."); Console.ReadLine(); mqttServer.StopAsync().Wait(); }
static async Task Main(string[] args) { var optionsBuilder = new MqttServerOptionsBuilder() .WithConnectionBacklog(100) .WithDefaultEndpointPort(1884); var mqttServer = new MqttFactory().CreateMqttServer(); await mqttServer.StartAsync(optionsBuilder.Build()); mqttServer.ApplicationMessageReceived += (s, e) => { Console.WriteLine(); Console.WriteLine("### Mensagem Recebida ###"); Console.WriteLine($"+ ClientId = {e.ClientId}"); Console.WriteLine($"+ Topico = {e.ApplicationMessage.Topic}"); Console.WriteLine($"+ Mensagem = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}"); Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}"); Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}"); Console.WriteLine(); }; Console.WriteLine("Server Mqtt iniciado..."); Console.WriteLine("Pressione qualquer tecla para fechar"); Console.ReadLine(); await mqttServer.StopAsync(); }
private static void PublishExcample() { // Setup and start a rx MQTT client. var options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(new MqttClientOptionsBuilder() .WithClientId("Client1") .WithTcpServer("127.0.0.1") .Build()) .Build(); using var mqttClient = new MqttFactory().CreateRxMqttClient(); _ = mqttClient.StartAsync(options); using var sub = Observable.Interval(TimeSpan.FromMilliseconds(1000)) .Select(_ => new MqttApplicationMessageBuilder() .WithTopic("MyTopic") .WithPayload("Hello World rx: " + DateTime.Now.ToLongTimeString()) .WithExactlyOnceQoS() .WithRetainFlag() .Build()) .PublishOn(mqttClient) .Subscribe(r => Console.WriteLine($"{r.ReasonCode} [{r.MqttApplicationMessage.Id}] :" + $" {r.MqttApplicationMessage.ApplicationMessage.Payload.ToUTF8String()}")); WaitForExit("Publish a message every secound."); }
private static async Task StartServer() { var optionsBuilder = new MqttServerOptionsBuilder() .WithConnectionBacklog(100) .WithDefaultEndpointPort(1883); var mqttServer = new MqttFactory().CreateMqttServer(); await mqttServer.StartAsync(optionsBuilder.Build()); var ct = new CancellationTokenSource(); var heartbeatTask = Task.Run(async() => await ServerHeartbeat(ct.Token, mqttServer)); Console.WriteLine("Type 'quit' to exit"); while (true) { string input = Console.ReadLine(); if (input != null && input.Contains("quit")) { break; } } ct.Cancel(); await heartbeatTask; await mqttServer.StopAsync(); }
static async Task Main(string[] args) { var deserializer = new DeserializerBuilder() .WithNamingConvention(new CamelCaseNamingConvention()) .Build(); Configuration = deserializer.Deserialize <Configuration>(File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "configuration.yaml"))); var mqttClientOptions = new MqttClientOptionsBuilder().WithClientId(Configuration.ClientId) .WithTcpServer(Configuration.Server, Configuration.Port) .WithCredentials(Configuration.Username, Configuration.Password); if (Configuration.UseSSL) { mqttClientOptions = mqttClientOptions.WithTls(); } var options = new ManagedMqttClientOptionsBuilder().WithAutoReconnectDelay(TimeSpan.FromSeconds(Configuration.ReconnectDelay)) .WithClientOptions(mqttClientOptions.Build()) .Build(); var client = new MqttFactory().CreateManagedMqttClient(); client.ApplicationMessageReceived += Client_ApplicationMessageReceived; client.ConnectingFailed += Client_ConnectingFailed; foreach (var topic in Configuration.Topics) { await client.SubscribeAsync(new TopicFilterBuilder().WithTopic(topic).Build()); } await client.StartAsync(options); Console.ReadLine(); }
public async Task MqttServer_Publish() { 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"); c1.ApplicationMessageReceived += (_, __) => receivedMessagesCount++; var message = new MqttApplicationMessageBuilder().WithTopic("a").WithAtLeastOnceQoS().Build(); await c1.SubscribeAsync(new TopicFilter("a", MqttQualityOfServiceLevel.AtLeastOnce)); s.PublishAsync(message).Wait(); await Task.Delay(500); } finally { await s.StopAsync(); } Assert.AreEqual(1, receivedMessagesCount); }
private void SetupMqttClient() { var solarEdgeSetting = Resolver.CreateConcreteInstanceWithDependencies <SolarEdgeSetting>(); var lwtMessage = new MqttApplicationMessageBuilder() .WithRetainFlag(true) .WithTopic("tele/solaredge/LWT") .WithPayload("offline") .Build(); var clientOptions = new MqttClientOptionsBuilder().WithClientId("SolarEdge") .WithTcpServer(solarEdgeSetting.MqttAddress) .WithWillMessage(lwtMessage); if (!string.IsNullOrWhiteSpace(solarEdgeSetting.MqttUsername)) { clientOptions.WithCredentials(solarEdgeSetting.MqttUsername, solarEdgeSetting.MqttPassword); } var options = new ManagedMqttClientOptionsBuilder().WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(clientOptions.Build()) .Build(); var mqttClient = new MqttFactory().CreateManagedMqttClient(); mqttClient.StartAsync(options).Wait(); ConfigurationResolver.AddRegistration(new SingletonRegistration <IManagedMqttClient>(mqttClient)); }
public async Task Subscribe() { 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.SubscribeAsync(new MqttClientSubscribeOptions() { SubscriptionIdentifier = 1, TopicFilters = new List <TopicFilter> { new TopicFilter { Topic = "a", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce } } }); await client.DisconnectAsync(); Assert.AreEqual(1, result.Items.Count); Assert.AreEqual(MqttClientSubscribeResultCode.GrantedQoS1, result.Items[0].ResultCode); } finally { await server.StopAsync(); } }
private async void MqttMultiClient(int clientsCount) { await Task.Factory.StartNew(async() => { for (int i = 0; i < clientsCount; i++) { var options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(new MqttClientOptionsBuilder() .WithClientId(Guid.NewGuid().ToString().Substring(0, 13)) .WithTcpServer(TxbServer.Text, Convert.ToInt32(TxbPort.Text)) .WithCredentials("admin", "public") .Build() ) .Build(); var c = new MqttFactory().CreateManagedMqttClient(); await c.SubscribeAsync( new TopicFilterBuilder().WithTopic(txbSubscribe.Text) .WithQualityOfServiceLevel( (MqttQualityOfServiceLevel) Enum.Parse(typeof(MqttQualityOfServiceLevel), CmbSubMqttQuality.Text)).Build()); await c.StartAsync(options); managedMqttClients.Add(c); Thread.Sleep(200); } }); }
public async Task Publish_With_Properties() { var server = new MqttFactory().CreateMqttServer(); var client = new MqttFactory().CreateMqttClient(); try { await server.StartAsync(new MqttServerOptions()); var applicationMessage = new MqttApplicationMessageBuilder() .WithTopic("Hello") .WithPayload("World") .WithAtMostOnceQoS() .WithUserProperty("x", "1") .WithUserProperty("y", "2") .WithResponseTopic("response") .WithContentType("text") .WithMessageExpiryInterval(50) .WithCorrelationData(new byte[12]) .WithTopicAlias(2) .Build(); await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").WithProtocolVersion(MqttProtocolVersion.V500).Build()); var result = await client.PublishAsync(applicationMessage); await client.DisconnectAsync(); Assert.AreEqual(MqttClientPublishReasonCode.Success, result.ReasonCode); } finally { await server.StopAsync(); } }
public static async Task GetMessages() { var fluksoIP = FluksoConfig.getConfig("FluksoServer:FluksoIP"); var options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(new MqttClientOptionsBuilder() .WithClientId("FluksoCore") .WithTcpServer(fluksoIP) .Build()) .Build(); var mqttClient = new MqttFactory().CreateManagedMqttClient(); await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("/sensor/+/+").Build()); await mqttClient.StartAsync(options); Console.WriteLine("Starting FluksoCore"); Console.WriteLine($"Listening on {fluksoIP}"); if (FluksoConfig.getConfig("Output:Console") == "true") { mqttClient.ApplicationMessageReceived += MessageHandler.ConsoleHandler; Console.WriteLine("Output Console enabled"); } if (FluksoConfig.getConfig("Output:EventHubs") == "true") { mqttClient.ApplicationMessageReceived += MessageHandler.EventHubsHandler; Console.WriteLine("Output EventHubs enabled"); } await Task.Delay(Timeout.Infinite); }
private static async Task RunServerAsync() { try { var mqttServer = new MqttFactory().CreateMqttServer(); ////var msgs = 0; ////var stopwatch = Stopwatch.StartNew(); ////mqttServer.ApplicationMessageReceived += (sender, args) => ////{ //// msgs++; //// if (stopwatch.ElapsedMilliseconds > 1000) //// { //// Console.WriteLine($"received {msgs}"); //// msgs = 0; //// stopwatch.Restart(); //// } ////}; await mqttServer.StartAsync(new MqttServerOptions()); Console.WriteLine("Press any key to exit."); Console.ReadLine(); await mqttServer.StopAsync(); } catch (Exception e) { Console.WriteLine(e); } Console.ReadLine(); }
static void Main(string[] args) { var optionsBuilder = new MqttServerOptionsBuilder() .WithDefaultEndpoint().WithDefaultEndpointPort(1883) // For testing purposes only //.WithEncryptedEndpoint().WithEncryptedEndpointPort(config.Port) //.WithEncryptionCertificate(certificate.Export(X509ContentType.Pfx)) //.WithEncryptionSslProtocol(SslProtocols.Tls12) .WithConnectionValidator( c => { Console.WriteLine(c.Username); c.ReasonCode = MqttConnectReasonCode.Success; }).WithSubscriptionInterceptor( c => { c.AcceptSubscription = false; }).WithApplicationMessageInterceptor( c => { c.AcceptPublish = false; }); var mqttServer = new MqttFactory().CreateMqttServer(); mqttServer.StartAsync(optionsBuilder.Build()); Console.ReadLine(); }
static async void StartServer() { var optionsBuilder = new MqttServerOptionsBuilder() .WithConnectionBacklog(int.Parse(_configuration["backlog"])) .WithDefaultEndpointPort(int.Parse(_configuration["portNumber"])); var mqttServer = new MqttFactory().CreateMqttServer(); var isEchoOn = bool.Parse(_configuration["echo"]); _topicsFilter = _configuration["echoTopicFilters"].Split(","); Console.WriteLine($"Mqtt broker listening on port {_configuration["portNumber"]} - press enter to exit."); if (isEchoOn) { Console.WriteLine($"echoing messages using topicFilter of {_configuration["echoTopicFilters"]}"); mqttServer.UseClientConnectedHandler(ClientConnectedHandler); mqttServer.UseClientDisconnectedHandler(ClientDisconnectedHandler); mqttServer.UseApplicationMessageReceivedHandler(MessageReceivedHandler); } await mqttServer.StartAsync(optionsBuilder.Build()); Console.ReadLine(); await mqttServer.StopAsync(); }
/// <inheritdoc/> public void Provide(IBindingProviderBuilder builder) { var mqttServer = new MqttFactory().CreateMqttServer(); mqttServer.StartAsync(new MqttServerOptions()).Wait(); builder.Bind <IMqttServer>().To(mqttServer); }
public async Task MqttServer_RetainedMessage() { 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("c1"); await c1.PublishAndWaitForAsync(s, new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[3]).WithRetainFlag().Build()); await c1.DisconnectAsync(); var c2 = await serverAdapter.ConnectTestClient("c2"); c2.ApplicationMessageReceived += (_, __) => receivedMessagesCount++; await c2.SubscribeAsync(new TopicFilterBuilder().WithTopic("retained").Build()); await Task.Delay(500); } finally { await s.StopAsync(); } Assert.AreEqual(1, receivedMessagesCount); }
public async Task MqttServer_ShutdownDisconnectsClientsGracefully() { var serverAdapter = new MqttTcpServerAdapter(new MqttNetLogger().CreateChildLogger()); var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger()); var clientOptions = new MqttClientOptionsBuilder() .WithTcpServer("localhost") .Build(); var disconnectCalled = 0; await s.StartAsync(new MqttServerOptions()); var c1 = new MqttFactory().CreateMqttClient(); c1.Disconnected += (sender, args) => disconnectCalled++; await c1.ConnectAsync(clientOptions); await Task.Delay(100); await s.StopAsync(); await Task.Delay(100); Assert.AreEqual(1, disconnectCalled); }
public static void Main() { var currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() // ReSharper disable once AssignNullToNotNullAttribute .WriteTo.File(Path.Combine(currentPath, @"log\SimpleMqttServer_.txt"), rollingInterval: RollingInterval.Day) .WriteTo.Console() .CreateLogger(); var config = ReadConfiguration(currentPath); var optionsBuilder = new MqttServerOptionsBuilder() .WithDefaultEndpoint().WithDefaultEndpointPort(config.Port).WithConnectionValidator( c => { var currentUser = config.Users.FirstOrDefault(u => u.UserName == c.Username); if (currentUser == null) { c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword; LogMessage(c, true); return; } if (c.Username != currentUser.UserName) { c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword; LogMessage(c, true); return; } if (c.Password != currentUser.Password) { c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword; LogMessage(c, true); return; } c.ReasonCode = MqttConnectReasonCode.Success; LogMessage(c, false); }).WithSubscriptionInterceptor( c => { c.AcceptSubscription = true; LogMessage(c, true); }).WithApplicationMessageInterceptor( c => { c.AcceptPublish = true; LogMessage(c); }); var mqttServer = new MqttFactory().CreateMqttServer(); mqttServer.StartAsync(optionsBuilder.Build()); Console.ReadLine(); }
public static async Task <IManagedMqttClient> GetClient(MqttOptions mqttOptions) { var clientConnectionOptionsBuilder = new MqttClientOptionsBuilder() .WithClientId(mqttOptions.ClientId) .WithTcpServer(mqttOptions.BrokerHostNameOrIp, mqttOptions.Port); if (!String.IsNullOrEmpty(mqttOptions.UserName) && !String.IsNullOrEmpty(mqttOptions.Password)) { clientConnectionOptionsBuilder = clientConnectionOptionsBuilder .WithCredentials(mqttOptions.UserName, mqttOptions.Password); } if (mqttOptions.EnableTls) { clientConnectionOptionsBuilder = clientConnectionOptionsBuilder .WithTls(); } var managedClientOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(clientConnectionOptionsBuilder.Build()) .Build(); var mqttClient = new MqttFactory().CreateManagedMqttClient(); await mqttClient.StartAsync(managedClientOptions); return(mqttClient); }
public static IDisposable CreateSubscriptionFor( MqttConfiguration configuration, Action <MqttApplicationMessageReceivedEventArgs> onMessageReceived) { var client = new MqttFactory().CreateManagedMqttClient(); var connectionOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(new MqttClientOptionsBuilder() .WithClientId(configuration.ClientId) .WithCleanSession(false) .WithTcpServer(configuration.HostName, configuration.Port) .WithCredentials(configuration.UserName, configuration.Password) .Build()) .Build(); void OnMessageReceived(MqttApplicationMessageReceivedEventArgs m) => onMessageReceived(m); client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnConnected); client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnDisconnected); client.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate(OnConnectingFailed); client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnMessageReceived); client.StartAsync(connectionOptions).Wait(); client.SubscribeAsync(new MqttTopicFilterBuilder() .WithTopic(configuration.SubscribeToTopic) .WithExactlyOnceQoS() .Build()).Wait(); return(new MqttReceiver(client)); }
public async Task MqttServer_HandleCleanDisconnect() { var serverAdapter = new MqttTcpServerAdapter(new MqttNetLogger().CreateChildLogger()); var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger()); var clientConnectedCalled = 0; var clientDisconnectedCalled = 0; s.ClientConnected += (_, __) => clientConnectedCalled++; s.ClientDisconnected += (_, __) => clientDisconnectedCalled++; var clientOptions = new MqttClientOptionsBuilder() .WithTcpServer("localhost") .Build(); await s.StartAsync(new MqttServerOptions()); var c1 = new MqttFactory().CreateMqttClient(); await c1.ConnectAsync(clientOptions); await Task.Delay(100); await c1.DisconnectAsync(); await Task.Delay(100); await s.StopAsync(); await Task.Delay(100); Assert.AreEqual(clientConnectedCalled, clientDisconnectedCalled); }