public async Task StartAsyncSubscribesToTopics() { // Arrange var mockMqttConnection = new Mock <IMqttConnection>(); var mockTriggeredFunctionExecutor = new Mock <ITriggeredFunctionExecutor>(); mockMqttConnection .Setup(x => x.SubscribeAsync(It.IsAny <TopicFilter[]>())) .Returns(Task.CompletedTask); mockTriggeredFunctionExecutor .Setup(x => x.TryExecuteAsync(It.IsAny <TriggeredFunctionData>(), It.IsAny <CancellationToken>())); var topicFilter = new TopicFilter[] { new TopicFilter() { Topic = "test/topic", QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce } }; var mqttListener = new MqttListener(mockMqttConnection.Object, topicFilter, mockTriggeredFunctionExecutor.Object, _mockLogger.Object); // Act await mqttListener.StartAsync(_cancellationToken).ConfigureAwait(false); await mqttListener.OnMessage(new MqttMessageReceivedEventArgs(DefaultMessage)); // Shouldnt we be able to raise the IMqttConnection.OnMessageEventHandler?? // Assert mockMqttConnection.VerifyAll(); mockTriggeredFunctionExecutor.VerifyAll(); }
private MqttSubscriptionInterceptorContext InterceptSubscribe(TopicFilter topicFilter) { var interceptorContext = new MqttSubscriptionInterceptorContext(_clientId, topicFilter); _options.SubscriptionInterceptor?.Invoke(interceptorContext); return(interceptorContext); }
async static void SubscribeMQTT(string Topic) { try { //Step 1 Set QOS (0,1,2) var qos = MqttQualityOfServiceLevel.AtMostOnce; TopicFilter topicFilter = new TopicFilter(); topicFilter = new TopicFilter { Topic = Topic, QualityOfServiceLevel = qos }; if (_mqttClient != null) { if (_mqttClient.IsConnected) { await _mqttClient.SubscribeAsync(topicFilter); } } } catch (Exception ex) { //WriteToFile(string.Format("ERROR SUBSCRIBE : {0} {1}", ex.Message, DateTime.Now.ToString("dd MMM yyyy HH:mm"))); } }
public override bool StepExecute(int operatorUserID, string param, ref long offset, ref int totalCount, ref int finishedCount, out string title, out bool isLastStep) { StringList paramData = StringList.Parse(param); TopicFilter filter = TopicFilter.Parse(paramData[0]); AuthUser operatorUser = UserBO.Instance.GetAuthUser(operatorUserID); int stepCount; if (PostBOV5.Instance.ApproveSearchTopics(operatorUser, filter, stepApproveCount, out stepCount)) // .DeleteDoingsBySearch(filter, 200); { finishedCount += stepCount; isLastStep = stepCount < stepApproveCount; title = "正在审核主题,总数 " + totalCount + ",已审核 " + finishedCount; return(true); } else { isLastStep = false; title = "发生错误"; return(false); } }
public async Task StopAsyncUnsubscribesToTopics() { // Arrange var mockMqttConnection = new Mock <IMqttConnection>(); var mockTriggeredFunctionExecutor = new Mock <ITriggeredFunctionExecutor>(); mockMqttConnection .Setup(x => x.SubscribeAsync(It.IsAny <TopicFilter[]>())) .Returns(Task.CompletedTask); mockMqttConnection .Setup(x => x.UnubscribeAsync(It.IsAny <string[]>())) .Returns(Task.CompletedTask); var topicFilter = new TopicFilter[] { new TopicFilter() { Topic = "test/topic", QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce } }; var mqttListener = new MqttListener(mockMqttConnection.Object, topicFilter, mockTriggeredFunctionExecutor.Object, _mockLogger.Object); // Act await mqttListener.StartAsync(_cancellationToken).ConfigureAwait(false); await mqttListener.StopAsync(_cancellationToken).ConfigureAwait(false); // Assert mockMqttConnection.VerifyAll(); }
public async Task MessageForOtherTopicThanSubscribedToIsProcessed() { // Arrange var mockMqttConnection = new Mock <IMqttConnection>(); var mockTriggeredFunctionExecutor = new Mock <ITriggeredFunctionExecutor>(); mockMqttConnection .Setup(x => x.SubscribeAsync(It.IsAny <TopicFilter[]>())) .Returns(Task.CompletedTask); mockTriggeredFunctionExecutor .Setup(x => x.TryExecuteAsync(It.IsAny <TriggeredFunctionData>(), It.IsAny <CancellationToken>())); var topicFilter = new TopicFilter[] { new TopicFilter() { Topic = "test/topic", QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce } }; var mqttListener = new MqttListener(mockMqttConnection.Object, topicFilter, mockTriggeredFunctionExecutor.Object, _mockLogger.Object); // Act await mqttListener.StartAsync(_cancellationToken).ConfigureAwait(false); var message = new MqttMessage("weird", new byte[] { }, MqttQualityOfServiceLevel.AtLeastOnce, true); await mqttListener.OnMessage(new MqttMessageReceivedEventArgs(message)); // Assert mockMqttConnection.VerifyAll(); mockTriggeredFunctionExecutor.VerifyAll(); }
private void BtnSubscribe_Click(object sender, EventArgs e) { string topic = txtSubTopic.Text.Trim(); if (string.IsNullOrEmpty(topic)) { MessageBox.Show(@"订阅主题不能为空!"); return; } if (!mqttClient.IsConnected) { MessageBox.Show(@"MQTT客户端尚未连接!"); return; } var topicFilter = new TopicFilter { Topic = topic, QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce }; mqttClient.SubscribeAsync(topicFilter); txtReceiveMessage.AppendText($"已订阅[{topic}]主题" + Environment.NewLine); txtSubTopic.Enabled = false; btnSubscribe.Enabled = false; }
private async void Subscribe(object sender, RoutedEventArgs e) { try { var qos = MqttQualityOfServiceLevel.AtMostOnce; if (SubscribeQoS1.IsChecked == true) { qos = MqttQualityOfServiceLevel.AtLeastOnce; } if (SubscribeQoS2.IsChecked == true) { qos = MqttQualityOfServiceLevel.ExactlyOnce; } var topicFilter = new TopicFilter { Topic = SubscribeTopic.Text, QualityOfServiceLevel = qos }; if (_mqttClient != null) { await _mqttClient.SubscribeAsync(topicFilter); } if (_managedMqttClient != null) { await _managedMqttClient.SubscribeAsync(topicFilter); } } catch (Exception exception) { Trace.Text += exception + Environment.NewLine; } }
private void button1_Click(object sender, EventArgs e) { TopicFilter topicFilter = new TopicFilter(this.tbTopic.Text, MqttQualityOfServiceLevel.AtLeastOnce); _mqttServer.SubscribeAsync(clientId, new List <TopicFilter>() { topicFilter }); }
public MqttClientUnsubscribeOptionsBuilder WithTopicFilter(TopicFilter topicFilter) { if (topicFilter is null) { throw new ArgumentNullException(nameof(topicFilter)); } return(WithTopicFilter(topicFilter.Topic)); }
public void Topic_Set() { var topic = "Topic"; // act var filter = new TopicFilter(topic); // test Assert.Equal(topic, filter.Topic); }
public Task HandleClientSubscribedTopicAsync(string clientId, TopicFilter topicFilter) { var handler = ClientSubscribedTopicHandler; if (handler == null) { return(Task.FromResult(0)); } return(handler.HandleClientSubscribedTopicAsync(new MqttServerClientSubscribedTopicEventArgs(clientId, topicFilter))); }
/// <summary> /// 数据模型转换 /// </summary> /// <param name="topics"></param> /// <returns></returns> private static List <TopicFilter> ConvertTopics(List <Model.MyTopic> topics) { //MQTTnet.TopicFilter List <TopicFilter> filters = new List <TopicFilter>(); foreach (Model.MyTopic model in topics) { TopicFilter filter = new TopicFilter(model.Topic, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce); filters.Add(filter); } return(filters); }
private void ApproveSearchResult() { TopicFilter filter = TopicForm;//TopicFilter.GetFromFilter("filter"); StringList param = new StringList(); param.Add(filter.ToString()); if (TaskManager.BeginTask(MyUserID, new ApproveTopicTask(), param.ToString())) { } }
private async Task subscribeTopic(String param) { topic = param; var tfl = new List <TopicFilter>(); var tf = new TopicFilter(); tf.Topic = param; tfl.Add(tf); var mqttClientSubscribeOptions = new MqttClientSubscribeOptions(); mqttClientSubscribeOptions.TopicFilters = tfl; await mqttClient.SubscribeAsync(mqttClientSubscribeOptions, CancellationToken.None); }
private void DeletedSearchResult() { TopicFilter filter = TopicForm;//TopicFilter.GetFromFilter("filter"); StringList param = new StringList(); param.Add(filter.ToString()); param.Add(_Request.Get("updatePoint", Method.Post, "1")); if (TaskManager.BeginTask(MyUserID, new DeleteTopicTask(), param.ToString())) { } }
// GET: /<controller>/ public IActionResult Index(string s) { var logic = new TopicLogic(); var filter = new TopicFilter() { SearchTerms = s }; ViewBag.SearchTerms = s; ViewBag.Topics = logic.GetTopics(filter); return(View()); }
public MqttClientSubscribeOptionsBuilder WithTopicFilter(TopicFilter topicFilter) { if (topicFilter == null) { throw new ArgumentNullException(nameof(topicFilter)); } if (_subscribeOptions.TopicFilters == null) { _subscribeOptions.TopicFilters = new List <TopicFilter>(); } _subscribeOptions.TopicFilters.Add(topicFilter); return(this); }
public MqttConfig Create(INameResolver nameResolver, ILogger logger) { var options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(new MqttClientOptionsBuilder() .WithClientId(Guid.NewGuid().ToString()) .WithTcpServer(nameResolver.Resolve("MqttServer"), 1883) .WithCredentials(nameResolver.Resolve("MqttUsername"), nameResolver.Resolve("MqttPassword")) .Build()) .Build(); var topics = new TopicFilter[] { new TopicFilter("owntracks/kees/kees01", MqttQualityOfServiceLevel.ExactlyOnce) }; return(new MqttConfigExample(options, topics)); }
private void Button_OnClick(object sender, RoutedEventArgs e) { _mqttService = new MQTTService(); var mqttClientOptions = new Options { Server = "test.mosquitto.org", //Server = "192.168.0.41", Port = 1883, ConnectionType = ConnectionType.Tcp, CleanSession = true, ClientId = Guid.NewGuid().ToString().Replace("-", string.Empty), UseTls = false }; var topic1 = new TopicFilter { QualityOfServiceLevel = QoSLevel.AtLeastOnce, //Topic = "PP/#" Topic = "/#" }; ITopicFilter[] topicFilters = { topic1, }; var MQTTService = _mqttService.CreateObservableMQTTService(mqttClientOptions, topicFilters); _disposable = MQTTService .observableMessage .SubscribeOnDispatcher() //.Throttle(TimeSpan.FromMilliseconds(100), Scheduler.Default) .ObserveOnDispatcher().Subscribe( msg => { textBlock.Text = Encoding.UTF8.GetString(msg.Payload); }, ex => { textBlock.Text = "Exception"; }, () => { }); //var MQTTService = await mqttService.CreateObservableMQTTServiceAsync(mqttClientOptions, topicFilters); }
public async Task SafeNotifyClientSubscribedTopicAsync(string clientId, TopicFilter topicFilter) { try { var handler = ClientSubscribedTopicHandler; if (handler == null) { return; } await handler.HandleClientSubscribedTopicAsync(new MqttServerClientSubscribedTopicEventArgs(clientId, topicFilter)).ConfigureAwait(false); } catch (Exception exception) { _logger.Error(exception, "Error while handling custom 'ClientSubscribedTopic' event."); } }
public override void AfterExecute(int operatorUserID, string param, bool success, int totalCount, int finishedCount, out string title) { if (success) { title = "审核主题成功,共审核 " + finishedCount + " 个主题"; StringList paramData = StringList.Parse(param); TopicFilter filter = TopicFilter.Parse(paramData[0]); User operatorUser = UserBO.Instance.GetUser(operatorUserID, GetUserOption.WithAll); Logs.LogManager.LogOperation( new Topic_DeleteTopicBySearch(operatorUserID, operatorUser.Name, IPUtil.GetCurrentIP(), filter, finishedCount) ); } else { title = "审核主题失败"; } }
public override bool BeforeExecute(int operatorUserID, string param, ref long offset, ref int totalCount, out string title) { StringList paramData = StringList.Parse(param); TopicFilter filter = TopicFilter.Parse(paramData[0]); AuthUser operatorUser = UserBO.Instance.GetAuthUser(operatorUserID); ThreadCollectionV5 threads = PostBOV5.Instance.GetThreads(operatorUser, filter, 1); if (threads == null || threads.Count == 0) { title = "没有数据可以审核"; return(false); } totalCount = threads.TotalRecords; title = "将审核 " + totalCount + " 个主题"; return(true); }
private static MqttBasePacket DecodeSubscribePacket(IMqttPacketBodyReader body) { ThrowIfBodyIsEmpty(body); var packet = new MqttSubscribePacket { PacketIdentifier = body.ReadTwoByteInteger() }; while (!body.EndOfStream) { var topicFilter = new TopicFilter { Topic = body.ReadStringWithLengthPrefix(), QualityOfServiceLevel = (MqttQualityOfServiceLevel)body.ReadByte() }; packet.TopicFilters.Add(topicFilter); } return(packet); }
private SearchField MapTopicToField(TopicFilter topic) { var field = topic.EventDtoProperty.GetCustomAttribute <SearchField>() ?? new SearchField(topic.EventDtoProperty.Name) { IsSearchable = true, IsSortable = true, IsFilterable = true, IsFacetable = true, IsSuggester = true }; field.SourceProperty = topic.EventDtoProperty; field.DataType = topic.EventDtoProperty.PropertyType; if (string.IsNullOrEmpty(field.Name)) { field.Name = topic.EventDtoProperty.Name; } return(field); }
public List <Topic> GetTopics(TopicFilter filter = null) { if (filter != null) { IQueryable <Topic> query = FakeData.Topics; if (!string.IsNullOrEmpty(filter.SearchTerms)) { query = query.Where(a => a.Name.ToLower().Contains(filter.SearchTerms)); } if (filter.Limit > 0) { query.Take(filter.Limit); } return(query.ToList()); } else { return(FakeData.Topics.ToList()); } }
public async void SubscribeMQTT(string Topic) { try { //Step 1 Set QOS (0,1,2) var qos = MqttQualityOfServiceLevel.AtMostOnce; TopicFilter topicFilter = new TopicFilter(); topicFilter = new TopicFilter { Topic = Topic, QualityOfServiceLevel = qos }; if (_mqttClient != null) { await _mqttClient.SubscribeAsync(topicFilter); } } catch (Exception ex) { //throw ex; } }
private string BuilderSearchThreadCondition(TopicFilter filter, IEnumerable<Guid> excludeRoleIDs, SqlQuery query, bool startWithWhere) { SqlConditionBuilder condition; if (startWithWhere) condition = new SqlConditionBuilder(SqlConditionStart.Where); else condition = new SqlConditionBuilder(SqlConditionStart.None); condition += (filter.ForumID == null ? "" : ("AND [ForumID] = @ForumID ")); condition += (filter.UserID == null ? "" : ("AND [PostUserID] = @UserID ")); condition += (filter.TopicID == null ? "" : ("AND [ThreadID] = @TopicID ")); condition += (string.IsNullOrEmpty(filter.CreateIP) ? "" : ("AND [IPAddress] = @CreateIP ")); if (filter.Status == null) condition += (filter.IncludeStick == false ? "AND [ThreadStatus] = 1 " : ("AND [ThreadStatus] < 4 ")); else if (filter.Status.Value == ThreadStatus.Recycled) condition += ("AND [ThreadStatus] = 4 "); else if (filter.Status.Value == ThreadStatus.UnApproved) condition += ("AND [ThreadStatus] = 5 "); condition += (filter.IncludeValued == true ? "" : ("AND [IsValued] = 0 ")); condition += (filter.MinReplyCount == null ? "" : ("AND [TotalReplies] >= @MinReplyCount ")); condition += (filter.MaxReplyCount == null ? "" : ("AND [TotalReplies] <= @MaxReplyCount ")); condition += (filter.MinViewCount == null ? "" : ("AND [TotalViews] >= @MinViewCount ")); condition += (filter.MaxViewCount == null ? "" : ("AND [TotalViews] <= @MaxViewCount ")); condition += (filter.BeginDate == null ? "" : ("AND [CreateDate] > @BeginDate ")); condition += (filter.EndDate == null ? "" : ("AND [CreateDate] < @EndDate ")); if (string.IsNullOrEmpty(filter.KeyWord) == false) { if (filter.SearchMode == SearchArticleMethod.Subject) { condition += " AND [Subject] LIKE '%'+@keyword+'%' "; } else if (filter.SearchMode == SearchArticleMethod.FullText) { condition += " AND [Content] LIKE '%'+@keyword+'%' "; } else { condition += " AND ([Subject] LIKE '%'+@keyword+'%' OR [Content] LIKE '%'+@keyword+'%') "; } query.CreateParameter<string>("@keyword", filter.KeyWord, SqlDbType.NVarChar, 256); } condition.AppendAnd(DaoUtil.GetExcludeRoleSQL("[PostUserID]", excludeRoleIDs, query)); if (filter.ForumID != null) query.CreateParameter<int?>("@ForumID", filter.ForumID, SqlDbType.Int); if (string.IsNullOrEmpty(filter.CreateIP) == false) query.CreateParameter<string>("@CreateIP", filter.CreateIP, SqlDbType.NVarChar, 64); if (filter.TopicID != null) query.CreateParameter<int?>("@TopicID", filter.TopicID, SqlDbType.Int); if (filter.MaxReplyCount != null) query.CreateParameter<int?>("@MaxReplyCount", filter.MaxReplyCount, SqlDbType.Int); if (filter.MaxViewCount != null) query.CreateParameter<int?>("@MaxViewCount", filter.MaxViewCount, SqlDbType.Int); if (filter.MinReplyCount != null) query.CreateParameter<int?>("@MinReplyCount", filter.MinReplyCount, SqlDbType.Int); if (filter.MinViewCount != null) query.CreateParameter<int?>("@MinViewCount", filter.MinViewCount, SqlDbType.Int); if (filter.UserID != null) query.CreateParameter<int?>("@UserID", filter.UserID, SqlDbType.Int); if (filter.BeginDate != null) query.CreateParameter<DateTime?>("@BeginDate", filter.BeginDate, SqlDbType.DateTime); if (filter.EndDate != null) query.CreateParameter<DateTime?>("@EndDate", filter.EndDate, SqlDbType.DateTime); return condition.ToString(); }
public override ThreadCollectionV5 GetThreads(int pageNumber, TopicFilter filter, Guid[] excludeRoleIDs, ref int totalCount) { using (SqlQuery query = new SqlQuery()) { query.Pager.IsDesc = filter.IsDesc; switch (filter.Order) { case TopicFilter.OrderBy.TopicID: query.Pager.SortField = "ThreadID"; break; case TopicFilter.OrderBy.LastReplyDate: query.Pager.SortField = "UpdateDate"; break; case TopicFilter.OrderBy.ReplyCount: query.Pager.SortField = "TotalReplies"; break; default: query.Pager.SortField = "TotalViews"; break; } query.Pager.PageNumber = pageNumber; query.Pager.PageSize = filter.PageSize; query.Pager.TotalRecords = totalCount; query.Pager.SelectCount = true; query.Pager.TableName = "[bx_TopicsWithContents]"; query.Pager.Condition = BuilderSearchThreadCondition(filter, excludeRoleIDs, query, false); ThreadCollectionV5 threads; using (XSqlDataReader reader = query.ExecuteReader()) { threads = new ThreadCollectionV5(reader); if (reader.NextResult()) { if (reader.Read()) totalCount = reader.Get<int>(0); } return threads; } } }
public override DeleteResult DeleteSearchTopics(TopicFilter filter, IEnumerable<Guid> excludeRoleIDs, bool getDeleteResult, int topCount, out int deletedCount, out List<int> threadIDs) { using (SqlQuery query = new SqlQuery()) { string conditon = BuilderSearchThreadCondition(filter, excludeRoleIDs, query, false); query.CommandText = @" DECLARE @Table table(TempTopicID int,TempUserID int,TempForumID int,TempThreadStatus tinyint); INSERT INTO @Table SELECT TOP (@TopCount) [ThreadID],[PostUserID],[ForumID],[ThreadStatus] FROM [bx_TopicsWithContents] WITH (NOLOCK) WHERE " + conditon + @"; SELECT TempTopicID FROM @Table; --SELECT FileID FROM [bx_Attachments] WHERE PostID IN(SELECT PostID FROM [bx_Posts] WHERE ThreadID IN(SELECT TempTopicID FROM @Table)) -- AND FileID NOT IN(SELECT FileID FROM [bx_Attachments] WHERE PostID NOT IN(SELECT PostID FROM [bx_Posts] WHERE ThreadID IN(SELECT TempTopicID FROM @Table))); "; if (getDeleteResult) { query.CommandText += @" SELECT [TempUserID],[TempForumID],COUNT(*) AS [Count] FROM @Table WHERE TempThreadStatus<4 GROUP BY [TempUserID],[TempForumID];"; } query.CommandText = query.CommandText + @" DELETE [bx_Threads] WHERE ThreadID IN(SELECT TempTopicID FROM @Table); SELECT @@ROWCOUNT; "; query.CreateTopParameter("@TopCount", topCount); threadIDs = new List<int>(); // fileIDs = new List<string>(); deletedCount = 0; using (XSqlDataReader reader = query.ExecuteReader()) { DeleteResult deleteResult = new DeleteResult(); while (reader.Read()) { threadIDs.Add(reader.Get<int>("TempTopicID")); } //if (reader.NextResult()) //{ // while (reader.Read()) // { // fileIDs.Add(reader.Get<string>("FileID")); // } //} if (getDeleteResult) { if (reader.NextResult()) { while (reader.Read()) { deleteResult.Add(reader.Get<int>("TempUserID"), reader.Get<int>("Count"), reader.Get<int>("TempForumID")); } } } if (reader.NextResult()) { while (reader.Read()) { deletedCount = reader.Get<int>(0); } } return deleteResult; } } }
public MqttSubscriptionInterceptorContext(string clientId, TopicFilter topicFilter) { ClientId = clientId; TopicFilter = topicFilter ?? throw new ArgumentNullException(nameof(topicFilter)); }
public void OnClientSubscribedTopic(string clientId, TopicFilter topicFilter) { ClientSubscribedTopic?.Invoke(this, new MqttClientSubscribedTopicEventArgs(clientId, topicFilter)); }
public MqttClientSubscribedTopicEventArgs(string clientId, TopicFilter topicFilter) { ClientId = clientId ?? throw new ArgumentNullException(nameof(clientId)); TopicFilter = topicFilter ?? throw new ArgumentNullException(nameof(topicFilter)); }