/** * Add a subscriber callback to this connection. There can be many subscribers. */ public void AddSubscriber(Type subscriber) { //Multiple subscribers for the same topic possible IsValidSubscriber(subscriber); string topic = GetMessageTopic(subscriber); _subscribers.Add(subscriber); if (_running) { //only announce if not announced yet, if (!m_SubscribedTopics.Contains(topic)) { //Debug.Log("[ROS WEBSOCKET] Adding Subscriber. Subscribing to " + topic); _ws.Send(ROSBridgeMsg.Subscribe(GetMessageTopic(subscriber), GetMessageType(subscriber))); m_SubscribedTopics.Add(topic); } else { Debug.Log("[ROS WEBSOCKET] ALREADY subscribed to " + topic); } } else { Debug.Log("[ROS WEBSOCKET] couldn't subscribe to " + topic + ". Websocket not running."); } }
/// <summary> /// Announces all publishers and subscribers which were previously added to the lists _publishers and _subscriers /// </summary> private void AnnouncePublishersAndSubscribers() { if (_running && _ws != null) { foreach (Type p in _subscribers) { string topic = GetMessageTopic(p); //only announce if not already known that we subscribed if (!m_SubscribedTopics.Contains(topic)) { Debug.Log("[ROS WEBSOCKET] Subscribing to " + topic); _ws.Send(ROSBridgeMsg.Subscribe(topic, GetMessageType(p))); } m_SubscribedTopics.Add(topic); } foreach (Type p in _publishers) { string topic = GetMessageTopic(p); //only announce new publisher if we didn't already announce one for this topic if (!m_AnnouncedTopics.Contains(topic)) { Debug.Log("[ROS WEBSOCKET] Advertising " + topic); _ws.Send(ROSBridgeMsg.Advertise(topic, GetMessageType(p))); } m_AnnouncedTopics.Add(topic); } } else { Debug.LogWarning("[ROS WEBSOCKET] COuld not advertise/ subscribe since websocket not running."); } }
private void Run() { _ws = new WebSocket(_host + ":" + _port); _ws.OnMessage += (sender, e) => this.OnMessage(e.Data); _ws.Connect(); foreach (Type p in _subscribers) { _ws.Send(ROSBridgeMsg.Subscribe(GetMessageTopic(p), GetMessageType(p))); Debug.Log("Sending " + ROSBridgeMsg.Subscribe(GetMessageTopic(p), GetMessageType(p))); } foreach (Type p in _publishers) { _ws.Send(ROSBridgeMsg.Advertise(GetMessageTopic(p), GetMessageType(p))); Debug.Log("Sending " + ROSBridgeMsg.Advertise(GetMessageTopic(p), GetMessageType(p))); } while (true) { Thread.Sleep(1000); } }