RosConnector.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. © Siemens AG, 2017-2019
  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;
  15. using System.Threading;
  16. using RosSharp.RosBridgeClient.Protocols;
  17. using UnityEngine;
  18. namespace RosSharp.RosBridgeClient
  19. {
  20. public class RosConnector : MonoBehaviour
  21. {
  22. public int SecondsTimeout = 10;
  23. public RosSocket RosSocket { get; private set; }
  24. public RosSocket.SerializerEnum Serializer;
  25. public Protocol protocol;
  26. public string RosBridgeServerUrl = "ws://192.168.0.1:9090";
  27. public ManualResetEvent IsConnected { get; private set; }
  28. //modified
  29. public bool connected { get; set; }
  30. public virtual void Awake()
  31. {
  32. IsConnected = new ManualResetEvent(false);
  33. new Thread(ConnectAndWait).Start();
  34. //modified
  35. connected = false;
  36. DontDestroyOnLoad(this.gameObject);
  37. }
  38. protected void ConnectAndWait()
  39. {
  40. RosSocket = ConnectToRos(protocol, RosBridgeServerUrl, OnConnected, OnClosed, Serializer);
  41. if (!IsConnected.WaitOne(SecondsTimeout * 1000))
  42. Debug.LogWarning("Failed to connect to RosBridge at: " + RosBridgeServerUrl);
  43. }
  44. public static RosSocket ConnectToRos(Protocol protocolType, string serverUrl, EventHandler onConnected = null, EventHandler onClosed = null, RosSocket.SerializerEnum serializer = RosSocket.SerializerEnum.Microsoft)
  45. {
  46. IProtocol protocol = ProtocolInitializer.GetProtocol(protocolType, serverUrl);
  47. protocol.OnConnected += onConnected;
  48. protocol.OnClosed += onClosed;
  49. return new RosSocket(protocol, serializer);
  50. }
  51. private void OnApplicationQuit()
  52. {
  53. RosSocket.Close();
  54. }
  55. private void OnConnected(object sender, EventArgs e)
  56. {
  57. IsConnected.Set();
  58. Debug.Log("Connected to RosBridge: " + RosBridgeServerUrl);
  59. //modified
  60. connected = true;
  61. }
  62. private void OnClosed(object sender, EventArgs e)
  63. {
  64. IsConnected.Reset();
  65. Debug.Log("Disconnected from RosBridge: " + RosBridgeServerUrl);
  66. //modified
  67. connected = false;
  68. }
  69. }
  70. }