Exemple #1
0
        public static bool RunSdbCommandAndCheckExitCode(SDBDeviceInfo device, string command)
        {
            int exitCode;

            return((RunSdbCommand(device, command, out exitCode, TimeSpan.MaxValue) == SdbRunResult.Success) &&
                   (exitCode == 0));
        }
Exemple #2
0
        public static bool RunSdbCommandAndGetError(SDBDeviceInfo device, string shellCommand,
                                                    OutputDataProcessor outputDataProcessor, out string errorString, TimeSpan?timeout = null)
        {
            int    exitResult    = 0;
            string nonEmptyLines = "";

            errorString = "";

            SDBLib.SdbRunResult sdbResult = RunSdbCommand(device,
                                                          shellCommand,
                                                          (bool isStdOut, string line) =>
            {
                if (line != "")
                {
                    nonEmptyLines += line;
                }
                return(false);
            },
                                                          out exitResult,
                                                          timeout);
            if (exitResult != 0)
            {
                sdbResult   = SdbRunResult.OtherError;
                errorString = nonEmptyLines;
            }
            return(sdbResult == SdbRunResult.Success);
        }
Exemple #3
0
        public void TerminateApplication(SDBDeviceInfo device, string appId)
        {
            OutputResponseMsg("Try to terminate running application: " + appId);

            var appCommand = new SDBAppCmd(device, SDBProtocol.killapp, appId);

            if (!appCommand.IsTargetFound)
            {
                OutputDeviceErrorMsg("Failed to get connection.");
                return;
            }

            string msg = "Failed to terminate application";

            switch (appCommand?.ExitCode)
            {
            case 0:
                msg = "Old application has been terminated to launch updated app";
                break;

            case 1:
                msg = "Application is not running";
                break;

            case 255:
                msg = "No application to be terminated";
                break;
            }

            OutputResponseMsg(string.Format("{0}: {1}", msg, appCommand?.ExitCode));
        }
Exemple #4
0
        public static bool RunSdbCommandAndGetLastNonEmptyLine(SDBDeviceInfo device, string сommand,
                                                               out string lastOutputLine, out string errorMessage, TimeSpan?timeout = null)
        {
            lastOutputLine = "";
            string       nonEmptyLine = "";
            int          exitCode;
            SdbRunResult sdbResult = RunSdbCommand(device, сommand,
                                                   (bool isStdOut, string line) =>
            {
                if (line != "")
                {
                    nonEmptyLine = line;
                }
                return(false);
            },
                                                   out exitCode, timeout);

            if (sdbResult == SdbRunResult.Success)
            {
                lastOutputLine = nonEmptyLine;
                errorMessage   = "";
                return(true);
            }

            errorMessage = "Cannot run command. " + FormatSdbRunResult(sdbResult, exitCode);
            return(false);
        }
Exemple #5
0
        public static SdbRunResult RunSdbCommand(SDBDeviceInfo device, string command,
                                                 OutputDataProcessor outputDataProcessor, TimeSpan?timeout = null)
        {
            int exitCode;

            return(RunSdbCommand(device, command, outputDataProcessor, out exitCode, timeout));
        }
        private void ProcessDeviceData(string deviceinfo)
        {
            string[] devices = deviceinfo.Split(
                new string[] { "\r\n", "\n" },
                StringSplitOptions.RemoveEmptyEntries);
            List <SDBDeviceInfo> deviceInfoList = new List <SDBDeviceInfo>();

            DeviceInfoCollection.Clear();

            foreach (string item in devices)
            {
                string[] onedevice = item.Split(DeviceToken,
                                                StringSplitOptions.RemoveEmptyEntries);

                SDBDeviceInfo devinfo = new SDBDeviceInfo(onedevice[0].TrimEnd(), onedevice[1].TrimEnd(), onedevice[2].TrimEnd());

                deviceInfoList.Add(devinfo);

                DeviceInfoCollection.Add(devinfo.Serial, devinfo);
            }

            lock (this.lockDeviceInfoList)
            {
                this.deviceInfoList = deviceInfoList;
            }
        }
 private static void PrioritizeSelectedDevice()
 {
     if (SelectedDevice != null)
     {
         SDBDeviceInfo movedUpDevice = DeviceInfoList.FindLast(device => SelectedDevice.Serial.Equals(device.Serial));
         DeviceInfoList.Remove(movedUpDevice);
         DeviceInfoList.Insert(DeviceInfoList.Count, SelectedDevice);
     }
 }
        public static void SelectDevice(SDBDeviceInfo newlySelectedDevice)
        {
            bool isNoDeviceSelected      = (newlySelectedDevice == null);
            bool isNewDeviceSelected     = !isNoDeviceSelected && !newlySelectedDevice.Serial.Equals(SelectedDevice?.Serial);
            bool isSelectedDeviceChanged = isNoDeviceSelected || isNewDeviceSelected;

            SelectedDevice = newlySelectedDevice;

            if (isSelectedDeviceChanged)
            {
                deviceManager?.BroadcastSelectedDeviceChangedEvent();
            }
        }
