예제 #1
0
        public void TouchPoint(Point point)
        {
            var receiver = new ConsoleOutputReceiver();

            log.Debug("Tap (point)" + point.X + " " + point.Y);
            client.ExecuteRemoteCommand("input tap " + point.X + " " + point.Y, device, receiver);
        }
예제 #2
0
        void syncContent(Content co, SlavedDevice dev)
        {
            var album = co.Album;
            var ti    = co.Title;
            var cont  = co.Body;

            Dispatcher.BackgroundThread(() =>
            {
                var adb = new AdbClient(AdbServer.Instance.EndPoint);
                //try
                //{
                //    adb.ExecuteRemoteCommand($"mkdir {Program.GlobalSetting.Get("ContentPath").Value}", dev.Object.Device, null);
                //}
                //catch
                //{

                //}
                //try
                //{
                //    adb.ExecuteRemoteCommand($"rm -rf {Program.GlobalSetting.Get("ContentPath").Value}/*", dev.Object.Device, null);
                //}
                //catch
                //{

                //}
                try
                {
                    adb.ExecuteRemoteCommand($"rm -rf {Program.GlobalSetting.Get("DroidAlbum").Value}/*", dev.Object.Device, null);
                }
                catch
                {
                }
                var sync = new SyncService(dev.Object.Device);
                //File.WriteAllText(Program.varDir + "/tmp.dat", cont, Encoding.UTF8);
                //var stream = File.OpenRead(Program.varDir + "/tmp.dat");
                // sync.Push(stream, $"{Program.GlobalSetting.Get("ContentPath").Value}/{ti}-{co.Key}.txt", 777, DateTime.Now, CancellationToken.None);
                foreach (var pic in album)
                {
                    if (File.Exists(pic))
                    {
                        var info = new FileInfo(pic);
                        sync     = new SyncService(dev.Object.Device);
                        sync.Push(File.OpenRead(pic), $"{Program.GlobalSetting.Get("DroidAlbum").Value}/{Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10)}{info.Extension}", 777, DateTime.Now, CancellationToken.None);
                    }
                }
                // 广播相册图片改变消息
                adb.ExecuteRemoteCommand($"am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d file://{Program.GlobalSetting.Get("DroidAlbum").Value}", dev.Object.Device, null);
                //File.Delete(Program.varDir + "/tmp.dat");
            });
        }
예제 #3
0
        public void WatchDirectory(string dir)
        {
            var adb = new AdbClient(AdbServer.Instance.EndPoint);

            try
            {
                adb.ExecuteRemoteCommand("mkdir /data/local/tmp/img", slave.Device, null);
            }
            catch { }
            Dispatcher.BackgroundThread(() =>
            {
                while (true)
                {
                    Thread.Sleep(500);
                    var o = AdbClient.Instance.ExecuteRemoteCommandSync(slave.Device, $"test -e {dir}/* && echo '1';");
                    if (o.Contains("1"))
                    {
                        o         = adb.ExecuteRemoteCommandSync(slave.Device, $"ls -l {dir}/*");
                        var lines = Regex.Split(o, "\r\n");
                        foreach (var l in lines)
                        {
                            if (string.IsNullOrWhiteSpace(l))
                            {
                                continue;
                            }

                            var idx      = l.LastIndexOf(" ") + 1;
                            var fileName = l.Substring(idx, l.Length - idx);
                            DirFileDetected?.Invoke(slave, dir + "/" + fileName);
                            adb.ExecuteRemoteCommandSync(slave.Device, $"su -c 'rm -f {dir}/{fileName}'");
                        }
                    }
                }
            });
        }
예제 #4
0
 void UploadFile(SharpAdbClient.DeviceData device, string fileLocal, string fileRemote)
 {
     //var device = AdbClient.Instance.GetDevices().First();
     try
     {
         AdbClient adbClient = new AdbClient();
         try
         {
             adbClient.Connect(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort));
             adbClient.ExecuteRemoteCommand("mkdir " + Constants.remotePath, device, new myReceiver());
         }catch (Exception ex)
         {
             System.Diagnostics.Debug.WriteLine(ex.Message);
         }
         using (SyncService service = new SyncService(new AdbSocket(adbClient.EndPoint), device))
             using (Stream stream = File.OpenRead(fileLocal))
             {
                 service.Push(stream, fileRemote, 444, DateTime.Now, null, CancellationToken.None);
             }
         textBox1.Text = "File send successfully";
     }
     catch (Exception ex)
     {
         textBox1.Text = ex.Message + " Is MTP enabled?";
     }
 }
예제 #5
0
        public void ExecuteScript()
        {
            Manipulation.Keypress(DroidKey.HOME);
            Thread.Sleep(500);
            var adb = new AdbClient(AdbServer.Instance.EndPoint);

            adb.ExecuteRemoteCommand("su -c 'am start com.touchsprite.android/.activity.Activity_Main'", Device, this);
            Thread.Sleep(1000 * int.Parse(
                             Program.GlobalSetting.Get("ExecuteScriptWait").Value.ToString()
                             ));
            // 选中第一个脚本
            var firstScript = getRelative(0.4708333, 0.23671875);
            // 点开下拉菜单
            var actMenu = getRelative(0.925333333, 0.223125);
            // 运行脚本
            var startBtn = getRelative(0.768055555, 0.33515625);

            Manipulation.Touch(firstScript, () =>
            {
                Thread.Sleep(1000);
                Manipulation.Touch(actMenu, () => {
                    Thread.Sleep(1000);
                    Manipulation.Touch(startBtn);
                });
            });
        }
