Exemple #1
0
 private void StartAdbServer()
 {
     try
     {
         log.Debug("Trying to connect to emulator");
         server = new AdbServer();
         server.StartServer(@"./resources/Android/adb.exe", restartServerIfNewer: false);
         client = (AdbClient)AdbClient.Instance;            // AdbClient.Instance.CreateAdbForwardRequest("localhost", 21503);
         device = AdbClient.Instance.GetDevices()[0];
         log.Debug("Connected to : " + device);
         log.Info("Đã kết nối đến máy : " + device.Name);
     }
     catch (Exception e)
     {
         client.KillAdb();
         log.Error("Không tìm thấy giả lập đang chạy : " + e.Data);
     }
 }
Exemple #2
0
        public void StartServerNotRunningTest()
        {
            this.adbSocketFactory = (endPoint) =>
            {
                throw new SocketException(AdbServer.ConnectionRefused);
            };

            this.adbClient = new AdbClient(AdbClient.DefaultEndPoint, this.adbSocketFactory);
            this.adbServer = new AdbServer(this.adbClient, this.adbCommandLineClientFactory);

            this.commandLineClient.Version = new Version(1, 0, 32);

            Assert.False(this.commandLineClient.ServerStarted);

            var result = this.adbServer.StartServer(this.ServerName, false);

            Assert.True(this.commandLineClient.ServerStarted);
        }
        private TcpClient startConnection()
        {
            Debug.Log("starting socket");
            tcpServer = new TcpListener(IPAddress.Parse(serverIP), hostPort);
            Debug.Log("waiting for device connection");
            tcpServer.Start();
            var acceptClientTask = tcpServer.AcceptTcpClientAsync();

            Debug.Log("starting android connection");
            //https://github.com/quamotion/madb
            var adbServer = new AdbServer();

            adbServer.StartServer(adbPath, true);
            adbClient = new AdbClient();
            var devices = adbClient.GetDevices();

            if (devices.Count == 0)
            {
                Debug.LogError("Error: Device not connected");
                return(null);
            }
            device = devices.Last();

            string command1  = @"am force-stop com.example.mediapipemultihandstrackingapp";
            var    receiver1 = new ConsoleOutputReceiver();

            adbClient.ExecuteRemoteCommand(command1, device, receiver1);
            Debug.Log("Stop remote app result: " + receiver1.ToString());

            Debug.Log("Resetting reverse connection");
            adbClient.RemoveAllReverseForwards(device);
            var reverseResult = adbClient.CreateReverseForward(
                device, "tcp:" + devicePort.ToString(), "tcp:" + hostPort.ToString(), true);

            string command2  = @"monkey -p com.example.mediapipemultihandstrackingapp -c android.intent.category.LAUNCHER 1";
            var    receiver2 = new ConsoleOutputReceiver();

            adbClient.ExecuteRemoteCommand(command2, device, receiver2);
            Debug.Log("Start remote app result: " + receiver2.ToString());

            return(acceptClientTask.Result);
        }
Exemple #4
0
        private static void RestartAction(AdbClient client, DeviceData device)
        {
            client.Reboot("device", device);

            Task.Factory.StartNew(async() =>
            {
                while (true)
                {
                    await Task.Delay(TimeSpan.FromSeconds(1));
                    var targetDevice = client.GetDevices().SingleOrDefault(d => d.Serial == device.Serial);

                    if (targetDevice != null && targetDevice.State == DeviceState.Online)
                    {
                        await Task.Delay(TimeSpan.FromSeconds(5));
                        ViewDevice(targetDevice);
                        return;
                    }
                }
            });
        }
Exemple #5
0
        internal static List <AndroidDevice> GetConnectedDevices()
        {
            List <AndroidDevice> androidDevices = new List <AndroidDevice>();

            try
            {
                AdbServer adb       = new AdbServer();
                var       result    = adb.StartServer(@"files/adb.exe", restartServerIfNewer: false);
                AdbClient adbClient = new AdbClient();
                var       devices   = adbClient.GetDevices();

                foreach (var item in devices)
                {
                    androidDevices.Add(new AndroidDevice(item.Model, item.Name, item.Product, item.Serial, item.State, item.TransportId, GetIMEI(item)));
                }
            }
            catch
            {
            }
            return(androidDevices);
        }
        static List <ProcInfo> GetProcs(AdbClient client, DeviceData device)
        {
            ConsoleOutputReceiver consoleOutput = new ConsoleOutputReceiver();

            client.ExecuteRemoteCommand("ps", device, consoleOutput);

            string[] lines = consoleOutput.ToString().Split("\r\n");

            if (lines.Length < 10)
            {
                // some devices require -A
                consoleOutput = new ConsoleOutputReceiver();
                client.ExecuteRemoteCommand("ps -A", device, consoleOutput);
                lines = consoleOutput.ToString().Split("\r\n");
            }

            //root             1     0   20264   2896 0                   0 S init
            //USER           PID  PPID     VSZ    RSS WCHAN            ADDR S NAME
            List <ProcInfo> procs = new List <ProcInfo>();

            string[] headers = lines[0].Split(' ').Where(n => n != "").ToArray();
            for (int c = 1; c < lines.Length; c++)
            {
                string[] parts = lines[c].Split(' ').Where(n => n != "").ToArray();
                if (parts.Length > 0)
                {
                    if (parts[0] != "system" && parts[0] != "root")
                    {
                        ProcInfo proc = new ProcInfo
                        {
                            User = parts[0],
                            Pid  = int.Parse(parts[1]),
                            Name = parts[8],
                        };
                        procs.Add(proc);
                    }
                }
            }
            return(procs);
        }
