/// <summary> /// MQTT subscribe to a topic. Remember, these subscriptionns are ephemeral. /// </summary> /// <param name="topicUriString"></param> /// <param name="qos"></param> /// <param name="action"></param> /// <returns></returns> public async Task SubscribeAsync(string topicUriString, QualityOfServiceLevelType qos, Action <string, string, byte[]> action) { try { Dictionary <string, QualityOfServiceLevelType> dict = new Dictionary <string, QualityOfServiceLevelType>(); dict.Add(topicUriString, qos); dispatcher.Register(topicUriString, action); SubscribeMessage msg = new SubscribeMessage(session.NewId(), dict); //if (channel.RequireBlocking) //{ // channel.SendAsync(msg.Encode()).GetAwaiter(); // //Task t = channel.SendAsync(msg.Encode()); // //Task.WaitAll(t); //} //else //{ await channel.SendAsync(msg.Encode()); //} } catch (Exception ex) { OnChannelError?.Invoke(this, new ChannelErrorEventArgs(channel.Id, ex)); } }
public void subscribe(String topic, QoS qos, Callback cb) //throws IOException { SubscribeMessage msg = new SubscribeMessage(topic, qos, this); msg.setMessageId(getNextMessageId()); sendCallbackMessage(msg, cb); }
private void OnLocalSubscribe(object sender, SubscribeMessage message) { foreach (var client in clients) { client.Subscribe(message).Wait(); } }
private void OnSubscribe(object sender, SubscribeMessage message) { if (!namespaceManager.TopicExists(message.Topic)) { namespaceManager.CreateTopic(message.Topic); } var gb = Guid.NewGuid().ToByteArray(); var subscriptionId = BitConverter.ToInt32(gb, 0); namespaceManager.CreateSubscription(message.Topic, subscriptionId.ToString()); var subscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, message.Topic, subscriptionId.ToString() , ReceiveMode.ReceiveAndDelete); subscriptionClients.Add(subscriptionId, subscriptionClient); var thread = new Thread(() => { while (true) { var sbMessage = subscriptionClient.Receive(); if (sbMessage != null) { var publicationId = long.Parse(sbMessage.MessageId); var payload = sbMessage.GetBody <string>(); RaiseEvent(new EventMessage(subscriptionId, publicationId, payload, null)); } } }); subscriptionThreads.Add(subscriptionId, thread); thread.Start(); Send(new SubscribedMessage(message.RequestId, subscriptionId)); }
public override async Task <MqttMessage> ProcessAsync() { if (!Session.IsConnected) { Session.Disconnect(Message); return(null); } Session.IncrementKeepAlive(); List <QualityOfServiceLevelType> list = new List <QualityOfServiceLevelType>(); SubscribeMessage msg = Message as SubscribeMessage; List <string> validSubs = Session.Subscribe(Message); IEnumerator <KeyValuePair <string, QualityOfServiceLevelType> > en = msg.Topics.GetEnumerator(); while (en.MoveNext()) { MqttUri uri = new MqttUri(en.Current.Key); QualityOfServiceLevelType qos = validSubs.Contains(uri.ToString()) ? en.Current.Value : QualityOfServiceLevelType.Failure; list.Add(qos); Session.AddQosLevel(uri.Resource, qos); } return(await Task.FromResult <MqttMessage>(new SubscriptionAckMessage(Message.MessageId, list))); }
public virtual async ValueTask <bool> SubscribeAsync( IPublication publication, SubscribeMessage subscribeMessage, CancellationToken cancellationToken) { var publicationId = publication.Id; if (Subscriptions.TryGetValue(publicationId, out var subscriptionProcessor)) { goto subscriptionExists; } lock (Lock) { // Double check locking if (Subscriptions.TryGetValue(publicationId, out subscriptionProcessor)) { goto subscriptionExists; } var publicationImpl = (IPublicationImpl)publication; subscriptionProcessor = publicationImpl.CreateSubscriptionProcessor(Channel, subscribeMessage); Subscriptions[publicationId] = subscriptionProcessor; } var _ = subscriptionProcessor.RunAsync() .ContinueWith(_ => UnsubscribeAsync(publication, default), CancellationToken.None); return(true); subscriptionExists: await subscriptionProcessor.OnMessageAsync(subscribeMessage, cancellationToken) .ConfigureAwait(false); return(true); }
/// <summary> /// MQTT subscribe to a topic. Remember, these subscriptions are ephemeral. /// </summary> /// <param name="subscriptions"></param> /// <returns></returns> public async Task SubscribeAsync(Tuple <string, QualityOfServiceLevelType, Action <string, string, byte[]> >[] subscriptions) { try { Dictionary <string, QualityOfServiceLevelType> dict = new Dictionary <string, QualityOfServiceLevelType>(); foreach (var tuple in subscriptions) { dict.Add(tuple.Item1, tuple.Item2); dispatcher.Register(tuple.Item1, tuple.Item3); } SubscribeMessage msg = new SubscribeMessage(session.NewId(), dict); //if (channel.RequireBlocking) //{ // channel.SendAsync(msg.Encode()).GetAwaiter(); // //Task t = channel.SendAsync(msg.Encode()); // //Task.WaitAll(t); //} //else //{ await channel.SendAsync(msg.Encode()); //} } catch (Exception ex) { OnChannelError?.Invoke(this, new ChannelErrorEventArgs(channel.Id, ex)); } }
public HistorianClientMock(SubscribeMessage subscribeMessage = null) { tags = new List <string>(); if (subscribeMessage != null) { tags.AddRange(subscribeMessage.Tags.Select(t => t.TagName)); } }
public void Subscribe(SubscribeMessage message) { message.DateReceived = DateTime.Now; var id = Guid.NewGuid(); var client = new WorkersHubClient(message, id.ToString(), this.Context.ConnectionId); this.session.AddWorker(client); }
public void AddEntry(SubscribeMessage message) { if (HashHistory.Count >= pubnubConfig.MaximumMessagesCacheSize) { HashHistory.Remove(HashHistory.Aggregate((l, r) => l.Value < r.Value ? l : r).Key); } HashHistory.Add(this.GetSubscribeMessageHashKey(message), Pubnub.TranslateDateTimeToPubnubUnixNanoSeconds(DateTime.UtcNow)); }
public async Task SubscribeAsync(string topic, QualityOfServiceLevelType qos, Action <string, string, byte[]> action) { Dictionary <string, QualityOfServiceLevelType> dict = new Dictionary <string, QualityOfServiceLevelType>(); dict.Add(topic, qos); dispatcher.Register(topic, action); SubscribeMessage msg = new SubscribeMessage(session.NewId(), dict); await channel.SendAsync(msg.Encode()); }
public void Subscribe(string topic, Qos qos = Qos.AtMostOnce) { var msg = new SubscribeMessage(); msg.FixedHeader.Qos = Qos.AtLeastOnce; msg.MessageIdentifier = 0; msg.Subscribe(topic, qos); conn.SendMessage(msg); }
protected SubscriptionProcessor( IPublicationImpl publication, Channel <Message> channel, SubscribeMessage subscribeMessage, ILogger?log = null) { Log = log ?? NullLogger.Instance; Publication = publication; Channel = channel; SubscribeMessage = subscribeMessage; AsyncLock = new AsyncLock(ReentryMode.CheckedPass, TaskCreationOptions.None); }
public async Task Subscribe(string symbol, CancellationToken cancellationToken = default) { if (socket.State != WebSocketState.Open) { throw new InvalidOperationException($"Subscribing is just possible when the socket is open. The socket's state is {socket.State}."); } var msg = new SubscribeMessage(symbol); var msgBytes = messageSerializer.Serialize(msg); await socket.SendAsync(msgBytes, WebSocketMessageType.Text, true, cancellationToken).ConfigureAwait(false); }
public void Subscribe() { //Socket socketListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); object[] poseSubscribe = { "/turtle1/pose", -1 }; SubscribeMessage m = new SubscribeMessage("/rosbridge/subscribe", poseSubscribe); _socket.Send(new byte[] { 0 }); _socket.Send(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(m))); _socket.Send(new byte[] { 255 }); System.Diagnostics.Debug.WriteLine("JSON published: " + JsonConvert.SerializeObject(m)); //debug }
private void Subscribe() { var subscribeMessage = new SubscribeMessage { Id = _random.Next(), Method = "SUBSCRIBE", Params = _channels }; _webSocketFeed.Send(JsonConvert.SerializeObject(subscribeMessage)); }
public void Subscribe(List <string> channels, List <string> productIds) { var subscribeMessage = new SubscribeMessage { Channels = channels, ProductsIds = productIds, Type = "subscribe" }; _webSocketFeed.Send(JsonConvert.SerializeObject(subscribeMessage)); }
public async Task <SubscribedMessage> Subscribe(SubscribeMessage message) { // TODO check for valid device id this.logger.LogDebug($"[{this.Context.ConnectionId}] Subscribe {message?.DeviceId ?? "none"}"); await this.Groups.AddToGroupAsync(this.Context.ConnectionId, message.DeviceId); //await this.Clients.Caller.Subscribed(new SubscribedMessage() { DeviceId = message.DeviceId}); return(new SubscribedMessage() { DeviceId = message.DeviceId }); }
public ValueTask <bool> SubscribeAsync( Channel <Message> channel, IPublication publication, bool sendUpdate, CancellationToken cancellationToken) { var message = new SubscribeMessage() { PublisherId = Id, PublicationId = Id, IsUpdateRequested = sendUpdate, }; return(SubscribeAsync(channel, publication, message, cancellationToken)); }
public async Task SubscribeAsync(Tuple <string, QualityOfServiceLevelType, Action <string, string, byte[]> >[] subscriptions) { Dictionary <string, QualityOfServiceLevelType> dict = new Dictionary <string, QualityOfServiceLevelType>(); foreach (var tuple in subscriptions) { dict.Add(tuple.Item1, tuple.Item2); dispatcher.Register(tuple.Item1, tuple.Item3); } SubscribeMessage msg = new SubscribeMessage(session.NewId(), dict); await channel.SendAsync(msg.Encode()); }
/// <summary> /// 存储消息 /// </summary> /// <param name="key"></param> /// <param name="subscribeMessage"></param> /// <returns></returns> public async Task StoreAsync(string key, SubscribeMessage subscribeMessage) { if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException(nameof(key)); } if (subscribeMessage == null) { throw new ArgumentNullException(nameof(subscribeMessage)); } logger.LogTrace("存储订阅的消息,key={key}", key); //存储消息,并设置90s有效期 await redisRepository.String.AddAsync(KeyPrefix + key, subscribeMessage, TimeSpan.FromSeconds(90)); }
protected virtual async Task SendWeChatTemplateMessagAsync(NotificationInfo notification, UserIdentifier identifier, CancellationToken cancellationToken = default) { var templateId = GetOrDefaultTemplateId(notification.Data); if (templateId.IsNullOrWhiteSpace()) { Logger.LogWarning("Wechat weapp template id be empty, can not send notification!"); return; } Logger.LogDebug($"Get wechat weapp template id: {templateId}"); var redirect = GetOrDefault(notification.Data, "RedirectPage", null); Logger.LogDebug($"Get wechat weapp redirect page: {redirect ?? "null"}"); var weAppState = GetOrDefault(notification.Data, "WeAppState", Options.DefaultWeAppState); Logger.LogDebug($"Get wechat weapp state: {weAppState ?? null}"); var weAppLang = GetOrDefault(notification.Data, "WeAppLanguage", Options.DefaultWeAppLanguage); Logger.LogDebug($"Get wechat weapp language: {weAppLang ?? null}"); var notificationData = NotificationData.ToStandardData(Options.DefaultMsgPrefix, notification.Data); // TODO: 如果微信端发布通知,请组装好 openid 字段在通知数据内容里面 string openId = GetOrDefault(notification.Data, AbpWeChatClaimTypes.OpenId, ""); if (openId.IsNullOrWhiteSpace()) { // 发送小程序订阅消息 await SubscribeMessager .SendAsync( identifier.UserId, templateId, redirect, weAppLang, weAppState, notificationData.Properties, cancellationToken); } else { var weChatWeAppNotificationData = new SubscribeMessage(templateId, redirect, weAppState, weAppLang); // 写入模板数据 weChatWeAppNotificationData.WriteData(notificationData.Properties); Logger.LogDebug($"Sending wechat weapp notification: {notification.Name}"); // 发送小程序订阅消息 await SubscribeMessager.SendAsync(weChatWeAppNotificationData, cancellationToken); } }
protected virtual ValueTask <bool> SubscribeAsync( Channel <Message> channel, IPublication publication, SubscribeMessage subscribeMessage, CancellationToken cancellationToken) { ThrowIfDisposedOrDisposing(); if (!ChannelProcessors.TryGetValue(channel, out var channelProcessor)) { return(ValueTaskEx.FalseTask); } if (publication.Publisher != this || publication.State.IsDisposed) { return(ValueTaskEx.FalseTask); } return(channelProcessor.SubscribeAsync(publication, subscribeMessage, cancellationToken)); }
/// <summary> /// MQTT subscribe to a topic. Remember, these subscriptionns are ephemeral. /// </summary> /// <param name="topicUriString"></param> /// <param name="qos"></param> /// <param name="action"></param> /// <returns></returns> public async Task SubscribeAsync(string topicUriString, QualityOfServiceLevelType qos, Action <string, string, byte[]> action) { try { Dictionary <string, QualityOfServiceLevelType> dict = new Dictionary <string, QualityOfServiceLevelType>(); dict.Add(topicUriString.ToLowerInvariant(), qos); dispatcher.Register(topicUriString.ToLowerInvariant(), action); SubscribeMessage msg = new SubscribeMessage(session.NewId(), dict); await channel.SendAsync(msg.Encode()); } catch (Exception ex) { OnChannelError?.Invoke(this, new ChannelErrorEventArgs(channel.Id, ex)); } }
public async Task SerializeSubscribeMessageLevel2Channel() { var message = SubscribeMessage.Create(new Level2Channel { Products = new List <string> { "XTZ-EUR" } }); var json = JsonSerializer.Serialize <FeedRequestMessage>(message, SerializerOptions); var expected = await File.ReadAllTextAsync("TestData/subscribe_level2.json"); json.ShouldBe(expected); }
public virtual async Task <dynamic> SendSubscribeMessageAsync(SubscribeMessage message) { if (message.miniprogram_state == null) { message.miniprogram_state = MiniprogramState.formal.ToString(); } if (message.lang == null) { message.lang = Language.zh_CN.ToString(); } var res = await SendRequest(message, CONSTANT.SUBSCRIBEMESSAGEURL, HttpMethod.Post); return(res); }
public OperationResult <string> Subscribe(string pairName, int period) { if (string.IsNullOrWhiteSpace(pairName) || period <= 0) { return(OperationResult <string> .Failure($"Параметры отписки на прослушку пары {nameof(pairName)}, {nameof(period)} не могут быть пустыми или null")); } var message = new SubscribeMessage { Event = MessageType.Subscribe, ChannelName = "candles", Key = $"trade:{period}m:t{pairName.ToUpper()}" }; return(OperationResult <string> .Success(JsonConvert.SerializeObject(message, _bitfinexJsonSettings))); }
private void OnSubscribe(object sender, SubscribeMessage message) { var subscriptionId = UniqueIdGenerationService.GenerateUniqueId(); if (!subscriptions.ContainsKey(message.Topic)) { cache.SubscribeAsync(message.Topic); subscriptions.Add(message.Topic, subscriptionId); } else { subscriptions[message.Topic] = subscriptionId; } Send(new SubscribedMessage(message.RequestId, subscriptionId)); }
private async Task SubscribeAsync(IEnumerable <FeedChannel> channels, CancellationToken cancellationToken) { if (_apiOptions.WebsocketFeedUri == null) { throw new InvalidOperationException(); } await _webSocket.ConnectAsync(_apiOptions.WebsocketFeedUri, cancellationToken); _log.LogInformation($"connected to {_apiOptions.WebsocketFeedUri}"); // To begin receiving feed messages, you must first send a subscribe message to the server indicating which channels and products // to receive. This message is mandatory - you will be disconnected if no subscribe has been received within 5 seconds. var message = SubscribeMessage.Create(channels); var bytes = JsonSerializer.SerializeToUtf8Bytes <FeedRequestMessage>(message, _serializerOptions); await _webSocket.SendAsync(bytes, WebSocketMessageType.Text, true, cancellationToken); }
public void TestPublishEligibleList(string uriString) { var firstCalled = false; var secondCalled = false; var thirdCalled = false; var uri = new Uri(uriString); _wampServer.AddSubscriptionChannel(uri); _wampServer.Start(config => { }); _wampServer.Start(config => { }); _wampServer.Start(config => { }); var connMock1 = _connections.First(); var connMock2 = _connections.Skip(1).First(); var connMock3 = _connections.Skip(2).First(); var subscribeMsg = new SubscribeMessage { TopicUri = uri }; connMock1.Object.OnSubscribe(subscribeMsg); connMock2.Object.OnSubscribe(subscribeMsg); connMock3.Object.OnSubscribe(subscribeMsg); connMock1.Setup(x => x.SendPublish(It.IsAny <PublishMessage>())).Callback(() => firstCalled = true); connMock2.Setup(x => x.SendPublish(It.IsAny <PublishMessage>())).Callback(() => secondCalled = true); connMock3.Setup(x => x.SendPublish(It.IsAny <PublishMessage>())).Callback(() => thirdCalled = true); var m = new PublishMessage { TopicUri = uri, Eligible = new HashSet <Guid>() { connMock2.Object.WebSocketConnectionInfo.Id } }; connMock1.Object.OnPublish(m); Assert.IsFalse(firstCalled); Assert.IsTrue(secondCalled); Assert.IsFalse(thirdCalled); }