예제 #6
0
        public void ConnectPhone(string Serial)
        {
            StartServer();

            var dns = GetCacheDnsEndPoint(Serial);

            if (dns != null)
            {
                AdbClient.Connect(dns.Host);
                DevicesConnected.Add(Serial, dns);
                return;
            }

            var deviceData = AdbClient.GetDevices().First(x => x.Serial == Serial);

            // Get ip addresse of the device
            var receiver = new ConsoleOutputReceiver();

            AdbClient.ExecuteRemoteCommand("ip addr show wlan0", deviceData, receiver);
            var ip = receiver.ToString().Split('\n').Where(x => x.Contains("inet")).First()
                     .Trim().Split(' ')[1].Split('/').First();

            // Setup the tcpip
            port++;
            CommandADB.StartTcpip(Serial, port);

            AdbClient.Connect(ip);
            dns = new DnsEndPoint(ip, port);
            DevicesConnected.Add(Serial, dns);
            DeviceCache.Add(Serial, dns);
        }
        /// <summary>
        /// Execute adb command to selected device
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        internal string Execute(string command, [CallerLineNumber] int lineNumber = 0, [CallerMemberName] string caller = null)
        {
            if (selectedDevice == null)
            {
                if (string.IsNullOrEmpty(adbipport))
                {
                    Console.Error.WriteLine("No adbipport registered. Please check you called SelectDevice(string adbipsocket)");
                    return(string.Empty);
                }
                if (!SelectDevice(adbipport))
                {
                    Console.Error.WriteLine("No such device found");
                    return(string.Empty);
                }
            }
            ConsoleOutputReceiver receiver = new ConsoleOutputReceiver();

            try
            {
                client.ExecuteRemoteCommand(command, selectedDevice, receiver);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("device offline"))
                {
                    throw new Exception("device offline");
                }
                receiver.AddOutput(ex.ToString());
            }
            logger.WritePrivateLog("Execute " + command + " Result:" + receiver.ToString(), lineNumber, caller);
            return(receiver.ToString());
        }
        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);
        }
        private void closeApp()
        {
            if (device == null)
            {
                return;
            }
            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());
        }
예제 #10
0
        public void UploadScript(string path)
        {
            var adb = new AdbClient(AdbServer.Instance.EndPoint);

            adb.ExecuteRemoteCommand("rm -rf /sdcard/TouchSprite/lua/*", Device, this);
            var sync = new SyncService(Device);
            var info = new FileInfo(path);

            sync.Push(
                File.OpenRead(info.FullName), "/sdcard/TouchSprite/lua/" + System.Web.HttpUtility.UrlEncode(info.Name), 777, DateTime.Now, CancellationToken.None
                );
        }
예제 #11
0
        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);
        }
예제 #12
0
 public void StartLocationService()
 {
     Dispatcher.BackgroundThread(() =>
     {
         var adb = new AdbClient(AdbServer.Instance.EndPoint);
         if (LocationPort == -1)
         {
             adb.ExecuteRemoteCommand("am start com.github.fakegps/.ui.MainActivity", Device, null);
             adb.CreateForward(Device, LocationPort = Program.getFreePort(Program.LocationBase), 9998);
             Thread.Sleep(1000);
             locClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             locClient.Connect("127.0.0.1", LocationPort);
         }
     });
 }
예제 #13
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);
        }
예제 #14
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());
        }
예제 #15
0
        private void Timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;

            //Point p;
            //if (pv[v] == -1) p = new Point(529, 1069);           // "Next Level"
            //else if (pv[v] == -2) p = new Point(874, 1120);      // "No" (Watch one video)
            //else p = new Point(194 + (910 - 194) * pv[v] / 8, 265);
            //client.ExecuteRemoteCommand($"input tap {p.X} {p.Y}", device, null);
            //v = (v + 1) % pv.Length;

            if (sw.ElapsedMilliseconds > (1 * 30) * 1000)
            {
                client.ExecuteRemoteCommand($"input tap 890 1120", device, null);  // "No" (Watch one video)
                client.ExecuteRemoteCommand($"input tap 220 1450", device, null);  // Retry level
                sw.Restart();
            }
            else
            {
                client.ExecuteRemoteCommand($"input tap {fireLaser.X} {fireLaser.Y}", device, null);
                if (v == 0)
                {
                    client.ExecuteRemoteCommand($"input swipe {p1.X} {p1.Y} {p4.X} {p4.Y} 500", device, null);
                }
                else
                {
                    client.ExecuteRemoteCommand($"input swipe {p2.X} {p2.Y} {p3.X} {p3.Y} 500", device, null);
                }
                v = (v + 1) % 2;
            }

            timer1.Enabled = true;
        }
예제 #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();
        }
예제 #17
0
        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;
        }
예제 #18
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();
                    }
                }
            });
        }
예제 #19
0
 public void ExecuteADBShell(string command)
 {
     client.ExecuteRemoteCommand(command, device, null);
 }
예제 #20
0
 void ExecuteADBShell(string command)
 {
     client.ExecuteRemoteCommand(command, TargetDevice, new Receiver());
 }
예제 #21
0
 public void Delete(string remotePath)
 {
     m_client.ExecuteRemoteCommand($"rm -rf /sdcard/Android/data/{GlobalData.Instance.AndroidPackageName}/files/{remotePath}", m_deviceData, null);
 }
예제 #22
0
 public string SetGeolocation(double latitude = 39.56, double longitude = 116.20)
 {
     Client.ExecuteRemoteCommand($"setprop persist.nox.gps.latitude {latitude}", deviceData, receiver);
     Client.ExecuteRemoteCommand($"setprop persist.nox.gps.longitude {longitude}", deviceData, receiver);
     return(receiver.ToString());
 }
예제 #23
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}");
            }
        }