Exemple #7
0
        /// <summary>
        /// Запуск на выполнение выбранной в комбобоксе команды
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_ADB_comstart_Click(object sender, EventArgs e)
        {
            AdbClient         client  = new AdbClient();
            List <DeviceData> devices = new List <DeviceData>(client.GetDevices());
            var    device             = devices[0];
            string Com_String         = textBox_ADB_commandstring.Text;

            try
            {
                switch (comboBox_ADB_commands.SelectedIndex)
                {
                case 0:
                    textBox_ADB.AppendText("Устройство перегружается в аварийный режим" + Environment.NewLine);
                    client.Reboot("edl", device);
                    Thread.Sleep(1000);
                    StopAdb();
                    break;

                case 1:
                    GetADBIDs(false);
                    break;

                case 2:
                    if (!string.IsNullOrEmpty(Com_String))
                    {
                        Adb_Comm_String(Com_String);
                    }
                    break;

                default:
                    break;
                }
            }
            catch (SharpAdbClient.Exceptions.AdbException ex)
            {
                textBox_ADB.AppendText(ex.AdbError + Environment.NewLine);
            }
            button_ADB_comstart.Enabled = false;
        }
Exemple #8
0
        /// <summary>
        /// Reboots assigned devices
        /// modes are: recovery, bootloader, fastboot
        /// </summary>
        /// <param name="device"></param>
        internal static void RebootDevice(string mode, DeviceData device)
        {
            AdbClient adbClient = new AdbClient();

            adbClient.Reboot(mode, device);
        }
