Esempio n. 1
0
        /// <summary>
        /// Gets the frame buffer from the specified end point.
        /// </summary>
        /// <param name="adbSockAddr">The adb sock addr.</param>
        /// <param name="device">The device.</param>
        /// <returns></returns>
        public RawImage GetFrameBuffer(IPEndPoint adbSockAddr, IDevice device)
        {
            RawImage imageParams = new RawImage( );

            byte[] request = FormAdbRequest("framebuffer:");                //$NON-NLS-1$
            byte[] nudge   =
            {
                0
            };
            byte[] reply;

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

            try {
                adbChan.Connect(adbSockAddr);
                adbChan.Blocking = true;

                // if the device is not -1, then we first tell adb we're looking to talk
                // to a specific device
                SetDevice(adbChan, device);
                if (!Write(adbChan, request))
                {
                    throw new AdbException("failed asking for frame buffer");
                }

                AdbResponse resp = ReadAdbResponse(adbChan, false /* readDiagString */);
                if (!resp.IOSuccess || !resp.Okay)
                {
                    Log.w(TAG, "Got timeout or unhappy response from ADB fb req: " + resp.Message);
                    adbChan.Close( );
                    return(null);
                }

                // first the protocol version.
                reply = new byte[4];
                if (!Read(adbChan, reply))
                {
                    Log.w(TAG, "got partial reply from ADB fb:");

                    adbChan.Close( );
                    return(null);
                }
                BinaryReader buf;
                int          version = 0;
                using (MemoryStream ms = new MemoryStream(reply)) {
                    buf     = new BinaryReader(ms);
                    version = buf.ReadInt16( );
                }

                // get the header size (this is a count of int)
                int headerSize = RawImage.GetHeaderSize(version);
                // read the header
                reply = new byte[headerSize * 4];
                if (!Read(adbChan, reply))
                {
                    Log.w(TAG, "got partial reply from ADB fb:");

                    adbChan.Close( );
                    return(null);
                }

                using (MemoryStream ms = new MemoryStream(reply)) {
                    buf = new BinaryReader(ms);

                    // fill the RawImage with the header
                    if (imageParams.ReadHeader(version, buf) == false)
                    {
                        Log.w(TAG, "Unsupported protocol: " + version);
                        return(null);
                    }
                }

                Log.d(TAG, "image params: bpp=" + imageParams.Bpp + ", size="
                      + imageParams.Size + ", width=" + imageParams.Width
                      + ", height=" + imageParams.Height);

                if (!Write(adbChan, nudge))
                {
                    throw new AdbException("failed nudging");
                }

                reply = new byte[imageParams.Size];
                if (!Read(adbChan, reply))
                {
                    Log.w(TAG, "got truncated reply from ADB fb data");
                    adbChan.Close( );
                    return(null);
                }

                imageParams.Data = reply;
            } finally {
                if (adbChan != null)
                {
                    adbChan.Close( );
                }
            }

            return(imageParams);
        }