Exemple #9
0
        public static bool RemoveForwardTcpPort(SDBDeviceInfo device, int localPort, out string errorMessage)
        {
            string lastLine;
            bool   success = SDBLib.RunSdbCommandAndGetLastNonEmptyLine(device,
                                                                        $"forward --remove tcp:{localPort}", out lastLine, out errorMessage);

            if (success && lastLine.StartsWith("error:"))
            {
                errorMessage = lastLine;
                success      = false;
            }
            return(success);
        }
Exemple #10
0
        public static bool ForwardTcpPort(SDBDeviceInfo device, int localPort, int remotePort, out string errorMessage)
        {
            // TODO!! do need to remove port forwarding first?
            RemoveForwardTcpPort(device, localPort, out errorMessage); // remove forward error is a valid case

            string lastLine;
            bool   success = SDBLib.RunSdbCommandAndGetLastNonEmptyLine(device,
                                                                        $"forward tcp:{localPort} tcp:{remotePort}", out lastLine, out errorMessage);

            if (success && lastLine.StartsWith("error:"))
            {
                errorMessage = lastLine;
                success      = false;
            }
            return(success);
        }
Exemple #11
0
 public static string AdjustSdbArgument(SDBDeviceInfo device, string argument)
 {
     if (device == null)
     {
         List <SDBDeviceInfo> devInfoList = DeviceInfoList;
         int itemCount = (devInfoList != null) ? devInfoList.Count : 0;
         if (itemCount > 1)
         {
             device = SelectedDevice;
         }
     }
     if (device != null)
     {
         return($"-s {device.Serial} {argument}");
     }
     return(argument);
 }
Exemple #12
0
        public static bool RunSdbShellCommandAndCheckExitStatus(SDBDeviceInfo device, string shellCommand,
                                                                OutputDataProcessor outputDataProcessor, out string errorMessage, TimeSpan?timeout = null, bool isRoot = false)
        {
            int          exitCode;
            bool         success   = false;
            SdbRunResult sdbResult = RunSdbCommand(device,
                                                   $"shell \"{shellCommand} && echo {ShellSuccess} || echo {ShellFailure}\"",
                                                   (bool isStdOut, string line) =>
            {
                if (line.Contains(ShellSuccess))
                {
                    success = true;
                    return(true);
                }
                if (line.Contains(ShellFailure))
                {
                    return(true);
                }
                if (outputDataProcessor != null)
                {
                    if (outputDataProcessor(isStdOut, line))
                    {
                        success = true;
                        return(true);
                    }
                }
                return(false);
            },
                                                   out exitCode, timeout, isRoot);

            if (sdbResult == SdbRunResult.Success)
            {
                if (!success)
                {
                    errorMessage = "Command failed";
                    return(false);
                }
                errorMessage = "";
                return(true);
            }

            errorMessage = "Cannot run command. " + FormatSdbRunResult(sdbResult, exitCode);
            return(false);
        }
Exemple #13
0
        /*
         * private string TransportCheckVersion(string AppId)
         * {
         *  int length;
         *  string requestcmd = "host:version";
         *  SDBRequest request = SDBConnection.MakeRequest(requestcmd);
         *  SDBResponse response = this.sdbconnection.Send(request);
         *  if (!response.IOSuccess || !response.Okay)
         *  {
         *      OutputDeviceErrorMsg("Cannot check transport version(1): " + AppId);
         *      return String.Empty;
         *  }
         *
         *  length = this.sdbconnection.ReadLength();
         *  if (length <= 0)
         *  {
         *      OutputDeviceErrorMsg("Cannot check transport version(2): " + AppId);
         *      return String.Empty;
         *  }
         *
         *  byte[] buffer = new byte[length];
         *  return this.sdbconnection.ReadData(buffer);
         * }
         *
         * private bool TransportStart(string AppId)
         * {
         *  string requestcmd = "host:transport-any";
         *  SDBRequest request = SDBConnection.MakeRequest(requestcmd);
         *  SDBResponse response = this.sdbconnection.Send(request);
         *  if (!response.IOSuccess || !response.Okay)
         *  {
         *      OutputDeviceErrorMsg("Cannot initiate transport: " + AppId);
         *      return false;
         *  }
         *
         *  return true;
         * }
         */

        public bool LaunchApplication(SDBDeviceInfo device, string appId)
        {
            OutputResponseMsg("Try to launch application: " + appId);

            var appCommand = new SDBAppCmd(device, SDBProtocol.runapp, appId);

            if (!appCommand.IsTargetFound)
            {
                OutputDeviceErrorMsg("Failed to get connection.");
                return(false);
            }

            bool   isLaunched = (appCommand.ExitCode == SDBReqExitCode.EXIT_SUCCESS);
            string msg        = isLaunched ? "Application launched." : "Application launch failed: " + appCommand.ExitCode;

            OutputResponseMsg(msg);

            return(isLaunched);
        }
