EmulatorClientSocket.cs
11.2 KB
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
//-----------------------------------------------------------------------
// <copyright file="EmulatorClientSocket.cs" company="Google Inc.">
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
// This class is only used in the Editor, so make sure to only compile it on that platform.
// Additionally, If this class is compiled on Android then Unity will insert the INTERNET permission
// into the manifest because of the reference to the type TCPClient. Excluding this class in the android
// build ensures that it is only included if the developer using the SDK actually uses INTERNET related services.
// This MonoBehaviour is only ever instantiated dynamically, so it is fine that it is only compiled in the Editor,
// Otherwise it would cause serialization issues.
#if UNITY_EDITOR
using UnityEngine;
using System;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using proto;
/// @cond
namespace Gvr.Internal
{
public enum EmulatorClientSocketConnectionState
{
Disconnected = 0,
Connecting = 1,
Connected = 2,
}
class EmulatorClientSocket : MonoBehaviour
{
private static readonly int kPhoneEventPort = 7003;
private const int kSocketReadTimeoutMillis = 5000;
// Minimum interval, in seconds, between attempts to reconnect the socket.
private const float kMinReconnectInterval = 1f;
private TcpClient phoneMirroringSocket;
private Thread phoneEventThread;
private volatile bool shouldStop = false;
// Flag used to limit connection state logging to initial failure and successful reconnects.
private volatile bool lastConnectionAttemptWasSuccessful = true;
private EmulatorManager phoneRemote;
public EmulatorClientSocketConnectionState connected { get; private set; }
public void Init(EmulatorManager remote)
{
phoneRemote = remote;
if (EmulatorConfig.Instance.PHONE_EVENT_MODE != EmulatorConfig.Mode.OFF)
{
phoneEventThread = new Thread(phoneEventSocketLoop);
phoneEventThread.IsBackground = true;
phoneEventThread.Start();
}
}
private void phoneEventSocketLoop()
{
while (!shouldStop)
{
long lastConnectionAttemptTime = DateTime.Now.Ticks;
try
{
phoneConnect();
}
catch (Exception e)
{
if (lastConnectionAttemptWasSuccessful)
{
Debug.LogWarningFormat("{0}\n{1}", e.Message, e.StackTrace);
// Suppress additional failures until we have successfully reconnected.
lastConnectionAttemptWasSuccessful = false;
}
}
// Wait a while in order to enforce the minimum time between connection attempts.
TimeSpan elapsed = new TimeSpan(DateTime.Now.Ticks - lastConnectionAttemptTime);
float toWait = kMinReconnectInterval - (float)elapsed.TotalSeconds;
if (toWait > 0)
{
Thread.Sleep((int)(toWait * 1000));
}
}
}
private void phoneConnect()
{
string addr = EmulatorConfig.Instance.PHONE_EVENT_MODE == EmulatorConfig.Mode.USB
? EmulatorConfig.USB_SERVER_IP : EmulatorConfig.WIFI_SERVER_IP;
try
{
if (EmulatorConfig.Instance.PHONE_EVENT_MODE == EmulatorConfig.Mode.USB)
{
setupPortForwarding(kPhoneEventPort);
}
TcpClient tcpClient = new TcpClient(addr, kPhoneEventPort);
connected = EmulatorClientSocketConnectionState.Connecting;
ProcessConnection(tcpClient);
tcpClient.Close();
}
finally
{
connected = EmulatorClientSocketConnectionState.Disconnected;
}
}
private void setupPortForwarding(int port)
{
#if !UNITY_WEBPLAYER
string adbCommand = string.Format("adb forward tcp:{0} tcp:{0}", port);
System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
string processFilename;
string processArguments;
int kExitCodeCommandNotFound;
if (Application.platform == RuntimePlatform.WindowsEditor ||
Application.platform == RuntimePlatform.WindowsPlayer)
{
processFilename = "CMD.exe";
processArguments = @"/k " + adbCommand + " & exit";
// See "Common Error Lookup Tool" (https://www.microsoft.com/en-us/download/details.aspx?id=985)
// MSG_DIR_BAD_COMMAND_OR_FILE (cmdmsg.h)
kExitCodeCommandNotFound = 9009; // 0x2331
}
else
{ // Unix
processFilename = "bash";
processArguments = string.Format("-l -c \"{0}\"", adbCommand);
// "command not found" (see http://tldp.org/LDP/abs/html/exitcodes.html)
kExitCodeCommandNotFound = 127;
}
System.Diagnostics.ProcessStartInfo myProcessStartInfo =
new System.Diagnostics.ProcessStartInfo(processFilename, processArguments);
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardError = true;
myProcessStartInfo.CreateNoWindow = true;
myProcess.StartInfo = myProcessStartInfo;
myProcess.Start();
myProcess.WaitForExit();
// Also wait for HasExited here, to avoid ExitCode access below occasionally throwing InvalidOperationException
while (!myProcess.HasExited)
{
Thread.Sleep(1);
}
int exitCode = myProcess.ExitCode;
string standardError = myProcess.StandardError.ReadToEnd();
myProcess.Close();
if (exitCode == 0)
{
// Port forwarding setup successfully.
return;
}
if (exitCode == kExitCodeCommandNotFound)
{
// Caught by phoneEventSocketLoop.
throw new Exception(
"Android Debug Bridge (`adb`) command not found." +
"\nVerify that the Android SDK is installed and that the directory containing" +
" `adb` is included in your PATH environment variable.");
}
// Caught by phoneEventSocketLoop.
throw new Exception(
string.Format(
"Failed to setup port forwarding." +
" Exit code {0} returned by process: {1} {2}\n{3}",
exitCode, processFilename, processArguments, standardError));
#endif // !UNITY_WEBPLAYER
}
private void ProcessConnection(TcpClient tcpClient)
{
byte[] buffer = new byte[4];
NetworkStream stream = tcpClient.GetStream();
stream.ReadTimeout = kSocketReadTimeoutMillis;
tcpClient.ReceiveTimeout = kSocketReadTimeoutMillis;
while (!shouldStop)
{
int bytesRead = blockingRead(stream, buffer, 0, 4);
if (bytesRead < 4)
{
// Caught by phoneEventSocketLoop.
throw new Exception(
"Failed to read from controller emulator app event socket." +
"\nVerify that the controller emulator app is running.");
}
int msgLen = unpack32bits(correctEndianness(buffer), 0);
byte[] dataBuffer = new byte[msgLen];
bytesRead = blockingRead(stream, dataBuffer, 0, msgLen);
if (bytesRead < msgLen)
{
// Caught by phoneEventSocketLoop.
throw new Exception(
"Failed to read from controller emulator app event socket." +
"\nVerify that the controller emulator app is running.");
}
PhoneEvent proto =
PhoneEvent.CreateBuilder().MergeFrom(dataBuffer).Build();
phoneRemote.OnPhoneEvent(proto);
connected = EmulatorClientSocketConnectionState.Connected;
if (!lastConnectionAttemptWasSuccessful)
{
Debug.Log("Successfully connected to controller emulator app.");
// Log first failure after after successful read from event socket.
lastConnectionAttemptWasSuccessful = true;
}
}
}
private int blockingRead(NetworkStream stream, byte[] buffer, int index,
int count)
{
int bytesRead = 0;
while (!shouldStop && bytesRead < count)
{
try
{
int n = stream.Read(buffer, index + bytesRead, count - bytesRead);
if (n <= 0)
{
// Failed to read.
return -1;
}
bytesRead += n;
}
catch (IOException)
{
// Read failed or timed out.
return -1;
}
catch (ObjectDisposedException)
{
// Socket closed.
return -1;
}
}
return bytesRead;
}
void OnDestroy()
{
shouldStop = true;
if (phoneMirroringSocket != null)
{
phoneMirroringSocket.Close();
phoneMirroringSocket = null;
}
if (phoneEventThread != null)
{
phoneEventThread.Join();
}
}
private int unpack32bits(byte[] array, int offset)
{
int num = 0;
for (int i = 0; i < 4; i++)
{
num += array[offset + i] << (i * 8);
}
return num;
}
static private byte[] correctEndianness(byte[] array)
{
if (BitConverter.IsLittleEndian)
{
Array.Reverse(array);
}
return array;
}
}
}
/// @endcond
#endif // UNITY_EDITOR