UnitySubscriber.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. © Siemens AG, 2017-2018
  3. Author: Dr. Martin Bischoff (martin.bischoff@siemens.com)
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. <http://www.apache.org/licenses/LICENSE-2.0>.
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. using System.Threading;
  15. using UnityEngine;
  16. namespace RosSharp.RosBridgeClient
  17. {
  18. [RequireComponent(typeof(RosConnector))]
  19. public abstract class UnitySubscriber<T> : MonoBehaviour where T: Message
  20. {
  21. public string Topic;
  22. public float TimeStep;
  23. private RosConnector rosConnector;
  24. private readonly int SecondsTimeout = 1;
  25. protected virtual void Start()
  26. {
  27. rosConnector = GetComponent<RosConnector>();
  28. new Thread(Subscribe).Start();
  29. }
  30. private void Subscribe()
  31. {
  32. if (!rosConnector.IsConnected.WaitOne(SecondsTimeout * 1000))
  33. Debug.LogWarning("Failed to subscribe: RosConnector not connected");
  34. rosConnector.RosSocket.Subscribe<T>(Topic, ReceiveMessage, (int)(TimeStep * 1000)); // the rate(in ms in between messages) at which to throttle the topics
  35. }
  36. protected abstract void ReceiveMessage(T message);
  37. }
  38. }