public static void Setup(Cumulus cumulus) { MqttPublisher.cumulus = cumulus; var mqttFactory = new MqttFactory(); mqttClient = (MqttClient)mqttFactory.CreateMqttClient(); var clientId = Guid.NewGuid().ToString(); MQTTnet.Client.Options.MqttClientTcpOptions mqttTcpOptions = new MQTTnet.Client.Options.MqttClientTcpOptions { Server = cumulus.MQTTServer, Port = cumulus.MQTTPort, TlsOptions = new MQTTnet.Client.Options.MqttClientTlsOptions { UseTls = cumulus.MQTTUseTLS } }; switch (cumulus.MQTTIpVersion) { case 4: mqttTcpOptions.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork; break; case 6: mqttTcpOptions.AddressFamily = System.Net.Sockets.AddressFamily.InterNetworkV6; break; default: mqttTcpOptions.AddressFamily = System.Net.Sockets.AddressFamily.Unspecified; break; } var mqttOptions = new MQTTnet.Client.Options.MqttClientOptions(); mqttOptions.ChannelOptions = mqttTcpOptions; mqttOptions.ClientId = clientId; mqttOptions.Credentials = String.IsNullOrEmpty(cumulus.MQTTPassword) ? null : new MQTTnet.Client.Options.MqttClientCredentials { Username = cumulus.MQTTUsername, Password = System.Text.Encoding.UTF8.GetBytes(cumulus.MQTTPassword) }; mqttOptions.CleanSession = true; Connect(mqttOptions); mqttClient.UseDisconnectedHandler(async e => { cumulus.LogMessage("Error: MQTT disconnected from the server"); await Task.Delay(TimeSpan.FromSeconds(5)); cumulus.LogDebugMessage("MQTT attempting to reconnect with server"); try { Connect(mqttOptions); cumulus.LogDebugMessage("MQTT reconnected OK"); } catch { cumulus.LogMessage("Error: MQTT reconnection to server failed"); } }); configured = true; }
private async Task WikiCode() { { // Write all trace messages to the console window. MqttNetGlobalLogger.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) { c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected; return; } if (c.Username != "mySecretUser") { c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword; return; } if (c.Password != "mySecretPassword") { c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword; return; } c.ReturnCode = 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 optionsBuilder = new MqttServerOptionsBuilder() .WithConnectionBacklog(100) .WithDefaultEndpointPort(1884); var options = new MqttServerOptions { }; options.ConnectionValidator = c => { if (c.ClientId != "Highlander") { c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected; return; } c.ReturnCode = MqttConnectReturnCode.ConnectionAccepted; }; var mqttServer = new MqttFactory().CreateMqttServer(); await mqttServer.StartAsync(optionsBuilder.Build()); } { // Setup client validator. var options = new MqttServerOptions { ConnectionValidator = c => { if (c.ClientId.Length < 10) { c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected; return; } if (c.Username != "mySecretUser") { c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword; return; } if (c.Password != "mySecretPassword") { c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword; return; } c.ReturnCode = 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); } }
public void Connect() { try { bool con = false; if (Certificates.IsCertificateEnabled()) { Certificates.GetCertificate("ABB Ability Edge"); } MqttFactory _mqttFactory = new MqttFactory(_clientLogger); var certificate = GetCert("ABB Ability Edge"); if (certificate == null) { certificate = new X509Certificate2(File.ReadAllBytes(this.certTxt.Text)); } this.exMsg.Content = ""; IMqttClientOptions options; MqttClientOptionsBuilder builderObj; builderObj = new MqttClientOptionsBuilder() .WithClientId(Guid.NewGuid().ToString()) .WithCleanSession(); if (this.layerCbox.SelectedItem.ToString().ToLower().Contains("tcp")) { builderObj = builderObj .WithClientId(Guid.NewGuid().ToString()) .WithTcpServer(this.ipTxt.Text, int.Parse(this.portTxt.Text)) .WithCleanSession(); } else { builderObj = builderObj .WithClientId(Guid.NewGuid().ToString()) .WithWebSocketServer(this.ipTxt.Text) .WithCleanSession().WithRequestProblemInformation(true); } if (!withoutCert) { builderObj = builderObj .WithTls(new MqttClientOptionsBuilderTlsParameters() { AllowUntrustedCertificates = true, UseTls = true, Certificates = new List <byte[]> { new X509Certificate2(certificate).Export(X509ContentType.Cert) }, CertificateValidationCallback = delegate { return(true); }, IgnoreCertificateChainErrors = false, IgnoreCertificateRevocationErrors = false }); } options = builderObj.Build(); client = _mqttFactory.CreateMqttClient(); var message = new MqttApplicationMessageBuilder() .WithTopic(this.topicTxt.Text) .WithPayload(this.msgTxt.Text + DateTime.Now.ToString()) .WithExactlyOnceQoS() .WithRetainFlag() .Build(); var result = client.ConnectAsync(options); if (result != null) { MessageBox.Show(result.ToString()); } client.UseConnectedHandler(async e => { MessageBox.Show("Connected"); //this.connection_status_lbl.Content = "Connected"; con = true; await client.PublishAsync(message); MessageBox.Show("Published"); }); this.connection_status_lbl.Content = ""; } catch (Exception ex) { MessageBox.Show(ex.Message); this.exMsg.Content = ex.StackTrace + Environment.NewLine; } }
public static async Task RunAsync() { try { MqttNetConsoleLogger.ForwardToConsole(); var factory = new MqttFactory(); var client = factory.CreateMqttClient(); var clientOptions = new MqttClientOptions { ChannelOptions = new MqttClientTcpOptions { Server = "127.0.0.1" } }; client.ApplicationMessageReceived += (s, 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(); }; client.Connected += async(s, e) => { Console.WriteLine("### CONNECTED WITH SERVER ###"); await client.SubscribeAsync(new TopicFilterBuilder().WithTopic("#").Build()); Console.WriteLine("### SUBSCRIBED ###"); }; client.Disconnected += async(s, e) => { Console.WriteLine("### DISCONNECTED FROM SERVER ###"); await Task.Delay(TimeSpan.FromSeconds(5)); try { await client.ConnectAsync(clientOptions); } catch { Console.WriteLine("### RECONNECTING FAILED ###"); } }; try { await client.ConnectAsync(clientOptions); } catch (Exception exception) { Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception); } Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###"); while (true) { Console.ReadLine(); await client.SubscribeAsync(new TopicFilter("test", MqttQualityOfServiceLevel.AtMostOnce)); var applicationMessage = new MqttMessageBuilder() .WithTopic("A/B/C") .WithPayload("Hello World") .WithAtLeastOnceQoS() .Build(); await client.PublishAsync(applicationMessage); } } catch (Exception exception) { Console.WriteLine(exception); } }
public static async Task Main(string[] args) { Console.WriteLine("Hello World!"); var factory = new MqttFactory(); var mqttClient = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithTcpServer("mqttserver") .WithCleanSession() .Build(); mqttClient.Disconnected += async(s, e) => { Console.WriteLine("### DISCONNECTED FROM SERVER ###"); await Task.Delay(TimeSpan.FromSeconds(5)); try { await mqttClient.ConnectAsync(options); } catch { Console.WriteLine("### RECONNECTING FAILED ###"); } }; mqttClient.Connected += async(s, e) => { Console.WriteLine("### CONNECTED WITH SERVER. Attempt subs ###"); // Subscribe to a topic try { await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("pulsePeriod").Build()); await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("impressions").Build()); await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("log").Build()); }catch (Exception ex) { Console.WriteLine("Exception"); Console.WriteLine(ex.Message); } Console.WriteLine("### SUBSCRIBED ###"); }; await mqttClient.ConnectAsync(options); mqttClient.ApplicationMessageReceived += async(s, e) => { var topic = e.ApplicationMessage.Topic; var value = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); Console.WriteLine($"Mqtt client received: ({topic}) {value}"); if (topic == "pulsePeriod") { var val = Convert.ToInt32(value); var kwh = KWHelper.CalcKWH(val); Console.WriteLine($"kwh -> {kwh.ToString("0.##")}"); var c = new HttpClient(); var result = await c.GetAsync($"http://apiserver:5000/impress/kwh?kwh={kwh}"); Console.WriteLine(result.Content.ReadAsStringAsync()); } // 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(); }; System.Threading.Thread.Sleep(Timeout.Infinite); }
private async Task WikiCode() { { // 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(); }); // 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 = "******" }, ChannelOptions = new MqttClientTcpOptions { Server = "broker.hivemq.org", TlsOptions = new MqttClientTlsOptions { UseTls = true } }, }; } } // ---------------------------------- { var options = new MqttServerOptions(); options.ConnectionValidator = new MqttServerConnectionValidatorDelegate(c => { if (c.ClientId.Length < 10) { c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected; return; } if (c.Username != "mySecretUser") { c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword; return; } if (c.Password != "mySecretPassword") { c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword; return; } c.ReturnCode = 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 optionsBuilder = new MqttServerOptionsBuilder() .WithConnectionBacklog(100) .WithDefaultEndpointPort(1884); var options = new MqttServerOptions { }; options.ConnectionValidator = new MqttServerConnectionValidatorDelegate(c => { if (c.ClientId != "Highlander") { c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected; return; } c.ReturnCode = MqttConnectReturnCode.ConnectionAccepted; }); 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.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected; return; } if (c.Username != "mySecretUser") { c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword; return; } if (c.Password != "mySecretPassword") { c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword; return; } c.ReturnCode = MqttConnectReturnCode.ConnectionAccepted; }) }; } { // Create a new MQTT server. var mqttServer = new MqttFactory().CreateMqttServer(); } { // 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.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(); } Console.WriteLine(trace); }; } }
public static async Task ReqRepTest(int LoopNum) { string requestTopic = "mytopic/A/request"; var sw = new System.Diagnostics.Stopwatch(); sw.Start(); using (var cts = new CancellationTokenSource()) using (var startedev = new ManualResetEventSlim()) using (var connectedev = new ManualResetEventSlim()) using (var recvev = new ManualResetEventSlim()) { var fac = new MqttFactory(); await Task.WhenAll( Task.Run(async() => { var svr = fac.CreateMqttServer(); var msgbuilder = new MqttApplicationMessageBuilder().WithPayload("req"); svr.ApplicationMessageReceived += async(sender, ev) => { if (ev.ApplicationMessage.Topic.Equals(requestTopic, StringComparison.Ordinal)) { var reqmsg = MessagePackSerializer.Deserialize <ReqMsg>(ev.ApplicationMessage.Payload); var msg = msgbuilder.WithTopic(reqmsg.ReplyTopic).Build(); await svr.PublishAsync(msg); } }; svr.Started += (sender, ev) => { startedev.Set(); }; var opt = new MqttServerOptionsBuilder() .WithDefaultEndpoint() .WithDefaultEndpointBoundIPAddress(IPAddress.Loopback) .WithDefaultEndpointPort(10012) .Build(); await svr.StartAsync(opt).ConfigureAwait(false); cts.Token.WaitHandle.WaitOne(); await svr.StopAsync().ConfigureAwait(false); }) , Task.Run(async() => { var client = fac.CreateMqttClient(); string replyTopic = "mytopic/A/reply"; var queue = new ConcurrentQueue <TaskCompletionSource <byte[]> >(); client.ApplicationMessageReceived += (sender, ev) => { if (queue.TryDequeue(out var tcs)) { tcs.TrySetResult(ev.ApplicationMessage.Payload); } }; client.Connected += (sender, ev) => { connectedev.Set(); }; var clientopt = new MqttClientOptionsBuilder() .WithClientId("clid") .WithTcpServer("localhost", 10012) .Build() ; await client.ConnectAsync(clientopt).ConfigureAwait(false); connectedev.Wait(); var topicFilter = new TopicFilterBuilder() .WithTopic(replyTopic) .WithAtLeastOnceQoS() .Build() ; await client.SubscribeAsync(topicFilter).ConfigureAwait(false); Console.WriteLine($"client task loop started:{sw.Elapsed}"); var beginTime = sw.Elapsed; var msgbuilder = new MqttApplicationMessageBuilder().WithTopic(requestTopic); for (int i = 0; i < LoopNum; i++) { var reqpayload = MessagePackSerializer.Serialize(new ReqMsg(replyTopic, "hoge")); var msg = msgbuilder .WithPayload(reqpayload) .Build(); ; var reqtcs = new TaskCompletionSource <byte[]>(); queue.Enqueue(reqtcs); await client.PublishAsync(msg).ConfigureAwait(false); await reqtcs.Task; } var endTime = sw.Elapsed; Console.WriteLine($"elapsed(mqtt):{sw.Elapsed},rps={LoopNum/(endTime.Subtract(beginTime).TotalSeconds)}"); }).ContinueWith(t => { Console.WriteLine($"all client task done:{sw.Elapsed}"); cts.Cancel(); if (t.IsCanceled) { throw new TaskCanceledException("server task cancelled", t.Exception); } else if (t.IsFaulted) { throw new AggregateException(t.Exception); } }) ).ConfigureAwait(false); } }
static async Task Main(string[] args) { // Create a new MQTT client. var factory = new MqttFactory(); var mqttClient = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithTcpServer("localhost") .WithClientId("Sample") .Build(); mqttClient.UseDisconnectedHandler(async e => { Console.WriteLine("### DISCONNECTED FROM SERVER ###"); await Task.Delay(TimeSpan.FromSeconds(5)); try { await mqttClient.ConnectAsync(options, CancellationToken.None); // Since 3.0.5 with CancellationToken } catch { Console.WriteLine("### RECONNECTING FAILED ###"); } }); mqttClient.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(); Task.Run(() => mqttClient.PublishAsync("hello/world")); }); mqttClient.UseConnectedHandler(async e => { Console.WriteLine("### CONNECTED WITH SERVER ###"); // Subscribe to a topic var filter = new MqttTopicFilter(); filter.Topic = "my/topic"; await mqttClient.SubscribeAsync(filter); Console.WriteLine("### SUBSCRIBED ###"); }); await mqttClient.ConnectAsync(options, CancellationToken.None); // Since 3.0.5 with CancellationToken var message = new MqttApplicationMessageBuilder() .WithTopic("my/topic") .WithPayload("Hello World1234") .WithExactlyOnceQoS() .WithRetainFlag() .Build(); await mqttClient.PublishAsync(message, CancellationToken.None); // Since 3.0.5 with CancellationToken Console.ReadLine(); }
public MQTTService(IMQTTSettings mqttSettings, IMQTTProcessingService mqttProcessingService) { _mqttProcessingService = mqttProcessingService; // no mqtt messaging if no MQTT broker if (string.IsNullOrEmpty(Program.mqttSettings.Host)) { return; } // when single tenant case, only 1 MQTT client needed for (var t = 0; t < Program.Tenants.Count; t++) { var mqttTopic = Program.mqttSettings.TopicTemplate.Replace("{TenantId}", Program.Tenants[t].TenantId); var mqttClient = _factory.CreateMqttClient(); var mqttClientID = Program.InstanceConfig.ServerInstanceID + ":" + Program.Tenants[t].TenantId; var myMqttClient = new MyMQTTClient() { TenantId = Program.Tenants[t].TenantId, mqttTopic = mqttTopic, mqttClient = mqttClient, mqttClientId = mqttClientID }; if (string.IsNullOrEmpty(Program.mqttSettings.User)) { _mqttClientOptions = new MqttClientOptionsBuilder() .WithTcpServer(Program.mqttSettings.Host, Program.mqttSettings.Port) .WithClientId(myMqttClient.mqttClientId) .Build(); } else { _mqttClientOptions = new MqttClientOptionsBuilder() .WithTcpServer(Program.mqttSettings.Host, Program.mqttSettings.Port) .WithCredentials(Program.mqttSettings.User, Program.mqttSettings.Password) .WithClientId(myMqttClient.mqttClientId) .Build(); } mqttClient.UseDisconnectedHandler(async disconnected => { UseDisconnectedHandler(mqttClient, disconnected); }); mqttClient.UseConnectedHandler(async conn => { UseConnectedHandler(mqttClient, myMqttClient.mqttTopic, conn); }); mqttClient.UseApplicationMessageReceivedHandler(async message => { UseApplicationMessageReceivedHandler(message); }); mqttClient.ConnectAsync(_mqttClientOptions); _mqttClients.Add(myMqttClient); } // start broadcast timer _broadcastPeerTimer = new System.Timers.Timer(Math.Min(Program.InstanceConfig.PeerEvictionInSecs - Program.InstanceConfig.PeerHeartbeatBeforeEvictionInSecs, Program.InstanceConfig.PeerMinHeartbeatInSecs) * 1000); _broadcastPeerTimer.AutoReset = true; _broadcastPeerTimer.Enabled = true; _broadcastPeerTimer.Elapsed += OnBroadcastTimedEvent; }
public static async Task TestMany(int loopNum, int taskNum) { var fac = new MqttFactory(); using (var cts = new CancellationTokenSource()) { var sw = new System.Diagnostics.Stopwatch(); sw.Start(); await Task.WhenAll( Task.Run(async() => { var svr = fac.CreateMqttServer(); svr.Started += (sender, ev) => { Console.WriteLine($"{sw.Elapsed} svr started"); }; svr.ClientConnected += (sender, ev) => { Console.WriteLine($"{sw.Elapsed} client connected(S): {ev.Client.ClientId}"); }; svr.ClientDisconnected += (sender, ev) => { Console.WriteLine($"{sw.Elapsed} client disconnected(S): {ev.Client.ClientId}"); }; var opt = new MqttServerOptionsBuilder() .WithDefaultEndpoint() .WithDefaultEndpointBoundIPAddress(IPAddress.Loopback) .WithDefaultEndpointPort(10012) .Build(); await svr.StartAsync(opt).ConfigureAwait(false); cts.Token.WaitHandle.WaitOne(); await svr.StopAsync().ConfigureAwait(false); }) , Task.Run(async() => { await Task.Delay(100).ConfigureAwait(false); var client = fac.CreateMqttClient(); var clientopt = new MqttClientOptionsBuilder() .WithClientId("clid") .WithTcpServer("localhost", 10012) .Build() ; // var opt = new ManagedMqttClientOptionsBuilder() // .WithClientOptions(clientopt) // .WithAutoReconnectDelay(TimeSpan.FromMilliseconds(100)) // .Build(); using (var connectedEvent = new ManualResetEventSlim(false)) { client.ApplicationMessageReceived += (sender, ev) => { Console.WriteLine($"{sw.Elapsed} recv {ev.ApplicationMessage.Topic},{ev.ApplicationMessage.Payload[0]}"); }; client.Connected += (sender, ev) => { Console.WriteLine($"{sw.Elapsed} client connected"); connectedEvent.Set(); }; client.Disconnected += (sender, ev) => { Console.WriteLine($"{sw.Elapsed} client disconnected"); }; var topicFilter = new TopicFilterBuilder() .WithTopic("mytopic/A").WithAtLeastOnceQoS().Build(); Console.WriteLine($"{sw.Elapsed} begin connection"); await client.ConnectAsync(clientopt).ConfigureAwait(false); // await client.StartAsync(opt).ConfigureAwait(false); connectedEvent.Wait(); if (!client.IsConnected) { Console.WriteLine($"not connected"); } else { Console.WriteLine($"{sw.Elapsed} connection established"); } await client.SubscribeAsync(new[] { topicFilter }).ConfigureAwait(false); Console.WriteLine($"{sw.Elapsed} subscribing done"); var msgbuilder = new MqttApplicationMessageBuilder(); msgbuilder = msgbuilder.WithTopic("mytopic/A").WithAtLeastOnceQoS(); var dat = new byte[1]; for (int i = 0; i < 100; i++) { await Task.Yield(); dat[0] = (byte)(i % 255); var msg = msgbuilder.WithPayload(dat).Build(); await client.PublishAsync(msg).ConfigureAwait(false); Console.WriteLine($"{sw.Elapsed}: publish{i}"); } await client.UnsubscribeAsync(new[] { topicFilter.Topic }).ConfigureAwait(false); await client.DisconnectAsync().ConfigureAwait(false); // await client.StopAsync().ConfigureAwait(false); // cts.Cancel(); } // var opt = new MqttClientOptionsBuilder() // .Build(); // await client.ConnectAsync(opt).ConfigureAwait(false); // var topicFilter = new TopicFilterBuilder() // .WithTopic("topic") // .Build(); // var subresults = await client.SubscribeAsync(new TopicFilter[] {topicFilter}).ConfigureAwait(false); // foreach(var subresult in subresults) // { // } }).ContinueWith(t => { cts.Cancel(); }) ); sw.Stop(); } }
public MainWindow() { InitializeComponent(); //"127.0.0.1" or "localhost" when you installed Mosquitto Broker in your local machine. //"test.mosquitto.org"; //string BrokerAddress = "192.168.3.5"; string BrokerAddress = "localhost"; int BrokerPort = 1883; // use a unique id as client id, each time we start the application clientId = Guid.NewGuid().ToString(); string username = "******"; string password = "******"; // Create a new MQTT client. var factory = new MqttFactory(); mqttClient = factory.CreateMqttClient(); //// Certificate based authentication //List<X509Certificate> certs = new List<X509Certificate> //{ // new X509Certificate2("certificate1.pfx") //}; // Create TCP based options using the builder. var options = new MqttClientOptionsBuilder() .WithClientId(clientId) .WithTcpServer(BrokerAddress, BrokerPort) .WithCredentials(username, password) //("bud", "%spencer%") //.WithTls(new MqttClientOptionsBuilderTlsParameters //{ // UseTls = true, // Certificates = certs, // CertificateValidationHandler = (MqttClientCertificateValidationCallbackContext context) => // { // // TODO: Check conditions of certificate by using above parameters. // return true; // } //}) //.WithTls() .WithCleanSession() .Build(); // Subscribing to a topic mqttClient.UseConnectedHandler(async e => { await UseConnectedMessage(); //Console.WriteLine("### CONNECTED WITH SERVER ###"); //// Subscribe to a topic //await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("my/topic").Build()); //Console.WriteLine("### SUBSCRIBED ###"); }); // Reconnecting mqttClient.UseDisconnectedHandler(async e => { Dispatcher.Invoke(delegate { sbMessage.Text = "Disconnected from MQTT Brokers."; }); //Console.WriteLine("### DISCONNECTED FROM SERVER ###"); await Task.Delay(TimeSpan.FromSeconds(5)); try { await mqttClient.ConnectAsync(options, CancellationToken.None); // Since 3.0.5 with CancellationToken } catch { //Console.WriteLine("### RECONNECTING FAILED ###"); } }); mqttClient.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}"); //Dispatcher.Invoke(delegate //{ // // we need this construction because the receiving code in the library and the UI with textbox run on different threads // txtReceived.Text = payload; // btnSubscribe2.Content = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture); //}); switch (topic.ToLower()) { case "picture": BitmapImage bitimg = Utils.ByteToImage(e.ApplicationMessage.Payload); Dispatcher.Invoke(delegate { ImageViewer2.Source = bitimg; btnSubscribe2.Content = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture); }); break; case "bundle": DataInfo imageData = ExtendedSerializerExtensions.Deserialize <DataInfo>(e.ApplicationMessage.Payload); Dispatcher.Invoke(delegate { ImageViewer2.Source = Utils.ByteToImage(imageData.ImageData); txtReceived.Text = (string.IsNullOrEmpty(imageData.PublisherMessage) ? "" : imageData.PublisherMessage + "\n") + imageData.FileName; txtReceivedDate.Text = imageData.SentDateTime.ToString(); btnSubscribe2.Content = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture); }); break; default: string ReceivedMessage = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); Dispatcher.Invoke(delegate { txtReceived.Text = ReceivedMessage; btnSubscribe2.Content = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture); }); break; } } //string ReceivedMessage = Encoding.UTF8.GetString(e.Message); } catch (Exception ex) { Console.WriteLine(ex.Message, ex); } }); //mqttClient.ConnectAsync(options, CancellationToken.None).Wait(CancellationToken.None); mqttClient.ConnectAsync(options).GetAwaiter().GetResult(); }
protected override void OnInitialized() { Logger.LogDebug("OnInitialized method called."); try { var factory = new MqttFactory(); mqttClient = factory.CreateMqttClient(); lock (mqttClient) { if (configMQTT.UseCredentials()) { clientOptions = new MqttClientOptionsBuilder() .WithClientId(Guid.NewGuid().ToString()) .WithTcpServer(configMQTT.Host) .WithCredentials(configMQTT.UserName, configMQTT.Password) .Build(); } else { clientOptions = new MqttClientOptionsBuilder() .WithClientId(Guid.NewGuid().ToString()) .WithTcpServer(configMQTT.Host) .Build(); } //Set delegate for processing MQTT messages mqttClient.ApplicationMessageReceived += onMqttMessageReceived; mqttClient.Connected += async(s, e) => { string msg = "### MQTT Service CONNECTED WITH MQTT-SERVER ###"; Logger.LogDebug(msg); Console.WriteLine(msg); }; mqttClient.Disconnected += async(s, e) => { Console.WriteLine("### DISCONNECTED FROM SERVER ###"); await Task.Delay(TimeSpan.FromSeconds(5)); try { await mqttClient.ConnectAsync(clientOptions); } catch { Console.WriteLine("### RECONNECTING FAILED ###"); } }; try { mqttClient.ConnectAsync(clientOptions); while (!mqttClient.IsConnected) { Thread.Sleep(100); } } catch (Exception exception) { Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception); } } Logger.LogDebug("### WAITING FOR APPLICATION MESSAGES ###"); } catch (Exception exception) { Console.WriteLine(exception); } }
private async Task ConnectMqttServerAsync() { // Create a new MQTT client. if (mqttClient == null) { var factory = new MqttFactory(); mqttClient = factory.CreateMqttClient(); mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; mqttClient.Connected += MqttClient_Connected; mqttClient.Disconnected += MqttClient_Disconnected; } //非托管客户端 try { ////Create TCP based options using the builder. //var options1 = new MqttClientOptionsBuilder() // .WithClientId("client001") // .WithTcpServer("192.168.88.3") // .WithCredentials("bud", "%spencer%") // .WithTls() // .WithCleanSession() // .Build(); //// Use TCP connection. //var options2 = new MqttClientOptionsBuilder() // .WithTcpServer("192.168.88.3", 8222) // Port is optional // .Build(); //// Use secure TCP connection. //var options3 = new MqttClientOptionsBuilder() // .WithTcpServer("192.168.88.3") // .WithTls() // .Build(); //Create TCP based options using the builder. var options = new MqttClientOptionsBuilder() .WithClientId(txtClientId.Text) .WithTcpServer(txtIp.Text, Convert.ToInt32(txtPort.Text)) .WithCredentials(txtUsername.Text, txtPsw.Text) //.WithTls()//服务器端没有启用加密协议,这里用tls的会提示协议异常 .WithCleanSession() .Build(); //// For .NET Framwork & netstandard apps: //MqttTcpChannel.CustomCertificateValidationCallback = (x509Certificate, x509Chain, sslPolicyErrors, mqttClientTcpOptions) => //{ // if (mqttClientTcpOptions.Server == "server_with_revoked_cert") // { // return true; // } // return false; //}; //2.4.0版本的 //var options0 = new MqttClientTcpOptions //{ // Server = "127.0.0.1", // ClientId = Guid.NewGuid().ToString().Substring(0, 5), // UserName = "******", // Password = "******", // CleanSession = true //}; await mqttClient.ConnectAsync(options); } catch (Exception ex) { Invoke((new Action(() => { txtReceiveMessage.AppendText($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine); }))); } //托管客户端 try { //// Setup and start a managed MQTT client. //var options = new ManagedMqttClientOptionsBuilder() // .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) // .WithClientOptions(new MqttClientOptionsBuilder() // .WithClientId("Client_managed") // .WithTcpServer("192.168.88.3", 8223) // .WithTls() // .Build()) // .Build(); //var mqttClient = new MqttFactory().CreateManagedMqttClient(); //await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("my/topic").Build()); //await mqttClient.StartAsync(options); } catch (Exception) { } }
private async void Connect(object sender, RoutedEventArgs e) { var tlsOptions = new MqttClientTlsOptions { UseTls = UseTls.IsChecked == true, IgnoreCertificateChainErrors = true, IgnoreCertificateRevocationErrors = true, AllowUntrustedCertificates = true }; var options = new MqttClientOptions { ClientId = ClientId.Text }; if (UseTcp.IsChecked == true) { options.ChannelOptions = new MqttClientTcpOptions { Server = Server.Text, Port = int.Parse(Port.Text), TlsOptions = tlsOptions }; } if (UseWs.IsChecked == true) { options.ChannelOptions = new MqttClientWebSocketOptions { Uri = Server.Text, TlsOptions = tlsOptions }; } if (options.ChannelOptions == null) { throw new InvalidOperationException(); } options.Credentials = new MqttClientCredentials { Username = User.Text, Password = Password.Text }; options.CleanSession = CleanSession.IsChecked == true; options.KeepAlivePeriod = TimeSpan.FromSeconds(double.Parse(KeepAliveInterval.Text)); try { if (_mqttClient != null) { await _mqttClient.DisconnectAsync(); _mqttClient.ApplicationMessageReceived -= OnApplicationMessageReceived; _mqttClient.Connected -= OnConnected; _mqttClient.Disconnected -= OnDisconnected; } var factory = new MqttFactory(); _mqttClient = factory.CreateMqttClient(); _mqttClient.ApplicationMessageReceived += OnApplicationMessageReceived; _mqttClient.Connected += OnConnected; _mqttClient.Disconnected += OnDisconnected; await _mqttClient.ConnectAsync(options); } catch (Exception exception) { Trace.Text += exception + Environment.NewLine; } }
private static void Main(string[] args) { var factory = new MqttFactory(); mqttClient = factory.CreateMqttClient(); clientId = "followingVehicle"; const string mqttUri = "localhost"; var mqttUser = "******"; var mqttPassword = "******"; var mqttPort = 1883; server = mqttUri; username = mqttUser; apiKey = mqttPassword; Console.WriteLine($"MQTT Server:{server} Username:{username} ClientID:{clientId}"); // wolkabout formatted client state update topic var topicD2C = "platooning/message/followingvehicle"; mqttOptions = new MqttClientOptionsBuilder() .WithTcpServer(server) .WithCredentials(username, apiKey) .WithClientId(clientId) //.WithTls() .Build(); mqttClient.ConnectAsync(mqttOptions).Wait(); mqttClient.UseConnectedHandler(e => { Console.WriteLine("Connected successfully with MQTT Brokers."); }); mqttClient.UseDisconnectedHandler(e => { new MqttClientDisconnectedHandlerDelegate(MqttClient_Disconnected); Console.WriteLine("Disconnected from MQTT Brokers.Client Was Connected " + e.ClientWasConnected); }); mqttClient.UseApplicationMessageReceivedHandler(e => { try { var topic = e.ApplicationMessage.Topic; if (!string.IsNullOrWhiteSpace(topic)) { var payload = HelperFunctions.GetPayload(e.ApplicationMessage.Payload); Console.WriteLine($"Topic: {topic}. Message Received: {JsonConvert.SerializeObject(payload, Formatting.Indented)}"); var platoonId = topic.Replace("platooning/" + clientId + "/", "").Split("/").Last(); if (payload.Maneuver == 2) { _ = SubscribeAsync("platooning/broadcast/" + platoonId + "/#"); Console.WriteLine("Client SubscribeAsync as " + "platooning/broadcast/" + platoonId + "/#"); } } } catch (Exception ex) { Console.WriteLine(ex.Message, ex); } }); do { while (!Console.KeyAvailable) { if (Console.ReadKey(true).Key == ConsoleKey.S) { _ = SubscribeAsync("platooning/" + clientId + "/#"); Console.WriteLine("Client SubscribeAsync as " + "platooning/" + clientId + "/#"); } else if (Console.ReadKey(true).Key == ConsoleKey.P) { var message = new BitArray(61); message.Set(0, false); message.Set(1, false); message.Set(2, true); //string message = HelperFunctions.RandomString(5,true); _ = PublishAsync("platooning/message/" + clientId, Encoding.ASCII.GetString(HelperFunctions.BitArrayToByteArray(message))); Console.WriteLine("Client Publish as " + "platooning/message/" + clientId + " payload => " + Encoding.ASCII.GetString(HelperFunctions.BitArrayToByteArray(message))); } } } while (Console.ReadKey(true).Key != ConsoleKey.Escape); }
static void Main(string[] args) { Console.WriteLine("Starting Publisher...."); try { // Create a new MQTT client. var factory = new MqttFactory(); _client = factory.CreateMqttClient(); //configure options _options = new MqttClientOptionsBuilder() .WithClientId("PublisherId") .WithTcpServer("127.0.0.1", 1884) .WithCredentials("sanjay", "%Welcome@123%") .WithCleanSession() .Build(); //handlers _client.UseConnectedHandler(e => { Console.WriteLine("Connected successfully with MQTT Brokers."); }); _client.UseDisconnectedHandler(e => { Console.WriteLine("Disconnected from MQTT Brokers."); }); _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); } }); //connect _client.ConnectAsync(_options).Wait(); Console.WriteLine("Press key to publish message."); Console.ReadLine(); //simulating publish SimulatePublish(); Console.WriteLine("Simulation ended! press any key to exit."); Console.ReadLine(); Task.Run(() => Thread.Sleep(Timeout.Infinite)).Wait(); _client.DisconnectAsync().Wait(); } catch (Exception e) { Console.WriteLine(e.Message); } }
static async Task Main(string[] args) { //Console.WriteLine("Hello World3!"); try { Console.WriteLine("Starting Subsriber...."); //create subscriber client var factory = new MqttFactory(); _client = factory.CreateMqttClient(); string sclientId = Guid.NewGuid().ToString(); //configure options _options = new MqttClientOptionsBuilder() .WithClientId(sclientId) .WithTcpServer("localhost", 1884) .WithCredentials("suhel", "%suhel@786%") .WithCleanSession() .Build(); //Handlers _client.UseConnectedHandler(async e => { Console.WriteLine("Connected successfully with MQTT Brokers."); //Subscribe to topic //_client.SubscribeAsync(new TopicFilterBuilder().WithTopic("test").Build()).Wait(); await _client.SubscribeAsync(new TopicFilterBuilder().WithTopic("test").Build()); }); _client.UseDisconnectedHandler(e => { Console.WriteLine("Disconnected from MQTT Brokers."); }); _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(); // Task.Run(() => _client.PublishAsync("hello/world")); }); //actually connect //_client.ConnectAsync(_options).Wait(); await _client.ConnectAsync(_options); Console.WriteLine("Press key to exit"); Console.ReadLine(); _client.DisconnectAsync().Wait(); } catch (Exception e) { Console.WriteLine(e); throw; } }
private const string _operating_state_code_for_alarming = "999"; // The operating state for alarming static async Task Main() { Console.WriteLine("Welcome to the alerting example (based on mqtt callbacks)!"); Console.WriteLine(""); TokenHandler tokenHandler = new TokenHandler(_user, _password, _urlForTokenGeneration); Token token = tokenHandler.GetAccessToken(); FORCEBridgeConnector connector = new FORCEBridgeConnector(_urlToBridgeAPI, token); Console.WriteLine("Connect to the Bridge API and get workplace ID of defined workplace " + _workplaceNumber); Console.WriteLine(""); string workplaceId = connector.GetWorkplaceByNumber(_workplaceNumber).Id; // Register Callback on Bridge API string MQTTTCPUrl = "mqtt://test.mosquitto.org"; //Define your MQTT-Broker and topic!!!! string PORT = "1883"; string MQTTTopicName = "external/statechange"; string EventType = "WORKPLACE_OPERATING_STATE_CHANGED"; Console.WriteLine("Register callback " + EventType + " of workplace " + workplaceId + " for MQTT-Broker " + MQTTTCPUrl + ", topic " + MQTTTopicName); Console.WriteLine(""); string callbackRegistrationJSON = BuildCallbackRegistrationJSON(MQTTTCPUrl + ":" + PORT + "/" + MQTTTopicName, workplaceId, EventType); connector.RegisterCallback(callbackRegistrationJSON); Console.WriteLine("Registration completed."); Console.WriteLine(""); // Inizialize a MQTT-Client and subscribe to the above defined topic Console.WriteLine("Initialize a MQTT Client and subscripe to the given topic " + MQTTTopicName + "..."); Console.WriteLine(""); var options = new MqttClientOptionsBuilder() .WithTcpServer(MQTTTCPUrl.Replace("mqtt://", String.Empty), 1883) .Build(); var factory = new MqttFactory(); var mqttClient = factory.CreateMqttClient(); await mqttClient.ConnectAsync(options, CancellationToken.None); // Subscribe to the defined topic await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(MQTTTopicName).Build()); Console.WriteLine("Wait for machine state changes ..."); Console.WriteLine(""); List <string> callbackIDs = new List <string>(); mqttClient.UseApplicationMessageReceivedHandler(e => { Console.WriteLine("---------------------------------------"); try { // WILL BE EXECUTED IF A MACHINE STATE OCCURES var payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); var callbackResponse = Newtonsoft.Json.JsonConvert.DeserializeObject <WorkplaceOperatingStateChangedCallbackResponse>(payload); if (!callbackIDs.Contains(callbackResponse.Properties.CallbackId)) { callbackIDs.Add(callbackResponse.Properties.CallbackId); } Console.WriteLine("--- RECEIVED " + EventType + " MESSAGE ---"); Console.WriteLine("---------------------------------------"); Console.WriteLine("Current operating state: " + callbackResponse.Properties.Data.CurrentOperatingState.Description + " (" + callbackResponse.Properties.Data.CurrentOperatingState.Code + ")"); Console.WriteLine("Previous operating state: " + callbackResponse.Properties.Data.PreviousOperatingState.Description + " (" + callbackResponse.Properties.Data.PreviousOperatingState.Code + ")"); if (callbackResponse.Properties.Data.CurrentOperatingState.Code == _operating_state_code_for_alarming) { Console.WriteLine("---------------------------------------"); Console.WriteLine(" !!! WARNING WARNING WARNING WARNING !!!"); Console.WriteLine(" --- MACHINE SWITCHED TO STATE CODE " + _operating_state_code_for_alarming + " ---"); } } catch (Exception ex) { Console.WriteLine(" !!! ERROR OCCURED !!! " + ex.ToString()); } Console.WriteLine("---------------------------------------"); Console.WriteLine(""); }); Console.ReadLine(); // DELETE THE CALLBACK Console.WriteLine("Delete the previous registered callback ..."); foreach (var id in callbackIDs) { Console.WriteLine("Delete the callback with id" + id); connector.DeleteCallback(id); } }
static void Main(string[] args) { MqttFactory factory = new MqttFactory(); mqttClient = factory.CreateMqttClient(); if ((args.Length != 5) && (args.Length != 6)) { Console.WriteLine("[MQTT Server] [UserName] [Password] [ClientID] [Channel]"); Console.WriteLine("[MQTT Server] [UserName] [Password] [ClientID] [ChannelData] [ChannelSubscribe]"); Console.WriteLine("Press <enter> to exit"); Console.ReadLine(); return; } server = args[0]; username = args[1]; password = args[2]; clientId = args[3]; channelData = args[4]; if (args.Length == 5) { Console.WriteLine($"MQTT Server:{server} Username:{username} ClientID:{clientId} ChannelData:{channelData}"); } if (args.Length == 6) { channelSubscribe = args[5]; Console.WriteLine($"MQTT Server:{server} Username:{username} ClientID:{clientId} ChannelData:{channelData} ChannelSubscribe:{channelSubscribe}"); } mqttOptions = new MqttClientOptionsBuilder() .WithTcpServer(server) .WithCredentials(username, password) .WithClientId(clientId) .WithTls() .Build(); mqttClient.ConnectAsync(mqttOptions).Wait(); if (args.Length == 6) { string topic = $"v1/{username}/things/{clientId}/cmd/{channelSubscribe}"; Console.WriteLine($"Subscribe Topic:{topic}"); mqttClient.SubscribeAsync(topic).Wait(); // mqttClient.SubscribeAsync(topic, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce).Wait(); // Thought this might help with subscription but it didn't, looks like ACK might be broken in MQTTnet mqttClient.UseApplicationMessageReceivedHandler(new MqttApplicationMessageReceivedHandlerDelegate(e => MqttClient_ApplicationMessageReceived(e))); } mqttClient.UseDisconnectedHandler(new MqttClientDisconnectedHandlerDelegate(e => MqttClient_Disconnected(e))); string topicTemperatureData = $"v1/{username}/things/{clientId}/data/{channelData}"; Console.WriteLine(); while (true) { string value = "22." + DateTime.UtcNow.Millisecond.ToString(); Console.WriteLine($"Publish Topic {topicTemperatureData} Value {value}"); var message = new MqttApplicationMessageBuilder() .WithTopic(topicTemperatureData) .WithPayload(value) .WithAtLeastOnceQoS() .WithRetainFlag() .Build(); Console.WriteLine("PublishAsync start"); mqttClient.PublishAsync(message).Wait(); Console.WriteLine("PublishAsync finish"); Console.WriteLine(); Thread.Sleep(30100); } }
private static IMqttClient CreateMqttClient() { var factory = new MqttFactory(); return(factory.CreateMqttClient()); }
/// <summary> /// 初始化各个参数 /// </summary> public static void Initial() { if (mqttClient != null) { return; } mqttClient = factory.CreateMqttClient(); //连接成功 mqttClient.UseConnectedHandler(e => { Log.Info(moudle, "已连接"); LuaEnv.LuaStates.Run("MQTT", "MQTT", new { t = "connected" }); }); //收到消息 mqttClient.UseApplicationMessageReceivedHandler(e => { Log.Debug(moudle, $"收到消息:{e.ApplicationMessage.Topic} {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}"); LuaEnv.LuaStates.Run("MQTT", "MQTT", new { t = "receive", topic = e.ApplicationMessage.Topic, payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload), qos = (int)e.ApplicationMessage.QualityOfServiceLevel }); }); //断线重连 mqttClient.UseDisconnectedHandler(async e => { Log.Warn(moudle, "MQTT连接已断开"); if (!Utils.Setting.MqttEnable) { return; } await Task.Delay(TimeSpan.FromSeconds(5)); Log.Warn(moudle, "MQTT尝试重连"); try { var op = new MqttClientOptionsBuilder() .WithClientId(Utils.Setting.ClientID) .WithTcpServer(Utils.Setting.MqttBroker, Utils.Setting.MqttPort) .WithCredentials(Utils.Setting.MqttUser, Utils.Setting.MqttPassword) .WithKeepAlivePeriod(new TimeSpan(0, 0, Utils.Setting.KeepAlive)); if (Utils.Setting.MqttTLS) { op.WithTls(); } var options = op.WithCleanSession().Build(); await mqttClient.ConnectAsync(options, CancellationToken.None); } catch (Exception ee) { Log.Warn(moudle, $"MQTT重连失败"); Log.Warn(moudle, $"原因: {ee.Message}"); } }); }
private async void Connect(object sender, RoutedEventArgs e) { var tlsOptions = new MqttClientTlsOptions { UseTls = UseTls.IsChecked == true, IgnoreCertificateChainErrors = true, IgnoreCertificateRevocationErrors = true, AllowUntrustedCertificates = true }; var options = new MqttClientOptions { ClientId = ClientId.Text, ProtocolVersion = MqttProtocolVersion.V500 }; if (UseTcp.IsChecked == true) { options.ChannelOptions = new MqttClientTcpOptions { Server = Server.Text, Port = int.Parse(Port.Text), TlsOptions = tlsOptions }; } if (UseWs.IsChecked == true) { options.ChannelOptions = new MqttClientWebSocketOptions { Uri = Server.Text, TlsOptions = tlsOptions }; } if (options.ChannelOptions == null) { throw new InvalidOperationException(); } if (!string.IsNullOrEmpty(User.Text)) { options.Credentials = new MqttClientCredentials { Username = User.Text, Password = Password.Text }; } options.CleanSession = CleanSession.IsChecked == true; options.KeepAlivePeriod = TimeSpan.FromSeconds(double.Parse(KeepAliveInterval.Text)); if (UseMqtt310.IsChecked == true) { options.ProtocolVersion = MqttProtocolVersion.V310; } else if (UseMqtt311.IsChecked == true) { options.ProtocolVersion = MqttProtocolVersion.V311; } else if (UseMqtt500.IsChecked == true) { options.ProtocolVersion = MqttProtocolVersion.V500; } try { if (_mqttClient != null) { await _mqttClient.DisconnectAsync(); _mqttClient.UseApplicationMessageReceivedHandler(HandleReceivedApplicationMessage); _mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(x => OnConnected(x)); _mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(x => OnDisconnected(x)); } var factory = new MqttFactory(); if (UseManagedClient.IsChecked == true) { _managedMqttClient = factory.CreateManagedMqttClient(); _managedMqttClient.UseApplicationMessageReceivedHandler(HandleReceivedApplicationMessage); _managedMqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(x => OnConnected(x)); _managedMqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(x => OnDisconnected(x)); await _managedMqttClient.StartAsync(new ManagedMqttClientOptions { ClientOptions = options }); } else { _mqttClient = factory.CreateMqttClient(); _mqttClient.UseApplicationMessageReceivedHandler(HandleReceivedApplicationMessage); _mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(x => OnConnected(x)); _mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(x => OnDisconnected(x)); await _mqttClient.ConnectAsync(options); } } catch (Exception exception) { Trace.Text += exception + Environment.NewLine; } }
//automatically passes the logger factory in to the constructor via dependency injection public MQTTService(ILoggerFactory loggerFactory) { fMeanCurrent = new float[4]; Factory = new MqttFactory(); MqttClnt = Factory.CreateMqttClient(); Logger = loggerFactory?.CreateLogger("MQTTSvc"); if (Logger == null) { throw new ArgumentNullException(nameof(loggerFactory)); } MqttNetGlobalLogger.LogMessagePublished += OnTraceMessagePublished; options = new MqttClientOptionsBuilder() .WithClientId(Guid.NewGuid().ToString()) .WithTcpServer("mqtt.symlink.se") .WithCredentials("fredrik:fredrik", "aivUGL6no") .WithCleanSession() .Build(); //var result = MqttClnt.ConnectAsync(options); MqttClnt.UseConnectedHandler(async e => { Console.WriteLine("### CONNECTED WITH SERVER ###"); // Subscribe to a topic await MqttClnt.SubscribeAsync(new TopicFilterBuilder().WithTopic("CurrentMeter/#").Build()); await MqttClnt.SubscribeAsync(new TopicFilterBuilder().WithTopic("EVCharger/#").Build()); Console.WriteLine("### SUBSCRIBED ###"); }); MqttClnt.UseDisconnectedHandler(async e => { Console.WriteLine("### DISCONNECTED FROM SERVER ###"); await Task.Delay(TimeSpan.FromSeconds(5)); if (fMeanCurrent[1] > 0) { try { await MqttClnt.ConnectAsync(options); } catch { Console.WriteLine("### RECONNECTING FAILED ###"); } } }); MqttClnt.UseApplicationMessageReceivedHandler(e => { //Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###"); string logstr = $"{DateTime.Now} {e.ApplicationMessage.Topic} \t {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}"; //Logger.LogInformation(logstr); Console.WriteLine(logstr); if (e.ApplicationMessage.Topic.Contains("current1d")) { //Save PNG to file Stream s = new FileStream("1d.png", FileMode.Create); var bw = new BinaryWriter(s); bw.Write(e.ApplicationMessage.Payload); //bw.Flush(); bw.Close(); } if (e.ApplicationMessage.Topic.Contains("current_l")) { float fCurrent = float.Parse(e.ApplicationMessage.Payload.ToString()); int iPhase = Int16.Parse(e.ApplicationMessage.Topic.Substring(e.ApplicationMessage.Topic.Length - 1)); fMeanCurrent[iPhase] = (4 * fMeanCurrent[iPhase] + fCurrent) / 5; Logger.LogInformation($"Phase: {iPhase}; Current: {fCurrent}; Mean Current: {fMeanCurrent[iPhase]}"); if (fMeanCurrent[iPhase] > fMaxCurrent) { float fNewChargeCurrent = fMeanCurrent[iPhase] - fMaxCurrent; string sNewChargeCurrent = fNewChargeCurrent.ToString(); Logger.LogInformation($"Holy Moses, too much power! Adjusting to {sNewChargeCurrent}"); MqttClnt.PublishAsync("TestCharger/set/current", sNewChargeCurrent, MqttQualityOfServiceLevel.AtLeastOnce, false); } } }); Logger.LogInformation("MQTTService created"); }