Exemple #9
0
        void Enslave(int virtualWid, int virtualHei)
        {
            Overseer = new Overseer(this);
            var adb = new AdbClient(AdbServer.Instance.EndPoint);

            // 初始化minicap
            adb.ExecuteRemoteCommand("getprop", Device, this);
            while (!flushed)
            {
                Thread.Sleep(100);
            }
            if (int.Parse(SDK) > 23)
            {
                throw new NotSupportedException($"SDK版本不支持:{SDK}");
            }
            try
            {
                adb.ExecuteRemoteCommand("mkdir /data/local", Device, null);
            }
            catch
            {
            }
            try
            {
                adb.ExecuteRemoteCommand("mkdir /data/local/tmp", Device, null);
            }
            catch
            {
            }
            try
            {
                adb.ExecuteRemoteCommand("chmpod -R 777 /data/local/tmp/", Device, null);
            }
            catch
            {
            }
            try
            {
                adb.ExecuteRemoteCommand($"mkdir {Program.GlobalSetting.Get("ContentPath").Value}", Device, null);
            }
            catch
            {
            }
            // 上传动态链接库
            new SyncService(Device).Push(
                File.OpenRead($@"{Program.usrDir + Program.DIR_LIBS}\android-{SDK}\{ABI}\minicap.so"),
                "/data/local/tmp/minicap.so", 777, DateTime.Now, CancellationToken.None);
            adb.ExecuteRemoteCommand("chmod 777 /data/local/tmp/minicap.so", Device, this);
            var exeFile = "minicap";

            if (int.Parse(SDK) < 16)
            {
                exeFile = "minicap-nopie";
            }
            // 上传可执行文件
            new SyncService(Device).Push(File.OpenRead(Program.usrDir + Program.DIR_EXE + ABI + @"\" + exeFile),
                                         "/data/local/tmp/minicap", 777, DateTime.Now, CancellationToken.None);
            adb.ExecuteRemoteCommand("chmod 777 /data/local/tmp/minicap", Device, this);
            // 分配端口
            ScreenPort     = Program.getFreePort(Program.ScreenPortBase);
            ManipulatePort = Program.getFreePort(Program.MonkeyPortBase);
            var touchFile = "minitouch";

            if (int.Parse(SDK) < 16)
            {
                touchFile = "minitouch-nopie";
            }
            new SyncService(Device).Push(
                File.OpenRead($@"{Program.usrDir}\bin\lib\touch\{ABI}\{touchFile}"), "/data/local/tmp/minitouch", 777, DateTime.Now, CancellationToken.None);
            adb.ExecuteRemoteCommand("chmod 777 /data/local/tmp/minitouch", Device, this);

            adb.CreateForward(Device,
                              new ForwardSpec()
            {
                Port = ManipulatePort, Protocol = ForwardProtocol.Tcp
            },
                              new ForwardSpec()
            {
                Protocol = ForwardProtocol.LocalAbstract, SocketName = "minitouch"
            }, true);

            ScreenService = new Screen(this, virtualWid, virtualHei);
            Manipulation  = new Manipulate(this);

            Overseer.WatchDirectory("/data/local/tmp/img/");
            Overseer.Watch(Program.GlobalSetting.Get("DroidLog").Value.ToString());
        }
Exemple #10
0
 public void FormAdbRequestTest()
 {
     Assert.Equal(Encoding.ASCII.GetBytes("0009host:kill"), AdbClient.FormAdbRequest("host:kill"));
     Assert.Equal(Encoding.ASCII.GetBytes("000Chost:version"), AdbClient.FormAdbRequest("host:version"));
 }
Exemple #11
0
        static void Main(string[] args)
        {
            Trace.Listeners.Add(new TextWriterTraceListener(errorFileName));
            Trace.AutoFlush = true;

            if (args.Any(c => c.ToLower() == "/armobs"))
            {
                if (args.Length == 1)
                {
                    var obs32List = Process.GetProcessesByName("obs32");
                    var obs64List = Process.GetProcessesByName("obs64");
                    if (obs32List.Length == 0 && obs64List.Length == 0)
                    {
                        //No OBS found. Cancel operation.
                        File.Delete(OBSUtils.obswszip);

                        return;
                    }
                    List <Process> obsProcesses = new List <Process>();
                    obsProcesses.AddRange(obs32List);
                    obsProcesses.AddRange(obs64List);

                    if (obsProcesses.Count != 1)
                    {
                        //Multiple OBS instances found. Cancel operation.
                        File.Delete(OBSUtils.obswszip);

                        return;
                    }
                    var obsProcess = obsProcesses.First();

                    string path = OBSUtils.GetProcessPath(obsProcess.Id);


                    string zipTempPath = Path.GetFileNameWithoutExtension(OBSUtils.obswszip);

                    OBSUtils.ExtractZip(OBSUtils.obswszip, zipTempPath);


                    OBSUtils.DirectoryCopy(zipTempPath, OBSUtils.GetPathFromOBSExecutable(path), true);

                    File.Delete(OBSUtils.obswszip);
                    Directory.Delete(zipTempPath, true);

                    var obsGlobalFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "obs-studio", "global.ini");

                    if (File.Exists(obsGlobalFilePath) && !File.ReadAllText(obsGlobalFilePath).Contains("[WebsocketAPI]"))
                    {
                        Trace.WriteLine("File exist and not contain web socket.");
                        while (!obsProcess.HasExited)
                        {
                            StringBuilder sb = new StringBuilder();
                            sb.AppendLine(Texts.rm.GetString("OBSINTEGRATIONINSTALL", Texts.cultereinfo));
                            sb.AppendLine("");
                            sb.AppendLine(Texts.rm.GetString("OBSINTEGRATIONAPPLY", Texts.cultereinfo));
                            MessageBox.Show(sb.ToString());
                        }

                        using (StreamWriter outputFile = new StreamWriter(obsGlobalFilePath))
                        {
                            outputFile.WriteLine("");
                            outputFile.WriteLine("[WebsocketAPI]");
                            outputFile.WriteLine("ServerPort=4444");
                            outputFile.WriteLine("DebugEnabled=false");
                            outputFile.WriteLine("AlertsEnabled=false");
                            outputFile.WriteLine("AuthRequired=false");
                        }

                        bool shouldRepeat = true;
                        while (shouldRepeat)
                        {
                            var obs32List2 = Process.GetProcessesByName("obs32");
                            var obs64List2 = Process.GetProcessesByName("obs64");

                            shouldRepeat = obs32List2.Length == 0 && obs64List2.Length == 0;
                            if (!shouldRepeat)
                            {
                                break;
                            }

                            StringBuilder sb = new StringBuilder();
                            sb.AppendLine(Texts.rm.GetString("OBSINTEGRATIONINSTALLSUCESSFULL", Texts.cultereinfo));
                            sb.AppendLine("");
                            sb.AppendLine(Texts.rm.GetString("OBSINTEGRATIONCONFIRMOBS", Texts.cultereinfo));
                            MessageBox.Show(sb.ToString());
                        }
                    }

                    return;
                }
            }

#if FORCE_SILENCE
            Silent = true;
#else
            Silent = args.Any(c => c.ToLower() == "/s");
#endif
            const string appName = "DisplayButtons";
            bool         createdNew;

            mutex = new Mutex(true, appName, out createdNew);

            if (!createdNew)
            {
                //app is already running! Exiting the application
                if (MessageBox.Show(Texts.rm.GetString("ALREADYDISPLAYBUTTONISOPEN", Texts.cultereinfo), Texts.rm.GetString("ALREADYDISPLAYBUTTONISOPENTITLE", Texts.cultereinfo), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    var myapp = Process.GetProcessesByName(Assembly.GetCallingAssembly().GetName().Name);

                    List <Process> obsProcesses = new List <Process>();
                    obsProcesses.AddRange(myapp);


                    if (obsProcesses.Count > 1)
                    {
                        var last = obsProcesses.First();
                        last.Kill();
                    }
                }
                //return;
            }


            Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;


            EventXml.LoadSettings();

            ApplicationSettingsManager.LoadSettings();
            Texts.initilizeLang();
            errorText = String.Format(Texts.rm.GetString("INTEGRATIONERROROCURRED", Texts.cultereinfo), errorFileName);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            OBSUtils.PrepareOBSIntegration();
            if (ApplicationSettingsManager.Settings.FirstRun)
            {
                FirstSetupForm firstRunForm = new FirstSetupForm();
                Application.Run(firstRunForm);
                if (!firstRunForm.FinishedSetup)
                {
                    return;
                }
            }
            //  EnsureBrowserEmulationEnabled("DisplayButtons.exe");

            new WebBrowserInstanceHelper().SetBrowserFeatureControl();

            dynamic form = Activator.CreateInstance(FindType("DisplayButtons.Forms.ActionHelperForms.MainFormMenuOption")) as Form;

            if (form.ShowDialog() == DialogResult.OK)
            {
                Initilizator.mode         = 0;
                Initilizator.ServerThread = new ServerThread();
                Initilizator.ServerThread.Start();


                Debug.WriteLine("MODO SOCKET CLIENT");
            }
            else
            {
                // Silent = true;
                Debug.WriteLine("MODO USB");
                Initilizator.mode = 1;

                Adbserver = new AdbServer();

                Adbserver.StartServer(Path.Combine(Application.StartupPath, @"Data\adb\adb.exe"), restartServerIfNewer: true);

                monitor = new DeviceMonitor(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)));
                client  = new AdbClient(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort), Factories.AdbSocketFactory);

                monitor.DeviceConnected    += MainForm.DeviceAdbConnected;
                monitor.DeviceDisconnected += MainForm.DeviceAdbDisconnected;
                monitor.Start();



                if (client.GetDevices().Count == 1)
                {
                    Debug.WriteLine("ONE DEVICE");



                    //   client.ExecuteRemoteCommand("am start -a android.intent.action.VIEW -e mode 1 net.nickac.DisplayButtons/.MainActivity", client.GetDevices().First(), null);

                    DevicePersistManager.PersistUsbMode(client.GetDevices().First());
                    //      client.CreateForward(client.GetDevices().First(), "tcp:5095", "tcp:5095", true);

                    Initilizator.ClientThread = new ClientThread();
                    Initilizator.ClientThread.Start();
                }
                else
                {
                    Initilizator.ClientThread = new ClientThread();
                }
            }
            Application.Run(new MainForm());


            //Application.Run(new MainFormMenuOption());
            OBSUtils.Disconnect();
            if (Initilizator.mode == 1)
            {
                foreach (var device in client.GetDevices().ToList())
                {
                    //   client.ExecuteRemoteCommand("am force-stop net.nickac.DisplayButtons", device, null);
                    // client.ExecuteRemoteCommand("kill-server", device, null);

                    //   client.KillAdb();
                }
            }

            //   client.KillAdb();
            EventXml.SaveSettings();
            ApplicationSettingsManager.SaveSettings();
            DevicePersistManager.SaveDevices();

            NetworkChange.NetworkAddressChanged      -= NetworkChange_NetworkAddressChanged;
            NetworkChange.NetworkAvailabilityChanged -= NetworkChange_NetworkAddressChanged;
            Trace.Flush();
        }
