Skip to content

Commit 7e18e4c

Browse files
author
wilinz
committed
增加手动连接ADB命令和手动关闭连接命令,修复若干BUG
1 parent 3b25011 commit 7e18e4c

File tree

4 files changed

+110
-33
lines changed

4 files changed

+110
-33
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@
5656
* 停止服务(Stop Server): 停止插件服务
5757
* 开始监听ADB设备(Start track adb devices): 开启后会自动连接ADB设备
5858
* 停止监听ADB设备(Stop track adb devices)
59+
* 手动连接ADB设备(Manually connect adb device)
60+
* 手动关闭设备连接(Manually disconnect device)
5961
* 打开文档(Open Document): 打开Auto.js开发文档
6062
* 显示服务端二维码(Show qr code): 显示服务端二维码,之后可用客户端扫码连接
6163
* 显示服务端ip地址(Show server address)

package.json

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
"onCommand:extension.stopAllServer",
2121
"onCommand:extension.startTrackADBDevices",
2222
"onCommand:extension.stopTrackADBDevices",
23+
"onCommand:extension.manuallyConnectADB",
24+
"onCommand:extension.manuallyDisconnect",
2325
"onCommand:extension.showQrCode",
2426
"onCommand:extension.showServerAddress",
2527
"onCommand:extension.openDocument",
@@ -126,6 +128,16 @@
126128
"title": "停止监听ADB设备(Stop track adb devices)",
127129
"category": "Auto.js autoxjs"
128130
},
131+
{
132+
"command": "extension.manuallyConnectADB",
133+
"title": "手动连接ADB设备(Manually connect adb device)",
134+
"category": "Auto.js autoxjs"
135+
},
136+
{
137+
"command": "extension.manuallyDisconnect",
138+
"title": "手动关闭设备连接(Manually disconnect device)",
139+
"category": "Auto.js autoxjs"
140+
},
129141
{
130142
"command": "extension.run",
131143
"title": "运行脚本(Run)",

src/autojs-debug.ts

Lines changed: 73 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@ import * as url from 'url';
66
import * as fs from 'fs'
77
import { Project, ProjectObserser } from './project';
88
import * as vscode from "vscode";
9-
import Adb, { DeviceClient } from '@devicefarmer/adbkit';
9+
import Adb, { DeviceClient, Forward } from '@devicefarmer/adbkit';
1010
import Tracker from '@devicefarmer/adbkit/dist/src/adb/tracker';
11+
import ADBDevice from '@devicefarmer/adbkit/dist/src/Device';
1112

1213
const DEBUG = false;
1314

@@ -22,14 +23,16 @@ const HANDSHAKE_TIMEOUT = 10 * 1000;
2223

2324
export class Device extends EventEmitter {
2425
public name: string;
25-
public address: string;
26+
public type: string;
27+
public id: string;
2628
private connection: ws.connection;
27-
private attached: boolean = false;
29+
public attached: boolean = false;
2830
public projectObserser: ProjectObserser;
2931

30-
constructor(connection: ws.connection, address: string) {
32+
constructor(connection: ws.connection, type: string, id: string) {
3133
super();
32-
this.address = address
34+
this.type = type
35+
this.id = id
3336
this.connection = connection;
3437
this.read(this.connection);
3538
this.on('data:hello', data => {
@@ -51,6 +54,14 @@ export class Device extends EventEmitter {
5154
}, HANDSHAKE_TIMEOUT);
5255
}
5356

57+
close() {
58+
let message_id = `${Date.now()}_${Math.random()}`;
59+
let closeMessage = JSON.stringify({ message_id, data: "close", debug: false, type: 'close' })
60+
this.connection.sendUTF(closeMessage);
61+
this.connection.close();
62+
this.connection = null;
63+
}
64+
5465
send(type: string, data: any): void {
5566
let message_id = `${Date.now()}_${Math.random()}`;
5667
console.log(data);
@@ -85,9 +96,9 @@ export class Device extends EventEmitter {
8596

8697
public toString = (): string => {
8798
if (!this.name) {
88-
return `Device (${this.address})`;
99+
return `Device (${this.type}: ${this.id})`;
89100
}
90-
return `Device ${this.name}(${this.address})`;
101+
return `Device ${this.name}(${this.type}: ${this.id})`;
91102
}
92103

93104
private read(connection: ws.connection) {
@@ -148,18 +159,24 @@ export class AutoJsDebugServer extends EventEmitter {
148159
response.end();
149160
}
150161
});
151-
var wsServer = new ws.server({ httpServer: this.httpServer });
162+
let wsServer = new ws.server({ httpServer: this.httpServer });
152163
wsServer.on('request', request => {
153164
let connection = request.accept();
154165
if (!connection) {
155166
return;
156167
}
157-
this.newDevice(connection, connection.remoteAddress)
168+
this.newDevice(connection, "tcp", connection.socket.remoteAddress + ":" + connection.socket.remotePort)
169+
})
170+
}
171+
172+
getDeviceById(id: string): Device {
173+
return this.devices.find((value) => {
174+
return value.id == id
158175
})
159176
}
160177

161-
private newDevice(connection: ws.connection, address: string) {
162-
let device = new Device(connection, address);
178+
private newDevice(connection: ws.connection, type: string, id: string) {
179+
let device = new Device(connection, type, id);
163180
logDebug(connection.state, "--->status")
164181
device.on("attach", (device) => {
165182
this.attachDevice(device);
@@ -183,11 +200,9 @@ export class AutoJsDebugServer extends EventEmitter {
183200

184201
client.on('connect', function (connection) {
185202
console.log("connected to " + url)
186-
autoJsDebugServer.newDevice(connection, "ADB: " + deviceId)
203+
autoJsDebugServer.newDevice(connection, "adb", deviceId)
187204
});
188-
189-
//下面不能加'echo-protocol',否则会报Can`t connect due to "Sec-WebSocket-Protocol header"的错。因为服务器没有返回对应协议规定的信息
190-
client.connect(url); //, 'echo-protocol');
205+
client.connect(url);
191206
}
192207

193208
listen(): void {
@@ -208,31 +223,40 @@ export class AutoJsDebugServer extends EventEmitter {
208223
});
209224
}
210225

226+
227+
async listADBDevices(): Promise<ADBDevice[]> {
228+
return this.adbClient.listDevices();
229+
}
230+
211231
async trackADBDevices() {
212232
let thisServer = this
233+
let devices = await thisServer.adbClient.listDevices()
234+
for (let device0 of devices) {
235+
await thisServer.connectDevice(device0.id)
236+
}
213237
if (this.tracker) {
214238
this.emit("adb:tracking_started");
215239
return
216240
}
217-
let devices = await thisServer.adbClient.listDevices()
218-
for (let device0 of devices) {
219-
const device = thisServer.adbClient.getDevice(device0.id)
220-
await thisServer.connectDevice(device, device0.id)
221-
}
222241
try {
223242
let tracker = await thisServer.adbClient.trackDevices()
224-
this.tracker = tracker
243+
thisServer.tracker = tracker
225244
tracker.on('add', async function (device0) {
226245
console.log("adb device " + device0.id + " added")
227246
const device = thisServer.adbClient.getDevice(device0.id)
228247
await device.waitForDevice()
229-
await thisServer.connectDevice(device, device0.id)
248+
await thisServer.connectDevice(device0.id, device)
230249
})
231250
tracker.on('remove', function (device) {
232251
console.log("adb device " + device.id + " removed")
252+
let wsDevice = thisServer.getDeviceById(device.id)
253+
if (wsDevice) {
254+
wsDevice.close()
255+
}
256+
233257
})
234258
tracker.on('end', function () {
235-
tracker=undefined
259+
thisServer.tracker = undefined
236260
console.log('ADB Tracking stopped')
237261
thisServer.emit("adb:tracking_stop")
238262
})
@@ -245,22 +269,36 @@ export class AutoJsDebugServer extends EventEmitter {
245269
this.emit("adb:tracking_start");
246270
}
247271

248-
private async connectDevice(device: DeviceClient, id: string) {
249-
let forwarded = await device.forward(`tcp:0`, `tcp:9317`)
250-
if (forwarded) {
251-
let forwards = await device.listForwards()
252-
if (forwards.length > 0) {
253-
let forward = forwards[0]
254-
console.log(`forward ${id}: ${forwards.toString()}`)
255-
let port = Number(forward.local.replace("tcp:", ""))
256-
this.connectAutoxjsByADB(port, id)
272+
async connectDevice(id: string, device: DeviceClient = undefined) {
273+
if (!device) device = this.adbClient.getDevice(id)
274+
let wsDevice = this.getDeviceById(id)
275+
if (wsDevice && wsDevice.attached) return
276+
let forwards: Forward[] = await this.listForwards(device, id)
277+
if (forwards.length == 0) {
278+
let forwarded = await device.forward(`tcp:0`, `tcp:9317`)
279+
if (forwarded) {
280+
forwards = await this.listForwards(device, id)
257281
}
258282
}
283+
if (forwards.length > 0) {
284+
let forward = forwards[0]
285+
console.log(`forward ${id}: local -> ${forward.local}, remote -> ${forward.remote}`)
286+
let port = Number(forward.local.replace("tcp:", ""))
287+
this.connectAutoxjsByADB(port, id)
288+
}
289+
}
290+
291+
private async listForwards(device: DeviceClient, id: string): Promise<Forward[]> {
292+
let forwards: Forward[] = await device.listForwards()
293+
return forwards.filter((value) => {
294+
return value.serial == id
295+
})
259296
}
260297

261298
stopTrackADBDevices() {
262299
if (this.tracker) {
263300
this.tracker.end()
301+
this.tracker = undefined
264302
}
265303
}
266304

@@ -314,6 +352,9 @@ export class AutoJsDebugServer extends EventEmitter {
314352
channel.dispose();
315353
});
316354
this.logChannels.clear();
355+
this.devices.forEach((device) => {
356+
device.close()
357+
})
317358
}
318359

319360
/** 获取本地IP */

src/extension.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,28 @@ class Extension {
255255
server.stopTrackADBDevices()
256256
}
257257

258+
async manuallyConnectADB() {
259+
let devices = await server.listADBDevices()
260+
let deviceIds = devices.map((device) => { return device.id })
261+
for (let device0 of devices) {
262+
vscode.window.showQuickPick(deviceIds)
263+
.then(id => {
264+
server.connectDevice(id)
265+
});
266+
}
267+
}
268+
269+
manuallyDisconnect() {
270+
let devices = server.devices
271+
let deviceIds = devices.map((device) => { return device.id })
272+
for (let device0 of devices) {
273+
vscode.window.showQuickPick(deviceIds)
274+
.then(id => {
275+
server.getDeviceById(id).close()
276+
});
277+
}
278+
}
279+
258280
run(url?) {
259281
this.runOrRerun('run', url);
260282
}
@@ -421,7 +443,7 @@ class Extension {
421443
let _context: any;
422444
let extension = new Extension();
423445
const commands = ['startAllServer', 'stopAllServer', 'startServer', 'stopServer', 'startTrackADBDevices',
424-
'stopTrackADBDevices', 'showServerAddress', 'showQrCode', 'openDocument', 'run', 'runOnDevice',
446+
'stopTrackADBDevices', 'manuallyConnectADB', 'manuallyDisconnect', 'showServerAddress', 'showQrCode', 'openDocument', 'run', 'runOnDevice',
425447
'stop', 'stopAll', 'rerun', 'save', 'saveToDevice', 'newProject', 'runProject', 'saveProject'];
426448

427449
export function activate(context: vscode.ExtensionContext) {

0 commit comments

Comments
 (0)