void ValidatePublishResult(MqttClientPublishResult publishResult) { if (publishResult.ReasonCode != MqttClientPublishReasonCode.Success) { throw new MqttException(isTemporary: IsTemporaryFailure(publishResult.ReasonCode), message: $"Publish failed: [code={publishResult.ReasonCode}, message={publishResult.ReasonString}]."); } }
public void SendMQTTMessageToMultipleInstances(string tenantId, List <string> toInstanceIds, MQTTMessage message) { Task task = Task.Factory.StartNew(async() => { MqttClientPublishResult res = null; var myMqttClient = _mqttClients.SingleOrDefault(c => (c.TenantId + "-" + c.TenantType).CompareTo(tenantId) == 0); message.ToInstancesIds = toInstanceIds; string jsonMessage = JsonConvert.SerializeObject(message); if (myMqttClient != null && myMqttClient.mqttClient.IsConnected) { res = await myMqttClient.mqttClient.PublishAsync(myMqttClient.mqttTopic, jsonMessage, MyMQTTClient.MQTTQualityOfService); InstanceHealthService.Health.MQTTMessagesSent += 1; } else { if (MQTTSendQueue.CheckIfMQTTIsConfigured()) { MQTTSendQueue.MessagesToSend.Add(new MQTTQueueMessage() { Topic = myMqttClient.mqttTopic, QueuedMessage = jsonMessage, QoS = MyMQTTClient.MQTTQualityOfService }); } } return(res); }); }
public override bool Send(string val, List <Variable> vars) { MqttApplicationMessage msg = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(val) .WithExactlyOnceQoS() .WithRetainFlag() .Build(); //"broker.hivemq.com", 1883) if (serverType == "tcp") { options = new MqttClientOptionsBuilder().WithTcpServer(mqttServer, mqttServerPort).Build(); } //"broker.hivemq.com:8000/mqtt" if (serverType == "ws") { options = new MqttClientOptionsBuilder().WithWebSocketServer(mqttServerURL).Build(); } if (!mqttClient.IsConnected) { mqttClient.ConnectAsync(options).Wait(); } MqttClientPublishResult result = mqttClient.PublishAsync(msg, CancellationToken.None).Result; if (result.ReasonCode != MqttClientPublishReasonCode.Success) { Console.WriteLine($"MQTT Send Failure {result.ReasonString}"); return(false); } return(true); }
private async void btTest_ClickAsync(object sender, EventArgs e) { btTest.Enabled = false; btnSave.Enabled = false; btnCancel.Enabled = false; try { AppSettings.Settings.mqtt_serverandport = tb_ServerPort.Text.Trim(); AppSettings.Settings.mqtt_password = tb_Password.Text.Trim(); AppSettings.Settings.mqtt_username = tb_Username.Text.Trim(); AppSettings.Settings.mqtt_UseTLS = cb_UseTLS.Checked; using (Global_GUI.CursorWait cw = new Global_GUI.CursorWait()) { Global.Log("------ TESTING MQTT --------"); string topic = AITOOL.ReplaceParams(this.cam, null, tb_Topic.Text.Trim()); string payload = AITOOL.ReplaceParams(this.cam, null, tb_Payload.Text.Trim()); List <string> topics = Global.Split(topic, ";|"); List <string> payloads = Global.Split(payload, ";|"); MQTTClient mq = new MQTTClient(); MqttClientPublishResult pr = null; for (int i = 0; i < topics.Count; i++) { pr = await mq.PublishAsync(topics[i], payloads[i], cam.Action_mqtt_retain_message); } Global.Log("------ DONE TESTING MQTT --------"); if (pr != null && (pr.ReasonCode == MqttClientPublishReasonCode.Success)) { MessageBox.Show("Success! See Log for details."); } else if (pr != null) { MessageBox.Show($"Failed. See log for details. Reason={pr.ReasonCode}", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show($"Failed. See log for details.", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } catch { } finally { btTest.Enabled = true; btnSave.Enabled = true; btnCancel.Enabled = true; } }
private static void EnsureResultSuccessful(MqttClientPublishResult result) { if (result.ReasonCode != MqttClientPublishReasonCode.Success) { throw new IOException("Failed to publish message!") { Data = { { "Result", result } } }; } }
/// <summary> /// Publishes the device slice. /// </summary> private bool PublishDeviceSlice(DeviceSlice deviceSlice) { try { if (topicByDevice.TryGetValue(deviceSlice.DeviceNum, out DeviceTopics deviceTopics)) { int dataIndex = 0; foreach (DeviceTag deviceTag in deviceSlice.DeviceTags) { if (!string.IsNullOrEmpty(deviceTag.Code) && deviceTopics.TryGetValue(deviceTag.Code, out string topic)) { string payloadStr = BuildPayload(deviceTag, deviceSlice.CnlData, dataIndex); MqttApplicationMessage message = new() { Topic = topic, Payload = Encoding.UTF8.GetBytes(payloadStr), QualityOfServiceLevel = (MqttQualityOfServiceLevel)dsOptions.PublishOptions.QosLevel, Retain = dsOptions.PublishOptions.Retain }; if (dsOptions.PublishOptions.DetailedLog) { dsLog.WriteAction("{0} {1} = {2}", CommPhrases.SendNotation, topic, payloadStr); } MqttClientPublishResult result = mqttClientHelper.Publish(message); if (result.ReasonCode != MqttClientPublishReasonCode.Success) { dsLog.WriteError(CommPhrases.ErrorPrefix + result.ReasonCode); return(false); } } dataIndex += deviceTag.DataLength; } } return(true); } catch (Exception ex) { dsLog.WriteError(ex, Locale.IsRussian ? "Ошибка при публикации данных" : "Error publishing data"); return(false); } }
public void SetResponseCode(MqttClientPublishReasonCode code) { var publishResult = new MqttClientPublishResult() { ReasonCode = code }; // Ensure that when the MQTT Client is called, it's published message is saved and that it returns // the specified response code MqttClient.Setup(m => m.PublishAsync(It.IsAny <MqttApplicationMessage>(), It.IsAny <CancellationToken>())) .Callback <MqttApplicationMessage, CancellationToken>((message, token) => { LastPublishedMessage = message; }) .ReturnsAsync(publishResult); }
private async Task <MQTTnet.Client.Publishing.MqttClientPublishResult> PublishAsync(string topic, string message) { if (_client != null && _client.IsConnected) { var mqttmsg = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(message) .Build(); MqttClientPublishResult result = await _client.PublishAsync(mqttmsg); return(result); } else { return(null); } }
public override async Task <ExchangeMessage> SendToOutputAsync(ExchangeMessage message) { // Create a new MQTT client. var msg = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(message.payload) .WithExactlyOnceQoS() .WithRetainFlag() .Build(); //"broker.hivemq.com", 1883) if (serverType == "tcp") { options = new MqttClientOptionsBuilder().WithTcpServer(mqttServer, mqttServerPort).Build(); } //"broker.hivemq.com:8000/mqtt" if (serverType == "ws") { options = new MqttClientOptionsBuilder().WithWebSocketServer(mqttServerURL).Build(); } if (!mqttClient.IsConnected) { mqttClient.ConnectAsync(options).Wait(); } MqttClientPublishResult result = await mqttClient.PublishAsync(msg, CancellationToken.None); if (result.ReasonCode == MqttClientPublishReasonCode.Success) { message.sent = true; message.status = $"Sent to MQTT topic {queueName}"; return(message); } else { message.sent = true; message.status = $"MQTT Send Failure {result.ReasonString}"; logger.Error($"MQTT Send Failure {result.ReasonString}"); return(message); } }
public MqttClientPublishResult CreatePublishResult(MqttPubAckPacket pubAckPacket) { var result = new MqttClientPublishResult { ReasonCode = MqttClientPublishReasonCode.Success, ReasonString = pubAckPacket?.Properties?.ReasonString, UserProperties = pubAckPacket?.Properties?.UserProperties }; if (pubAckPacket != null) { // QoS 0 has no response. So we treat it as a success always. // Both enums have the same values. So it can be easily converted. result.ReasonCode = (MqttClientPublishReasonCode)pubAckPacket.ReasonCode; result.PacketIdentifier = pubAckPacket.PacketIdentifier; } return(result); }
public MqttClientPublishResult CreatePublishResult(MqttPubRecPacket pubRecPacket, MqttPubCompPacket pubCompPacket) { if (pubRecPacket == null || pubCompPacket == null) { return(new MqttClientPublishResult { ReasonCode = MqttClientPublishReasonCode.UnspecifiedError }); } // The PUBCOMP is the last packet in QoS 2. So we use the results from that instead of PUBREC. if (pubCompPacket.ReasonCode == MqttPubCompReasonCode.PacketIdentifierNotFound) { return(new MqttClientPublishResult { PacketIdentifier = pubCompPacket.PacketIdentifier, ReasonCode = MqttClientPublishReasonCode.UnspecifiedError, ReasonString = pubCompPacket.Properties?.ReasonString, UserProperties = pubCompPacket.Properties?.UserProperties }); } var result = new MqttClientPublishResult { PacketIdentifier = pubCompPacket.PacketIdentifier, ReasonCode = MqttClientPublishReasonCode.Success, ReasonString = pubCompPacket.Properties?.ReasonString, UserProperties = pubCompPacket.Properties?.UserProperties }; if (pubRecPacket.ReasonCode.HasValue) { // Both enums share the same values. result.ReasonCode = (MqttClientPublishReasonCode)pubRecPacket.ReasonCode.Value; } return(result); }
private async void btTest_ClickAsync(object sender, EventArgs e) { AppSettings.Settings.mqtt_serverandport = tb_ServerPort.Text.Trim(); AppSettings.Settings.mqtt_password = tb_Password.Text.Trim(); AppSettings.Settings.mqtt_username = tb_Username.Text.Trim(); AppSettings.Settings.mqtt_UseTLS = cb_UseTLS.Checked; MQTTClient mq = new MQTTClient(); MqttClientPublishResult pr = await mq.PublishAsync(tb_Topic.Text.Trim(), tb_Payload.Text.Trim()); if (pr != null && (pr.ReasonCode == MqttClientPublishReasonCode.Success)) { MessageBox.Show("Success."); } else if (pr != null) { MessageBox.Show($"Failed. See log. Reason={pr.ReasonCode}", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show($"Failed. See log.", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public EventPublishedResult(EventType publishedEvent, MqttClientPublishResult publishResult) { PublishedEvent = publishedEvent; PublishResult = publishResult; }
/// <summary> /// Initializes a new instance of the <see cref="MqttProduceException" /> class with the /// specified message. /// </summary> /// <param name="message"> /// The exception message. /// </param> /// <param name="result"> /// The <see cref="MqttClientPublishResult" />. /// </param> public MqttProduceException(string message, MqttClientPublishResult result) : base(message) { Result = result; }
public async Task <MqttClientPublishResult> PublishAsync(string topic, string payload, bool retain, ClsImageQueueItem CurImg) { using var Trace = new Trace(); //This c# 8.0 using feature will auto dispose when the function is done. MqttClientPublishResult res = null; Stopwatch sw = Stopwatch.StartNew(); await Task.Run(async() => { MqttFactory factory = new MqttFactory(); IMqttClient mqttClient = null; bool subscribed = false; bool IsConnected = false; using (mqttClient = factory.CreateMqttClient()) { try { string server = Global.GetWordBetween(AppSettings.Settings.mqtt_serverandport, "", ":"); string port = Global.GetWordBetween(AppSettings.Settings.mqtt_serverandport, ":", "/"); int portint = 0; if (!string.IsNullOrEmpty(port)) { portint = Convert.ToInt32(port); } if (portint == 0 && AppSettings.Settings.mqtt_UseTLS) { portint = 8883; } else if (portint == 0) { 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.ToLower().Contains("wss://")); bool UseCreds = (!string.IsNullOrWhiteSpace(AppSettings.Settings.mqtt_username)); IMqttClientOptions options; //===================================================================== //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. //===================================================================== if (UseTLS) { if (UseCreds) { 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() .WithCleanSession() .Build(); } else { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithTcpServer(server, portint) .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password) .WithTls() .WithCleanSession() .Build(); } } else { if (IsWebSocket) { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithWebSocketServer(AppSettings.Settings.mqtt_serverandport) .WithTls() .WithCleanSession() .Build(); } else { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithTcpServer(server, portint) .WithTls() .WithCleanSession() .Build(); } } } else { if (UseCreds) { if (IsWebSocket) { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithWebSocketServer(AppSettings.Settings.mqtt_serverandport) .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password) .WithCleanSession() .Build(); } else { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithTcpServer(server, portint) .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password) .WithCleanSession() .Build(); } } else { if (IsWebSocket) { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithTcpServer(server, portint) .WithCleanSession() .Build(); } else { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithWebSocketServer(AppSettings.Settings.mqtt_serverandport) .WithCleanSession() .Build(); } } } if (string.IsNullOrWhiteSpace(topic)) { topic = Guid.NewGuid().ToString(); } mqttClient.UseDisconnectedHandler(async e => { IsConnected = false; string excp = ""; if (e.Exception != null) { excp = e.Exception.Message; } Log($"Debug: MQTT: ### DISCONNECTED FROM SERVER ### - Reason: {e.ReasonCode}, 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}"); if (e.ApplicationMessage.Payload.Length < 64) { Log($"Debug: MQTT: + Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}"); } 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.AuthenticateResult.ResultCode}, '{e.AuthenticateResult.ReasonString}'"); // Subscribe to the topic await mqttClient.SubscribeAsync(topic, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce); subscribed = true; Log($"Debug: MQTT: ### SUBSCRIBED to topic '{topic}'"); }); Log($"Debug: MQTT: Sending topic '{topic}' with payload '{payload}' to server '{server}:{portint}'..."); MqttClientAuthenticateResult cres = await mqttClient.ConnectAsync(options, CancellationToken.None); if (cres != null && mqttClient.IsConnected && cres.ResultCode == MqttClientConnectResultCode.Success) { IsConnected = true; MqttApplicationMessage ma; if (CurImg != null) { using FileStream image_data = System.IO.File.OpenRead(CurImg.image_path); ma = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(image_data) .WithAtLeastOnceQoS() .WithRetainFlag(retain) .Build(); res = await mqttClient.PublishAsync(ma, CancellationToken.None); if (res.ReasonCode == MqttClientPublishReasonCode.Success) { Log($"Debug: MQTT: ...Sent image in {sw.ElapsedMilliseconds}ms, Reason: '{res.ReasonCode}' ({Convert.ToInt32(res.ReasonCode)} - '{res.ReasonString}')"); } else { Log($"Error: MQTT: sending image: ({sw.ElapsedMilliseconds}ms) Reason: '{res.ReasonCode}' ({Convert.ToInt32(res.ReasonCode)} - '{res.ReasonString}')"); } } else { ma = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(payload) .WithAtLeastOnceQoS() .WithRetainFlag(retain) .Build(); res = await mqttClient.PublishAsync(ma, CancellationToken.None); //Success = 0, // NoMatchingSubscribers = 0x10, // UnspecifiedError = 0x80, // ImplementationSpecificError = 0x83, // NotAuthorized = 0x87, // TopicNameInvalid = 0x90, // PacketIdentifierInUse = 0x91, // QuotaExceeded = 0x97, // PayloadFormatInvalid = 0x99 if (res.ReasonCode == MqttClientPublishReasonCode.Success) { Log($"Debug: MQTT: ...Sent in {sw.ElapsedMilliseconds}ms, Reason: '{res.ReasonCode}' ({Convert.ToInt32(res.ReasonCode)} - '{res.ReasonString}')"); } else { Log($"Error: MQTT: sending: ({sw.ElapsedMilliseconds}ms) Reason: '{res.ReasonCode}' ({Convert.ToInt32(res.ReasonCode)} - '{res.ReasonString}')"); } } } else if (cres != null) { IsConnected = false; Log($"Error: MQTT: connecting: ({sw.ElapsedMilliseconds}ms) Result: '{cres.ResultCode}' - '{cres.ReasonString}'"); } else { IsConnected = false; Log($"Error: MQTT: Error connecting: ({sw.ElapsedMilliseconds}ms) cres=null"); } if (mqttClient != null && mqttClient.IsConnected && IsConnected) { if (subscribed) { Log($"Debug: MQTT: Unsubscribing from topic '{topic}'"); await mqttClient.UnsubscribeAsync(topic); } if (mqttClient.IsConnected && IsConnected) { Log($"Debug: MQTT: Disconnecting from server."); try { await mqttClient.DisconnectAsync(); } catch (Exception ex) { //dont throw ERROR in the log if fail to disconnect Log($"Debug: MQTT: Could not disconnect from server, got: {Global.ExMsg(ex)}"); } } else { Log($"Debug: MQTT: Already disconnected from server, no need to disconnect."); } IsConnected = false; } } catch (Exception ex) { Log($"Error: MQTT: Unexpected Problem: Topic '{topic}' Payload '{payload}': " + Global.ExMsg(ex)); } finally { if (mqttClient != null && mqttClient.IsConnected) { if (subscribed) { Log($"Debug: MQTT: Un-Subscribing from topic '{topic}'"); await mqttClient.UnsubscribeAsync(topic); } Log($"Debug: MQTT: Disconnecting from server."); await mqttClient.DisconnectAsync(); mqttClient.Dispose(); //using should dispose anyway } } } }); return(res); }
private async void btTest_ClickAsync(object sender, EventArgs e) { this.btTest.Enabled = false; this.btnSave.Enabled = false; this.btnCancel.Enabled = false; try { AppSettings.Settings.mqtt_serverandport = this.tb_ServerPort.Text.Trim(); AppSettings.Settings.mqtt_password = this.tb_Password.Text.Trim(); AppSettings.Settings.mqtt_username = this.tb_Username.Text.Trim(); AppSettings.Settings.mqtt_UseTLS = this.cb_UseTLS.Checked; using (Global_GUI.CursorWait cw = new Global_GUI.CursorWait()) { Log("------ TESTING MQTT --------"); string topic = AITOOL.ReplaceParams(this.cam, null, null, this.tb_Topic.Text.Trim()); string payload = AITOOL.ReplaceParams(this.cam, null, null, this.tb_Payload.Text.Trim()); List <string> topics = Global.Split(topic, ";|"); List <string> payloads = Global.Split(payload, ";|"); MQTTClient mq = new MQTTClient(); MqttClientPublishResult pr = null; ClsImageQueueItem CurImg = null; for (int i = 0; i < topics.Count; i++) { if (this.cam.Action_mqtt_send_image) { if (topics[i].IndexOf("/image", StringComparison.OrdinalIgnoreCase) >= 0) { if (!string.IsNullOrEmpty(this.cam.last_image_file_with_detections) && File.Exists(this.cam.last_image_file_with_detections)) { CurImg = new ClsImageQueueItem(this.cam.last_image_file_with_detections, 0); } else if (!string.IsNullOrEmpty(this.cam.last_image_file) && File.Exists(this.cam.last_image_file)) { CurImg = new ClsImageQueueItem(this.cam.last_image_file, 0); } else { CurImg = null; } } else { CurImg = null; } } pr = await mq.PublishAsync(topics[i], payloads[i], this.cam.Action_mqtt_retain_message, CurImg); } Log("------ DONE TESTING MQTT --------"); if (pr != null && (pr.ReasonCode == MqttClientPublishReasonCode.Success)) { MessageBox.Show("Success! See Log for details."); } else if (pr != null) { MessageBox.Show($"Failed. See log for details. Reason={pr.ReasonCode}", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show($"Failed. See log for details.", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } catch { } finally { this.btTest.Enabled = true; this.btnSave.Enabled = true; this.btnCancel.Enabled = true; } }
public async Task <MqttClientPublishResult> PublishAsync(string topic, string payload) { MqttClientPublishResult res = null; Stopwatch sw = Stopwatch.StartNew(); await Task.Run(async() => { MqttFactory factory = new MqttFactory(); IMqttClient mqttClient = null; bool subscribed = false; using (mqttClient = factory.CreateMqttClient()) { try { string server = Global.GetWordBetween(AppSettings.Settings.mqtt_serverandport, "", ":"); string port = Global.GetWordBetween(AppSettings.Settings.mqtt_serverandport, ":", "/"); int portint = 0; if (!string.IsNullOrEmpty(port)) { portint = Convert.ToInt32(port); } if (portint == 0 && AppSettings.Settings.mqtt_UseTLS) { portint = 8883; } else if (portint == 0) { portint = 1883; } bool IsWebSocket = (AppSettings.Settings.mqtt_serverandport.ToLower().Contains("ws://") || AppSettings.Settings.mqtt_serverandport.ToLower().Contains("/mqtt") || AppSettings.Settings.mqtt_serverandport.ToLower().Contains("wss://")); bool UseTLS = (AppSettings.Settings.mqtt_UseTLS || portint == 8883 || AppSettings.Settings.mqtt_serverandport.ToLower().Contains("wss://")); bool UseCreds = (!string.IsNullOrWhiteSpace(AppSettings.Settings.mqtt_username)); IMqttClientOptions options; //===================================================================== //Seems like there should be a better way here with this Options builder... //===================================================================== if (UseTLS) { if (UseCreds) { 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() .WithCleanSession() .Build(); } else { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithTcpServer(server, portint) .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password) .WithTls() .WithCleanSession() .Build(); } } else { if (IsWebSocket) { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithWebSocketServer(AppSettings.Settings.mqtt_serverandport) .WithTls() .WithCleanSession() .Build(); } else { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithTcpServer(server, portint) .WithTls() .WithCleanSession() .Build(); } } } else { if (UseCreds) { if (IsWebSocket) { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithWebSocketServer(AppSettings.Settings.mqtt_serverandport) .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password) .WithCleanSession() .Build(); } else { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithTcpServer(server, portint) .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password) .WithCleanSession() .Build(); } } else { if (IsWebSocket) { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithTcpServer(server, portint) .WithCleanSession() .Build(); } else { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithWebSocketServer(AppSettings.Settings.mqtt_serverandport) .WithCleanSession() .Build(); } } } if (string.IsNullOrWhiteSpace(topic)) { topic = Guid.NewGuid().ToString(); } mqttClient.UseDisconnectedHandler(async e => { string excp = ""; if (e.Exception != null) { excp = e.Exception.Message; } Global.Log($"MQTT: ### DISCONNECTED FROM SERVER ### - Reason: {e.ReasonCode}, ClientWasDisconnected: {e.ClientWasConnected}, {excp}"); //reconnect here if needed? }); mqttClient.UseApplicationMessageReceivedHandler(async e => { Global.Log($"MQTT: ### RECEIVED APPLICATION MESSAGE ###"); Global.Log($"MQTT: + Topic = {e.ApplicationMessage.Topic}"); Global.Log($"MQTT: + Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}"); Global.Log($"MQTT: + QoS = {e.ApplicationMessage.QualityOfServiceLevel}"); Global.Log($"MQTT: + Retain = {e.ApplicationMessage.Retain}"); Global.Log(""); }); mqttClient.UseConnectedHandler(async e => { Global.Log($"MQTT: ### CONNECTED WITH SERVER '{AppSettings.Settings.mqtt_serverandport}' ### - Result: {e.AuthenticateResult.ResultCode}, '{e.AuthenticateResult.ReasonString}'"); // Subscribe to the topic await mqttClient.SubscribeAsync(topic, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce); subscribed = true; Global.Log($"MQTT: ### SUBSCRIBED to topic '{topic}'"); }); Global.Log($"MQTT: Sending topic '{topic}' with payload '{payload}' to server '{server}:{portint}'..."); MqttClientAuthenticateResult cres = await mqttClient.ConnectAsync(options, CancellationToken.None); if (cres != null && cres.ResultCode == MqttClientConnectResultCode.Success) { MqttApplicationMessage ma = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(payload) .WithAtLeastOnceQoS() .Build(); res = await mqttClient.PublishAsync(ma, CancellationToken.None); //Success = 0, // NoMatchingSubscribers = 0x10, // UnspecifiedError = 0x80, // ImplementationSpecificError = 0x83, // NotAuthorized = 0x87, // TopicNameInvalid = 0x90, // PacketIdentifierInUse = 0x91, // QuotaExceeded = 0x97, // PayloadFormatInvalid = 0x99 if (res.ReasonCode == MqttClientPublishReasonCode.Success) { Global.Log($"MQTT: ...Sent in {sw.ElapsedMilliseconds}ms, Reason: '{res.ReasonCode}' ({Convert.ToInt32(res.ReasonCode)} - '{res.ReasonString}')"); } else { Global.Log($"MQTT: Error sending: ({sw.ElapsedMilliseconds}ms) Reason: '{res.ReasonCode}' ({Convert.ToInt32(res.ReasonCode)} - '{res.ReasonString}')"); } } else if (cres != null) { Global.Log($"MQTT: Error connecting: ({sw.ElapsedMilliseconds}ms) Result: '{cres.ResultCode}' - '{cres.ReasonString}'"); } else { Global.Log($"MQTT: Error connecting: ({sw.ElapsedMilliseconds}ms) cres=null"); } if (mqttClient != null && mqttClient.IsConnected) { if (subscribed) { Global.Log($"MQTT: Unsubscribing from topic '{topic}'"); await mqttClient.UnsubscribeAsync(topic); } Global.Log($"MQTT: Disconnecting from server."); await mqttClient.DisconnectAsync(); } } catch (Exception ex) { Global.Log($"MQTT: Unexpected Error: Topic '{topic}' Payload '{payload}': " + Global.ExMsg(ex)); } finally { if (mqttClient != null && mqttClient.IsConnected) { if (subscribed) { Global.Log($"MQTT: Unsubscribing from topic '{topic}'"); await mqttClient.UnsubscribeAsync(topic); } Global.Log($"MQTT: Disconnecting from server."); await mqttClient.DisconnectAsync(); mqttClient.Dispose(); //using should dispose anyway } } } }); return(res); }
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 { 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.AuthenticateResult.ResultCode}, '{e.AuthenticateResult.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 async Task <MqttClientPublishResult> PublishAsync(string topic, string payload, bool retain, ClsImageQueueItem CurImg) { using var Trace = new Trace(); //This c# 8.0 using feature will auto dispose when the function is done. MqttClientPublishResult res = null; Stopwatch sw = Stopwatch.StartNew(); this.LastRetain = retain; this.LastPayload = payload; this.LastTopic = topic; if (string.IsNullOrWhiteSpace(topic)) { this.LastTopic = Guid.NewGuid().ToString(); } if (!this.IsConnected) { await this.Connect(); } if (!this.IsConnected) { return(res); } await Task.Run(async() => { try { Log($"Debug: MQTT: Sending topic '{this.LastTopic}' with payload '{this.LastPayload}' to server '{this.server}:{this.portint}'..."); if (cres != null && mqttClient.IsConnected && cres.ResultCode == MqttClientConnectResultCode.Success) { IsConnected = true; MqttApplicationMessage ma; if (CurImg != null) { //using FileStream image_data = System.IO.File.OpenRead(CurImg.image_path); ma = new MqttApplicationMessageBuilder() .WithTopic(this.LastTopic) .WithPayload(CurImg.ToStream()) .WithAtLeastOnceQoS() .WithRetainFlag(this.LastRetain) .Build(); res = await mqttClient.PublishAsync(ma, CancellationToken.None); if (res.ReasonCode == MqttClientPublishReasonCode.Success) { Log($"Debug: MQTT: ...Sent image in {sw.ElapsedMilliseconds}ms, Reason: '{res.ReasonCode}' ({Convert.ToInt32(res.ReasonCode)} - '{res.ReasonString}')"); } else { Log($"Error: MQTT: sending image: ({sw.ElapsedMilliseconds}ms) Reason: '{res.ReasonCode}' ({Convert.ToInt32(res.ReasonCode)} - '{res.ReasonString}')"); } } else { ma = new MqttApplicationMessageBuilder() .WithTopic(this.LastTopic) .WithPayload(this.LastPayload) .WithAtLeastOnceQoS() .WithRetainFlag(this.LastRetain) .Build(); res = await mqttClient.PublishAsync(ma, CancellationToken.None); //Success = 0, // NoMatchingSubscribers = 0x10, // UnspecifiedError = 0x80, // ImplementationSpecificError = 0x83, // NotAuthorized = 0x87, // TopicNameInvalid = 0x90, // PacketIdentifierInUse = 0x91, // QuotaExceeded = 0x97, // PayloadFormatInvalid = 0x99 if (res.ReasonCode == MqttClientPublishReasonCode.Success) { Log($"Debug: MQTT: ...Sent in {sw.ElapsedMilliseconds}ms, Reason: '{res.ReasonCode}' ({Convert.ToInt32(res.ReasonCode)} - '{res.ReasonString}')"); } else { Log($"Error: MQTT: sending: ({sw.ElapsedMilliseconds}ms) Reason: '{res.ReasonCode}' ({Convert.ToInt32(res.ReasonCode)} - '{res.ReasonString}')"); } } } else if (cres != null) { IsConnected = false; Log($"Error: MQTT: connecting: ({sw.ElapsedMilliseconds}ms) Result: '{cres.ResultCode}' - '{cres.ReasonString}'"); } else { IsConnected = false; Log($"Error: MQTT: Error connecting: ({sw.ElapsedMilliseconds}ms) cres=null"); } } catch (Exception ex) { Log($"Error: MQTT: Unexpected Problem: Topic '{this.LastTopic}' Payload '{this.LastPayload}': " + ex.Msg()); } finally { } }); return(res); }