Exemple #12
0
 public void FormAdbRequestTest()
 {
     CollectionAssert.AreEqual(Encoding.ASCII.GetBytes("0009host:kill\n"), AdbClient.FormAdbRequest("host:kill"));
     CollectionAssert.AreEqual(Encoding.ASCII.GetBytes("000Chost:version\n"), AdbClient.FormAdbRequest("host:version"));
 }
Exemple #13
0
 public Form SetSlave(Slavery.Slave slave)
 {
     this.slave = slave;
     adb        = new AdbClient(AdbServer.Instance.EndPoint);
     return(this);
 }
Exemple #14
0
 public AndroidDevice(AdbClient client, DeviceData deviceData)
 {
     m_client     = client;
     m_deviceData = deviceData;
 }
Exemple #15
0
        private static async Task Main()
        {
            StartServerResult serverResult;
            var server = new AdbServer();

            try
            {
                serverResult = server.StartServer(@"C:\Program Files (x86)\Essential\ADB\adb.exe", false);
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("ADB path not found!");
                await Task.Delay(1500);

                return;
            }

            Console.WriteLine(serverResult == StartServerResult.Started
                ? "ADB server started!"
                : "ADB server already started!");

            DeviceData device;
            var        fastboot  = new Fastboot();
            var        connected = false;
            var        client    = new AdbClient();

            do
            {
                device = client.GetDevices().FirstOrDefault();
                if (device == null)
                {
                    Console.WriteLine("No adb devices found! Checking if system is in fastboot and sleeping 1.5s.");

                    try
                    {
                        fastboot.Connect();
                        Console.WriteLine("Found fastboot device!");
                        connected = true;
                    }
                    catch
                    {
                        Console.WriteLine("No fastboot devices found!");
                        await Task.Delay(1500);
                    }
                }
                else
                {
                    Console.WriteLine("Device found! Rebooting to bootloader.");

                    client.ExecuteRemoteCommand("reboot bootloader", device, null);
                }
            } while (device == null && !connected);

            FileInfo file;
            var      dirInfo    = new DirectoryInfo(@"C:\Users\Kuran Kaname\Downloads");
            bool     firstCycle = true;

            do
            {
                file = (from f in dirInfo.GetFiles(PatternDownloading) orderby f.LastWriteTime descending select f)
                       .FirstOrDefault() ??
                       (from f in dirInfo.GetFiles(Pattern) orderby f.LastWriteTime descending select f)
                       .FirstOrDefault();

                if (file?.Name.Contains("crdownload") ?? true)
                {
                    if (firstCycle)
                    {
                        Console.WriteLine();
                        firstCycle = false;
                    }

                    Console.WriteLine("File is still downloading! Sleeping 1.5s.");
                    await Task.Delay(1500);
                }
            } while (file?.Name.Contains("crdownload") ?? true);

            Console.WriteLine();
            Console.WriteLine($"Found file: {file.Name}");
            Console.WriteLine();

            while (!connected)
            {
                try
                {
                    fastboot.Connect();
                    connected = true;
                    Console.WriteLine("Fastboot device found!");
                }
                catch
                {
                    Console.WriteLine("No fastboot devices found! Sleeping 1.5s.");
                    await Task.Delay(1500);
                }
            }

            var slot = fastboot.Command("getvar:current-slot");

            Console.WriteLine($"Current slot is: {slot.Payload}");

            fastboot.UploadData($@"{file.Directory}\{file.Name}");

            string flashSlot;

            if (slot.Payload.Contains("a"))
            {
                flashSlot = "flash:boot_a";
            }
            else if (slot.Payload.Contains("b"))
            {
                flashSlot = "flash:boot_b";
            }
            else
            {
                Console.WriteLine("No slot found!");
                await Task.Delay(2500);

                return;
            }

            Fastboot.Response result = fastboot.Command(flashSlot);

            if (result.Status == Fastboot.Status.Okay)
            {
                Console.WriteLine("Flash succesful! Rebooting!");
                fastboot.Command("reboot");
            }
            else
            {
                Console.WriteLine($"Flash unsuccesful! Status: {result.Status}");
            }

            await Task.Delay(2500).ConfigureAwait(false);
        }
Exemple #16
0
        public Screen(Slave slave, int virtualWid, int virtualHei)
        {
            // initialize
            this.port = slave.ScreenPort;
            _dev      = slave;
            // 获取屏幕大小
            var adb = new AdbClient(AdbServer.Instance.EndPoint);

            adb.ExecuteRemoteCommand("dumpsys window", slave.Device, this);
            // 等待执行完毕
            while (!flushed)
            {
                Thread.Sleep(100);
            }
            // 运行
            new Thread(() =>
            {
                var realSiz    = $"{Width}x{Height}";
                var virtualSiz = $"{virtualWid}x{virtualHei}";
                // 启动minicap
                new AdbClient(AdbServer.Instance.EndPoint)
                .ExecuteRemoteCommand($"LD_LIBRARY_PATH=/data/local/tmp/ /data/local/tmp/minicap -S -P {realSiz}@{virtualSiz}/0", slave.Device, this);
            })
            {
                IsBackground = true
            }.Start();
            // 等待minicap服务启动
            Thread.Sleep(1000);
            // 转发
            AdbClient.Instance.CreateForward(slave.Device,
                                             new ForwardSpec()
            {
                Port = port, Protocol = ForwardProtocol.Tcp
            },
                                             new ForwardSpec()
            {
                Protocol = ForwardProtocol.LocalAbstract, SocketName = "minicap"
            },
                                             true);

            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            new Thread(() => {
#if DEBUG
                var secAccu   = 0.0;
                var frameAccu = 0;
#endif
                while (true)
                {
                    if (!started)
                    {
                        Thread.Sleep(100);
                        continue;
                    }

                    try
                    {
                        var before = DateTime.Now;
                        // 帧前4字节为长度
                        var lenBuf = new byte[4];
                        client.Receive(lenBuf, 4, SocketFlags.None);
                        var length = BitConverter.ToInt32(lenBuf, 0);
                        if (length <= 0)
                        {
                            // wrong frame
                            continue;
                        }
                        if (length / 1024 > 1000)
                        {
                            continue;
                        }
                        var frameBuf = new byte[length];
                        int len      = 0;
                        var ms       = new MemoryStream();
                        while (ms.Length < length)
                        {
                            len = client.Receive(frameBuf, length - (int)ms.Length, SocketFlags.None);
                            ms.Write(frameBuf, 0, len);
                        }
                        var imgBuffer = ms.ToArray();
                        // jpeg header
                        if ((imgBuffer[0] != 0xff || imgBuffer[1] != 0xD8))
                        {
                            continue;
                        }
                        var img = Image.FromStream(ms, true, true);
                        FrameArrived?.Invoke(slave.Device, this, img);
                        GC.Collect();

                        var subTime   = DateTime.Now.Subtract(before);
                        var frameTime = 1000 / frameLimiter;
                        //// 还没消耗够1frame所需的时间
                        //if (subTime.TotalMilliseconds < frameTime)
                        //{
                        //    Thread.Sleep(frameTime - (int)subTime.TotalMilliseconds);
                        //}
#if DEBUG
                        secAccu += subTime.TotalMilliseconds < frameTime ? frameTime : subTime.TotalMilliseconds;
                        if (secAccu >= 1000)
                        {
                            //Debug.WriteLine($"***************** frame rate: {frameAccu}");
                            frameAccu = 0;
                            secAccu   = 0;
                        }
                        //Debug.WriteLine($"frame size: {imgBuffer.Length / 1024} kB.");
                        //Debug.WriteLine($"proc time: {subTime.TotalMilliseconds} ms.");
                        ++frameAccu;
#endif
                    }
                    catch (Exception ex)
                    {
                        Program.Logs.WriteLog("读取帧字节出错!", ex.Message, Core.LogLevel.Exception);
                    }
                }
            })
            {
                IsBackground = true
            }.Start();
        }
