/// <summary> /// 发布消息 /// </summary> /// <param name="topic">通道</param> /// <param name="message">消息</param> /// <param name="qosLevel">0:最多一次,1:至少一次,2:有且仅有一次</param> /// <param name="retain"></param> /// <returns></returns> public bool Publish(string topic, byte[] message, byte qosLevel = 0, bool retain = false) { try { if (!Connect()) { return(false); } var mamb = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(message).WithRetainFlag(retain); if (qosLevel == 0) { mamb = mamb.WithAtMostOnceQoS(); } else if (qosLevel == 1) { mamb = mamb.WithAtLeastOnceQoS(); } else if (qosLevel == 2) { mamb = mamb.WithExactlyOnceQoS(); } var result = mqttClient.PublishAsync(mamb.Build()).Result; return(result.ReasonCode == MqttClientPublishReasonCode.Success); } catch (Exception ex) { OnException?.Invoke(ex); return(false); } }
private void onSend(object state) { var topic = ServiceOptions.MqttClientSettings.Topic.ProcessTemplate(ServiceOptions.TemplateVariables.Variables, _clientId); var payload = ServiceOptions.MqttClientSettings.Payload.ProcessTemplate(ServiceOptions.TemplateVariables.Variables, _clientId); var messagebuilder = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(payload); if (ServiceOptions.MqttClientSettings.Qos == 1) { messagebuilder.WithAtLeastOnceQoS(); } else if (ServiceOptions.MqttClientSettings.Qos == 2) { messagebuilder.WithExactlyOnceQoS(); } else { messagebuilder.WithAtMostOnceQoS(); } var message = messagebuilder.Build(); _logger.Debug($"Zombie publishing {payload} to {topic}"); _totalClientPublishes.Inc(); _clientPublishes.WithLabels(_clientId).Inc(); Task.Run(() => _mqttClient.PublishAsync(message, CancellationToken.None)); }
/// <summary> /// 发布 /// <paramref name="QoS"/> /// <para>0 - 最多一次</para> /// <para>1 - 至少一次</para> /// <para>2 - 仅一次</para> /// </summary> /// <param name="Topic">发布主题</param> /// <param name="Message">发布内容</param> /// <returns></returns> public string Publish(string Topic, string Message) { try { if (mqttClient == null) { return("失败"); } if (mqttClient.IsConnected == false) { mqttClient.ConnectAsync(options); } if (mqttClient.IsConnected == false) { return("失败"); } // Console.WriteLine("Publish >>Topic: " + Topic + "; QoS: " + QualityOfServiceLevel + "; Retained: " + Retained + ";"); // Console.WriteLine("Publish >>Message: " + Message); MqttApplicationMessageBuilder mamb = new MqttApplicationMessageBuilder() .WithTopic(Topic) .WithPayload(Message).WithRetainFlag(Retained); if (QualityOfServiceLevel == 0) { mamb = mamb.WithAtMostOnceQoS(); } else if (QualityOfServiceLevel == 1) { mamb = mamb.WithAtLeastOnceQoS(); } else if (QualityOfServiceLevel == 2) { mamb = mamb.WithExactlyOnceQoS(); } mqttClient.PublishAsync(mamb.Build()); return("成功"); } catch (Exception exp) { return(exp.Message); } }
public async Task PublishOnAsync(string topic, string message, bool retain) { MqttApplicationMessageBuilder builder; MqttApplicationMessage msg; if (!this.Client.IsConnected) { return; } builder = new MqttApplicationMessageBuilder(); builder.WithAtMostOnceQoS(); builder.WithPayload(message); builder.WithTopic(topic); builder.WithRetainFlag(retain); msg = builder.Build(); await this.Client.PublishAsync(msg).ConfigureAwait(false); }
private static void ConvertToQualityOfServiceLevel(MqttApplicationMessageBuilder builder, QoSLevel qos) { switch (qos) { case QoSLevel.AtMostOnce: builder.WithAtMostOnceQoS(); break; case QoSLevel.AtLeastOnce: builder.WithAtLeastOnceQoS(); break; case QoSLevel.ExactlyOnce: builder.WithExactlyOnceQoS(); break; default: throw new ArgumentOutOfRangeException(nameof(qos), qos, null); } }
public async Task PublicshAsync(string topic, byte[] payload, int retain = 0, int qos = 0) { if (mqttClient != null) { bool retainFlag = retain == 1; var mqMessageBuilder = new MqttApplicationMessageBuilder().WithTopic(topic).WithPayload(payload).WithRetainFlag(retainFlag); mqMessageBuilder.WithAtMostOnceQoS(); var result = await mqttClient.PublishAsync(mqMessageBuilder.Build()); if (result.ReasonCode != MQTTnet.Client.Publishing.MqttClientPublishReasonCode.Success) { Console.WriteLine("发送消息失败,topic[" + topic + "],Code:" + result.ReasonCode.ToString()); } else { Console.WriteLine("发送消息成功topic[" + topic + "]:" + Encoding.UTF8.GetString(payload)); } } }
private void btn_send_Click(object sender, EventArgs e) { if (this.mqttclient.IsConnected) { for (int i = 0; i < int.Parse(this.nud_sendNum.Value.ToString()); i++) { MqttApplicationMessageBuilder builder = new MqttApplicationMessageBuilder(); builder.WithPayload(this.mtb_sendmsg.Text.Trim()) .WithTopic(this.mtb_sendTopic.Text.Trim()); switch (this.cb_sendQos.SelectedText) { case "0": builder.WithAtMostOnceQoS(); break; case "1": builder.WithAtLeastOnceQoS(); break; case "2": builder.WithExactlyOnceQoS(); break; } if (this.nud_sendDelay.Value > 0) { Task.Delay(new TimeSpan(0, 0, 0, 0, int.Parse(this.nud_sendDelay.Value.ToString()))).Wait(); } this.mqttclient.PublishAsync(builder.Build()); insertLog($"topic:{this.mtb_sendTopic.Text.Trim()},value:{this.mtb_sendmsg.Text.Trim()}"); } } else { MessageBox.Show("当前连接已断开,请连接后重试", "系统提示"); } }
/// <summary> /// Send a message to the MQTT broker asynchronously. /// </summary> /// <param name="topic">Topic that the message will be sent to.</param> /// <param name="payload">Message payload.</param> /// <param name="qualityOfService"> /// <para>Optional: packet quality of service.</para> /// <para>Default value is <see cref="MqttQualityOfServiceLevel.AtLeastOnce"/>.</para> /// </param> /// <param name="cancellationToken">Optional: cancellation token.</param> /// <exception cref="ArgumentNullException"><paramref name="topic"/> is null or empty.</exception> /// <exception cref="ArgumentNullException"><paramref name="payload"/> is null.</exception> public async Task SendMessage( string topic, byte[] payload, MqttQualityOfServiceLevel qualityOfService = MqttQualityOfServiceLevel.AtLeastOnce, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(topic)) { throw new ArgumentNullException(paramName: nameof(topic), message: "Topic must not be null."); } if (payload == null || payload == default) { throw new ArgumentNullException(paramName: nameof(payload), message: "Payload must not be null."); } var messageBuilder = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(payload) .WithRetainFlag(); switch (qualityOfService) { case MqttQualityOfServiceLevel.AtLeastOnce: messageBuilder.WithAtLeastOnceQoS(); break; case MqttQualityOfServiceLevel.AtMostOnce: messageBuilder.WithAtMostOnceQoS(); break; case MqttQualityOfServiceLevel.ExactlyOnce: messageBuilder.WithExactlyOnceQoS(); break; } var message = messageBuilder.Build(); await Client.ConnectAsync(Options, cancellationToken); await Client.PublishAsync(message, cancellationToken); }
public async Task <MQTTnet.Client.Connecting.MqttClientAuthenticateResult> ConnectAsync(CancellationToken cancellationToken) { var cancelToken = cancellationToken != null ? cancellationToken : CancellationToken.None; MqttClientAuthenticateResult connectPrimary = null; if (!PrimaryClient.IsConnected) { PrimaryClient.UseConnectedHandler(async e => { var primaryFilters = Options.PrimaryFilters != null && Options.PrimaryFilters.Any() ? Options.PrimaryFilters : new TopicFilter[] { new TopicFilterBuilder().WithTopic("#").Build() }; await PrimaryClient.SubscribeAsync(primaryFilters); }); connectPrimary = await PrimaryClient.ConnectAsync(Options.PrimaryOptions, cancelToken); if (connectPrimary.ResultCode != MqttClientConnectResultCode.Success) { throw new ArgumentException("PrimaryOptions, could not connect to primary server."); } } if (!SecondaryClient.IsConnected) { var connectSecondary = await SecondaryClient.ConnectAsync(Options.SecondaryOptions, cancelToken); if (connectSecondary.ResultCode != MqttClientConnectResultCode.Success) { throw new ArgumentException("SecondaryOptions, could not connect to secondary server."); } } PrimaryClient.UseDisconnectedHandler(async e => { var connectRetry = Policy .Handle <Exception>() .WaitAndRetryForeverAsync( retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (exception, timespan) => { Console.WriteLine("### DISCONNECTED FROM SERVER ###"); }); await connectRetry.ExecuteAsync(async() => { var response = await PrimaryClient.ConnectAsync(Options.PrimaryOptions, cancelToken); Console.Write($"{response.ResultCode} {response.ReasonString}"); }); }); SecondaryClient.UseDisconnectedHandler(async e => { var connectRetry = Policy .Handle <Exception>() .WaitAndRetryForeverAsync( retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (exception, timespan) => { Console.WriteLine("### DISCONNECTED FROM SERVER ###"); }); await connectRetry.ExecuteAsync(async() => { var response = await SecondaryClient.ConnectAsync(Options.SecondaryOptions, cancelToken); Console.Write($"{response.ResultCode} {response.ReasonString}"); }); }); PrimaryClient.UseApplicationMessageReceivedHandler(e => { var message = new MqttApplicationMessageBuilder() .WithTopic(e.ApplicationMessage.Topic) .WithPayload(e.ApplicationMessage.Payload); if (e.ApplicationMessage.Retain) { message = message.WithRetainFlag(); } switch (e.ApplicationMessage.QualityOfServiceLevel) { case MqttQualityOfServiceLevel.ExactlyOnce: message = message.WithExactlyOnceQoS(); break; case MqttQualityOfServiceLevel.AtLeastOnce: message = message.WithAtLeastOnceQoS(); break; case MqttQualityOfServiceLevel.AtMostOnce: message = message.WithAtMostOnceQoS(); break; default: throw new ArgumentOutOfRangeException(); } Task.Run(() => SecondaryClient.PublishAsync(message.Build(), cancelToken), cancelToken); }); if (Options.SyncMode) { SecondaryClient.UseConnectedHandler(async e => { var secondaryFilters = Options.SecondaryFilters != null && Options.SecondaryFilters.Any() ? Options.SecondaryFilters : new TopicFilter[] { new TopicFilterBuilder().WithTopic("#").Build() }; await SecondaryClient.SubscribeAsync(secondaryFilters); }); SecondaryClient.UseApplicationMessageReceivedHandler(e => { var message = new MqttApplicationMessageBuilder() .WithTopic(e.ApplicationMessage.Topic) .WithPayload(e.ApplicationMessage.Payload); if (e.ApplicationMessage.Retain) { message = message.WithRetainFlag(); } switch (e.ApplicationMessage.QualityOfServiceLevel) { case MqttQualityOfServiceLevel.ExactlyOnce: message = message.WithExactlyOnceQoS(); break; case MqttQualityOfServiceLevel.AtLeastOnce: message = message.WithAtLeastOnceQoS(); break; case MqttQualityOfServiceLevel.AtMostOnce: message = message.WithAtMostOnceQoS(); break; default: throw new ArgumentOutOfRangeException(); } Task.Run(() => PrimaryClient.PublishAsync(message.Build(), cancelToken), cancelToken); }); } return(connectPrimary); }