Esempio n. 2
0
        private void DeviceClientMonitorLoop( )
        {
            do
            {
                try {
                    // This synchronized block stops us from doing the select() if a new
                    // Device is being added.
                    // @see startMonitoringDevice()
                    lock ( Devices ) {
                    }

                    //int count = Selector.Select ( );
                    int count = 0;

                    if (!IsRunning)
                    {
                        return;
                    }

                    lock ( ClientsToReopen ) {
                        if (ClientsToReopen.Count > 0)
                        {
                            Dictionary <IClient, int> .KeyCollection clients = ClientsToReopen.Keys;
                            MonitorThread monitorThread = MonitorThread.Instance;

                            foreach (IClient client in clients)
                            {
                                Device device = client.DeviceImplementation;
                                int    pid    = client.ClientData.Pid;

                                monitorThread.DropClient(client, false /* notify */);

                                // This is kinda bad, but if we don't wait a bit, the client
                                // will never answer the second handshake!
                                WaitBeforeContinue( );

                                int port = ClientsToReopen[client];

                                if (port == DebugPortManager.NO_STATIC_PORT)
                                {
                                    port = GetNextDebuggerPort( );
                                }
                                Log.d("DeviceMonitor", "Reopening " + client);
                                OpenClient(device, pid, port, monitorThread);
                                device.OnClientListChanged(EventArgs.Empty);
                            }

                            ClientsToReopen.Clear( );
                        }
                    }

                    if (count == 0)
                    {
                        continue;
                    }

                    /*List<SelectionKey> keys = Selector.selectedKeys();
                     * List<SelectionKey>.Enumerator iter = keys.GetEnumerator();
                     *
                     * while (iter.MoveNext()) {
                     *              SelectionKey key = iter.next();
                     *              iter.remove();
                     *
                     *              if (key.isValid() && key.isReadable()) {
                     *                              Object attachment = key.attachment();
                     *
                     *                              if (attachment instanceof Device) {
                     *                                              Device device = (Device)attachment;
                     *
                     *                                              SocketChannel socket = device.getClientMonitoringSocket();
                     *
                     *                                              if (socket != null) {
                     *                                                              try {
                     *                                                                              int length = readLength(socket, mLengthBuffer2);
                     *
                     *                                                                              processIncomingJdwpData(device, socket, length);
                     *                                                              } catch (IOException ioe) {
                     *                                                                              Log.d("DeviceMonitor",
                     *                                                                                                              "Error reading jdwp list: " + ioe.getMessage());
                     *                                                                              socket.close();
                     *
                     *                                                                              // restart the monitoring of that device
                     *                                                                              synchronized (mDevices) {
                     *                                                                                              if (mDevices.contains(device)) {
                     *                                                                                                              Log.d("DeviceMonitor",
                     *                                                                                                                                              "Restarting monitoring service for " + device);
                     *                                                                                                              startMonitoringDevice(device);
                     *                                                                                              }
                     *                                                                              }
                     *                                                              }
                     *                                              }
                     *                              }
                     *              }
                     * }*/
                } catch (IOException e) {
                    if (!IsRunning)
                    {
                    }
                }
            } while (IsRunning);
        }
Esempio n. 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="entries"></param>
        /// <param name="localPath"></param>
        /// <param name="fls"></param>
        /// <param name="monitor"></param>
        /// <returns></returns>
        /// <exception cref="System.IO.IOException">Throws if unable to create a file or folder</exception>
        /// <exception cref="System.ArgumentNullException">Throws if the ISyncProgressMonitor is null</exception>
        private SyncResult DoPull(IEnumerable <FileEntry> entries, string localPath, FileListingService fileListingService, ISyncProgressMonitor monitor)
        {
            if (monitor == null)
            {
                throw new ArgumentNullException("monitor", "Monitor cannot be null");
            }

            // check if we're cancelled
            if (monitor.IsCanceled)
            {
                return(new SyncResult(ErrorCodeHelper.RESULT_CANCELED));
            }

            // check if we need to create the local directory
            DirectoryInfo localDir = new DirectoryInfo(localPath);

            if (!localDir.Exists)
            {
                localDir.Create( );
            }

            foreach (FileEntry e in entries)
            {
                // check if we're cancelled
                if (monitor.IsCanceled)
                {
                    return(new SyncResult(ErrorCodeHelper.RESULT_CANCELED));
                }

                // the destination item (folder or file)


                String dest = Path.Combine(localPath, e.Name);

                // get type (we only pull directory and files for now)
                FileListingService.FileTypes type = e.Type;
                if (type == FileListingService.FileTypes.Directory)
                {
                    monitor.StartSubTask(e.FullPath, dest);
                    // then recursively call the content. Since we did a ls command
                    // to get the number of files, we can use the cache
                    FileEntry[] children = fileListingService.GetChildren(e, true, null);
                    SyncResult  result   = DoPull(children, dest, fileListingService, monitor);
                    if (result.Code != ErrorCodeHelper.RESULT_OK)
                    {
                        return(result);
                    }
                    monitor.Advance(1);
                }
                else if (type == FileListingService.FileTypes.File)
                {
                    monitor.StartSubTask(e.FullPath, dest);
                    SyncResult result = DoPullFile(e.FullPath, dest, monitor);
                    if (result.Code != ErrorCodeHelper.RESULT_OK)
                    {
                        return(result);
                    }
                }
                else if (type == FileListingService.FileTypes.Link)
                {
                    monitor.StartSubTask(e.FullPath, dest);
                    SyncResult result = DoPullFile(e.FullResolvedPath, dest, monitor);
                    if (result.Code != ErrorCodeHelper.RESULT_OK)
                    {
                        return(result);
                    }
                }
                else
                {
                    Log.d("ddms-sync", String.Format("unknown type to transfer: {0}", type));
                }
            }

            return(new SyncResult(ErrorCodeHelper.RESULT_OK));
        }
