/
SharingStage.cs
244 lines (206 loc) · 8.17 KB
/
SharingStage.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
using HoloToolkit.Unity;
using System;
using UnityEngine;
namespace HoloToolkit.Sharing
{
public class SharingStage : Singleton<SharingStage>
{
/// <summary>
/// SharingManagerConnected event notifies when the sharing manager is created and connected.
/// </summary>
public event EventHandler SharingManagerConnected;
/// <summary>
/// Set whether this app should be a Primary or Secondary client.
/// Primary: Connects directly to the Session Server, can create/join/leave sessions
/// Secondary: Connects to a Primary client. Cannot do any session management
/// </summary>
public ClientRole ClientRole = ClientRole.Primary;
public string ServerAddress = "localhost";
public int ServerPort = 20602;
private SharingManager sharingMgr;
public SharingManager Manager { get { return this.sharingMgr; } }
/// <summary>
/// Set whether this app should provide audio input / output features.
/// </summary>
public bool IsAudioEndpoint = true;
public bool AutoDiscoverServer = false;
[Tooltip("Determines how often the discovery service should ping the network in search of a server.")]
public float PingIntervalSec = 2;
/// <summary>
/// Pipes XTools console output to Unity's output window for debugging
/// </summary>
private ConsoleLogWriter logWriter;
/// <summary>
/// Enables Server Discovery on the network
/// </summary>
private DiscoveryClient discoveryClient;
/// <summary>
/// Provides callbacks when server is discovered or lost.
/// </summary>
private DiscoveryClientAdapter discoveryClientAdapter;
/// <summary>
/// Provides callbacks for when we connect to a server.
/// </summary>
private NetworkConnectionAdapter networkConnectionAdapter = null;
private NetworkConnection networkConnection = null;
private float pingIntervalCurrent = 0;
private bool isTryingToFindServer = false;
private void Awake()
{
this.logWriter = new ConsoleLogWriter();
if (AutoDiscoverServer)
{
AutoDiscoverInit();
}
networkConnectionAdapter = new NetworkConnectionAdapter();
}
private void Start()
{
if (!AutoDiscoverServer)
{
Connect();
}
}
protected void OnDestroy()
{
if (this.discoveryClient != null)
{
discoveryClient.RemoveListener(discoveryClientAdapter);
discoveryClient.Dispose();
discoveryClient = null;
if (discoveryClientAdapter != null)
{
discoveryClientAdapter.Dispose();
discoveryClientAdapter = null;
}
}
if (this.networkConnection != null)
{
networkConnection.RemoveListener((byte)MessageID.StatusOnly, networkConnectionAdapter);
networkConnection.Dispose();
networkConnection = null;
if (networkConnectionAdapter != null)
{
networkConnectionAdapter.Dispose();
networkConnectionAdapter = null;
}
}
if (this.sharingMgr != null)
{
// Force a disconnection so that we can stop and start Unity without connections hanging around
this.sharingMgr.GetPairedConnection().Disconnect();
this.sharingMgr.GetServerConnection().Disconnect();
// Release the XTools manager so that it cleans up the C++ copy
this.sharingMgr.Dispose();
this.sharingMgr = null;
}
// Forces a garbage collection to try to clean up any additional reference to SWIG-wrapped objects
System.GC.Collect();
}
private void LateUpdate()
{
if (this.isTryingToFindServer)
{
AutoDiscoverUpdate();
}
if (this.sharingMgr != null)
{
// Update the XToolsManager to processes any network messages that have arrived
this.sharingMgr.Update();
}
}
private void OnEnable()
{
Application.logMessageReceived += HandleLog;
}
private void OnDisable()
{
Application.logMessageReceived -= HandleLog;
}
private void Connect()
{
ClientConfig config = new ClientConfig(this.ClientRole);
config.SetIsAudioEndpoint(this.IsAudioEndpoint);
config.SetLogWriter(this.logWriter);
config.SetServerAddress(this.ServerAddress);
config.SetServerPort(this.ServerPort);
config.SetProfilerEnabled(false);
this.sharingMgr = SharingManager.Create(config);
//set up callbacks so that we know when we've connected successfully
this.networkConnection = sharingMgr.GetServerConnection();
this.networkConnectionAdapter = new NetworkConnectionAdapter();
networkConnectionAdapter.ConnectedCallback += NetworkConnectionAdapter_ConnectedCallback;
networkConnection.AddListener((byte)MessageID.StatusOnly, networkConnectionAdapter);
}
private void NetworkConnectionAdapter_ConnectedCallback(NetworkConnection obj)
{
SendConnectedNotification();
}
private void SendConnectedNotification()
{
if (Manager.GetServerConnection().IsConnected())
{
//Send notification that we're connected
EventHandler connectedEvent = SharingManagerConnected;
if (connectedEvent != null)
{
connectedEvent(this, EventArgs.Empty);
}
}
else
{
Log.Error(string.Format("Cannot connect to server {0}:{1}", ServerAddress, ServerPort));
}
}
private void AutoDiscoverInit()
{
discoveryClientAdapter = new DiscoveryClientAdapter();
discoveryClientAdapter.DiscoveredEvent += OnSystemDiscovered;
discoveryClient = DiscoveryClient.Create();
discoveryClient.AddListener(discoveryClientAdapter);
//Start Finding Server
isTryingToFindServer = true;
}
private void AutoDiscoverUpdate()
{
//Searching Enabled-> Update DiscoveryClient to check results, Wait Interval then Ping network.
pingIntervalCurrent += Time.deltaTime;
if (pingIntervalCurrent > PingIntervalSec)
{
pingIntervalCurrent = 0;
discoveryClient.Ping();
}
discoveryClient.Update();
}
private void OnSystemDiscovered(DiscoveredSystem obj)
{
if (obj.GetRole() == SystemRole.SessionDiscoveryServerRole)
{
//Found a server. Stop pinging the network and connect
isTryingToFindServer = false;
this.ServerAddress = obj.GetAddress();
Debug.Log("System Discovered at: " + this.ServerAddress);
Connect();
Debug.Log(string.Format("Connected to: {0}:{1}", this.ServerAddress, this.ServerPort));
}
}
void HandleLog(string logString, string stackTrace, LogType type)
{
switch (type)
{
case LogType.Error:
case LogType.Assert:
case LogType.Exception:
Log.Error(string.Format("{0} \n {1}", logString, stackTrace));
break;
case LogType.Warning:
Log.Warning(string.Format("{0} \n {1}", logString, stackTrace));
break;
case LogType.Log:
default:
Log.Info(logString);
break;
}
}
}
}