/// <summary>
 /// Create new adb controller
 /// </summary>
 /// <param name="adbPath"></param>
 internal AdbController(string adbPath, ILog logger)
 {
     server.StartServer(Path.Combine(adbPath, "adb.exe"), false);
     this.logger = logger;
     KillPortUsage();
     monitor = new DeviceMonitor(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)));
     monitor.DeviceConnected    += OnDeviceConnected;
     monitor.DeviceDisconnected += OnDeviceDisconnected;
     devices = client.GetDevices();
 }
Ejemplo n.º 2
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);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Get the connected devices
        /// </summary>
        /// <returns> List of the devices </returns>
        public static List <DeviceData> GetConnectedDevices()
        {
            var deviceList = new List <DeviceData>();

            if (Server.GetStatus().IsRunning)
            {
                foreach (var device in Client.GetDevices())
                {
                    if (device.State != DeviceState.NoPermissions)
                    {
                        deviceList.Add(device);
                    }
                }
            }

            return(deviceList);
        }
Ejemplo n.º 4
0
        public MyADB(string AdbShellFilename)
        {
            server = new AdbServer();
            var result = server.StartServer(AdbShellFilename, restartServerIfNewer: false);

            Console.WriteLine("Adb server connection state: " + result.ToString());
            client = new AdbClient();

            TargetDevice = client.GetDevices()[0];
        }
Ejemplo n.º 5
0
        public void ListProcessesIntegrationTest()
        {
            var adbClient = new AdbClient();
            var devices   = adbClient.GetDevices().ToArray();

            foreach (var device in devices)
            {
                var processes = device.ListProcesses().ToArray();
            }
        }
Ejemplo n.º 6
0
        public static IDevice[] CollectAndroidDevices()
        {
            var client        = new AdbClient();
            var devices       = client.GetDevices();
            var deviceProxies = new IDevice[devices.Count];

            for (int i = 0; i < devices.Count; i++)
            {
                deviceProxies[i] = new AndroidDevice(client, devices[i]);
            }

            return(deviceProxies);
        }
Ejemplo n.º 7
0
        public void TestMethod1()
        {
            var adb    = new AdbClient();
            var device = adb.GetDevices().FirstOrDefault();

            if (device == null)
            {
                Assert.Inconclusive("No device connected.");
                return;
            }

            var adc = new Scrcpy(device);

            adc.Start();
        }
Ejemplo n.º 8
0
        public Form1()
        {
            server = new AdbServer();
            var result = server.StartServer(@"C:\adb\adb.exe", restartServerIfNewer: false);

            Console.WriteLine("Adb server connection state: " + result.ToString());

            client = new AdbClient();
            var devices = client.GetDevices();

            TargetDevice = devices[0];            //to-do: query user; 0 devices;

            InitializeComponent();

            GetAndShowContinously();
        }
Ejemplo n.º 9
0
        private void Initialize()
        {
            AdbServer server = new AdbServer();
            var       result = server.StartServer(@"D:\Android\Sdk\platform-tools\adb.exe", restartServerIfNewer: false);

            client = (AdbClient)AdbClient.Instance;
            device = client.GetDevices().Single();

            //timer1 = new System.Windows.Forms.Timer { Interval = 50, Enabled = true };
            //timer1.Tick += Timer1_Tick;
            //sw.Start();

            ReadBonusImages();
            ImageUpdateLoop();
            initialized = true;
        }
Ejemplo n.º 10
0
        private void Bindlist()
        {
            try
            {
                lstDevices.ItemsSource = null;
                devices = null;
                devices = adbClient.GetDevices();

                List <DeviceData> listofD = new List <DeviceData>();

                lstDevices.ItemsSource = devices;
            }
            catch (Exception ex)
            {
                return;
            }
        }
        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);
        }
Ejemplo n.º 12
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;
                    }
                }
            });
        }
Ejemplo n.º 13
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);
        }
Ejemplo n.º 14
0
        public void extract(string timeStamp)
        {
            //check connected devices
            var devices = _adb.GetDevices();

            if (devices.Count == 0)
            {
                throw new Exception("ADB error: no device detected. Please connect device and start program again.");
            }
            if (devices.Count > 1)
            {
                //show all connected devices
                sendMessage(
                    "ADB warning: more than 1 device detected. This could potentially cause problems. If export will be unsuccessful, please disconnect all devices but Amazfit.",
                    WarningMsg);
                sendNewLine();
                sendMessage("List of connected devices:", WarningMsg);
                var count = devices.Count;
                for (var i = 0; i < count; i++)
                {
                    sendMessage(i + ": " + devices[i].Name + " " + devices[i].Model + " " + devices[i].Product,
                                WarningMsg);
                }

                sendNewLine();
            }

            //get backup of apk, that holds database
            sendMessage("Sending request for backup on Amazfit...", LogMsg);
            _adbCmd.runAdbProcess(@"backup -noapk com.huami.watch.newsport -f " + "\"" + Paths.backupFilePath(timeStamp).cleanPath() + "\"", null,
                                  null);
            //convert backup to .tar
            sendMessage("Converting backup to .tar", LogMsg);
            var conv = new Convertor(timeStamp);

            conv.backupToTar();
            //extract tar to folder
            sendMessage("Extracting tar file", LogMsg);
            conv.extractTar();
        }
Ejemplo n.º 15
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;
        }
Ejemplo n.º 16
0
 private DeviceData GetDeviceById(string deviceId)
 {
     return(Client.GetDevices().Find(d => d.Serial == deviceId));
 }
Ejemplo n.º 17
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();
        }
Ejemplo n.º 18
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;
        }
Ejemplo n.º 19
0
 public List <DeviceData> GetDevices()
 {
     return(client.GetDevices());
 }
Ejemplo n.º 20
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}");
            }
        }
Ejemplo n.º 21
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);
        }
Ejemplo n.º 22
0
 public List <DeviceData> GetDevicesData()
 {
     StartServer();
     return(AdbClient.GetDevices());
 }