public CheckSubscriptionsResult CheckSubscriptions(string topic, MqttQualityOfServiceLevel qosLevel) { var qosLevels = new HashSet <MqttQualityOfServiceLevel>(); lock (_subscriptions) { foreach (var subscription in _subscriptions) { if (!MqttTopicFilterComparer.IsMatch(topic, subscription.Key)) { continue; } qosLevels.Add(subscription.Value.QualityOfServiceLevel); } } if (qosLevels.Count == 0) { return(new CheckSubscriptionsResult { IsSubscribed = false }); } return(CreateSubscriptionResult(qosLevel, qosLevels)); }
public Task PublishAsync(string topic, string v, MqttQualityOfServiceLevel atLeastOnce) { return(PublishAsync(new MqttMessage() { Topic = topic, QualityOfServiceLevel = atLeastOnce, Payload = Encoding.UTF8.GetBytes(v) })); }
public static Task <MqttClientPublishResult> PublishBinaryAsync( this IMqttClient mqttClient, string topic, IEnumerable <byte> payload = null, MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false, CancellationToken cancellationToken = default) { if (mqttClient == null) { throw new ArgumentNullException(nameof(mqttClient)); } if (topic == null) { throw new ArgumentNullException(nameof(topic)); } var applicationMessage = new MqttApplicationMessageBuilder().WithTopic(topic) .WithPayload(payload) .WithRetainFlag(retain) .WithQualityOfServiceLevel(qualityOfServiceLevel) .Build(); return(mqttClient.PublishAsync(applicationMessage, cancellationToken)); }
async Task TestPublishAsync( string topic, MqttQualityOfServiceLevel qualityOfServiceLevel, string topicFilter, MqttQualityOfServiceLevel filterQualityOfServiceLevel, int expectedReceivedMessagesCount) { using (var testEnvironment = CreateTestEnvironment()) { await testEnvironment.StartServer(); var c1 = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithClientId("receiver")); var c1MessageHandler = testEnvironment.CreateApplicationMessageHandler(c1); await c1.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(topicFilter).WithQualityOfServiceLevel(filterQualityOfServiceLevel).Build()); var c2 = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithClientId("sender")); await c2.PublishAsync(new MqttApplicationMessageBuilder().WithTopic(topic).WithPayload(new byte[0]).WithQualityOfServiceLevel(qualityOfServiceLevel).Build()); await Task.Delay(500); await c2.DisconnectAsync().ConfigureAwait(false); await Task.Delay(500); await c1.UnsubscribeAsync(topicFilter); await Task.Delay(500); Assert.AreEqual(expectedReceivedMessagesCount, c1MessageHandler.ReceivedEventArgs.Count); } }
private static async Task TestPublishAsync( string topic, MqttQualityOfServiceLevel qualityOfServiceLevel, string topicFilter, MqttQualityOfServiceLevel filterQualityOfServiceLevel, int expectedReceivedMessagesCount) { using (var testEnvironment = new TestEnvironment()) { var receivedMessagesCount = 0; await testEnvironment.StartServerAsync(new MqttServerOptionsBuilder()); var c1 = await testEnvironment.ConnectClientAsync(new MqttClientOptionsBuilder().WithClientId("receiver")); c1.UseApplicationMessageReceivedHandler(c => Interlocked.Increment(ref receivedMessagesCount)); await c1.SubscribeAsync(new TopicFilterBuilder().WithTopic(topicFilter).WithQualityOfServiceLevel(filterQualityOfServiceLevel).Build()); var c2 = await testEnvironment.ConnectClientAsync(new MqttClientOptionsBuilder().WithClientId("sender")); await c2.PublishAsync(new MqttApplicationMessageBuilder().WithTopic(topic).WithPayload(new byte[0]).WithQualityOfServiceLevel(qualityOfServiceLevel).Build()); await c2.DisconnectAsync().ConfigureAwait(false); await Task.Delay(500); await c1.UnsubscribeAsync(topicFilter); await Task.Delay(500); Assert.AreEqual(expectedReceivedMessagesCount, receivedMessagesCount); } }
public MqttApplicationMessage(string topic, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, bool retain) { Topic = topic ?? throw new ArgumentNullException(nameof(topic)); Payload = payload ?? throw new ArgumentNullException(nameof(payload)); QualityOfServiceLevel = qualityOfServiceLevel; Retain = retain; }
CheckSubscriptionsResult CheckSubscriptions(string topic, MqttQualityOfServiceLevel applicationMessageQoSLevel, string senderClientId) { ulong topicHashMask; // not needed bool hasWildcard; // not needed MqttSubscription.CalculateTopicHash(topic, out var topicHash, out topicHashMask, out hasWildcard); return(_subscriptionsManager.CheckSubscriptions(topic, topicHash, applicationMessageQoSLevel, senderClientId)); }
/// <summary> /// 发布消息 /// </summary> public Task Publish(string topic, string data, MqttQualityOfServiceLevel level) { if (data == null) { return(Task.CompletedTask); } return(Publish(topic, Encoding.UTF8.GetBytes(data), level)); }
public async Task SubscribeAsync(string topic, MqttQualityOfServiceLevel qos = MqttQualityOfServiceLevel.AtMostOnce) { await SubscribeAsync(new [] { new MqttTopicFilter() { QualityOfServiceLevel = qos, Topic = topic } }); }
/// <summary> /// 发送消息 /// </summary> public Task Send(string data, MqttQualityOfServiceLevel level, string topic = null) { if (data == null) { return(Task.CompletedTask); } return(Send(Encoding.UTF8.GetBytes(data), level, topic)); }
public static TopicFilter BuildTopic(string topic, MqttQualityOfServiceLevel qualityOfServiceLevel) { return(new TopicFilter() { Topic = topic, QualityOfServiceLevel = qualityOfServiceLevel }); }
public void InitOptions(ProtocolType protocolType, string ipAddress, int?port = null, MqttQualityOfServiceLevel mqttQuality = MqttQualityOfServiceLevel.AtMostOnce) { IsConnected = false; IpAddress = ipAddress; Port = port; ProtocolType = protocolType; MqttQualityOfServiceLevel = mqttQuality; }
public MqttApplicationMessage CreateApplicationMessage(string topic, MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false) { if (topic == null) { throw new ArgumentNullException(nameof(topic)); } return(CreateApplicationMessage(topic, new byte[0], qualityOfServiceLevel, retain)); }
public MQTTPublisher(MqttQualityOfServiceLevel qosLevel, IManagedMqttClient client, string topic) { _cancellationToken = new CancellationTokenSource(); _serializer = new MessageSerializer <PubSubMessage, TMessage>(); _qosLevel = qosLevel; _client = client ?? throw new ArgumentNullException(nameof(client)); Topic = topic ?? throw new ArgumentNullException(nameof(topic)); }
/// <summary> /// Filter the stream by a <see cref="MqttQualityOfServiceLevel"/>. /// </summary> /// <param name="source">The source observable.</param> /// <param name="mqttQualityOfServiceLevel">The level to filter for.</param> /// <returns>The filtered source.</returns> /// <exception cref="ArgumentNullException"></exception> public static IObservable <MqttApplicationMessageReceivedEventArgs> FilterQoS( this IObservable <MqttApplicationMessageReceivedEventArgs> source, MqttQualityOfServiceLevel mqttQualityOfServiceLevel) { if (source is null) { throw new ArgumentNullException(nameof(source)); } return(source.Where(@event => @event.ApplicationMessage.QualityOfServiceLevel == mqttQualityOfServiceLevel)); }
/// <summary> /// Creates logger configuration for MQTT. /// </summary> /// <param name="sinkConfiguration">Sink configuration</param> /// <param name="clientOptions">MQTT client options</param> /// <param name="topic">MQTT topic under which the logs are to be published.</param> /// <param name="qoS">Quality of service level. <seealso cref="MqttQualityOfServiceLevel"/></param> /// <param name="restrictedToMinimumLevel">Restricted min level.</param> /// <param name="formatter">Custom formatter.</param> /// <returns></returns> public static LoggerConfiguration MQTT( this LoggerSinkConfiguration sinkConfiguration, IMqttClientOptions clientOptions, string topic, MqttQualityOfServiceLevel qoS = MqttQualityOfServiceLevel.AtMostOnce, LogEventLevel restrictedToMinimumLevel = LogEventLevel.Information, Formatting.ITextFormatter formatter = null) { return(sinkConfiguration.Sink(new MQTTSink(clientOptions, topic, qoS, formatter), restrictedToMinimumLevel)); }
public void InitOptions(ProtocolType protocolType, string ipAddress, int port, string userName, string password, MqttQualityOfServiceLevel mqttQuality = MqttQualityOfServiceLevel.AtMostOnce) { IsConnected = false; IpAddress = ipAddress; Port = port; ProtocolType = protocolType; MqttQualityOfServiceLevel = mqttQuality; UserName = userName; Password = password; }
/// <summary> /// 接收消息 /// </summary> private void MqttServe_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e) { string ClientId = e.ClientId; string Topic = e.ApplicationMessage.Topic; string Payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); MqttQualityOfServiceLevel Qos = e.ApplicationMessage.QualityOfServiceLevel; var Retain = e.ApplicationMessage.Retain; log.LogInformation($"client [{ClientId}] pushed topic [{Topic}] payload [{Payload}] Qos [{Qos}] Retain [{Retain}]"); }
private async Task Publish(string topic, byte[] payload, bool retain, MqttQualityOfServiceLevel qualityOfService) { await mqttClient .PublishAsync(new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(payload) .WithRetainFlag(retain) .WithQualityOfServiceLevel(qualityOfService) .Build()) .ConfigureAwait(false); }
public Task SubscribeAsync( string topic, MqttQualityOfServiceLevel qos = MqttQualityOfServiceLevel.AtLeastOnce ) => _mqttClient.SubscribeAsync( new MqttTopicFilter() { Topic = topic, QualityOfServiceLevel = qos } );
private string GetRequestTopic(string target, MqttQualityOfServiceLevel qos) { var topic = $"from/{ClientId}/rpc"; if (!string.IsNullOrEmpty(target)) { topic += $"/to/{target}"; } topic += $"/qos{(int) qos}"; return(topic); }
/// <summary> /// Creates new instance of <see cref="MQTTSink"/> /// </summary> /// <param name="clientOptions">MQTT client options <seealso cref="https://github.com/chkr1011/MQTTnet/wiki/Client"/></param> /// <param name="topic">Topic under which the logs are to be published.</param> /// <param name="qoS">Quality of service level. <see cref="MqttQualityOfServiceLevel"/></param> /// <param name="formatter">Custom log formatter.</param> public MQTTSink(IMqttClientOptions clientOptions, string topic, MqttQualityOfServiceLevel qoS = MqttQualityOfServiceLevel.AtMostOnce, Formatting.ITextFormatter formatter = null) { Topic = topic; QoS = qoS; Formatter = formatter ?? Formatter; MqttClientOptions = clientOptions; MqttClient.ConnectAsync(MqttClientOptions).Wait(); }
private async Task PublishAsync(string topic, byte[] payload, MqttQualityOfServiceLevel qos = MqttQualityOfServiceLevel.AtLeastOnce, bool retain = true) { //System.Diagnostics.Debug.WriteLine("Topic: " + topic); await PublishAsync(new MqttApplicationMessage() { Topic = topic, Payload = payload, QualityOfServiceLevel = qos, Retain = retain }); }
public static Task <MqttClientPublishResult> PublishStringAsync( this MqttClient mqttClient, string topic, string payload = null, MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false, CancellationToken cancellationToken = default) { var payloadBuffer = Encoding.UTF8.GetBytes(payload ?? string.Empty); return(mqttClient.PublishBinaryAsync(topic, payloadBuffer, qualityOfServiceLevel, retain, cancellationToken)); }
public async Task SendMessage(string topic, string payload, MqttQualityOfServiceLevel qos, bool retain) { var message = new MqttApplicationMessage() { Topic = topic, Payload = Encoding.UTF8.GetBytes(payload), QualityOfServiceLevel = qos, Retain = retain }; await _mqttClient.PublishAsync(message); }
protected async Task <MqttApplicationMessage> ExecuteAsync(string target, string methodName, byte[] payload, bool utf8Payload, string contentType, MqttQualityOfServiceLevel qos, TimeSpan timeout, CancellationToken cancellationToken = default) { await InitSubscription(); var id = Guid.NewGuid().ToString("N"); var requestMessage = BuildMessage(methodName, payload, utf8Payload, contentType, qos, timeout, target, builder => { builder.WithUserProperty("Id", id); }); try { var tcs = new TaskCompletionSource <MqttApplicationMessage>(); if (!_waitingCalls.TryAdd(id, tcs)) { throw new InvalidOperationException(); } await MqttClient.PublishAsync(requestMessage).ConfigureAwait(false); using var timeoutCts = new CancellationTokenSource(timeout); using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token); linkedCts.Token.Register(() => { if (!tcs.Task.IsCompleted && !tcs.Task.IsFaulted && !tcs.Task.IsCanceled) { tcs.TrySetCanceled(); } }); try { var result = await tcs.Task.ConfigureAwait(false); timeoutCts.Cancel(false); return(result); } catch (OperationCanceledException exception) { if (timeoutCts.IsCancellationRequested && !cancellationToken.IsCancellationRequested) { throw new MqttCommunicationTimedOutException(exception); } else { throw; } } } finally { _waitingCalls.TryRemove(id, out _); } }
private static MqttSubscribeReturnCode ConvertToMaximumQoS(MqttQualityOfServiceLevel qualityOfServiceLevel) { switch (qualityOfServiceLevel) { case MqttQualityOfServiceLevel.AtMostOnce: return(MqttSubscribeReturnCode.SuccessMaximumQoS0); case MqttQualityOfServiceLevel.AtLeastOnce: return(MqttSubscribeReturnCode.SuccessMaximumQoS1); case MqttQualityOfServiceLevel.ExactlyOnce: return(MqttSubscribeReturnCode.SuccessMaximumQoS2); default: return(MqttSubscribeReturnCode.Failure); } }
private static MqttSubscribeReasonCode ConvertToSubscribeReasonCode(MqttQualityOfServiceLevel qualityOfServiceLevel) { switch (qualityOfServiceLevel) { case MqttQualityOfServiceLevel.AtMostOnce: return(MqttSubscribeReasonCode.GrantedQoS0); case MqttQualityOfServiceLevel.AtLeastOnce: return(MqttSubscribeReasonCode.GrantedQoS1); case MqttQualityOfServiceLevel.ExactlyOnce: return(MqttSubscribeReasonCode.GrantedQoS2); default: return(MqttSubscribeReasonCode.UnspecifiedError); } }
private static QoSLevel ConvertToQoSLevel(MqttQualityOfServiceLevel qos) { switch (qos) { case MqttQualityOfServiceLevel.AtMostOnce: return(QoSLevel.AtMostOnce); case MqttQualityOfServiceLevel.AtLeastOnce: return(QoSLevel.AtLeastOnce); case MqttQualityOfServiceLevel.ExactlyOnce: return(QoSLevel.ExactlyOnce); default: throw new ArgumentOutOfRangeException(nameof(qos), qos, null); } }
/// <summary> /// 初始化驱动 /// </summary> /// <param name="server"></param> /// <param name="communication"></param> /// <param name="ioDevices"></param> /// <param name="driver"></param> /// <returns></returns> protected override bool InitCommunicateKernel(IO_SERVER server, IO_COMMUNICATION communication, List <IO_DEVICE> ioDevices, SCADA_DRIVER driver) { try { ParaPack communicatePack = new ParaPack(communication.IO_COMM_PARASTRING); if (communication.IO_COMM_PARASTRING != null && communication.IO_COMM_PARASTRING != "") { this.ServerIP = communicatePack.GetValue("服务器IP"); this.ServerPort = int.Parse(communicatePack.GetValue("端口号")); this.UserName = communicatePack.GetValue("用户名"); this.Password = communicatePack.GetValue("密码"); this.EaableAnonymousAuthentication = bool.Parse(communicatePack.GetValue("开启匿名验证")); this.HeartTime = int.Parse(communicatePack.GetValue("心跳时间")); string msgqulity = communicatePack.GetValue("消息质量"); switch (msgqulity) { case "QoS 0 最多分发一次": MessageQulity = MqttQualityOfServiceLevel.AtMostOnce; break; case "QoS 1 至少分发一次": MessageQulity = MqttQualityOfServiceLevel.AtLeastOnce; break; case "QoS 2 只分发一次": MessageQulity = MqttQualityOfServiceLevel.ExactlyOnce; break; } this.WillFlag = communicatePack.GetValue("遗愿标志"); this.MqttDataType = communicatePack.GetValue("数据格式"); this.EaableClientIDAuthentication = bool.Parse(communicatePack.GetValue("开启Mqtt客户端识别")); } if (IsCreateControl) { CommunicationControl = new MQTTServerCtrl(); if (communication != null && communication.IO_COMM_PARASTRING != "") { CommunicationControl.SetUIParameter(communication.IO_COMM_PARASTRING); } } } catch (Exception emx) { this.DeviceException(emx.Message); return(false); } return(true); }