@aiot-toolkit/emulator 2.0.2-beta.1 → 2.0.2-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -35,79 +35,115 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
35
35
  return (mod && mod.__esModule) ? mod : { "default": mod };
36
36
  };
37
37
  Object.defineProperty(exports, "__esModule", { value: true });
38
- const JavascriptDefaultCompileOption_1 = __importDefault(require("@aiot-toolkit/aiotpack/lib/compiler/javascript/JavascriptDefaultCompileOption"));
39
38
  const ColorConsole_1 = __importDefault(require("@aiot-toolkit/shared-utils/lib/ColorConsole"));
40
39
  const adbMiwt = __importStar(require("@miwt/adb"));
41
40
  const child_process_1 = require("child_process");
42
41
  const fs_extra_1 = __importDefault(require("fs-extra"));
43
42
  const os_1 = __importDefault(require("os"));
44
43
  const path_1 = __importDefault(require("path"));
45
- const portfinder_1 = __importDefault(require("portfinder"));
46
44
  const ws_1 = __importStar(require("ws"));
47
45
  const constants_1 = require("../static/constants");
48
46
  const utils_1 = require("../utils");
49
47
  const common_1 = __importDefault(require("./common"));
48
+ const dayjs_1 = __importDefault(require("dayjs"));
50
49
  const MAX_RECONNECT_COUNT = 8;
51
50
  /**
52
51
  * MiwearInstance
53
- * 针对 vela4.0 的镜像
52
+ * 针对 Vela正式版(4.0)的镜像
54
53
  */
