adbutils

package module
v0.0.0-...-97782b5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 24, 2024 License: MIT Imports: 23 Imported by: 0

README

adbutils

GoDoc Go Report Card Sourcegraph Release Goproxy.cn

Transfer from python adbutils

Table of Contents

Install

  • No development plan yet

Usage

Example

Connect ADB Server

package test

import (
	"fmt"
	"testing"

	"github.com/lzy1102/adbutils"
)

var adb = adbutils.AdbClient{Host: "localhost", Port: 5037, SocketTime: 10}

func TestConnect(t *testing.T) {
	for _, i := range adb.DeviceList() {
		adb.Connect(i.Serial)
		snNtid := adbutils.SerialNTransportID{
			Serial: i.Serial,
		}
		fmt.Println(adb.Device(snNtid).SayHello())
	}

}

List all the devices and get device object

package main

import (
	"fmt"

	"github.com/lzy1102/adbutils"
)
adb := adbutils.NewAdb("localhost", 5037, 10)

func ShowSerials() {
	for _, device := range adb.DeviceList() {
		fmt.Println("", device.Serial)
	}
}

type SerialNTransportID struct {
    // you get this struct by adbutils.SerialNTransportID
	Serial      string
	TransportID int
}

just_serial := SerialNTransportID{Serial: "33ff22xx"}
adb.Device(just_serial)

// or
just_transport_id := SerialNTransportID{TransportID: 24}
adb.Device(just_transport_id) // transport_id can be found in: adb devices -l

// # You do not need to offer serial if only one device connected
// # RuntimeError will be raised if multi device connected
// d = adb.Device()

The following code will not write from adbutils import adb for short

Connect or disconnect remote device

Same as command adb connect

output := adb.Connect("127.0.0.1:5555")
// output: already connected to 127.0.0.1:5555

# connect with timeout
// timeout 10
adb := adbutils.NewAdb("localhost", 5037, 10)


// Disconnect
adb.Disconnect("127.0.0.1:5555")
adb.Disconnect("127.0.0.1:5555", raise_error=True) # if device is not present, AdbError will raise

// wait-for-device
// TODO

Create socket connection to the device

For example

func (adbConnection AdbConnection) ReadString(n int) string {
	res := adbConnection.Read(n)
	return string(res)
}

func (adbConnection AdbConnection) ReadStringBlock() string {
	str := adbConnection.ReadString(4)
	if len(str) == 0 {
		log.Fatal("receive data error connection closed")
	}
	size, _ := strconv.ParseUint(str, 16, 32)
	return adbConnection.ReadString(int(size))
}

func (adbConnection AdbConnection) ReadUntilClose() string {
	buf := []byte{}
	for {
		chunk := adbConnection.Read(4096)
		if len(chunk) == 0 {
			break
		}

		buf = append(buf, chunk...)
	}
	return string(buf)
}
func (adbConnection AdbConnection) createSocket() (*net.Conn, error) {
	conn, err := net.Dial("tcp", fmt.Sprintf("%v:%d", adbConnection.Host, adbConnection.Port))
	if err != nil {
		return nil, err
	}
	return &conn, nil
}

There are many other usage, see SERVICES.TXT for more details

Run shell command

I assume there is only one device connected.

package main

import (
	"fmt"

	"github.com/lzy1102/adbutils"
)

// 获取序列号
func GetServerVersion() {
	adb := adbutils.AdbClient{Host: "localhost", Port: 5037, SocketTime: 10}
	version := adb.ServerVersion()
	fmt.Printf("version: %d\n\n", version)
}

func Shell(arg string) {
	adb := adbutils.NewAdb("localhost", 5037, 10)
	for _, device := range adb.DeviceList() {
		fmt.Printf("Now show device: %s, ls: \n", device.Serial)
		fmt.Println(device.Shell(arg, false))
	}
}

func main() {
	GetServerVersion()
	Shell("ls")
}

Other You Can Send:

  • Argument just support str Shell(["getprop", "ro.serial"]) - can't work

  • Can't Set timeout for shell command Shell("sleep 1", timeout=0.5) - Recommend you set timeout by adb's socketTime

  • The advanced shell (returncode archieved by add command suffix: ;echo EXIT:$?)

ret := device.Shell("echo 1")
fmt.Println(ret)
  • show property, also based on d.shell TODO
Environment variables
ANDROID_SERIAL  serial number to connect to
ANDROID_ADB_SERVER_HOST adb server host to connect to
ANDROID_ADB_SERVER_PORT adb server port to connect to
Color Logcat
  • No development plan yet

Experiment

TODO

For more usage, please see the code for details.

Examples

Record video using screenrecord

It is highly recommended that you follow this

// TODO

Reading Logcat

// TODO

Develop

Make sure you can connect Github, Now you can edit code in adbutils and test with

package test
import (
	"github.com/lzy1102/adbutils"
	"testing"
)
// .... test code here ...

