| // Copyright (C) 2016 The Android Open Source Project |
| // |
| // Licensed under the Apache License, Version 2.0 (the "License"); |
| // you may not use this file except in compliance with the License. |
| // You may obtain a copy of the License at |
| // |
| // http://www.apache.org/licenses/LICENSE-2.0 |
| // |
| // Unless required by applicable law or agreed to in writing, software |
| // distributed under the License is distributed on an "AS IS" BASIS, |
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| // See the License for the specific language governing permissions and |
| // limitations under the License. |
| |
| package adb |
| |
| import ( |
| "errors" |
| "net/url" |
| "strings" |
| |
| "android.googlesource.com/platform/tools/gpu/client/bind" |
| "android.googlesource.com/platform/tools/gpu/client/shell" |
| "android.googlesource.com/platform/tools/gpu/framework/log" |
| ) |
| |
| // Devices returns the list of attached Android devices. |
| func Devices(ctx log.Context) ([]Device, error) { |
| out, err := shell.Command(ADB, "devices").Call(ctx) |
| if err != nil { |
| return nil, err |
| } |
| return parseDevices(ctx, out) |
| } |
| |
| func parseDevices(ctx log.Context, out string) ([]Device, error) { |
| a := strings.SplitAfter(out, "List of devices attached") |
| if len(a) != 2 { |
| return nil, errors.New("Device list not returned") |
| } |
| lines := strings.Split(a[1], "\n") |
| devices := make([]Device, 0, len(lines)) |
| for _, line := range lines { |
| if strings.HasPrefix(line, "adb server version") && strings.HasSuffix(line, "killing...") { |
| continue // adb server version (36) doesn't match this client (35); killing... |
| } |
| if strings.HasPrefix(line, "*") { |
| continue // For example, "* daemon started successfully *" |
| } |
| fields := strings.Fields(line) |
| switch len(fields) { |
| case 0: |
| continue |
| case 2: |
| device, err := bind.URL(ctx, &url.URL{Scheme: Scheme, Path: fields[0]}) |
| if err != nil { |
| return nil, err |
| } |
| d := device.(*binding) |
| status := fields[1] |
| switch status { |
| case "unknown": |
| d.LastStatus = bind.Status_Unknown |
| case "offline": |
| d.LastStatus = bind.Status_Offline |
| case "device": |
| d.LastStatus = bind.Status_Online |
| case "unauthorized": |
| d.LastStatus = bind.Status_Unauthorized |
| default: |
| return nil, ctx.V("Value", status).AsError("Invalid status string") |
| } |
| devices = append(devices, d) |
| default: |
| return nil, errors.New("Could not parse device list") |
| } |
| } |
| return devices, nil |
| } |