@@ -51,10 +51,18 @@ func FromSerial(serial string, adbPath string) (*ADBConnection, error) {
5151 adbPath = FindAdbPath ()
5252 }
5353
54- return & ADBConnection {
54+ conn := & ADBConnection {
5555 host : serial ,
5656 adbPath : adbPath ,
57- }, nil
57+ }
58+
59+ if connected , err := conn .IsConnected (); err != nil {
60+ return nil , err
61+ } else if ! connected {
62+ return nil , fmt .Errorf ("device %s is not connected" , serial )
63+ }
64+
65+ return conn , nil
5866}
5967
6068func FromHost (host string , adbPath string ) (* ADBConnection , error ) {
@@ -71,6 +79,23 @@ func FromHost(host string, adbPath string) (*ADBConnection, error) {
7179 return FromSerial (host , adbPath )
7280}
7381
82+ func (a * ADBConnection ) IsConnected () (bool , error ) {
83+ cmd , err := paths .NewProcess (nil , a .adbPath , "-s" , a .host , "get-state" )
84+ if err != nil {
85+ return false , fmt .Errorf ("failed to create ADB command: %w" , err )
86+ }
87+
88+ output , err := cmd .RunAndCaptureCombinedOutput (context .TODO ())
89+ if err != nil {
90+ if strings .Contains (string (output ), "device offline" ) {
91+ return false , nil
92+ }
93+ return false , fmt .Errorf ("failed to get ADB device state: %w: %s" , err , output )
94+ }
95+
96+ return string (bytes .TrimSpace (output )) == "device" , nil
97+ }
98+
7499func (a * ADBConnection ) Forward (ctx context.Context , localPort int , remotePort int ) error {
75100 if ! ports .IsAvailable (localPort ) {
76101 return remote .ErrPortAvailable
0 commit comments