55
54
  class MiwearInstance extends common_1.default {
56
55
  constructor(params) {
57
56
  super(params);
57
+ this.params = params;
58
58
  this.appPathInEmulator = '/data/quickapp/app';
59
59
  this.reconnectCount = 0;
60
60
  }
61
- /** 在goldfish模拟器中运行快应用 */
61
+ /**
62
+ * 1. 启动模拟器
63
+ * 2. 启动成功后,adb连接模拟器
64
+ * 3. 连接成功后,在模拟器中启动快应用
65
+ */
62
66
  start(options) {
63
67
  return __awaiter(this, void 0, void 0, function* () {
64
68
  this.startOptions = options;
69
+ this.sn = `127.0.0.1:${this.startOptions.adbPort}`;
65
70
  // 启动模拟器
66
71
  yield this.startGoldfish(options);
67
72
  // adb连接模拟器
68
- const connected = yield this.connectGoldfish();
73
+ const connected = yield this.connectGoldfish(120);
69
74
  if (connected) {
70
75
  ColorConsole_1.default.info('### Emulator ### Goldfish emulator connected successfully');
76
+ // 如果是首次启动,创建server端监听事件
71
77
  if (this.isFirstStart && this.startOptions.serverPort) {
72
78
  yield this.createWebsockeServer();
73
79
  }
80
+ // 在模拟器中启动快应用
74
81
  this.startupQuickApp(options);
75
82
  this.isFirstStart = false;
76
83
  }
77
84
  else {
78
- ColorConsole_1.default.throw('### Emulator ### Failed to connect emulator, please check whether the adb is normal');
85
+ const msg = '### Emulator ### Failed to connect emulator, please check whether the adb is normal';
86
+ ColorConsole_1.default.throw(msg);
87
+ throw new Error(msg);
79
88
  }
80
89
  });
81
90
  }
82
- /** 启动goldfish模拟器 */
91
+ /**
92
+ * 启动模拟器
93
+ * 1. 通过options生成模拟器的启动命令
94
+ * 2. 执行启动命令
95
+ * 3. 判断模拟器是否启动成功
96
+ * 3.1 若disableNSH=true,输出流中匹配到/quickapp_rpk_installer_init|rpk installer init done/,认为模拟器启动成功了
97
+ * 3.2 若disableNSH=false,认为8s过后模拟器启动成功了
98
+ * @param options
99
+ * @returns
100
+ */
83
101
  startGoldfish(options) {
84
102
  var _a;
85
103
  return __awaiter(this, void 0, void 0, function* () {
86
- const { avdName, devtool } = options;
104
+ const { avdName, devtool, origin = 'terminal' } = options;
105
+ // 获取emulator bin的绝对路径
87
106
  const emulatorBin = this.getEmulatorBinPath();
88
107
  ColorConsole_1.default.log(`### Emulator ### emulator path: ${emulatorBin}`);
108
+ // 获取vela镜像的绝对路径
89
109
  const avdInfo = this.velaAvdCls.getVelaAvdInfo(avdName);
90
110
  const { avdArch, avdImagePath } = avdInfo;
91
- this.adbPort = yield portfinder_1.default.getPortPromise({ port: this.adbPort });
92
- ColorConsole_1.default.log(`### Emulator ### adb port: ${this.adbPort}`);
111
+ ColorConsole_1.default.log(`### Emulator ### adb port: ${options.adbPort}`);
93
112
  if (!avdImagePath) {
94
113
  return ColorConsole_1.default.throw(`### Emulator ### Unable to find vela image via avd`);
95
114
  }
96
115
  const nuttxBinPath = path_1.default.resolve(avdImagePath, 'nuttx');
97
116
  ColorConsole_1.default.log(`### Emulator ### nuttx path: ${nuttxBinPath}`);
98
- // 端口映射
99
- let portMappingStr = `-network-user-mode-options hostfwd=tcp:127.0.0.1:${this.adbPort}-10.0.2.15:5555`;
117
+ // 端口映射,adb端口和debug端口
118
+ let portMappingStr = `-network-user-mode-options hostfwd=tcp:127.0.0.1:${options.adbPort}-10.0.2.15:5555`;
100
119
  if (devtool) {
101
- this.debugPort = yield portfinder_1.default.getPortPromise({ port: this.debugPort });
102
- portMappingStr += `,hostfwd=tcp:127.0.0.1:${this.debugPort}-10.0.2.15:101`;
120
+ portMappingStr += `,hostfwd=tcp:127.0.0.1:${options.debugPort}-10.0.2.15:101`;
103
121
  }
104
- // 文件系统配置,第一次使用fatfs镜像挂载,后续使用adb push更新应用
105
- const systemImageBin = path_1.default.resolve(avdImagePath, 'vela_resource.img');
106
- const dataImageBin = path_1.default.resolve(avdImagePath, 'data.img');
107
- const imageMountStr = `-drive index=0,id=system,if=none,format=raw,file=${systemImageBin} \
122
+ // 设备挂载节点
123
+ const systemImageBin = path_1.default.resolve(avdImagePath, 'vela_resource.bin'); // 只读
124
+ const dataImageBin = path_1.default.resolve(avdImagePath, 'vela_data.bin'); // 可读可写
125
+ const coreBin = path_1.default.resolve(avdImagePath, 'coredump.core'); // 只读
126
+ // 复制可写文件到AVD目录下(多模拟器实例时需要)
127
+ const dataImageBinInAvd = path_1.default.join(this.avdHome, `${avdName}.avd`, 'vela_data.bin');
128
+ if (!fs_extra_1.default.existsSync(dataImageBinInAvd)) {
129
+ // vela_data.bin不存在时直接copy
130
+ fs_extra_1.default.copyFileSync(dataImageBin, dataImageBinInAvd);
131
+ }
132
+ else {
133
+ // vela_data.bin存在时,如果.export里的时间晚于avd里的时候,说明更新了镜像,需要重新copy
134
+ const statsInAvd = fs_extra_1.default.statSync(dataImageBinInAvd);
135
+ const stats = fs_extra_1.default.statSync(dataImageBin);
136
+ if ((0, dayjs_1.default)(stats.mtime).isAfter(statsInAvd.mtime)) {
137
+ fs_extra_1.default.copyFileSync(dataImageBin, dataImageBinInAvd);
138
+ }
139
+ }
140
+ // 挂载节点配置,只读文件加入read-only标识
141
+ const imageMountStr = `-drive index=0,id=system,if=none,format=raw,file=${systemImageBin},read-only \
108
142
  -device virtio-blk-device,bus=virtio-mmio-bus.0,drive=system \
109
- -drive index=1,id=userdata,if=none,format=raw,file=${dataImageBin} \
143
+ -drive index=1,id=userdata,if=none,format=raw,file=${dataImageBinInAvd} \
110
144
  -device virtio-blk-device,bus=virtio-mmio-bus.1,drive=userdata \
145
+ -drive index=2,id=vendor,if=none,format=raw,file=${coreBin},read-only \
146
+ -device virtio-blk-device,bus=virtio-mmio-bus.4,drive=vendor \
111
147
  -device virtio-snd,bus=virtio-mmio-bus.2 -allow-host-audio -semihosting`;
112
148
  // vnc配置
113
149
  let windowStr = '';
@@ -117,163 +153,188 @@ class MiwearInstance extends common_1.default {
117
153
  const portSuffix = this.startOptions.vncPort - constants_1.defaultVncPort;
118
154
  vncStr = `-vnc :${portSuffix}`;
119
155
  }
120
- const stdioType = options.disableNSH ? 'pipe' : 'inherit';
121
- // 启动goldfish的命令和参数
156
+ // 启动模拟器的命令和参数
122
157
  const cmd = `${emulatorBin} -nuttx -avd ${avdName} -avd-arch ${avdArch} -show-kernel -kernel ${nuttxBinPath} ${portMappingStr} ${windowStr} -qemu ${vncStr} ${imageMountStr}`;
123
158
  const spawnArgs = cmd.split(' ');
124
159
  const spawnBin = spawnArgs.shift();
125
160
  ColorConsole_1.default.log(`### Emulator ### Start CMD: ${cmd}`);
126
161
  return new Promise((resolve) => {
127
- var _a, _b, _c;
128
- this.goldfishProcess = (0, child_process_1.spawn)(spawnBin, spawnArgs, { stdio: stdioType, shell: true });
129
- (_a = this.goldfishProcess.stderr) === null || _a === void 0 ? void 0 : _a.on('data', (data) => {
130
- const stderrCb = options.stderrCallback || console.log;
131
- stderrCb(data.toString());
162
+ var _a, _b, _c, _d, _e;
163
+ this.goldfishProcess = (0, child_process_1.spawn)(spawnBin, spawnArgs, {
164
+ stdio: 'pipe',
165
+ shell: true,
166
+ cwd: this.sdkHome
132
167
  });
168
+ // 处理origin为terminal
169
+ if (origin === 'terminal') {
170
+ process.stdout.pipe(this.goldfishProcess.stdin);
171
+ (_a = this.goldfishProcess.stdout) === null || _a === void 0 ? void 0 : _a.pipe(process.stdout);
172
+ (_b = this.goldfishProcess.stderr) === null || _b === void 0 ? void 0 : _b.pipe(process.stderr);
173
+ }
174
+ // 监听模拟器的退出事件
133
175
  this.goldfishProcess.on('exit', (code) => {
134
176
  ColorConsole_1.default.error(`### Emulator ### Goldfish emulator exited with code ${code}`);
135
177
  if (options.exitCallback) {
136
178
  options.exitCallback(code);
137
179
  }
138
180
  });
139
- if (options.disableNSH) {
140
- (_c = (_b = this.goldfishProcess) === null || _b === void 0 ? void 0 : _b.stdout) === null || _c === void 0 ? void 0 : _c.on('data', (data) => {
141
- const msg = data.toString();
142
- const stdoutCb = options.stdoutCallback || console.log;
143
- stdoutCb(msg);
144
- if (msg.match(/quickapp_rpk_installer_init|rpk installer init done/)) {
145
- ColorConsole_1.default.info(`### Emulator ### Goldfish emulator starts successfully`);
146
- resolve();
147
- }
181
+ // 监听错误流
182
+ if (origin === 'ide') {
183
+ (_c = this.goldfishProcess.stderr) === null || _c === void 0 ? void 0 : _c.on('data', (data) => {
184
+ const stderrCb = options.stderrCallback || console.log;
185
+ stderrCb(data.toString());
148
186
  });
149
187
  }
150
- else {
151
- setTimeout(() => {
188
+ // 监听输出流
189
+ (_e = (_d = this.goldfishProcess) === null || _d === void 0 ? void 0 : _d.stdout) === null || _e === void 0 ? void 0 : _e.on('data', (data) => {
190
+ const msg = data.toString();
191
+ if (origin === 'ide') {
192
+ const stdoutCb = options.stdoutCallback || console.log;
193
+ stdoutCb(msg);
194
+ // 应用安装成功,则启动它
195
+ // if (msg.match(/InstallState_Finished|install finished/)) {
196
+ // ColorConsole.info(`### Emulator ### Install quickapp successfully`)
197
+ // this.launchQuickapp()
198
+ // }
199
+ }
200
+ // 匹配到,则认为模拟器启动成功
201
+ if (msg.match(/quickapp_rpk_installer_init|rpk installer init done/)) {
152
202
  ColorConsole_1.default.info(`### Emulator ### Goldfish emulator starts successfully`);
153
203
  resolve();
154
- }, 8000);
155
- ColorConsole_1.default.info(`### Emulator ### Goldfish emulator starts successfully`);
156
- resolve();
157
- }
158
- });
159
- });
160
- }
161
- /** 通过adb连接模拟器 */
162
- connectGoldfish() {
163
- return __awaiter(this, void 0, void 0, function* () {
164
- let adbConnected = false;
165
- const connectFn = () => __awaiter(this, void 0, void 0, function* () {
166
- const sn = `127.0.0.1:${this.adbPort}`;
167
- while (!adbConnected) {
168
- const adbKillCmd = `adb kill-server`;
169
- ColorConsole_1.default.log(`### Emulator ### Excuting adb cmd: ${adbKillCmd}`);
170
- yield adbMiwt.execAdbCmdAsync(adbKillCmd);
171
- const adbConnectCmd = `adb connect ${sn}`;
172
- ColorConsole_1.default.log(`### Emulator ### Excuting adb cmd: ${adbConnectCmd}`);
173
- const str = yield adbMiwt.execAdbCmdAsync(adbConnectCmd);
174
- ColorConsole_1.default.log(`### Emulator ### ${str}`);
175
- const devices = yield adbMiwt.getAdbDevices();
176
- ColorConsole_1.default.log(`### Emulator ### adb devices: ${JSON.stringify(devices)}`);
177
- adbConnected =
178
- devices.filter((item) => item.sn === sn && item.status === 'device').length > 0;
179
- }
180
- Promise.resolve(adbConnected);
204
+ }
205
+ });
181
206
  });
182
- yield Promise.race([
183
- connectFn(),
184
- new Promise((resolve) => {
185
- setTimeout(() => resolve(false), 600 * 1000);
186
- })
187
- ]);
188
- return adbConnected;
189
207
  });
190
208
  }
191
- /** 在goldfish中启动快应用 */
209
+ /**
210
+ * 在模拟器中启动快应用
211
+ * 1. 检查release目录是否有打包好的rpk
212
+ * 2. 检查当前是否为调试模式.
213
+ * 若是,将debugger_ip.cfg推到模拟器的/data/目录下
214
+ * 若否,则要删除模拟器中已有的data/debugger_ip.cfg
215
+ * 3. 调用installRpkToAppList将当前快应用安装到模拟器的应用列表中
216
+ * @param options
217
+ */
192
218
  startupQuickApp(options) {
219
+ var _a;
193
220
  return __awaiter(this, void 0, void 0, function* () {
194
221
  const { package: appPackageName } = this.projectInfo;
195
- const releaseDir = path_1.default.resolve(this.projectPath, JavascriptDefaultCompileOption_1.default.releasePath || 'dist');
222
+ const releaseDir = this.isRpk
223
+ ? path_1.default.resolve(this.projectPath, '../')
224
+ : path_1.default.resolve(this.projectPath, ((_a = this.params.compilerOption) === null || _a === void 0 ? void 0 : _a.releasePath) || 'dist');
196
225
  const files = fs_extra_1.default
197
226
  .readdirSync(releaseDir)
198
- .filter(item => item.includes(appPackageName) && item.endsWith('.rpk'));
199
- if (files.length < 0) {
227
+ .filter((item) => item.includes(appPackageName) && item.endsWith('.rpk'));
228
+ if (files.length === 0) {
200
229
  ColorConsole_1.default.error(`### Emulator the rpk does not exist`);
201
230
  }
202
231
  const rpkPath = path_1.default.resolve(releaseDir, files[0]);
203
232
  // 调试模式需要push一个文件至miwear中
204
- const sn = `127.0.0.1:${this.adbPort}`;
205
233
  if (options.devtool) {
206
234
  const debuggerCfgFile = path_1.default.join(__dirname, '../static/debugger_ip.cfg');
207
- yield adbMiwt.execAdbCmdAsync(`adb -s ${sn} push ${debuggerCfgFile} /data/debugger_ip.cfg`);
235
+ yield adbMiwt.execAdbCmdAsync(`adb -s ${this.sn} push ${debuggerCfgFile} /data/debugger_ip.cfg`);
208
236
  }
209
237
  else {
210
- adbMiwt.execAdbCmdAsync(`adb -s ${sn} shell rm /data/debugger_ip.cfg`);
238
+ adbMiwt.execAdbCmdAsync(`adb -s ${this.sn} shell rm /data/debugger_ip.cfg`);
211
239
  }
212
240
  this.installRpkToAppList(rpkPath, this.appPathInEmulator);
213
241
  });
214
242
  }
215
- /** 将快应用安装到应用列表 */
243
+ /**
244
+ * 将快应用安装到模拟器的应用列表
245
+ * 1. 使用adb push将打包好的rpk推到模拟器的/data/quickapp/app/
246
+ * 2. nsh中调用pm install命令安装应用
247
+ * @param rpkPath rpk的绝对目录
248
+ * @param targetDir 要将rpk放到模拟器的哪个目录下
249
+ */
216
250
  installRpkToAppList(rpkPath, targetDir) {
217
251
  return __awaiter(this, void 0, void 0, function* () {
218
252
  try {
219
- const sn = `127.0.0.1:${this.adbPort}`;
220
253
  const { package: packageName } = this.projectInfo;
221
- const rpkName = path_1.default.basename(rpkPath);
222
- // 1. 查询应用是否已经安装,如果安装了,则先卸载
223
- const lsCmd = `adb -s ${sn} shell ls ${this.appPathInEmulator}`;
224
- const res = yield adbMiwt.execAdbCmdAsync(lsCmd);
225
- if (res.includes(packageName)) {
226
- const uninstallCmd = `adb -s ${sn} shell pm uninstall ${packageName}`;
227
- ColorConsole_1.default.info(`### Emulator ### Excuting cmd: ${uninstallCmd}`);
228
- adbMiwt.execAdbCmdAsync(uninstallCmd);
229
- // 这里等待2s的作用是等qemu执行完uninstall操作的一系列工作
230
- yield (0, utils_1.sleep)(2000);
231
- }
232
- // 2. adb push应用的rpk
254
+ // 1. adb push应用的rpk
233
255
  const targetPath = `${targetDir}/${packageName}.rpk`;
234
- const pushCmd = `adb -s ${sn} push ${rpkPath} ${targetPath}`;
256
+ const pushCmd = `adb -s ${this.sn} push "${rpkPath}" ${targetPath}`;
235
257
  ColorConsole_1.default.info(`### Emulator ### Excuting cmd: ${pushCmd}`);
236
258
  yield adbMiwt.execAdbCmdAsync(pushCmd);
237
- yield (0, utils_1.sleep)(100);
238
- // 3. 安装应用
239
- const installCmd = `adb -s ${sn} shell pm install ${targetPath}`;
259
+ yield (0, utils_1.sleep)(1000);
260
+ // 2. 安装应用(pm install时如何应用重名会覆盖)
261
+ const installCmd = `adb -s ${this.sn} shell pm install ${targetPath}`;
240
262
  ColorConsole_1.default.info(`### Emulator ### Excuting cmd: ${installCmd}`);
241
- adbMiwt.execAdbCmdAsync(installCmd);
263
+ yield adbMiwt.execAdbCmdAsync(installCmd);
264
+ // 3. 应用安装成功后,启动应用
265
+ const lsCmd = `adb -s ${this.sn} shell ls ${this.appPathInEmulator}`;
266
+ let installed = false;
267
+ let currCount = 0;
268
+ while (!installed && currCount < 10) {
269
+ yield (0, utils_1.sleep)(1000);
270
+ const res = yield adbMiwt.execAdbCmdAsync(lsCmd);
271
+ // 如果没有上传的rpk了,则表示安装成功
272
+ installed = !res.includes(`${packageName}.rpk`);
273
+ currCount++;
274
+ }
275
+ if (installed) {
276
+ this.launchQuickapp();
277
+ }
278
+ else {
279
+ ColorConsole_1.default.error(`### Emulator ### install ${packageName} failed`);
280
+ }
281
+ }
282
+ catch (e) {
283
+ ColorConsole_1.default.error(`### Emulator ### ${e.message}`);
242
284
  }
243
- catch (e) { }
244
285
  });
245
286
  }
287
+ /** 使用am start启动快应用 */
288
+ launchQuickapp() {
289
+ return __awaiter(this, void 0, void 0, function* () {
290
+ const { package: packageName } = this.projectInfo;
291
+ const startCmd = `adb -s ${this.sn} shell am start ${packageName}`;
292
+ ColorConsole_1.default.info(`### Emulator ### Excuting cmd: ${startCmd}`);
293
+ adbMiwt.execAdbCmdAsync(startCmd);
294
+ });
295
+ }
296
+ /** 连接模拟器中的调试服务,创建debugSocket
297
+ * 主要用于热更新时,通过debugSocket通知调试服务更新页面
298
+ * 设置了重连机制,会重复连接8次
299
+ */
246
300
  initDebugSocket() {
247
- if (this.debugSocket && this.debugSocket.OPEN) {
248
- return Promise.resolve();
249
- }
250
- this.debugSocket = new ws_1.default(`ws://localhost:${this.debugPort}`);
251
- this.debugSocket.onopen = () => {
252
- ColorConsole_1.default.info(`### Emulator debugSocket connect success`);
253
- return Promise.resolve();
254
- };
255
- this.debugSocket.onerror = (e) => {
301
+ return new Promise((resolve, reject) => {
256
302
  var _a;
257
- // 重连机制
258
- (_a = this.debugSocket) === null || _a === void 0 ? void 0 : _a.terminate();
259
- if (this.reconnectCount < MAX_RECONNECT_COUNT) {
260
- ColorConsole_1.default.info(`### Emulator the ${this.reconnectCount + 1}th time to reconnect debug server`);
261
- this.reconnectCount++;
262
- setTimeout(() => this.initDebugSocket(), 2000);
303
+ if (this.debugSocket && this.debugSocket.OPEN) {
304
+ return resolve();
263
305
  }
264
- else {
306
+ this.debugSocket = new ws_1.default(`ws://localhost:${(_a = this.startOptions) === null || _a === void 0 ? void 0 : _a.debugPort}`);
307
+ this.debugSocket.onopen = () => {
308
+ ColorConsole_1.default.info(`### Emulator debugSocket connect success`);
309
+ return resolve();
310
+ };
311
+ this.debugSocket.onerror = (errorEvent) => {
312
+ var _a;
313
+ // 重连机制
314
+ (_a = this.debugSocket) === null || _a === void 0 ? void 0 : _a.terminate();
315
+ if (this.reconnectCount < MAX_RECONNECT_COUNT) {
316
+ ColorConsole_1.default.info(`### Emulator the ${this.reconnectCount + 1}th time to reconnect debug server`);
317
+ this.reconnectCount++;
318
+ setTimeout(() => this.initDebugSocket(), 2000);
319
+ }
320
+ else {
321
+ this.debugSocket = undefined;
322
+ this.reconnectCount = 0;
323
+ return reject(`### Emulator debugSocket connect failed, ${errorEvent.message}`);
324
+ }
325
+ };
326
+ this.debugSocket.onclose = (closeEvent) => {
265
327
  this.debugSocket = undefined;
266
328
  this.reconnectCount = 0;
267
- return Promise.reject(`### Emulator debugSocket connect failed`);
268
- }
269
- };
270
- this.debugSocket.onclose = (e) => {
271
- this.debugSocket = undefined;
272
- this.reconnectCount = 0;
273
- ColorConsole_1.default.log(`### Emulator debugSocket connect close: ${e.data}`);
274
- };
329
+ ColorConsole_1.default.log(`### Emulator debugSocket connect close: ${closeEvent.reason}`);
330
+ };
331
+ });
275
332
  }
276
- /** 通知模拟器更新 */
333
+ /** 通知模拟器更新
334
+ * 1. 确保已经成功连接模拟器中的调试服务
335
+ * 2. 使用adb push将build文件下的内容推到/data/quickapp/app/${packageName}
336
+ * 3. 发送Page.reload命令给调试服务,通知更新
337
+ */
277
338
  handleUpdate() {
278
339
  var _a, _b;
279
340
  return __awaiter(this, void 0, void 0, function* () {
@@ -281,21 +342,7 @@ class MiwearInstance extends common_1.default {
281
342
  this.reconnectCount = 0;
282
343
  yield this.initDebugSocket();
283
344
  // 1. 将整包重新推到miwear中(TODO:增量更新)
284
- const sn = `127.0.0.1:${this.adbPort}`;
285
- const { package: appPackageName } = this.projectInfo;
286
- // windows平台adb push时无法使用通配符,需另外处理
287
- if (os_1.default.platform() === 'win32') {
288
- const rmCmd = `adb -s ${sn} shell rm -r ${this.appPathInEmulator}/${appPackageName}`;
289
- yield adbMiwt.execAdbCmdAsync(rmCmd);
290
- const sourcePath = path_1.default.resolve(this.projectPath, './build');
291
- const pushCmd = `adb -s ${sn} push ${sourcePath} ${this.appPathInEmulator}/${appPackageName}`;
292
- yield adbMiwt.execAdbCmdAsync(pushCmd);
293
- }
294
- else {
295
- const sourcePath = path_1.default.resolve(this.projectPath, './build/*');
296
- yield adbMiwt.execAdbCmdAsync(`adb -s ${sn} push ${sourcePath} ${this.appPathInEmulator}/${appPackageName}`);
297
- }
298
- ColorConsole_1.default.info(`### Emulator push to ${this.appPathInEmulator}/${appPackageName} successfully`);
345
+ yield this.pushBuild();
299
346
  // 2. 下发CDP命令给调试服务告知刷新
300
347
  if (((_a = this.debugSocket) === null || _a === void 0 ? void 0 : _a.readyState) === ws_1.default.OPEN) {
301
348
  (_b = this.debugSocket) === null || _b === void 0 ? void 0 : _b.send(JSON.stringify({ id: 10000, method: 'Page.reload', params: {} }));
@@ -306,18 +353,67 @@ class MiwearInstance extends common_1.default {
306
353
  }
307
354
  });
308
355
  }
309
- /** 创建server */
356
+ /** 热更新时push目录 */
357
+ pushBuild() {
358
+ return __awaiter(this, void 0, void 0, function* () {
359
+ const { package: appPackageName } = this.projectInfo;
360
+ // windows平台adb push时无法使用通配符,需另外处理;
361
+ // 项目路径包含空格时,无法通过加引号来使用 * 通配符
362
+ if (os_1.default.platform() === 'win32' || this.projectPath.indexOf(' ') > 0) {
363
+ const rmCmd = `adb -s ${this.sn} shell rm -r ${this.appPathInEmulator}/${appPackageName}`;
364
+ yield adbMiwt.execAdbCmdAsync(rmCmd);
365
+ const sourcePath = path_1.default.resolve(this.projectPath, './build');
366
+ const pushCmd = `adb -s ${this.sn} push "${sourcePath}" ${this.appPathInEmulator}/${appPackageName}`;
367
+ yield adbMiwt.execAdbCmdAsync(pushCmd);
368
+ }
369
+ else {
370
+ const sourcePath = path_1.default.resolve(this.projectPath, './build/*');
371
+ yield adbMiwt.execAdbCmdAsync(`adb -s ${this.sn} push ${sourcePath} ${this.appPathInEmulator}/${appPackageName}`);
372
+ }
373
+ ColorConsole_1.default.info(`### Emulator push to ${this.appPathInEmulator}/${appPackageName} successfully`);
374
+ });
375
+ }
376
+ /** 在模拟器中重启快应用(基于am命令,需要保证镜像中已经有am功能)
377
+ * 1. 使用adb push将build文件下的内容推到/data/quickapp/app/${packageName}
378
+ * 2. nsh中执行am stop命令退出快应用
379
+ * 3. nsh中执行am start命令启动快应用
380
+ */
381
+ reloadApp() {
382
+ return __awaiter(this, void 0, void 0, function* () {
383
+ try {
384
+ // 1. 将整包重新推到miwear中(TODO:增量更新)
385
+ const { package: appPackageName } = this.projectInfo;
386
+ yield this.pushBuild();
387
+ // 2. 执行am stop和am start命令
388
+ const stopCmd = `adb -s ${this.sn} shell am stop ${appPackageName}`;
389
+ yield adbMiwt.execAdbCmdAsync(stopCmd);
390
+ ColorConsole_1.default.info(`### Emulator stop ${appPackageName} successfully`);
391
+ // 这里是为了等am stop命令清除资源等
392
+ yield (0, utils_1.sleep)(500);
393
+ const startCmd = `adb -s ${this.sn} shell am start ${appPackageName}`;
394
+ yield adbMiwt.execAdbCmdAsync(startCmd);
395
+ ColorConsole_1.default.info(`### Emulator start ${appPackageName} successfully`);
396
+ }
397
+ catch (e) {
398
+ ColorConsole_1.default.error(`${e}`);
399
+ }
400
+ });
401
+ }
402
+ /**
403
+ * 创建server端,监听打包过程中client端发来的消息
404
+ */
310
405
  createWebsockeServer() {
311
406
  var _a;
312
407
  return __awaiter(this, void 0, void 0, function* () {
313
408
  const wsServer = new ws_1.WebSocketServer({
314
- port: (_a = this.startOptions) === null || _a === void 0 ? void 0 : _a.serverPort,
409
+ port: (_a = this.startOptions) === null || _a === void 0 ? void 0 : _a.serverPort
315
410
  });
316
- wsServer.on('connection', socket => {
411
+ wsServer.on('connection', (socket) => {
317
412
  ColorConsole_1.default.success(`### App Socket server ### Websocket connects to websocket server`);
318
- socket.on('error', err => {
413
+ socket.on('error', (err) => {
319
414
  ColorConsole_1.default.error(`### App Socket server ### Websocket server error: ${err.message}`);
320
415
  });
416
+ // data的格式:{ type: string, data: any }
321
417
  socket.on('message', (data) => __awaiter(this, void 0, void 0, function* () {
322
418
  var _a;
323
419
  const message = JSON.parse(data.toString());
@@ -2,20 +2,48 @@
2
2
  import { ChildProcess } from 'child_process';
3
3
  import { INewGoldfishInstanceParams, IStartOptions } from '../typing/Instance';
4
4
  import CommonInstance from './common';
5
+ /**
6
+ * OldGoldfishInstance
7
+ * 针对 Vela开发版(dev, 0.0.2)的镜像
8
+ */
5
9
  declare class OldGoldfishInstance extends CommonInstance {
6
10
  private host9pPort;
7
11
  v9fsProcess: ChildProcess | undefined;
8
12
  constructor(params: INewGoldfishInstanceParams);
9
- /** 在goldfish模拟器中运行快应用 */
13
+ /**
14
+ * 1. 启动9p server
15
+ * 2. 将打包好的rpk推到host的挂载目录
16
+ * 3. 启动模拟器
17
+ * 4. 模拟器启动成功后,adb连接模拟器
18
+ * 5. 连接成功后,在模拟器中启动快应用
19
+ */
10
20
  start(options: IStartOptions): Promise<void>;
11
- /** 在goldfish中启动快应用 */
21
+ /**
22
+ * 在模拟器中启动快应用(快应用都在模拟器的/data/app目录下)
23
+ * 1. 是否为调试模式
24
+ * 若是,在模拟器终端执行vapp app/${packageName} &
25
+ * 若否,在模拟器终端执行vapp --jsdebugger=10.0.2.15:101 app/${packageName} &
26
+ */
12
27
  startupQuickApp(options: IStartOptions): void;
13
- /** host启动9pServer */
28
+ /** host启动9pServer
29
+ * 作用是将本地的quickappMountDir目录挂载到模拟器的/data目录
30
+ */
14
31
  ensure9pServerRunnning(): Promise<void>;
15
- /** 启动goldfish模拟器 */
32
+ /**
33
+ * 启动模拟器
34
+ * 1. 通过options生成模拟器的启动命令
35
+ * 2. 执行启动命令
36
+ * 3. 判断模拟器是否启动成功
37
+ * 3.1 若disableNSH=true,输出流中匹配到/quickapp_rpk_installer_init|rpk installer init done/,认为模拟器启动成功了
38
+ * 3.2 若disableNSH=false,认为8s过后模拟器启动成功了
39
+ * @param options
40
+ * @returns
41
+ */
16
42
  startGoldfish(options: IStartOptions): Promise<void>;
17
- /** 通过adb连接模拟器 */
18
- connectGoldfish(): Promise<boolean>;
43
+ /**
44
+ * 推送文件到本地的${sdkHome}/qa/app/${packageName}目录
45
+ * @param sourceRoot 源目录
46
+ */
19
47
  pushRpk(sourceRoot: string): Promise<void>;
20
48
  /** 停止模拟器并释放相关资源 */
21
49
  stop(): Promise<void>;