Exemple #14
0
        public bool IsPackageDetected(SDBDeviceInfo device, string packageName)
        {
            OutputResponseMsg("Try to find installed package: " + packageName);

            var appCommand = new SDBAppCmd(device, SDBProtocol.appinfo, packageName);

            if (!appCommand.IsTargetFound)
            {
                OutputDeviceErrorMsg("Failed to get connection.");
                return(false);
            }

            bool   isDetected = (appCommand.ExitCode == SDBReqExitCode.EXIT_SUCCESS);
            string msg        = isDetected ? "Package is already installed." : "Package is not installed.";

            OutputResponseMsg(msg);

            return(isDetected);
        }
Exemple #15
0
        public static bool CheckIsRoot(SDBDeviceInfo device, out bool isRoot, out string errorMessage, TimeSpan?timeout = null)
        {
            string checkIsRootScript = $"if [ $UID == 0 ]; then echo {ShellSuccess}; else echo {ShellFailure}; fi";

            isRoot = false;
            bool         result  = false;
            bool         success = false;
            int          exitCode;
            SdbRunResult sdbResult = RunSdbCommand(device, $"shell \"{checkIsRootScript}\"",
                                                   (bool isStdOut, string line) =>
            {
                if (line.Contains(ShellSuccess))
                {
                    result  = true;
                    success = true;
                    return(true);
                }
                if (line.Contains(ShellFailure))
                {
                    success = true;
                    return(true);
                }
                return(false);
            },
                                                   out exitCode, timeout, false);

            if (sdbResult == SdbRunResult.Success)
            {
                if (!success)
                {
                    errorMessage = "Command failed";
                    return(false);
                }
                isRoot       = result;
                errorMessage = "";
                return(true);
            }

            errorMessage = "Cannot run command. " + FormatSdbRunResult(sdbResult, exitCode);
            return(false);
        }
Exemple #16
0
 /// <summary>
 /// Run the specified command using SDB and process its output using outputDataProcessor (if its not null).
 /// The outputDataProcessor delegate returns true to indicate it got some expected result so the function
 /// may exit (the command continues to work), and false if the result has not been obtained yet so the delegate
 /// "wants" to continue receiving the command output.
 /// </summary>
 /// <param name="command">the command to run (e.g. 'shell \"ls /usr\"')</param>
 /// <param name="outputDataProcessor">the delegate which processes the output of the command and returns
 /// true to stop (in this case the function exits but the command continues to work) or false to continue</param>
 /// <param name="outputLog">only if outputDataProcessor == null: copy process output to Tizen pane</param>
 /// <param name="exitCode">if SDB process has finished before the function returns then the SDB process exit code
 /// is copied to this out parameter else it's equal to -1</param>
 /// <param name="timeout">the timeout: if it elapses before outputDataProcessor returned true or the
 /// command finished then the function returns Timeout (the command continues to work);
 /// the default value is 30 seconds</param>
 /// <param name="isRoot">whether to execute command from root</param>
 /// <returns>
 /// if outputDataProcessor is not null:
 ///   Success if outputDataProcessor returned true, or another SdbCommandResult value otherwise (if an error
 ///   occurred or the command finished or the timeout elapsed);
 /// if outputDataProcessor is null:
 ///   Success if the command finished before the timeout elapsed, or another SdbCommandResult value otherwise.
 /// </returns>
 public static SdbRunResult RunSdbCommand(SDBDeviceInfo device, string command,
                                          OutputDataProcessor outputDataProcessor, out int exitCode, TimeSpan?timeout, bool isRoot)
 {
     if (isRoot)
     {
         if (!SwitchToRoot(device, true))
         {
             exitCode = -1;
             return(SdbRunResult.OtherError);
         }
     }
     try
     {
         return(RunSdbCommand(device, command, outputDataProcessor, out exitCode, timeout));
     }
     finally
     {
         if (isRoot)
         {
             SwitchToRoot(device, false);
         }
     }
 }
