Repository navigation
Expand file tree
/
Copy pathAdbClient.cs
More file actions
915 lines (759 loc) · 34 KB
/
Copy pathAdbClient.cs
File metadata and controls
915 lines (759 loc) · 34 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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
// <copyright file="AdbClient.cs" company="The Android Open Source Project, Ryan Conrad, Quamotion, yungd1plomat, wherewhere">
// Copyright (c) The Android Open Source Project, Ryan Conrad, Quamotion, yungd1plomat, wherewhere. All rights reserved.
// </copyright>
using AdvancedSharpAdbClient.Exceptions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Xml;
#if NET
using System.Runtime.Versioning;
#endif
namespace AdvancedSharpAdbClient
{
/// <summary>
/// <para>
/// Implements the <see cref="IAdbClient"/> interface, and allows you to interact with the
/// adb server and devices that are connected to that adb server.
/// </para>
/// <para>
/// For example, to fetch a list of all devices that are currently connected to this PC, you can
/// call the <see cref="GetDevices"/> method.
/// </para>
/// <para>
/// To run a command on a device, you can use the <see cref="ExecuteRemoteCommandAsync(string, DeviceData, IShellOutputReceiver, CancellationToken)"/>
/// method.
/// </para>
/// </summary>
/// <remarks><para><seealso href="https://github.com/android/platform_system_core/blob/master/adb/SERVICES.TXT">SERVICES.TXT</seealso></para>
/// <para><seealso href="https://github.com/android/platform_system_core/blob/master/adb/adb_client.c">adb_client.c</seealso></para>
/// <para><seealso href="https://github.com/android/platform_system_core/blob/master/adb/adb.c">adb.c</seealso></para></remarks>
public partial class AdbClient : IAdbClient
{
/// <summary>
/// The port at which the Android Debug Bridge server listens by default.
/// </summary>
public const int AdbServerPort = 5037;
/// <summary>
/// The default port to use when connecting to a device over TCP/IP.
/// </summary>
public const int DefaultPort = 5555;
/// <summary>
/// Gets a new instance of the <see cref="AdbClient"/> class.
/// </summary>
[Obsolete("This function has been removed since SharpAdbClient. Here is a placeholder which functon is gets a new instance instead of gets or sets the default instance.")]
public static IAdbClient Instance => new AdbClient();
private readonly Func<EndPoint, IAdbSocket> adbSocketFactory;
/// <summary>
/// Initializes a new instance of the <see cref="AdbClient"/> class.
/// </summary>
public AdbClient() : this(new IPEndPoint(IPAddress.Loopback, AdbServerPort), Factories.AdbSocketFactory)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AdbClient"/> class.
/// </summary>
/// <param name="endPoint">The <see cref="System.Net.EndPoint"/> at which the adb server is listening.</param>
/// <param name="adbSocketFactory">The <see cref="Func{EndPoint, IAdbSocket}"/> to create <see cref="IAdbSocket"/>.</param>
public AdbClient(EndPoint endPoint, Func<EndPoint, IAdbSocket> adbSocketFactory)
{
if (endPoint == null)
{
throw new ArgumentNullException(nameof(endPoint));
}
if (endPoint is not (IPEndPoint or DnsEndPoint))
{
throw new NotSupportedException("Only TCP endpoints are supported");
}
EndPoint = endPoint;
this.adbSocketFactory = adbSocketFactory ?? throw new ArgumentNullException(nameof(adbSocketFactory));
}
/// <summary>
/// Get or set default encoding
/// </summary>
public static Encoding Encoding { get; set; } = Encoding.UTF8;
/// <summary>
/// The Default <see cref="System.Net.EndPoint"/> at which the adb server is listening.
/// </summary>
public static EndPoint DefaultEndPoint => new IPEndPoint(IPAddress.Loopback, DefaultPort);
/// <summary>
/// Gets the <see cref="System.Net.EndPoint"/> at which the adb server is listening.
/// </summary>
public EndPoint EndPoint { get; private set; }
/// <summary>
/// Create an ASCII string preceded by four hex digits. The opening "####"
/// is the length of the rest of the string, encoded as ASCII hex(case
/// doesn't matter).
/// </summary>
/// <param name="req">The request to form.</param>
/// <returns>An array containing <c>####req</c>.</returns>
public static byte[] FormAdbRequest(string req)
{
int payloadLength = Encoding.GetByteCount(req);
string resultStr = string.Format("{0}{1}", payloadLength.ToString("X4"), req);
byte[] result = Encoding.GetBytes(resultStr);
return result;
}
/// <summary>
/// Creates the adb forward request.
/// </summary>
/// <param name="address">The address.</param>
/// <param name="port">The port.</param>
/// <returns>This returns an array containing <c>"####tcp:{port}:{addStr}"</c>.</returns>
public static byte[] CreateAdbForwardRequest(string address, int port)
{
string request = address == null ? $"tcp:{port}" : $"tcp:{port}:{address}";
return FormAdbRequest(request);
}
/// <inheritdoc/>
public int GetAdbVersion()
{
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SendAdbRequest("host:version");
AdbResponse response = socket.ReadAdbResponse();
string version = socket.ReadString();
return int.Parse(version, NumberStyles.HexNumber);
}
/// <inheritdoc/>
public void KillAdb()
{
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SendAdbRequest("host:kill");
// The host will immediately close the connection after the kill
// command has been sent; no need to read the response.
}
/// <inheritdoc/>
public List<DeviceData> GetDevices()
{
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SendAdbRequest("host:devices-l");
socket.ReadAdbResponse();
string reply = socket.ReadString();
string[] data = reply.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
return data.Select(DeviceData.CreateFromAdbData).ToList();
}
/// <inheritdoc/>
public int CreateReverseForward(DeviceData device, string remote, string local, bool allowRebind)
{
EnsureDevice(device);
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
string rebind = allowRebind ? string.Empty : "norebind:";
socket.SendAdbRequest($"reverse:forward:{rebind}{remote};{local}");
_ = socket.ReadAdbResponse();
_ = socket.ReadAdbResponse();
string portString = socket.ReadString();
return portString != null && int.TryParse(portString, out int port) ? port : 0;
}
/// <inheritdoc/>
public void RemoveReverseForward(DeviceData device, string remote)
{
EnsureDevice(device);
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest($"reverse:killforward:{remote}");
AdbResponse response = socket.ReadAdbResponse();
}
/// <inheritdoc/>
public void RemoveAllReverseForwards(DeviceData device)
{
EnsureDevice(device);
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest($"reverse:killforward-all");
AdbResponse response = socket.ReadAdbResponse();
}
/// <inheritdoc/>
public int CreateForward(DeviceData device, string local, string remote, bool allowRebind)
{
EnsureDevice(device);
using IAdbSocket socket = adbSocketFactory(EndPoint);
string rebind = allowRebind ? string.Empty : "norebind:";
socket.SendAdbRequest($"host-serial:{device.Serial}:forward:{rebind}{local};{remote}");
_ = socket.ReadAdbResponse();
_ = socket.ReadAdbResponse();
string portString = socket.ReadString();
return portString != null && int.TryParse(portString, out int port) ? port : 0;
}
/// <inheritdoc/>
public int CreateForward(DeviceData device, ForwardSpec local, ForwardSpec remote, bool allowRebind) =>
CreateForward(device, local?.ToString(), remote?.ToString(), allowRebind);
/// <inheritdoc/>
public void RemoveForward(DeviceData device, int localPort)
{
EnsureDevice(device);
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SendAdbRequest($"host-serial:{device.Serial}:killforward:tcp:{localPort}");
AdbResponse response = socket.ReadAdbResponse();
}
/// <inheritdoc/>
public void RemoveAllForwards(DeviceData device)
{
EnsureDevice(device);
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SendAdbRequest($"host-serial:{device.Serial}:killforward-all");
AdbResponse response = socket.ReadAdbResponse();
}
/// <inheritdoc/>
public IEnumerable<ForwardData> ListForward(DeviceData device)
{
EnsureDevice(device);
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SendAdbRequest($"host-serial:{device.Serial}:list-forward");
AdbResponse response = socket.ReadAdbResponse();
string data = socket.ReadString();
string[] parts = data.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
return parts.Select(ForwardData.FromString);
}
/// <inheritdoc/>
public IEnumerable<ForwardData> ListReverseForward(DeviceData device)
{
EnsureDevice(device);
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest($"reverse:list-forward");
AdbResponse response = socket.ReadAdbResponse();
string data = socket.ReadString();
string[] parts = data.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
return parts.Select(ForwardData.FromString);
}
/// <inheritdoc/>
public void ExecuteRemoteCommand(string command, DeviceData device, IShellOutputReceiver receiver) =>
ExecuteRemoteCommand(command, device, receiver, Encoding);
/// <inheritdoc/>
public void ExecuteRemoteCommand(string command, DeviceData device, IShellOutputReceiver receiver, Encoding encoding)
{
EnsureDevice(device);
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest($"shell:{command}");
AdbResponse response = socket.ReadAdbResponse();
try
{
using StreamReader reader = new(socket.GetShellStream(), encoding);
// Previously, we would loop while reader.Peek() >= 0. Turns out that this would
// break too soon in certain cases (about every 10 loops, so it appears to be a timing
// issue). Checking for reader.ReadLine() to return null appears to be much more robust
// -- one of the integration test fetches output 1000 times and found no truncations.
while (true)
{
string line = reader.ReadLine();
if (line == null) { break; }
receiver?.AddOutput(line);
}
}
finally
{
receiver?.Flush();
}
}
/// <inheritdoc/>
public Framebuffer CreateRefreshableFramebuffer(DeviceData device)
{
EnsureDevice(device);
return new Framebuffer(device, this);
}
/// <inheritdoc/>
public void Reboot(string into, DeviceData device)
{
EnsureDevice(device);
string request = $"reboot:{into}";
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest(request);
AdbResponse response = socket.ReadAdbResponse();
}
/// <inheritdoc/>
public string Pair(DnsEndPoint endpoint, string code)
{
if (endpoint == null)
{
throw new ArgumentNullException(nameof(endpoint));
}
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SendAdbRequest($"host:pair:{code}:{endpoint.Host}:{endpoint.Port}");
AdbResponse response = socket.ReadAdbResponse();
string results = socket.ReadString();
return results;
}
/// <inheritdoc/>
public string Connect(DnsEndPoint endpoint)
{
if (endpoint == null)
{
throw new ArgumentNullException(nameof(endpoint));
}
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SendAdbRequest($"host:connect:{endpoint.Host}:{endpoint.Port}");
AdbResponse response = socket.ReadAdbResponse();
string results = socket.ReadString();
return results;
}
/// <inheritdoc/>
public string Disconnect(DnsEndPoint endpoint)
{
if (endpoint == null)
{
throw new ArgumentNullException(nameof(endpoint));
}
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SendAdbRequest($"host:disconnect:{endpoint.Host}:{endpoint.Port}");
AdbResponse response = socket.ReadAdbResponse();
string results = socket.ReadString();
return results;
}
/// <inheritdoc/>
public void Root(DeviceData device) => Root("root:", device);
/// <inheritdoc/>
public void Unroot(DeviceData device) => Root("unroot:", device);
/// <inheritdoc/>
protected void Root(string request, DeviceData device)
{
EnsureDevice(device);
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest(request);
AdbResponse response = socket.ReadAdbResponse();
// ADB will send some additional data
byte[] buffer = new byte[1024];
int read = socket.Read(buffer);
string responseMessage = Encoding.UTF8.GetString(buffer, 0, read);
// see https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/master/daemon/restart_service.cpp
// for possible return strings
if (responseMessage.IndexOf("restarting", StringComparison.OrdinalIgnoreCase) == -1)
{
throw new AdbException(responseMessage);
}
else
{
// Give adbd some time to kill itself and come back up.
// We can't use wait-for-device because devices (e.g. adb over network) might not come back.
Utilities.Delay(3000).GetAwaiter().GetResult();
}
}
/// <inheritdoc/>
public List<string> GetFeatureSet(DeviceData device)
{
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SendAdbRequest($"host-serial:{device.Serial}:features");
AdbResponse response = socket.ReadAdbResponse();
string features = socket.ReadString();
List<string> featureList = features.Split(new char[] { '\n', ',' }).ToList();
return featureList;
}
/// <inheritdoc/>
public void Install(DeviceData device, Stream apk, params string[] arguments)
{
EnsureDevice(device);
if (apk == null)
{
throw new ArgumentNullException(nameof(apk));
}
if (!apk.CanRead || !apk.CanSeek)
{
throw new ArgumentOutOfRangeException(nameof(apk), "The apk stream must be a readable and seekable stream");
}
StringBuilder requestBuilder = new();
_ = requestBuilder.Append("exec:cmd package 'install' ");
if (arguments != null)
{
foreach (string argument in arguments)
{
_ = requestBuilder.Append(' ');
_ = requestBuilder.Append(argument);
}
}
// add size parameter [required for streaming installs]
// do last to override any user specified value
_ = requestBuilder.Append($" -S {apk.Length}");
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest(requestBuilder.ToString());
AdbResponse response = socket.ReadAdbResponse();
byte[] buffer = new byte[32 * 1024];
int read = 0;
while ((read = apk.Read(buffer, 0, buffer.Length)) > 0)
{
socket.Send(buffer, read);
}
read = socket.Read(buffer);
string value = Encoding.UTF8.GetString(buffer, 0, read);
if (!value.Contains("Success"))
{
throw new AdbException(value);
}
}
/// <inheritdoc/>
public string InstallCreated(DeviceData device, string packageName = null, params string[] arguments)
{
EnsureDevice(device);
StringBuilder requestBuilder = new();
_ = requestBuilder.Append("exec:cmd package 'install-create' ");
_ = requestBuilder.Append(packageName.IsNullOrWhiteSpace() ? string.Empty : $"-p {packageName}");
if (arguments != null)
{
foreach (string argument in arguments)
{
_ = requestBuilder.Append(' ');
_ = requestBuilder.Append(argument);
}
}
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest(requestBuilder.ToString());
AdbResponse response = socket.ReadAdbResponse();
using StreamReader reader = new(socket.GetShellStream(), Encoding);
string result = reader.ReadLine();
if (!result.Contains("Success"))
{
throw new AdbException(reader.ReadToEnd());
}
int arr = result.IndexOf("]") - 1 - result.IndexOf("[");
string session = result.Substring(result.IndexOf("[") + 1, arr);
return session;
}
/// <inheritdoc/>
public void InstallWrite(DeviceData device, Stream apk, string apkname, string session)
{
EnsureDevice(device);
if (apk == null)
{
throw new ArgumentNullException(nameof(apk));
}
if (!apk.CanRead || !apk.CanSeek)
{
throw new ArgumentOutOfRangeException(nameof(apk), "The apk stream must be a readable and seekable stream");
}
if (session == null)
{
throw new ArgumentNullException(nameof(session));
}
if (apkname == null)
{
throw new ArgumentNullException(nameof(apkname));
}
StringBuilder requestBuilder = new();
requestBuilder.Append($"exec:cmd package 'install-write' ");
// add size parameter [required for streaming installs]
// do last to override any user specified value
requestBuilder.Append($" -S {apk.Length}");
requestBuilder.Append($" {session} {apkname}.apk");
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest(requestBuilder.ToString());
AdbResponse response = socket.ReadAdbResponse();
byte[] buffer = new byte[32 * 1024];
int read = 0;
while ((read = apk.Read(buffer, 0, buffer.Length)) > 0)
{
socket.Send(buffer, read);
}
read = socket.Read(buffer);
string value = Encoding.UTF8.GetString(buffer, 0, read);
if (!value.Contains("Success"))
{
throw new AdbException(value);
}
}
/// <inheritdoc/>
public void InstallCommit(DeviceData device, string session)
{
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest($"exec:cmd package 'install-commit' {session}");
AdbResponse response = socket.ReadAdbResponse();
using StreamReader reader = new(socket.GetShellStream(), Encoding);
string result = reader.ReadLine();
if (!result.Contains("Success"))
{
throw new AdbException(reader.ReadToEnd());
}
}
/// <inheritdoc/>
public void InstallMultiple(DeviceData device, Stream baseapk, Stream[] splitapks, params string[] arguments)
{
EnsureDevice(device);
if (baseapk == null)
{
throw new ArgumentNullException(nameof(baseapk));
}
if (!baseapk.CanRead || !baseapk.CanSeek)
{
throw new ArgumentOutOfRangeException(nameof(baseapk), "The apk stream must be a readable and seekable stream");
}
string session = InstallCreated(device, null, arguments);
InstallWrite(device, baseapk, nameof(baseapk), session);
int i = 0;
foreach (Stream splitapk in splitapks)
{
if (splitapk == null || !splitapk.CanRead || !splitapk.CanSeek)
{
Debug.WriteLine("The apk stream must be a readable and seekable stream");
continue;
}
try
{
InstallWrite(device, splitapk, $"{nameof(splitapk)}{i++}", session);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
InstallCommit(device, session);
}
/// <inheritdoc/>
public void InstallMultiple(DeviceData device, Stream[] splitapks, string packageName, params string[] arguments)
{
EnsureDevice(device);
if (packageName == null)
{
throw new ArgumentNullException(nameof(packageName));
}
string session = InstallCreated(device, packageName, arguments);
int i = 0;
foreach (Stream splitapk in splitapks)
{
if (splitapk == null || !splitapk.CanRead || !splitapk.CanSeek)
{
Debug.WriteLine("The apk stream must be a readable and seekable stream");
continue;
}
try
{
InstallWrite(device, splitapk, $"{nameof(splitapk)}{i++}", session);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
InstallCommit(device, session);
}
/// <inheritdoc/>
public XmlDocument DumpScreen(DeviceData device)
{
XmlDocument doc = new();
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest("shell:uiautomator dump /dev/tty");
AdbResponse response = socket.ReadAdbResponse();
using StreamReader reader = new(socket.GetShellStream(), Encoding);
string xmlString = reader.ReadToEnd().Replace("Events injected: 1\r\n", "").Replace("UI hierchary dumped to: /dev/tty", "").Trim();
if (xmlString != "" && !xmlString.StartsWith("ERROR"))
{
doc.LoadXml(xmlString);
return doc;
}
return null;
}
/// <inheritdoc/>
public void Click(DeviceData device, Cords cords)
{
EnsureDevice(device);
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest(string.Format("shell:input tap {0} {1}", cords.X, cords.Y));
AdbResponse response = socket.ReadAdbResponse();
using StreamReader reader = new(socket.GetShellStream(), Encoding);
if (reader.ReadToEnd().ToUpper().Contains("ERROR")) // error or ERROR
{
throw new ElementNotFoundException("Coordinates of element is invalid");
}
}
/// <inheritdoc/>
public void Click(DeviceData device, int x, int y)
{
EnsureDevice(device);
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest(string.Format("shell:input tap {0} {1}", x, y));
AdbResponse response = socket.ReadAdbResponse();
using StreamReader reader = new(socket.GetShellStream(), Encoding);
if (reader.ReadToEnd().ToUpper().Contains("ERROR"))
{
throw new ElementNotFoundException("Coordinates of element is invalid");
}
}
/// <inheritdoc/>
public void Swipe(DeviceData device, Element first, Element second, long speed)
{
EnsureDevice(device);
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest(string.Format("shell:input swipe {0} {1} {2} {3} {4}", first.Cords.X, first.Cords.Y, second.Cords.X, second.Cords.Y, speed));
AdbResponse response = socket.ReadAdbResponse();
using StreamReader reader = new(socket.GetShellStream(), Encoding);
if (reader.ReadToEnd().ToUpper().Contains("ERROR"))
{
throw new ElementNotFoundException("Coordinates of element is invalid");
}
}
/// <inheritdoc/>
public void Swipe(DeviceData device, int x1, int y1, int x2, int y2, long speed)
{
EnsureDevice(device);
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest(string.Format("shell:input swipe {0} {1} {2} {3} {4}", x1, y1, x2, y2, speed));
AdbResponse response = socket.ReadAdbResponse();
using StreamReader reader = new(socket.GetShellStream(), Encoding);
if (reader.ReadToEnd().ToUpper().Contains("ERROR"))
{
throw new ElementNotFoundException("Coordinates of element is invalid");
}
}
/// <inheritdoc/>
public Element FindElement(DeviceData device, string xpath, TimeSpan timeout = default)
{
Stopwatch stopwatch = new();
stopwatch.Start();
while (timeout == TimeSpan.Zero || stopwatch.Elapsed < timeout)
{
XmlDocument doc = DumpScreen(device);
if (doc != null)
{
XmlNode xmlNode = doc.SelectSingleNode(xpath);
if (xmlNode != null)
{
string bounds = xmlNode.Attributes["bounds"].Value;
if (bounds != null)
{
int[] cords = bounds.Replace("][", ",").Replace("[", "").Replace("]", "").Split(',').Select(int.Parse).ToArray(); // x1, y1, x2, y2
Dictionary<string, string> attributes = new();
foreach (XmlAttribute at in xmlNode.Attributes)
{
attributes.Add(at.Name, at.Value);
}
Cords cord = new((cords[0] + cords[2]) / 2, (cords[1] + cords[3]) / 2); // Average x1, y1, x2, y2
return new Element(this, device, cord, attributes);
}
}
}
if (timeout == TimeSpan.Zero)
{
break;
}
}
return null;
}
/// <inheritdoc/>
public Element[] FindElements(DeviceData device, string xpath, TimeSpan timeout = default)
{
Stopwatch stopwatch = new();
stopwatch.Start();
while (timeout == TimeSpan.Zero || stopwatch.Elapsed < timeout)
{
XmlDocument doc = DumpScreen(device);
if (doc != null)
{
XmlNodeList xmlNodes = doc.SelectNodes(xpath);
if (xmlNodes != null)
{
Element[] elements = new Element[xmlNodes.Count];
for (int i = 0; i < elements.Length; i++)
{
string bounds = xmlNodes[i].Attributes["bounds"].Value;
if (bounds != null)
{
int[] cords = bounds.Replace("][", ",").Replace("[", "").Replace("]", "").Split(',').Select(int.Parse).ToArray(); // x1, y1, x2, y2
Dictionary<string, string> attributes = new();
foreach (XmlAttribute at in xmlNodes[i].Attributes)
{
attributes.Add(at.Name, at.Value);
}
Cords cord = new((cords[0] + cords[2]) / 2, (cords[1] + cords[3]) / 2); // Average x1, y1, x2, y2
elements[i] = new Element(this, device, cord, attributes);
}
}
return elements.Length == 0 ? null : elements;
}
}
if (timeout == TimeSpan.Zero)
{
break;
}
}
return null;
}
/// <inheritdoc/>
public void SendKeyEvent(DeviceData device, string key)
{
EnsureDevice(device);
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest(string.Format("shell:input keyevent {0}", key));
AdbResponse response = socket.ReadAdbResponse();
using StreamReader reader = new(socket.GetShellStream(), Encoding);
if (reader.ReadToEnd().ToUpper().Contains("ERROR"))
{
throw new InvalidKeyEventException("KeyEvent is invalid");
}
}
/// <inheritdoc/>
public void SendText(DeviceData device, string text)
{
EnsureDevice(device);
using IAdbSocket socket = adbSocketFactory(EndPoint);
socket.SetDevice(device);
socket.SendAdbRequest(string.Format("shell:input text {0}", text));
AdbResponse response = socket.ReadAdbResponse();
using StreamReader reader = new(socket.GetShellStream(), Encoding);
if (reader.ReadToEnd().ToUpper().Contains("ERROR"))
{
throw new InvalidTextException();
}
}
/// <inheritdoc/>
public void ClearInput(DeviceData device, int charcount)
{
SendKeyEvent(device, "KEYCODE_MOVE_END");
ExecuteRemoteCommandAsync("input keyevent " + Utilities.Join(" ", Enumerable.Repeat("KEYCODE_DEL ", charcount)), device, null, CancellationToken.None).Wait();
}
/// <inheritdoc/>
public void StartApp(DeviceData device, string packagename) =>
ExecuteRemoteCommand($"monkey -p {packagename} 1", device, null);
/// <inheritdoc/>
public void StopApp(DeviceData device, string packagename) =>
ExecuteRemoteCommand($"am force-stop {packagename}", device, null);
/// <inheritdoc/>
public void BackBtn(DeviceData device) => SendKeyEvent(device, "KEYCODE_BACK");
/// <inheritdoc/>
public void HomeBtn(DeviceData device) => SendKeyEvent(device, "KEYCODE_HOME");
/// <summary>
/// Sets default encoding (default - UTF8)
/// </summary>
/// <param name="encoding"></param>
public static void SetEncoding(Encoding encoding) => Encoding = encoding;
/// <summary>
/// Throws an <see cref="ArgumentNullException"/> if the <paramref name="device"/>
/// parameter is <see langword="null"/>, and a <see cref="ArgumentOutOfRangeException"/>
/// if <paramref name="device"/> does not have a valid serial number.
/// </summary>
/// <param name="device">A <see cref="DeviceData"/> object to validate.</param>
protected void EnsureDevice(DeviceData device)
{
if (device == null)
{
throw new ArgumentNullException(nameof(device));
}
if (string.IsNullOrEmpty(device.Serial))
{
throw new ArgumentOutOfRangeException(nameof(device), "You must specific a serial number for the device");
}
}
}
/// <summary>
/// See as the <see cref="AdbClient"/> class.
/// </summary>
[Obsolete("AdvancedAdbClient is too long to remember. Please use AdbClient instead.")]
public class AdvancedAdbClient : AdbClient
{
}
}