Exemple #17
0
        static async Task RunTest(Dictionary <string, string> arguments)
        {
            processExitCancellationTokenSource = new CancellationTokenSource();

            if (arguments.ContainsKey("settings") && File.Exists(arguments["settings"]))
            {
                settingsXml = File.ReadAllText(arguments["settings"]);
            }

            System.Net.IPEndPoint testAdapterEndpoint = null;
            if (arguments.ContainsKey("remoteIp"))
            {
                var val = arguments["remoteIp"];
                if (val.Contains(":") && System.Net.IPAddress.TryParse(val.Split(':')[0], out System.Net.IPAddress ip) && int.TryParse(val.Split(':')[1], out int port))
                {
                    testAdapterEndpoint = new System.Net.IPEndPoint(ip, port);
                }
                else
                {
                    System.Console.WriteLine("Invalid remote ip and/or port");
                    testRunCompleted.TrySetResult(1);
                    return;
                }
            }
            if (testAdapterEndpoint != null)
            {
                await OnApplicationLaunched(testAdapterEndpoint);
            }
            else
            {
                // Launch Android android app
                client = new AdbClient();
                var devices = await client.GetDevicesAsync();

                if (!devices.Any())
                {
                    System.Console.WriteLine("No devices connected to ADB");
                    testRunCompleted.TrySetResult(1);
                    return;
                }
                if (arguments.ContainsKey("deviceid"))
                {
                    device = devices.Where(d => d.Serial == arguments["deviceid"]).FirstOrDefault();
                    if (device == null)
                    {
                        System.Console.WriteLine($"ERROR Device '{arguments["deviceid"]}' not found");
                        testRunCompleted.TrySetResult(1);
                        return;
                    }
                }
                if (device == null)
                {
                    if (devices.Count() > 1)
                    {
                        System.Console.WriteLine($"ERROR. Multiple devices connected. Please specify -deviceId <deviceid>");
                        foreach (var d in devices)
                        {
                            System.Console.WriteLine($"\t{d.Serial}\t{d.Name}\t{d.Model}\t{d.Product}\t{d.State}");
                        }
                        testRunCompleted.TrySetResult(1);
                        return;
                    }
                    device = devices.First();
                }
                if (arguments.ContainsKey("apkid"))
                {
                    apk_id = arguments["apkid"];
                }
                if (arguments.ContainsKey("activity"))
                {
                    activityName = arguments["activity"];
                }

                await ShutdownApp();

                if (arguments.ContainsKey("apkpath"))
                {
                    var path = arguments["apkpath"];
                    if (!File.Exists(path))
                    {
                        System.Console.WriteLine("ERROR. APK Not Found: " + path);
                        testRunCompleted.TrySetResult(1);
                    }
                    if (apk_id == null || activityName == null)
                    {
                        string id;
                        string name;
                        ApkHelper.GetAPKInfo(path, out id, out name);
                        if (apk_id == null)
                        {
                            apk_id = id;
                        }
                        if (activityName == null)
                        {
                            activityName = name;
                        }
                    }
                    System.Console.WriteLine("Installing app...");
                    await device.InstallApk(path);
                }

                // Get unlock state
                var state = await device.GetPowerState();

                if (!state.IsDisplayOn)
                {
                    await device.TurnOnDisplayAsync();

                    while (!state.IsDisplayOn)
                    {
                        await Task.Delay(500);

                        state = await device.GetPowerState();
                    }
                }

                if (state.DisplayState == Device.DisplayState.OnAndLocked)
                {
                    if (arguments.ContainsKey("pin"))
                    {
                        string pin = null;
                        if (int.TryParse(arguments["pin"], out int numericPin)) //Ensures it's numeric
                        {
                            pin = arguments["pin"];
                        }
                        System.Console.WriteLine("Unlocking phone...");
                        await device.UnlockAsync(pin);
                    }
                    else
                    {
                        System.Console.WriteLine("Device appears to be locked. Please unlock your device");
                        //    System.Console.ReadKey();
                    }
                }
                if (File.Exists("RunLog.txt"))
                {
                    File.Delete("RunLog.txt");
                }

                if (arguments.ContainsKey("logFileName"))
                {
                    outputFilename = arguments["logFileName"];
                }
                else
                {
                    string defaultFilename = device.Serial + "_" + DateTime.Now.ToString("yyyy-MM-dd_HH_mm_ss");
                    if (apk_id != null)
                    {
                        defaultFilename += "_" + apk_id;
                    }
                    outputFilename = Path.Combine(System.Environment.CurrentDirectory, defaultFilename + ".trx");
                }

                monitor = new LogCatMonitor(device.Serial);
                // Connecting to logcat...
                await client.SendDeviceCommandAsync("shell:logcat -b all -c", device.Serial); //Configure logcat

                bool result;
                if (device.ApiLevel > 22)
                {
                    result = await monitor.OpenAsync($"{apk_id} -T 1");
                }
                else
                {
                    result = await monitor.OpenAsync($"");
                }
                if (result)
                {
                    System.Console.WriteLine("Connected logcat to " + device.Serial);
                }
                else
                {
                    System.Console.WriteLine("Failed to connect to LogCat");
                    return;
                }
                monitor.LogReceived += Monitor_LogReceived;

                await device.SetPortForward(38300, 38300);  //Set up port forwarding for socket communication

                System.Console.WriteLine($"Launching app {apk_id}/{activityName} on device " + device.Serial + "...");

                await device.LaunchApp(apk_id, activityName, new Dictionary <string, object>() { { "TestAdapterPort", 38300 } });

                // Keep looking for process starting up
                bool launched = false;
                while (!launched)
                {
                    await Task.Delay(1000);

                    var pid = await device.GetProcessId(apk_id);

                    if (appLaunchDetected)
                    {
                        break;
                    }
                    if (pid > 0)
                    {
                        launched = true;
                        System.Console.WriteLine($"Test Host Launched. Process ID '{pid}'");
                        OnApplicationLaunched();
                        break;
                    }
                    else
                    {
                        //Keep retrying. Doesn't always launch the first time
                        await device.LaunchApp(apk_id, activityName, new Dictionary <string, object>() { { "TestAdapterPort", 38300 } });
                    }
                }
            }
        }
