private void CloseMqtt() { if (!(this.mqttConnection is null)) { if (this.mqttConnection.State == MqttState.Connected) { BinaryOutput Output = new BinaryOutput(); Output.WriteByte(2); Output.WriteString(this.applicationName); Output.WriteGuid(this.localPlayer.PlayerId); this.mqttTerminatedPacketIdentifier = this.mqttConnection.PUBLISH(this.mqttNegotiationTopic, MqttQualityOfService.AtLeastOne, false, Output); this.mqttConnection.OnPublished += new PacketAcknowledgedEventHandler(mqttConnection_OnPublished); #if LineListener Console.Out.WriteLine("Tx: BYE(" + this.localPlayer.ToString() + ")"); #endif } else { this.mqttConnection.Dispose(); this.mqttConnection = null; } } }
public async Task NewMessageIsProcessedWell() { // Arrange var mockManagedMqttClient = new Mock <IManagedMqttClient>(); var mockManagedMqttClientOptions = new Mock <IManagedMqttClientOptions>(); var mockMqttClientFactory = new Mock <IMqttClientFactory>(); mockMqttClientFactory .Setup(m => m.CreateManagedMqttClient()) .Returns(mockManagedMqttClient.Object); var config = new MqttConfiguration("CustomConfig", mockManagedMqttClientOptions.Object); var mqttConnection = new MqttConnection(mockMqttClientFactory.Object, config, _mockLogger.Object); IMqttMessage receivedMessage = null; mqttConnection.OnMessageEventHandler += (MqttMessageReceivedEventArgs arg) => { receivedMessage = arg.Message; return(Task.CompletedTask); }; // Act await mqttConnection.StartAsync(); mockManagedMqttClient.Raise(x => x.ApplicationMessageReceived += null, new MqttApplicationMessageReceivedEventArgs("ClientId", DefaultMessage)); // Assert Assert.NotNull(receivedMessage); Assert.Equal(DefaultMessage.Topic, receivedMessage.Topic); Assert.Equal(DefaultMessage.Retain, receivedMessage.Retain); Assert.Equal(DefaultMessage.QualityOfServiceLevel.ToString(), receivedMessage.QosLevel.ToString()); Assert.Equal(DefaultMessage.Payload, receivedMessage.GetMessage()); }
public async Task StartAsyncSubscribesToTopics() { // Arrange var mockManagedMqttClient = new Mock <IManagedMqttClient>(); var mockManagedMqttClientOptions = new Mock <IManagedMqttClientOptions>(); var mockMqttClientFactory = new Mock <IManagedMqttClientFactory>(); var messageProcessor = new Mock <IProcesMqttMessage>(); mockMqttClientFactory .Setup(m => m.CreateManagedMqttClient()) .Returns(mockManagedMqttClient.Object); mockManagedMqttClient .Setup(m => m.StartAsync(It.Is <IManagedMqttClientOptions>(y => y == mockManagedMqttClientOptions.Object))) .Returns(Task.CompletedTask); messageProcessor.Setup(x => x.OnMessage(It.IsAny <MqttMessageReceivedEventArgs>())).Returns(Task.CompletedTask); var config = new MqttConfiguration("CustomConfig", mockManagedMqttClientOptions.Object); var mqttConnection = new MqttConnection(mockMqttClientFactory.Object, config, _mockLogger.Object); // Act await mqttConnection.StartAsync(messageProcessor.Object); await mqttConnection.HandleConnectedAsync(new MqttClientConnectedEventArgs(new MqttClientAuthenticateResult { IsSessionPresent = true, ResultCode = MqttClientConnectResultCode.Success })); // Assert Assert.Equal(ConnectionState.Connected, mqttConnection.ConnectionState); mockMqttClientFactory.VerifyAll(); mockManagedMqttClient.VerifyAll(); }
public SubscribeMessage(String topic, QoS topicQos, MqttConnection conn) : base(MessageType.SUBSCRIBE, conn) { setQos(QoS.AT_LEAST_ONCE); topics.Add(topic); topicQoSs.Add(topicQos); }
public PublishMessage(String topic, byte[] data, QoS qos, MqttConnection conn) : base(MessageType.PUBLISH, conn) { this.topic = topic; this.data = data; setQos(qos); }
private void CreateMQChannel() { if (m_mqttClient.IsPublishing) { return; } StopMQTTChannel(); try { var connArgs = new MqttConnectionArgs() { ClientId = m_clientId, Hostname = m_mqttServerAddress, Port = m_mqttPort, Keepalive = new TimeSpan(1, 0, 0) }; m_mqttClient = new MqttConnection(connArgs, m_mqttPersistence, null); m_mqttClient.Connect(); } catch (Exception ex) { string text = "创建MQTTChannel失败," + ex.Message; m_eventLogger.WriteWarning(text); USeNotifyEventArgs notify = new USeNotifyEventArgs(USeNotifyLevel.Warning, text); SafeRaiseNotifyEvent(this, notify); } }
public async Task NewMessageIsProcessed() { // Arrange var mockManagedMqttClient = new Mock <IManagedMqttClient>(); var mockManagedMqttClientOptions = new Mock <IManagedMqttClientOptions>(); var mockMqttClientFactory = new Mock <IManagedMqttClientFactory>(); var messageProcessor = new Mock <IProcesMqttMessage>(); mockMqttClientFactory .Setup(m => m.CreateManagedMqttClient()) .Returns(mockManagedMqttClient.Object); messageProcessor.Setup(x => x.OnMessage(It.IsAny <MqttMessageReceivedEventArgs>())).Returns(Task.CompletedTask); var config = new MqttConfiguration("CustomConfig", mockManagedMqttClientOptions.Object); var mqttConnection = new MqttConnection(mockMqttClientFactory.Object, config, _mockLogger.Object); // Act await mqttConnection.StartAsync(messageProcessor.Object); await mqttConnection.HandleApplicationMessageReceivedAsync(new MqttApplicationMessageReceivedEventArgs("ClientId", DefaultMessage)); // Assert messageProcessor.Verify(x => x.OnMessage(It.Is <MqttMessageReceivedEventArgs>(y => y.Message.Topic == DefaultMessage.Topic))); messageProcessor.Verify(x => x.OnMessage(It.Is <MqttMessageReceivedEventArgs>(y => y.Message.Retain == DefaultMessage.Retain))); messageProcessor.Verify(x => x.OnMessage(It.Is <MqttMessageReceivedEventArgs>(y => y.Message.QosLevel.ToString() == DefaultMessage.QualityOfServiceLevel.ToString()))); messageProcessor.Verify(x => x.OnMessage(It.Is <MqttMessageReceivedEventArgs>(y => y.Message.GetMessage() == DefaultMessage.Payload))); }
//synchronized //[MethodImpl(MethodImplOptions.Synchronized)] public void connectToBroker() { if (isConnected() || isConnecting()) { return; } if (mqttConnection == null) { if (!init()) { return; } mqttConnection = new MqttConnection(clientId, brokerHostName, brokerPortNumber, uid, password, new ConnectCB(this)); mqttConnection.MqttListener = this; } try { // try to connect setConnectionStatus(MQTTConnectionStatus.CONNECTING); mqttConnection.connect(); } catch (Exception e) { /* couldn't connect, schedule a ping even earlier? */ } }
private static void SubscribeWithWildcard(string topic, byte qosLevel, MqttConnection connection) { var topicReplaced = topic.Replace(PLUS_WILDCARD, PLUS_WILDCARD_REPLACE) .Replace(SHARP_WILDCARD, SHARP_WILDCARD_REPLACE); var subscriptionsForTopic = WildcardSubscriptions.GetOrAdd(topicReplaced, new List <MqttSubscription>()); lock (subscriptionsForTopic) { if (!AlreadySubscribed(connection.ClientId, subscriptionsForTopic)) { var subscription = new MqttSubscription() { ClientId = connection.ClientId, Topic = topicReplaced, QosLevel = qosLevel, Connection = connection }; subscriptionsForTopic.Add(subscription); connection.Subscriptions.TryAdd(topicReplaced, subscription); } } }
/// <summary> /// Initializes a new instance of the <see cref="MqttTriggerAttribute"/> class. /// </summary> /// <param name="parameter">The parameter to bind to.</param> /// <param name="connection">The MQTT connection.</param> /// <param name="topics">The topics to subscribe to.</param> /// <param name="logger">The logger.</param> public MqttTriggerBinding(ParameterInfo parameter, MqttConnection connection, MqttTopicFilter[] topics, ILogger logger) { _parameter = parameter; _connection = connection; _topics = topics; _logger = logger; }
/// <summary> /// Initializes a new instance of the <see cref="HomeViewModel"/> class /// </summary> /// <param name="dialogCoordinator">Dialog coordinator to show dialog</param> public HomeViewModel(IDialogCoordinator dialogCoordinator) { this.dialogCoordinator = dialogCoordinator; this.proc = new MqttConnection("localhost", 5672, "userTest", "userTest", "hello"); this.proc.Connect(); this.proc.ReadDataEvnt(this.WhenMessageReceived); this.ProjectItems = new ObservableCollection <ProjectItem>(); this.CloseWindowCommand = new RelayCommand(this.WindowClosingAction); this.LoadedWindowCommand = new RelayCommand(this.WindowLoadedAction); this.ClickInRenameContextMenu = new RelayCommand(this.ClickInRenameActionAsync); this.ClickInDeleteContextMenu = new RelayCommand(this.ClickInDeleteAction); this.CreateProjectCommand = new RelayCommand(this.CreateProjectAction); this.SelectProjectCommand = new RelayCommand(this.SelectProjectAction); this.DeleteSensorCommand = new RelayCommand(this.DeleteSensorAction); this.DeleteAnalysisCommand = new RelayCommand(this.DeleteAnalysisAction); this.AddNewSensorCommand = new AddSensorCommand(this); this.ClickInTabCategoryCommand = new RelayCommand(this.ClickInTabCategoryAction); this.EditSensorDataCommand = new ChangeSensorDataCommand(this); this.BrowseFileCommand = new RelayCommand(this.BrowseFileAction); this.ClickInAnalysisItem = new RelayCommand(this.ClickInAnalysisAction); this.ClickInExportToTxtCommand = new RelayCommand(this.ClickInExportToTxtAction); this.currentDirectory = System.IO.Directory.GetCurrentDirectory(); this.lastMessageReceivedTime = DateTime.Now; }
/// <summary> /// Opens the component with given connection and credential parameters. /// </summary> /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param> public async override Task OpenAsync(string correlationId) { if (IsOpen()) { return; } if (_connection == null) { _connection = CreateConnection(); _localConnection = true; } if (_localConnection) { await _connection.OpenAsync(correlationId); } if (!_connection.IsOpen()) { throw new InvalidStateException(correlationId, "CONNECT_FAILED", "MQTT connection is not opened"); } await base.OpenAsync(correlationId); _opened = true; }
private int SendPubrel( MqttConnection connection, MqttMsgContext msgContext, MqttMsgBase msgInflight, int timeout) { // QoS 2, PUBREL message to send to broker, state change to wait PUBCOMP if (msgContext.Flow == MqttMsgFlow.ToPublish) { msgContext.State = MqttMsgState.WaitForPubcomp; msgContext.Timestamp = Environment.TickCount; msgContext.Attempt++; // retry ? set dup flag [v3.1.1] no needed if (connection.ProtocolVersion == MqttProtocolVersion.Version_3_1 && msgContext.Attempt > 1) { outgoingMessageHandler.Pubrel(connection, msgInflight.MessageId, true); } else { outgoingMessageHandler.Pubrel(connection, msgInflight.MessageId, false); } // update timeout : minimum between delay (based on current message sent) or current timeout timeout = connection.Settings.DelayOnRetry < timeout ? connection.Settings.DelayOnRetry : timeout; // re-enqueue message connection.EnqueueInflight(msgContext); } return(timeout); }
/// <summary> /// Constructor /// </summary> /// <param name="clientId">Client Id of the subscription</param> /// <param name="topic">Topic of subscription</param> /// <param name="qosLevel">QoS level of subscription</param> /// <param name="connection">Client related to the subscription</param> public MqttSubscription(string clientId, string topic, byte qosLevel, MqttConnection connection = null) { this.ClientId = clientId; this.Topic = topic; this.QosLevel = qosLevel; this.Connection = connection; }
/// <summary> /// Constructor /// </summary> public MqttSubscription() { this.ClientId = null; this.Topic = null; this.QosLevel = 0; this.Connection = null; }
public SubscribeMessage(List <String> topics, List <QoS> topicQoSs, MqttConnection conn) : base(MessageType.SUBSCRIBE, conn) { setQos(QoS.AT_LEAST_ONCE); this.topics = topics; this.topicQoSs = topicQoSs; }
public async Task StartAsyncSubscribesToTopics() { // Arrange var mockManagedMqttClient = new Mock <IManagedMqttClient>(); var mockManagedMqttClientOptions = new Mock <IManagedMqttClientOptions>(); var mockMqttClientFactory = new Mock <IMqttClientFactory>(); mockMqttClientFactory .Setup(m => m.CreateManagedMqttClient()) .Returns(mockManagedMqttClient.Object); mockManagedMqttClient .Setup(m => m.StartAsync(It.Is <IManagedMqttClientOptions>(y => y == mockManagedMqttClientOptions.Object))) .Returns(Task.CompletedTask); var config = new MqttConfiguration("CustomConfig", mockManagedMqttClientOptions.Object); var mqttConnection = new MqttConnection(mockMqttClientFactory.Object, config, _mockLogger.Object); // Act await mqttConnection.StartAsync(); mockManagedMqttClient.Raise(x => x.Connected += null, new MqttClientConnectedEventArgs(true)); // Assert Assert.Equal(ConnectionState.Connected, mqttConnection.ConnectionState); mockMqttClientFactory.VerifyAll(); mockManagedMqttClient.VerifyAll(); }
private static void UnsubscribeFromTopicWithWildcard(string topic, MqttConnection connection) { var topicReplaced = topic.Replace(PLUS_WILDCARD, PLUS_WILDCARD_REPLACE) .Replace(SHARP_WILDCARD, SHARP_WILDCARD_REPLACE); List <MqttSubscription> subscriptionsForTopic; if (WildcardSubscriptions.TryGetValue(topicReplaced, out subscriptionsForTopic)) { lock (subscriptionsForTopic) { foreach (var subscription in subscriptionsForTopic) { if (subscription.ClientId == connection.ClientId) { subscriptionsForTopic.Remove(subscription); // TODO deal with topic with no subscribers MqttSubscription subscriptionToBeRemoved; connection.Subscriptions.TryRemove(topicReplaced, out subscriptionToBeRemoved); return; } } } } }
private void mqttConnection_OnPublished(MqttConnection Sender, ushort PacketIdentifier) { if (!(this.mqttConnection is null) && PacketIdentifier == this.mqttTerminatedPacketIdentifier) { this.mqttConnection.Dispose(); this.mqttConnection = null; } }
private int HandleQueuedQos1SendSubscribeAndSendUnsubscribe( MqttConnection connection, MqttMsgContext msgContext, MqttMsgBase msgInflight, int timeout) { InternalEvent internalEvent; // QoS 1, PUBLISH or SUBSCRIBE/UNSUBSCRIBE message to send to broker, state change to wait PUBACK or SUBACK/UNSUBACK if (msgContext.Flow == MqttMsgFlow.ToPublish) { msgContext.Timestamp = Environment.TickCount; msgContext.Attempt++; if (msgInflight.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) { // PUBLISH message to send, wait for PUBACK msgContext.State = MqttMsgState.WaitForPuback; // retry ? set dup flag [v3.1.1] only for PUBLISH message if (msgContext.Attempt > 1) { msgInflight.DupFlag = true; } } else if (msgInflight.Type == MqttMsgBase.MQTT_MSG_SUBSCRIBE_TYPE) { // SUBSCRIBE message to send, wait for SUBACK msgContext.State = MqttMsgState.WaitForSuback; } else if (msgInflight.Type == MqttMsgBase.MQTT_MSG_UNSUBSCRIBE_TYPE) { // UNSUBSCRIBE message to send, wait for UNSUBACK msgContext.State = MqttMsgState.WaitForUnsuback; } outgoingMessageHandler.Send(connection, msgInflight); // update timeout : minimum between delay (based on current message sent) or current timeout timeout = connection.Settings.DelayOnRetry < timeout ? connection.Settings.DelayOnRetry : timeout; // re-enqueue message (I have to re-analyze for receiving PUBACK, SUBACK or UNSUBACK) connection.EnqueueInflight(msgContext); } // QoS 1, PUBLISH message received from broker to acknowledge, send PUBACK else if (msgContext.Flow == MqttMsgFlow.ToAcknowledge) { outgoingMessageHandler.Puback(connection, msgInflight.MessageId); internalEvent = new InternalEvent(msgInflight); // notify published message from broker and acknowledged connection.EnqueueInternalEvent(internalEvent); } return(timeout); }
public void onDisconnected() { setConnectionStatus(MQTTConnectionStatus.NOTCONNECTED_UNKNOWNREASON); mqttConnection = null; if (!disconnectCalled) { disconnectFromBroker(true); } }
private MqttMsgBase WaitForPubrel( MqttConnection connection, MqttMsgContext msgContext, MqttMsgBase msgInflight, ref bool msgReceivedProcessed) { // QoS 2, waiting for PUBREL of a PUBREC message sent if (msgContext.Flow != MqttMsgFlow.ToAcknowledge) { return(null); } if (!connection.InternalQueue.TryPeek(out MqttMsgBase msgReceived)) { return(null); } InternalEvent internalEvent; // it is a PUBREL message if (msgReceived != null && msgReceived.Type == MqttMsgBase.MQTT_MSG_PUBREL_TYPE) { if (msgReceived.MessageId == msgInflight.MessageId) { // received message processed connection.InternalQueue.TryDequeue(out MqttMsgBase dequeuedMsg); msgReceivedProcessed = true; outgoingMessageHandler.Pubcomp(connection, msgInflight.MessageId); internalEvent = new InternalEvent(msgInflight); // notify published message from broker and acknowledged connection.EnqueueInternalEvent(internalEvent); // PUBREL received (and PUBCOMP sent) for PUBLISH message with QoS Level 2, remove from session state if (msgInflight.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE && connection.Session != null && connection.Session.InflightMessages.ContainsKey(msgContext.Key)) { connection.Session.InflightMessages.TryRemove( msgContext.Key, out MqttMsgContext contextToBeRemoved); } } else { // re-enqueue message connection.EnqueueInflight(msgContext); } } else { connection.EnqueueInflight(msgContext); } return(msgReceived); }
/// <summary> /// Publish retained message for a topic to a client /// </summary> /// <param name="topic">Topic to search for a retained message</param> /// <param name="clientId">Client Id to send retained message</param> public void PublishRetaind(string topic, MqttConnection connection) { var subscription = subscriptionManager.GetSubscription(topic, connection); // add subscription to list of subscribers for receiving retained messages if (subscription != null) { SubscribersForRetained.Add(subscription); } }
private void OnMqttMsgUnsubscribeReceived(MqttConnection connection, ushort messageId, string[] topics) { for (var i = 0; i < topics.Length; i++) { subscriptionManager.Unsubscribe(topics[i], connection); } // send UNSUBACK message to the client outgoingMessageHandler.Unsuback(connection, messageId); }
/// <summary> /// 读数据线程 /// </summary> private void DoWork() { lock (m_locker) { try { var connArgs = new MqttConnectionArgs() { ClientId = m_clientId, Hostname = m_mqttServerAddress, Port = m_mqttPort, Keepalive = new TimeSpan(1, 0, 0) }; using (m_mqttClient = new MqttConnection(connArgs)) { m_mqttClient.Connect(); while (m_runFlag) { USeMarketData marketData = null; m_marketDataQueue.TryDequeue(out marketData); if (marketData == null) { Thread.Sleep(1000); continue; } Debug.WriteLine(string.Format("当前MQTT链接:{0}", connArgs.ClientId)); //[hanyu]暂时只推送上期的品种行情 if (marketData.Instrument.Market == USeMarket.SHFE || marketData.Instrument.Market == USeMarket.LME) { InternalSendTotMQTT(marketData); } } } } catch (Exception ex) { Debug.WriteLine(ex.Message); string text = string.Format("** {0}链接MQTT失败,{1}", this.StoreageName, ex.Message); m_eventLogger.WriteError(text); USeNotifyEventArgs notify = new USeNotifyEventArgs(USeNotifyLevel.Warning, text); SafeRaiseNotifyEvent(this, notify); } finally { m_mqttClient.Disconnect(); DoWork(); } } }
protected async override void OnStart() { App.MqttConnection = new MqttConnection(ServerName, Port, ClientID, Username, Password, TopicList); await App.MqttConnection.CreateMQTTConnection(); MqttConnection.OnConnected += MqttConnection_OnConnected; MqttConnection.OnDisconnected += MqttConnection_OnDisconnected; MqttConnection.OnErrorAtSending += MqttConnection_OnErrorAtSending; MqttConnection.OnMessageReceived += MqttConnection_OnMessageReceived; }
private void Send(MqttConnection connection, byte[] msgBytes) { try { mqttAsyncTcpSender.Send(connection.ReceiveSocketAsyncEventArgs.AcceptSocket, msgBytes); } catch (Exception) { //TODO } }
/// <summary> /// Add a subscriber for a topic /// </summary> /// <param name="topic">Topic for subscription</param> /// <param name="qosLevel">QoS level for the topic subscription</param> /// <param name="connection">Client to subscribe</param> public void Subscribe(string topic, byte qosLevel, MqttConnection connection) { if (IsWildcardSubscription(topic)) { SubscribeWithWildcard(topic, qosLevel, connection); } else { SubscribeWithoutWildcard(topic, qosLevel, connection); } }
/// <summary> /// Remove a subscriber for a topic /// </summary> /// <param name="topic">Topic for unsubscription</param> /// <param name="connection">Client to unsubscribe</param> public void Unsubscribe(string topic, MqttConnection connection) { if (IsWildcardSubscription(topic)) { UnsubscribeFromTopicWithWildcard(topic, connection); } else { UnsubscribeFromTopicWithoutWildcard(topic, connection); } }
public void ReloadApp() { var wasConnected = MqttConnection.IsConnected; MqttConnection.Connect(); // Reinitialize workers only if client was connected to the server before if (wasConnected) { MqttConnection.InitializeWorkers(); } }