Esempio n. 4
0
        /// <summary>
        /// Monitors the devices. This connects to the Debug Bridge
        /// </summary>
        private void DeviceMonitorLoop( )
        {
            IsRunning = true;
            do
            {
                try {
                    if (MainAdbConnection == null)
                    {
                        Log.d(TAG, "Opening adb connection");
                        MainAdbConnection = OpenAdbConnection( );

                        if (MainAdbConnection == null)
                        {
                            ConnectionAttemptCount++;
                            Log.e(TAG, "Connection attempts: {0}", ConnectionAttemptCount);

                            if (ConnectionAttemptCount > 10)
                            {
                                if (Server.Start( ) == false)
                                {
                                    RestartAttemptCount++;
                                    Log.e(TAG, "adb restart attempts: {0}", RestartAttemptCount);
                                }
                                else
                                {
                                    RestartAttemptCount = 0;
                                }
                            }
                            WaitBeforeContinue( );
                        }
                        else
                        {
                            Log.d(TAG, "Connected to adb for device monitoring");
                            ConnectionAttemptCount = 0;
                        }
                    }
                    if (MainAdbConnection != null && !IsMonitoring && MainAdbConnection.Connected)
                    {
                        IsMonitoring = SendDeviceListMonitoringRequest( );
                    }

                    if (IsMonitoring)
                    {
                        // read the length of the incoming message
                        int length = ReadLength(MainAdbConnection, LengthBuffer);

                        if (length >= 0)
                        {
                            // read the incoming message
                            ProcessIncomingDeviceData(length);

                            // flag the fact that we have build the list at least once.
                            HasInitialDeviceList = true;
                        }
                    }
                } catch (IOException ioe) {
                    if (!IsRunning)
                    {
                        Log.e(TAG, "Adb connection Error: ", ioe);
                        IsMonitoring = false;
                        if (MainAdbConnection != null)
                        {
                            try {
                                MainAdbConnection.Close( );
                            } catch (IOException) {
                                // we can safely ignore that one.
                            }
                            MainAdbConnection = null;
                        }
                    }
                } catch (Exception ex) {
                    Log.e(TAG, ex);
                }
            } while (IsRunning);
        }
        /// <summary>
        /// Queries adb for its version number and checks it against #MIN_VERSION_NUMBER and MAX_VERSION_NUMBER
        /// </summary>
        private void CheckAdbVersion( )
        {
            // default is bad check
            VersionCheck = false;

            if (String.IsNullOrEmpty(AdbOsLocation))
            {
                Console.WriteLine("AdbOsLocation is Empty");
                return;
            }

            try {
                Log.d(DDMS, String.Format("Checking '{0} version'", AdbOsLocation));

                ProcessStartInfo psi = new ProcessStartInfo(AdbOsLocation, "version");
                psi.WindowStyle            = ProcessWindowStyle.Hidden;
                psi.CreateNoWindow         = true;
                psi.UseShellExecute        = false;
                psi.RedirectStandardError  = true;
                psi.RedirectStandardOutput = true;

                List <String> errorOutput = new List <String> ( );
                List <String> stdOutput   = new List <String> ( );
                using (Process proc = Process.Start(psi)) {
                    int status = GrabProcessOutput(proc, errorOutput, stdOutput, true /* waitForReaders */);
                    if (status != 0)
                    {
                        StringBuilder builder = new StringBuilder("'adb version' failed!");
                        builder.AppendLine(string.Empty);
                        foreach (String error in errorOutput)
                        {
                            builder.AppendLine(error);
                        }
                        Log.LogAndDisplay(LogLevel.Error, "adb", builder.ToString( ));
                    }
                }

                // check both stdout and stderr
                bool versionFound = false;
                foreach (String line in stdOutput)
                {
                    versionFound = ScanVersionLine(line);
                    if (versionFound)
                    {
                        break;
                    }
                }

                if (!versionFound)
                {
                    foreach (String line in errorOutput)
                    {
                        versionFound = ScanVersionLine(line);
                        if (versionFound)
                        {
                            break;
                        }
                    }
                }

                if (!versionFound)
                {
                    // if we get here, we failed to parse the output.
                    Log.LogAndDisplay(LogLevel.Error, ADB, "Failed to parse the output of 'adb version'");
                }
            } catch (IOException e) {
                Log.LogAndDisplay(LogLevel.Error, ADB, "Failed to get the adb version: " + e.Message);
            }
        }