Exemple #18
0
        static void Main(string[] args)
        {
            try
            {
                var adbClient = new AdbClient();

                var version = 0;
                try
                {
                    version = adbClient.GetServerVersion();
                }
                catch
                {
                    Console.WriteLine("ADB server is not running, trying to start it");
                    adbClient.StartServer();
                    version = adbClient.GetServerVersion();
                }

                Console.WriteLine($"ADB server version {version} running on {adbClient.ServerHost} port {adbClient.ServerPort}");

                Console.WriteLine();

                var devices = adbClient.GetDevices();

                if (0 == devices.Length)
                {
                    Console.WriteLine("No Android devices are connected");
                    return;
                }

                Console.WriteLine($"Connected Android devices ({devices.Length}):");
                foreach (var device in devices)
                {
                    Console.WriteLine($"{device}");
                }

                Console.WriteLine();

                adbClient.SetDevice(devices[0].SerialNumber);
                Console.WriteLine($"Connected to device {devices[0].SerialNumber}");

                Console.WriteLine();

                var props = adbClient.GetDeviceProperties();
                Console.WriteLine($"{props.Count} properties:");
                foreach (var prop in props)
                {
                    Console.WriteLine($"{prop.Key}={prop.Value}");
                }

                Console.WriteLine();

                Console.WriteLine($"Manufacturer: {props["ro.product.manufacturer"]}");
                Console.WriteLine($"Model: {props["ro.product.model"]}");
                Console.WriteLine($"Android version: {props["ro.build.version.release"]}");
                Console.WriteLine($"Android SDK: {props["ro.build.version.sdk"]}");

                Console.WriteLine();

                var response = adbClient.ExecuteRemoteCommand("ls -l /mnt/sdcard/DCIM/Camera");
                Console.WriteLine($"Result:\n{String.Join("\r\n", response)}");

                Console.WriteLine();

                var fileInfos = adbClient.GetDirectoryListing("/mnt/sdcard/DCIM/Camera");
                Console.WriteLine($"{fileInfos.Length} files:");
                foreach (var fileInfo in fileInfos)
                {
                    Console.WriteLine($"{fileInfo.Name} {fileInfo.Size} {fileInfo.Mode:X04} {fileInfo.FullName}");

                    var fileInfo2 = adbClient.GetFileInfo(fileInfo.FullName);
                    Console.WriteLine($"{fileInfo2.Name} {fileInfo2.Size} {fileInfo2.Mode:X04} {fileInfo2.FullName}");

                    if (fileInfo.IsFile)
                    {
                        var now = DateTime.Now;
                        adbClient.DownloadFile(fileInfo.FullName, @"C:\Temp\" + fileInfo.Name);
                        var sec = (DateTime.Now - now).TotalMilliseconds / 1000;
                        Console.WriteLine($"Downloaded: {fileInfo.Size / 1024 / sec:N0} KB/s ({fileInfo.Size} bytes in {sec:N3}s)");
                    }
                }

                Console.WriteLine();

                var fileInfo1 = fileInfos[0];
                Console.WriteLine($"{fileInfo1.Name} {fileInfo1.Size} {fileInfo1.Mode:X04} {fileInfo1.FullName}");

                var now1 = DateTime.Now;
                adbClient.UploadFile(@"C:\Temp\" + fileInfo1.Name, "/mnt/sdcard/DCIM");
                var sec1 = (DateTime.Now - now1).TotalMilliseconds / 1000;
                Console.WriteLine($"Uploaded: {fileInfo1.Size / 1024 / sec1:N0} KB/s ({fileInfo1.Size} bytes in {sec1:N3}s)");

                Console.WriteLine();

                response = adbClient.ExecuteRemoteCommand("ls -l /mnt/sdcard/DCIM");
                Console.WriteLine($"Result:\n{String.Join("\r\n", response)}");

                Console.WriteLine();

                adbClient.InstallApplication(@"C:\Temp\MP3Tube_v1.0_apkpure.com.apk", false);
                Console.WriteLine("Application installed");

                Console.WriteLine();

                adbClient.UninstallApplication("angel.engmp3tube");
                Console.WriteLine("Application uninstalled");

                Console.WriteLine();

                var apps = adbClient.GetInstalledApplications();
                foreach (var app in apps)
                {
                    Console.WriteLine($"{app.Name}\t{app.Location}\t{app.Type}\t{app.FileName}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[Exception] {ex.Message}");
            }
        }
Exemple #19
0
 public void CreateAdbForwardRequestTest()
 {
     CollectionAssert.AreEqual(Encoding.ASCII.GetBytes("0008tcp:1984\n"), AdbClient.CreateAdbForwardRequest(null, 1984));
     CollectionAssert.AreEqual(Encoding.ASCII.GetBytes("0012tcp:1981:127.0.0.1\n"), AdbClient.CreateAdbForwardRequest("127.0.0.1", 1981));
 }
 internal Communicator()
 {
     DeviceMonitor = new DeviceMonitor(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)));
     Client        = new AdbClient();
 }
        static void Main(string[] args)
        {
            Console.WriteLine("Connecting to the ADB server. Please wait..");

            AdbServer       server        = new AdbServer();
            AdbServerStatus currentStatus = server.GetStatus();

            StartServerResult startStatus = server.StartServer(ConfigurationManager.AppSettings["AdbPath"], restartServerIfNewer: false);

            switch (startStatus)
            {
            case StartServerResult.AlreadyRunning:
                Console.WriteLine("ADB daemon already running.");
                break;

            case StartServerResult.RestartedOutdatedDaemon:
                Console.WriteLine("Restarted outdated ADB daemon.");
                break;

            case StartServerResult.Started:
                Console.WriteLine("ADB daemon has been started.");
                break;
            }

            AdbClient client = new AdbClient();

            Console.WriteLine("Currently connected devices:");

            List <DeviceData> devices = client.GetDevices();

            for (int c = 0; c < devices.Count; c++)
            {
                Console.WriteLine($"\t{c}: {devices[c].Name}");
            }

            Console.Write("Device to attach: ");
            int deviceNumber = int.Parse(Console.ReadLine());

            Console.WriteLine("Running processes: ");

            List <ProcInfo> procs = GetProcs(client, devices[deviceNumber]);

            foreach (ProcInfo proc in procs)
            {
                Console.WriteLine($"\t{proc.Name}");
            }

            Console.Write("Process to monitor (name): ");
            string procName = Console.ReadLine();

            Console.Write("Keyword to search for: ");
            string keyWord = Console.ReadLine();

            if (string.IsNullOrEmpty(keyWord))
            {
                keyWord = null;
            }

            ProcInfo procToMonitor = procs.Where(n => n.Name == procName).FirstOrDefault();

            if (procToMonitor != null)
            {
                Console.WriteLine($"Watching {procToMonitor.Name} with PID {procToMonitor.Pid}...");
                DateTime lastLoggedAt = new DateTime();
                for (; ;)
                {
                    procs = GetProcs(client, devices[deviceNumber]);
                    if (procs.Any(n => n.Pid == procToMonitor.Pid && n.Name == n.Name))
                    {
                        ConsoleOutputReceiver logcatInspect = new ConsoleOutputReceiver();
                        client.ExecuteRemoteCommand("logcat -d", devices[deviceNumber], logcatInspect);
                        string[] allLogs = logcatInspect.ToString().Split("\n");
                        foreach (string log in allLogs)
                        {
                            string dateTimeString = Regex.Match(log, @"\d{2}-\d{2} \d{1,2}:\d{1,2}:\d{1,2}.\d{1,3}").Value;
                            if (!string.IsNullOrEmpty(dateTimeString))
                            {
                                DateTime loggedAt = DateTime.ParseExact(dateTimeString, "MM-dd HH:mm:ss.fff", null);
                                if (loggedAt > lastLoggedAt)
                                {
                                    if (keyWord != null && log.Contains(keyWord))
                                    {
                                        Console.WriteLine($"Keyword {keyWord} found: {log}");
                                    }
                                    lastLoggedAt = loggedAt;
                                }
                            }
                        }
                        Thread.Sleep(1000);
                    }
                    else
                    {
                        Console.WriteLine("Broke! Dumping logs!");
                        break;
                    }
                }
            }

            ConsoleOutputReceiver consoleOutput = new ConsoleOutputReceiver();

            client.ExecuteRemoteCommand("logcat -d", devices[deviceNumber], consoleOutput);

            File.WriteAllText($"logcat_dump_{procToMonitor.Name}_{procToMonitor.Pid}.txt", consoleOutput.ToString());

            return;
        }
Exemple #22
0
 public Bridge(string ADBPath)
 {
     AdbServer.Instance.StartServer(ADBPath, false);
     client = new AdbClient();
 }
Exemple #23
0
 public DeviceHelper(AdbClient c, DeviceData d)
 {
     client = c;
     device = d;
 }
Exemple #24
0
        private void btnExecute_Click(object sender, EventArgs e)
        {
            if (lstScripts.SelectedItems.Count == 0)
            {
                return;
            }

            var curScript = lstScripts.SelectedItems[0];
            var resScript = Program.Scripts.Get(curScript.Tag as string) as Script;

            // 需要配置文件执行
            if (resScript.Configuration != null)
            {
                var require = JArray.Parse(resScript.Require);
                foreach (var req in require)
                {
                    var type = req["type"].ToString();
                    switch (type)
                    {
                    case "select":
                        // 需要选择框
                        var arr = (JArray)req["value"];
                        // 选择列表
                        var candidate = (from r in arr select r.ToString()).ToArray <string>();
                        var sel       = new SelectForm();
                        var ti        = req["title"].ToString();
                        sel.SetSelection(ti, ti, candidate);
                        if (sel.ShowDialog() == DialogResult.OK)
                        {
                            var idx    = sel.GetSelection();
                            var varKey = req["return"].ToString();
                            resScript.SetValue(varKey, idx.ToString());
                            break;
                        }
                        return;

                    case "content":
                        var titleList = (from t in Program.Contents.ListAll().Cast <Content>() select t.Title).ToArray();
                        var idList    = (from t in Program.Contents.ListAll().Cast <Content>() select t.Key).ToArray();

                        var coSel = new SelectForm();
                        coSel.SetSelection("素材", "素材", titleList);
                        if (coSel.ShowDialog() == DialogResult.OK)
                        {
                            var varKey = req["return"].ToString();
                            var idx    = coSel.GetSelection();
                            var co     = Program.Contents.Get(idList[idx]) as Content;
                            resScript.SetValue("selContent", co);
                            resScript.SetValue(varKey, co.Body.Replace("\r\n", "#ENTER#"));
                            break;
                        }
                        return;

                    case "input":
                        var ib       = new InputForm();
                        var _default = req["value"].ToString();
                        var title    = req["title"].ToString();
                        ib.SetDefault(_default, title, title);
                        if (ib.ShowDialog() == DialogResult.OK)
                        {
                            var keyword  = ib.GetInput();
                            var variable = req["return"].ToString();
                            resScript.SetValue(variable, keyword);
                            break;
                        }
                        return;

                    default:
                        return;
                    }
                }
            }
            Dispatcher.BackgroundThread(() =>
            {
                btnSync_Click(null, null);
                Thread.Sleep(1000);
                foreach (ListViewItem dev in lstDevices.Items)
                {
                    if (dev.Selected)
                    {
                        var serial = dev.Text;
                        var slDev  = Program.Slaves.Get(serial) as SlavedDevice;
                        var slave  = slDev.Object;
                        // 如果有配置文件则生成配置文件
                        if (resScript.Configuration != null)
                        {
                            // 同步素材图片
                            syncContent(resScript.GetValue("selContent") as Content, slDev);


                            var configPath = Program.GlobalSetting.Get("TouchSpriteConfig").Value as string;
                            Dispatcher.BackgroundThread(() =>
                            {
                                var adb = new AdbClient(AdbServer.Instance.EndPoint);
                                adb.ExecuteRemoteCommand($"rm -rf {configPath}/*", slave.Device, null);
                            });
                            configPath += "/";
                            configPath += resScript.ConfigName;
                            // 生成配置文件
                            var config = resScript.ForgeConfig();
                            Dispatcher.BackgroundThread(() =>
                            {
                                lock (slave)
                                {
                                    var sync = new SyncService(slave.Device);
                                    File.WriteAllText(Program.varDir + $@"\tmp_{slave.Device.Serial}.config", config, Encoding.UTF8);
                                    sync.Push(File.OpenRead(Program.varDir + $@"\tmp_{slave.Device.Serial}.config"), configPath, 777, DateTime.Now, CancellationToken.None);
                                }
                            });
                        }
                        new Thread(() =>
                        {
                            Thread.Sleep(3000);
                            slave.ExecuteScript();
                        })
                        {
                            IsBackground = true
                        }.Start();
                    }
                }
            });
        }
Exemple #25
0
 public void CreateAdbForwardRequestTest()
 {
     Assert.Equal(Encoding.ASCII.GetBytes("0008tcp:1984"), AdbClient.CreateAdbForwardRequest(null, 1984));
     Assert.Equal(Encoding.ASCII.GetBytes("0012tcp:1981:127.0.0.1"), AdbClient.CreateAdbForwardRequest("127.0.0.1", 1981));
 }
Exemple #26
0
        async static Task MainAsync()
        {
            AdbClient Client    = new AdbClient();
            Stopwatch StopWatch = new Stopwatch();

            List <Emulator> Emulators = new List <Emulator>();
            List <UIObject> Objects   = new List <UIObject>();

            while (true)
            {
                Emulators = Client.GetEmulators();
                Emulators.ForEach(Emulator => Console.WriteLine($"Emulator:{Emulator.EndPoint.Address}:{Emulator.EndPoint.Port}\n"));

                await Task.Delay(1000);

                Console.Write("> ");
                string        Command = Console.ReadLine();
                List <string> Result;
                XmlDocument   UIXmlDocument;
                Console.WriteLine("");

                try
                {
                    if (Command == "scan")
                    {
                        Emulators = Client.GetEmulators();
                        Emulators.ForEach(Emulator => Console.WriteLine($"Emulator:{Emulator.EndPoint.Address}:{Emulator.EndPoint.Port}\n"));
                    }
                    else if (Command.StartsWith("select"))
                    {
                        throw new NotImplementedException();
                    }
                    else if (Command.StartsWith("ui"))
                    {
                        StopWatch.Start();
                        UIXmlDocument = await Emulators[0].Shell.GetUIXml();
                        StopWatch.Stop();

                        Objects = UIParser(UIXmlDocument);
                        DrawUITree(Objects);
                    }
                    else if (Command.StartsWith("pull"))
                    {
                        StopWatch.Start();
                        await Emulators[0].Sync.Pull(Command.Split('"')[1]);
                        StopWatch.Stop();
                        Console.WriteLine("[Task Completed]");
                    }
                    else if (Command.StartsWith("install"))
                    {
                        StopWatch.Start();
                        Console.WriteLine(await Emulators[0].Install.Apk(Command.Split('"')[1]));
                        StopWatch.Stop();
                    }
                    else if (Command.StartsWith("root"))
                    {
                        StopWatch.Start();
                        Console.WriteLine(await Emulators[0].Root.Enable());
                        StopWatch.Stop();
                    }
                    else if (Command.StartsWith("mini"))
                    {
                        StopWatch.Start();
                        UIXmlDocument = await Emulators[0].Shell.GetUIXml();
                        StopWatch.Stop();

                        if (Objects.Count == 0)
                        {
                            Objects = UIParser(UIXmlDocument);
                        }
                        string Shell = GenerateShell(Objects, Command);
                        await  Emulators[0].Shell.Excute(Shell);
                    }
                    else
                    {
                        StopWatch.Start();
                        Result = await Emulators[0].Shell.Excute(Command);
                        StopWatch.Stop();
                        Result.ForEach(Line => Console.WriteLine(Line));
                    }
                }
                catch (Exception Error)
                {
                    StopWatch.Stop();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Error: {Error.Message}");
                    Console.ForegroundColor = ConsoleColor.Green;
                }

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine($"\nTime Taken: {StopWatch.ElapsedMilliseconds.ToString("d")} Milliseconds");
                Console.ForegroundColor = ConsoleColor.Green;


                StopWatch.Reset();
                Console.WriteLine("");
            }
        }