Exemple #17
0
 public static bool SwitchToRoot(SDBDeviceInfo device, bool on)
 {
     return(RunSdbCommandAndCheckExitCode(device, $"root {(on ? "on" : "off")}"));
 }
Exemple #18
0
 public static bool RemountRootFileSystem(SDBDeviceInfo device, bool readWrite, out string errorMessage)
 {
     return(RunSdbShellCommandAndCheckExitStatus(device, $"mount / -o remount,{(readWrite ? "rw" : "ro")}", null,
                                                 out errorMessage, null, true));
 }
Exemple #19
0
 public static bool RunSdbShellSecureCommand(SDBDeviceInfo device, string secureCommand,
                                             OutputDataProcessor outputDataProcessor, out string errorString, TimeSpan?timeout = null)
 {
     return(RunSdbCommandAndGetError(device, $"shell 0 {secureCommand}", outputDataProcessor, out errorString, timeout));
 }
Exemple #20
0
        public static SdbRunResult RunSdbCommand(SDBDeviceInfo device, string command,
                                                 OutputDataProcessor outputDataProcessor, out int exitCode, TimeSpan?timeout = null)
        {
            Debug.Assert((timeout == null) || (timeout >= TimeSpan.Zero));

            exitCode = -1;
            TimeSpan effectiveTimeout = timeout ?? TimeSpan.FromSeconds(30); // the default timeout is 30 seconds

            using (ProcessProxy process = CreateSdbProcess(true, false))
            {
                if (process == null)
                {
                    return(SdbRunResult.CreateProcessError);
                }
                process.StartInfo.Arguments = DeviceManager.AdjustSdbArgument(device, command);
                Debug.WriteLine("{0} RunSdbCommand command '{1}'", DateTime.Now, process.StartInfo.Arguments);
                if (outputDataProcessor != null)
                {
                    object eventsGuard    = new object();
                    var    gotOutputEvent = new ManualResetEvent(false);
                    try
                    {
                        bool stopped = false; // should be volatile actually but it's not allowed for locals
                        process.OutputDataReceived += (sender, args) =>
                        {
                            if (!stopped && (args.Data != null))
                            {
                                lock (eventsGuard)
                                {
                                    if (outputDataProcessor == null)
                                    {
                                        return;
                                    }
                                    if (outputDataProcessor(true, args.Data))
                                    {
                                        gotOutputEvent.Set();
                                        stopped = true;
                                    }
                                }
                            }
                        };
                        process.ErrorDataReceived += (sender, args) =>
                        {
                            if (!stopped && (args.Data != null))
                            {
                                lock (eventsGuard)
                                {
                                    if (outputDataProcessor == null)
                                    {
                                        return;
                                    }
                                    if (outputDataProcessor(false, args.Data))
                                    {
                                        gotOutputEvent.Set();
                                        stopped = true;
                                    }
                                }
                            }
                        };
                        if (!RunProcess(process))
                        {
                            return(SdbRunResult.RunProcessError);
                        }
                        process.BeginOutputReadLine();
                        process.BeginErrorReadLine();
                        Stopwatch watch = Stopwatch.StartNew();
                        do
                        {
                            try
                            {
                                if (process.WaitForExit(0))
                                {
                                    process.WaitForExit(); // wait until redirected stdin/stdout streams are processed
                                    exitCode = process.ExitCode;
                                    return(SdbRunResult.Success);
                                }
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                                return(SdbRunResult.OtherError);
                            }
                        }while (watch.Elapsed < effectiveTimeout);
                        if (!process.HasExited)
                        {
                            process.Kill();
                        }
                    }
                    finally
                    {
                        lock (eventsGuard)
                        {
                            outputDataProcessor = null;
                        }
                        gotOutputEvent.Dispose();
                    }
                }
                else // outputDataProcessor == null
                {
                    if (!RunProcess(process))
                    {
                        return(SdbRunResult.RunProcessError);
                    }
                    try
                    {
                        double timeoutMilliseconds = effectiveTimeout.TotalMilliseconds;
                        if (process.WaitForExit((timeoutMilliseconds <= int.MaxValue) ? (int)timeoutMilliseconds : int.MaxValue))
                        {
                            exitCode = process.ExitCode;
                            return(SdbRunResult.Success);
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                        return(SdbRunResult.OtherError);
                    }
                }
            }
            return(SdbRunResult.Timeout);
        }
Exemple #21
0
 public static SdbRunResult RunSdbCommand(SDBDeviceInfo device, string command,
                                          out int exitCode, TimeSpan?timeout = null)
 {
     return(RunSdbCommand(device, command, null, out exitCode, timeout));
 }