Run tests requires one device connected to your computer

# change to repo directory
cd adbutils

go test test/*

Environment

Some environment can affect the adbutils behavior

  • ADBUTILS_ADB_PATH: specify adb path, default search from PATH
  • ANDROID_SERIAL: default adb serial
  • ANDROID_ADB_SERVER_HOST: default 127.0.0.1
  • ANDROID_ADB_SERVER_PORT: default 5037

Watch adb socket data

Watch the adb socket data using socat

$ socat -t100 -x -v TCP-LISTEN:5577,reuseaddr,fork TCP4:localhost:5037

open another terminal, type the following command then you will see the socket data

$ export ANDROID_ADB_SERVER_PORT=5577
$ adb devices

Generate TOC

gh-md-toc --insert README.md

https://github.com/ekalinin/github-markdown-toc

Thanks

Alternative

just like pure-python-adb

Alternative

Ref

LICENSE

MIT

Documentation

Index

Constants

View Source
const (
	OKAY            = "OKAY"
	FAIL            = "FAIL"
	DENT            = "DENT"
	DONE            = "DONE"
	DATA            = "DATA"
	TCP             = "tcp"
	UNIX            = "unix"
	DEV             = "dev"
	LOCAL           = "local"
	LOCALRESERVED   = "localreserved"
	LOCALFILESYSTEM = "localfilesystem"
	LOCALABSTRACT   = "localabstract"
	Windows         = "windows"
	Mac             = "darwin"
	Linux           = "linux"

	WinAdbURL = "https://dl.google.com/android/repository/platform-tools-latest-windows.zip"
)
View Source
const Version = "0.0.2"

Variables

This section is empty.

Functions

func AdbPath

func AdbPath() string

func Compression

func Compression(src, dst string) error

func GetFreePort

func GetFreePort() int

func Uncompression

func Uncompression(src, dst string) error

Types

type AdbClient

type AdbClient struct {
	Host       string
	Port       int
	SocketTime time.Duration
}

AdbClient region AdbClient

func NewAdb

func NewAdb(host string, port int, timeOut time.Duration) *AdbClient

func (*AdbClient) Connect

func (adb *AdbClient) Connect(addr string) string

func (*AdbClient) Device

func (adb *AdbClient) Device(snNtid SerialNTransportID) AdbDevice

func (*AdbClient) DeviceList

func (adb *AdbClient) DeviceList() []AdbDevice

func (*AdbClient) Disconnect

func (adb *AdbClient) Disconnect(addr string, raiseErr bool) string

func (*AdbClient) ServerKill

func (adb *AdbClient) ServerKill()

func (*AdbClient) ServerVersion

func (adb *AdbClient) ServerVersion() int

func (*AdbClient) Shell

func (adb *AdbClient) Shell(serial string, command string, stream bool) interface{}

func (*AdbClient) WaitFor

func (adb *AdbClient) WaitFor()

type AdbConnection

type AdbConnection struct {
	Host string
	Port int
	Conn net.Conn
}

func (AdbConnection) CheckOkay

func (adbConnection AdbConnection) CheckOkay()

func (AdbConnection) Close

func (adbConnection AdbConnection) Close()

func (AdbConnection) Read

func (adbConnection AdbConnection) Read(n int) []byte

func (AdbConnection) ReadString

func (adbConnection AdbConnection) ReadString(n int) string

func (AdbConnection) ReadStringBlock

func (adbConnection AdbConnection) ReadStringBlock() string

func (AdbConnection) ReadUntilClose

func (adbConnection AdbConnection) ReadUntilClose() string

func (AdbConnection) SendCommand

func (adbConnection AdbConnection) SendCommand(cmd string)

func (AdbConnection) SetTimeout

func (adbConnection AdbConnection) SetTimeout(timeOut time.Duration) error

type AdbDevice

type AdbDevice struct {
	ShellMixin
}

func (AdbDevice) AdbOut

func (adbDevice AdbDevice) AdbOut(command string) string

func (AdbDevice) CreateConnection

func (adbDevice AdbDevice) CreateConnection(netWork, address string) net.Conn

func (AdbDevice) ForWard

func (adbDevice AdbDevice) ForWard(local, remote string, noRebind bool) *AdbConnection

func (AdbDevice) ForWardPort

func (adbDevice AdbDevice) ForWardPort(remote interface{}) int

func (AdbDevice) ForwardList

func (adbDevice AdbDevice) ForwardList() []ForwardItem

func (AdbDevice) GetDevPath

func (adbDevice AdbDevice) GetDevPath() string

func (AdbDevice) GetFeatures

func (adbDevice AdbDevice) GetFeatures() string

func (AdbDevice) GetSerialNo

func (adbDevice AdbDevice) GetSerialNo() string

func (AdbDevice) GetState

func (adbDevice AdbDevice) GetState() string

func (AdbDevice) Info

func (adbDevice AdbDevice) Info() map[string]string

func (AdbDevice) Push

func (adbDevice AdbDevice) Push(local, remote string) string

func (AdbDevice) Shell

func (adbDevice AdbDevice) Shell(cmdargs string, stream bool, timeOut time.Duration) interface{}

func (AdbDevice) ShellOutPut

func (adbDevice AdbDevice) ShellOutPut(cmd string) string

func (AdbDevice) StartTCPIP

func (adbDevice AdbDevice) StartTCPIP(port string) string

func (AdbDevice) String

func (adbDevice AdbDevice) String()

func (AdbDevice) Sync

func (adbDevice AdbDevice) Sync() Sync

type AdbDeviceInfo

type AdbDeviceInfo struct {
	Serial string
	State  string
}

type DeviceEvent

type DeviceEvent struct {
	Present bool
	Serial  string
	Status  string
}

type FileInfo

type FileInfo struct {
	Mode  int
	Size  int
	Mtime *time.Time
	Path  string
}

type ForwardItem

type ForwardItem struct {
	Serial string
	Local  string
	Remote string
}

type ReverseItem

type ReverseItem struct {
	Remote string
	Local  string
}

type RunningAppInfo

type RunningAppInfo struct {
	Package  string
	Activity string
	Pid      int
}

type SerialNTransportID

type SerialNTransportID struct {
	Serial      string
	TransportID int
}

type ShellMixin

type ShellMixin struct {
	Client      *AdbClient
	Serial      string
	TransportID int
	Properties  map[string]string
}

func (ShellMixin) AppClear

func (mixin ShellMixin) AppClear(packageName string)

func (ShellMixin) AppStart

func (mixin ShellMixin) AppStart(packageName, activity string)

func (ShellMixin) AppStop

func (mixin ShellMixin) AppStop(packageName string)

func (ShellMixin) CLick

func (mixin ShellMixin) CLick(x, y int)

func (ShellMixin) CurrentApp

func (mixin ShellMixin) CurrentApp() string

func (ShellMixin) DumpHierarchy

func (mixin ShellMixin) DumpHierarchy() string

func (ShellMixin) GetProp

func (mixin ShellMixin) GetProp(prop string) string

func (ShellMixin) InstallRemote

func (mixin ShellMixin) InstallRemote(remotePath string, clean bool)

func (ShellMixin) IsScreenOn

func (mixin ShellMixin) IsScreenOn() bool

func (ShellMixin) KeyEvent

func (mixin ShellMixin) KeyEvent(keyCode string) string

func (ShellMixin) ListPackages

func (mixin ShellMixin) ListPackages() []string

func (ShellMixin) OpenBrowser

func (mixin ShellMixin) OpenBrowser(url string)

func (ShellMixin) PackageInfo

func (mixin ShellMixin) PackageInfo(packageName string)

func (ShellMixin) Remove

func (mixin ShellMixin) Remove(path string)

func (ShellMixin) Rotation

func (mixin ShellMixin) Rotation()

func (ShellMixin) SayHello

func (mixin ShellMixin) SayHello() string

func (ShellMixin) SendKeys

func (mixin ShellMixin) SendKeys(text string)

func (ShellMixin) Swipe

func (mixin ShellMixin) Swipe(x, y, tox, toy int, duration time.Duration)

func (ShellMixin) SwitchAirPlane

func (mixin ShellMixin) SwitchAirPlane(status bool)

func (ShellMixin) SwitchScreen

func (mixin ShellMixin) SwitchScreen(status bool)

func (ShellMixin) SwitchWifi

func (mixin ShellMixin) SwitchWifi(status bool)

func (ShellMixin) Uninstall

func (mixin ShellMixin) Uninstall(packageName string)

func (ShellMixin) WindowSize

func (mixin ShellMixin) WindowSize()

func (ShellMixin) WlanIp

func (mixin ShellMixin) WlanIp() string

type ShellReturn

type ShellReturn struct {
	Command    string
	ReturnCode int
	Output     string
}

type Sync

type Sync struct {
	*AdbClient
	Serial string
}

Sync region ync

func (Sync) Exist

func (sync Sync) Exist(path string) bool

func (Sync) IterContent

func (sync Sync) IterContent(path string) []byte

func (Sync) IterDirectory

func (sync Sync) IterDirectory(path string) []FileInfo

func (Sync) List

func (sync Sync) List(path string) []FileInfo

func (Sync) Pull

func (sync Sync) Pull(src, dst string) int

func (Sync) Push

func (sync Sync) Push(src, dst string, mode int, check bool) int

func (Sync) ReadBytes

func (sync Sync) ReadBytes(path string) []byte

func (Sync) ReadText

func (sync Sync) ReadText(path string) string

func (Sync) Stat

func (sync Sync) Stat(path string) FileInfo

type WindowSize

type WindowSize struct {
	Width  int
	Height int
}

Directories

Path Synopsis
* Test localhost Only one Device *
* Test localhost Only one Device *

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL