public MqttClientDisconnectedEventArgs(bool clientWasConnected, Exception exception, MqttClientConnectResult connectResult, MqttClientDisconnectReason reason) { ClientWasConnected = clientWasConnected; Exception = exception; ConnectResult = connectResult; Reason = reason; ReasonCode = reason; }
private static async void ConnectWs(string presignedurl) { var client = new MqttFactory().CreateMqttClient(logger); var options = new MqttClientOptionsBuilder() .WithWebSocketServer(presignedurl) .WithProtocolVersion(MqttProtocolVersion.V311) .Build(); (options.ChannelOptions as MqttClientWebSocketOptions).SubProtocols = new List <string>(); (options.ChannelOptions as MqttClientWebSocketOptions).SubProtocols.Add("mqtt"); MqttClientConnectResult res = await client.ConnectAsync(options); }
public static async Task RunClientTaskAsync() { MyTrueWriteLine("Creating a new client....."); var mqttclient = new MqttFactory().CreateMqttClient(); MqttClientTcpOptions mqttClientTcpOptions = new MqttClientTcpOptions() { Server = "127.0.0.1", Port = 1883, }; var optionbuilder = new MqttClientOptionsBuilder() .WithWillMessage(BuildMessage()) .WithTcpServer("127.0.0.1", 1883) .WithClientId("Test1") .WithCredentials("user", "password") .WithTls() .WithCommunicationTimeout(new TimeSpan(0, 0, 20)) .WithKeepAlivePeriod(new TimeSpan(0, 0, 20)) .WithCleanSession(true); var options = optionbuilder.Build(); MyTrueWriteLine("Client starting to connect the server......"); try { MqttClientConnectResult clientConnectResult = await mqttclient.ConnectAsync(options); MyTrueWriteLine("The result of action:" + clientConnectResult.ToString()); } catch (Exception e) { MyTrueWriteLine("Failed:" + Environment.NewLine + e); } mqttclient.Connected += (s, e) => { MyTrueWriteLine("Client has connected to server successfully!"); MyTrueWriteLine($"Detail:{e.ConnectResult.ToString()}"); }; mqttclient.Disconnected += (s, e) => { MyTrueWriteLine("Client has disconnected from the server"); }; }
public async Task <bool> Connect() { using var Trace = new Trace(); //This c# 8.0 using feature will auto dispose when the function is done. bool ret = false; try { if (this.mqttClient.IsConnected) { await this.mqttClient.DisconnectAsync(); } this.server = AppSettings.Settings.mqtt_serverandport.GetWord("", ":"); this.port = AppSettings.Settings.mqtt_serverandport.GetWord(":", "/"); this.portint = 0; if (!string.IsNullOrEmpty(this.port)) { this.portint = Convert.ToInt32(this.port); } if (this.portint == 0 && AppSettings.Settings.mqtt_UseTLS) { this.portint = 8883; } else if (this.portint == 0) { this.portint = 1883; } bool IsWebSocket = (AppSettings.Settings.mqtt_serverandport.IndexOf("ws://", StringComparison.OrdinalIgnoreCase) >= 0 || AppSettings.Settings.mqtt_serverandport.IndexOf("/mqtt", StringComparison.OrdinalIgnoreCase) >= 0 || AppSettings.Settings.mqtt_serverandport.IndexOf("wss://", StringComparison.OrdinalIgnoreCase) >= 0); bool UseTLS = (AppSettings.Settings.mqtt_UseTLS || portint == 8883 || AppSettings.Settings.mqtt_serverandport.IndexOf("wss://", StringComparison.OrdinalIgnoreCase) >= 0); //bool UseCreds = (!string.IsNullOrWhiteSpace(AppSettings.Settings.mqtt_username)); //===================================================================== //Seems like there should be a better way here with this Options builder... //I dont see an obvious way to directly modify options without the builder //and I cant seem to put IF statements around each part of the option builder //parameters. //===================================================================== var lw = new MqttApplicationMessage() { Topic = AppSettings.Settings.mqtt_LastWillTopic, Payload = Encoding.UTF8.GetBytes(AppSettings.Settings.mqtt_LastWillPayload), QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce, Retain = true }; if (UseTLS) { if (IsWebSocket) { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithWebSocketServer(AppSettings.Settings.mqtt_serverandport) .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password) .WithTls() .WithWillMessage(lw) .WithCleanSession() .Build(); } else { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithTcpServer(server, portint) .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password) .WithTls() .WithWillMessage(lw) .WithCleanSession() .Build(); } } else { if (IsWebSocket) { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithWebSocketServer(AppSettings.Settings.mqtt_serverandport) .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password) .WithWillMessage(lw) .WithCleanSession() .Build(); } else { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithTcpServer(server, portint) .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password) .WithWillMessage(lw) .WithCleanSession() .Build(); } } mqttClient.UseDisconnectedHandler(async e => { IsConnected = false; string excp = ""; if (e.Exception != null) { excp = e.Exception.Message; } Log($"Debug: MQTT: ### DISCONNECTED FROM SERVER ### - Reason: {e.Reason}, ClientWasDisconnected: {e.ClientWasConnected}, {excp}"); //reconnect here if needed? }); mqttClient.UseApplicationMessageReceivedHandler(async e => { Log($"Debug: MQTT: ### RECEIVED APPLICATION MESSAGE ###"); Log($"Debug: MQTT: + Topic = {e.ApplicationMessage.Topic}"); Log($"Debug: MQTT: + Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload).Truncate(128, true)}"); Log($"Debug: MQTT: + QoS = {e.ApplicationMessage.QualityOfServiceLevel}"); Log($"Debug: MQTT: + Retain = {e.ApplicationMessage.Retain}"); Log(""); }); mqttClient.UseConnectedHandler(async e => { IsConnected = true; Log($"Debug: MQTT: ### CONNECTED WITH SERVER '{AppSettings.Settings.mqtt_serverandport}' ### - Result: {e.ConnectResult.ResultCode}, '{e.ConnectResult.ReasonString}'"); MqttApplicationMessage ma = new MqttApplicationMessageBuilder() .WithTopic(AppSettings.Settings.mqtt_LastWillTopic) .WithPayload(AppSettings.Settings.mqtt_OnlinePayload) .WithAtLeastOnceQoS() .WithRetainFlag(true) .Build(); Log($"Debug: MQTT: Sending '{AppSettings.Settings.mqtt_OnlinePayload}' message..."); MqttClientPublishResult res = await mqttClient.PublishAsync(ma, CancellationToken.None); //if (!string.IsNullOrWhiteSpace(this.LastTopic)) //{ // // Subscribe to the topic // MqttClientSubscribeResult res = await mqttClient.SubscribeAsync(this.LastTopic, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce); // IsSubscribed = true; // Log($"Debug: MQTT: ### SUBSCRIBED to topic '{this.LastTopic}'"); //} }); Log($"Debug: MQTT: Connecting to server '{this.server}:{this.portint}' with ClientID '{AppSettings.Settings.mqtt_clientid}', Username '{AppSettings.Settings.mqtt_username}', Password '{AppSettings.Settings.mqtt_username.ReplaceChars('*')}'..."); cres = await mqttClient.ConnectAsync(options, CancellationToken.None); } catch (Exception ex) { Log($"Error: {ex.Msg()}"); } return(ret); }
public ConnectingFailedEventArgs(MqttClientConnectResult connectResult, Exception exception) { ConnectResult = connectResult; Exception = exception; }
public MqttConnectingFailedException(string message, Exception innerException, MqttClientConnectResult connectResult) : base(message, innerException) { Result = connectResult; }