device-manager.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import { ipcMain, BrowserWindow } from 'electron';
  2. import { exec } from 'child_process';
  3. import { promisify } from 'util';
  4. import { getCachedAdbPath, loadConfig } from '../config.js';
  5. const execAsync = promisify(exec);
  6. // 获取主窗口引用(用于实时推送设备发现事件)
  7. function getMainWindow() {
  8. const windows = BrowserWindow.getAllWindows();
  9. return windows.length > 0 ? windows[0] : null;
  10. }
  11. // 获取 ADB 设备列表(每次都重新扫描网络)
  12. export async function getADBDevices() {
  13. try {
  14. // 每次都重新扫描网络设备,不记录已连接的设备
  15. return await scanNetworkDevices(null);
  16. } catch (error) {
  17. return [];
  18. }
  19. }
  20. // 网络扫描:按顺序扫描 192.168.0、192.168.1、192.168.2 三个网段,尝试连接设备(实时推送结果)
  21. export async function scanNetworkDevices(event) {
  22. const adbPath = getCachedAdbPath();
  23. const port = 5555;
  24. const maxConcurrent = 50; // 限制并发数,避免过载
  25. const connectTimeout = 1500; // 连接超时时间(毫秒)
  26. const foundDevices = new Set(); // 使用 Set 避免重复
  27. // 定义要扫描的网段(按顺序:0.0 -> 1.0 -> 2.0)
  28. const networkSegments = ['192.168.0', '192.168.1', '192.168.2'];
  29. // 推送设备发现的辅助函数
  30. const pushDevice = (ipPort) => {
  31. if (!foundDevices.has(ipPort)) {
  32. foundDevices.add(ipPort);
  33. const device = {
  34. id: ipPort,
  35. status: 'device'
  36. };
  37. // 实时发送发现的设备
  38. if (event && event.sender) {
  39. event.sender.send('device-found', device);
  40. } else {
  41. const mainWindow = getMainWindow();
  42. if (mainWindow) {
  43. mainWindow.webContents.send('device-found', device);
  44. }
  45. }
  46. }
  47. };
  48. // 扫描单个 IP 地址的函数
  49. const scanIP = async (ip) => {
  50. const ipPort = `${ip}:${port}`;
  51. try {
  52. // 先尝试连接设备
  53. await execAsync(`${adbPath} connect ${ipPort}`, {
  54. timeout: connectTimeout,
  55. maxBuffer: 1024 * 1024
  56. });
  57. // 连接后稍等片刻,让设备注册到 ADB 服务器
  58. await new Promise(resolve => setTimeout(resolve, 500));
  59. } catch (error) {
  60. // 连接失败是正常的,继续检查设备列表
  61. }
  62. // 调用 adb devices 命令获取所有设备列表,检查是否包含端口 5555 的设备
  63. try {
  64. const { stdout } = await execAsync(`${adbPath} devices`, {
  65. timeout: 2000,
  66. maxBuffer: 1024 * 1024
  67. });
  68. // 检查输出中是否包含该 IP:PORT(匹配端口 5555)
  69. // 使用正则表达式匹配 IP:5555 格式
  70. const devicePattern = new RegExp(`${ip.replace(/\./g, '\\.')}:${port}\\s+device`, 'i');
  71. if (devicePattern.test(stdout)) {
  72. // 发现设备,立即推送显示(不等待整批完成)
  73. pushDevice(ipPort);
  74. return ipPort;
  75. }
  76. // 如果没有匹配到,说明没有设备
  77. } catch (checkError) {
  78. // 检查失败,忽略
  79. }
  80. return null;
  81. };
  82. // 按顺序扫描每个网段
  83. for (const baseIP of networkSegments) {
  84. // 生成当前网段的 IP 地址列表
  85. const ipList = [];
  86. for (let i = 1; i <= 255; i++) {
  87. ipList.push(`${baseIP}.${i}`);
  88. }
  89. // 分批并发扫描当前网段,扫描到一个显示一个
  90. for (let i = 0; i < ipList.length; i += maxConcurrent) {
  91. const batch = ipList.slice(i, i + maxConcurrent);
  92. const promises = batch.map(ip => scanIP(ip));
  93. // 并发执行当前批次,但不等待所有完成才推送
  94. // 每个 promise 一旦发现设备就会立即推送
  95. await Promise.all(promises);
  96. }
  97. }
  98. // 返回所有发现的设备
  99. return Array.from(foundDevices).map(ipPort => ({
  100. id: ipPort,
  101. status: 'device'
  102. }));
  103. }
  104. // 连接 ADB 设备
  105. export async function connectDevice(ipPort) {
  106. try {
  107. const adbPath = getCachedAdbPath();
  108. await execAsync(`${adbPath} connect ${ipPort}`);
  109. return { success: true };
  110. } catch (error) {
  111. return { success: false, error: error.message };
  112. }
  113. }
  114. // 注册 IPC 处理器
  115. export function registerIpcHandlers() {
  116. // IPC 处理程序:获取 ADB 路径配置
  117. ipcMain.handle('get-adb-path-config', async () => {
  118. const config = loadConfig();
  119. return config ? config['adb-path'] : null;
  120. });
  121. // IPC 处理程序:获取 ADB 设备列表
  122. ipcMain.handle('get-adb-devices', async () => {
  123. return await getADBDevices();
  124. });
  125. // IPC 处理程序:扫描网络设备(支持实时推送)
  126. ipcMain.handle('scan-adb-devices', async (event) => {
  127. try {
  128. const devices = await scanNetworkDevices(event);
  129. return devices;
  130. } catch (error) {
  131. return [];
  132. }
  133. });
  134. // IPC 处理程序:连接 ADB 设备
  135. ipcMain.handle('connect-adb-device', async (event, ipPort) => {
  136. return await connectDevice(ipPort);
  137. });
  138. }