socket.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. const Log = require('ee-core/log');
  2. const CoreWindow = require('ee-core/electron/window');
  3. const WebSocket = require('ws'); // 引入原生 ws 库
  4. const { readConfigFile } = require('./config');
  5. const pyapp = readConfigFile().pyapp
  6. const { app } = require('electron');
  7. const path = require('path');
  8. const fs = require('fs');
  9. const typeToMessage = {
  10. run_mcu_single:['seeting','default'],
  11. get_device_info:['seeting','default'],
  12. get_deviation_data:["developer","seeting"],
  13. set_deviation:"developer",
  14. get_mcu_other_info:"developer",
  15. set_mcu_other_info:"developer",
  16. send_command:"developer",
  17. smart_shooter_get_camera_property:"seeting",
  18. detail_progress:"PhotographyDetail",
  19. segment_progress:"PhotographyDetail",
  20. upper_footer_progress:"PhotographyDetail",
  21. scene_progress:"PhotographyDetail",
  22. upload_goods_progress:"PhotographyDetail",
  23. detail_result_progress:"PhotographyDetail",
  24. "get_dynamic_config":"seeting",
  25. "set_dynamic_config":"seeting"
  26. }
  27. // MCU 错误日志配置(从 config 读取,默认100条)
  28. let mcuErrorLogConfig = {
  29. maxLogs: 100, // 最大日志条数
  30. };
  31. // 初始化时从配置读取
  32. try {
  33. const config = readConfigFile();
  34. if (config.mcuErrorLog && typeof config.mcuErrorLog.maxLogs === 'number') {
  35. mcuErrorLogConfig.maxLogs = config.mcuErrorLog.maxLogs;
  36. }
  37. } catch (e) {
  38. console.log('读取 MCU 日志配置失败,使用默认值');
  39. }
  40. // MCU 错误日志存储
  41. const mcuErrorLogs = [];
  42. let mcuErrorUnreadCount = 0;
  43. const previewPath = path.join(app.getPath("userData"),'preview','liveview.png');
  44. // 确保目录存在的函数
  45. function ensureDirectoryExistence(filePath) {
  46. const dir = path.dirname(filePath);
  47. if (fs.existsSync(dir)) {
  48. return true;
  49. }
  50. ensureDirectoryExistence(path.dirname(dir));
  51. fs.mkdirSync(dir);
  52. }
  53. function livePreview(data){
  54. if(data.msg === '预览数据发送' && data.code === 1){
  55. ensureDirectoryExistence(previewPath);
  56. const tempFilePath = `${previewPath}.tmp`;
  57. fs.writeFile(tempFilePath, data.data.smart_shooter_preview, 'base64', (err) => {
  58. if (err) {
  59. Log.error('写入临时文件失败:', err);
  60. } else {
  61. fs.rename(tempFilePath, previewPath, (renameErr) => {
  62. if (renameErr) {
  63. } else {
  64. }
  65. });
  66. }
  67. });
  68. }
  69. }
  70. const pySocket = function () {
  71. this.app = null;
  72. // 重连配置
  73. this.reconnectConfig = {
  74. maxRetries: 5, // 最大重连次数
  75. retryInterval: 3000, // 重连间隔(毫秒)
  76. maxRetryInterval: 30000, // 最大重连间隔
  77. retryMultiplier: 1.5 // 重连间隔递增倍数
  78. };
  79. this.reconnectAttempts = 0; // 当前重连次数
  80. this.isReconnecting = false; // 是否正在重连
  81. this.shouldReconnect = true; // 是否应该重连(用于手动断开时阻止重连)
  82. // 心跳配置
  83. this.heartbeatConfig = {
  84. interval: 10000, // 心跳间隔(10秒)
  85. timeout: 30000, // 心跳超时时间(30秒)
  86. maxMissed: 3 // 最大允许丢失的心跳次数
  87. };
  88. this.heartbeatTimer = null; // 心跳定时器
  89. this.heartbeatTimeout = null; // 心跳超时定时器
  90. this.missedHeartbeats = 0; // 丢失的心跳次数
  91. this.lastHeartbeatTime = 0; // 最后一次心跳时间
  92. // 启动心跳机制
  93. this.startHeartbeat = function() {
  94. this.stopHeartbeat(); // 先停止之前的心跳
  95. console.log('启动心跳机制,间隔:', this.heartbeatConfig.interval + 'ms');
  96. this.heartbeatTimer = setInterval(() => {
  97. if (app.socket && app.socket.readyState === WebSocket.OPEN) {
  98. this.sendPing();
  99. this.lastHeartbeatTime = Date.now();
  100. // 设置心跳超时检测
  101. this.setHeartbeatTimeout();
  102. }
  103. }, this.heartbeatConfig.interval);
  104. };
  105. // 停止心跳机制
  106. this.stopHeartbeat = function() {
  107. if (this.heartbeatTimer) {
  108. clearInterval(this.heartbeatTimer);
  109. this.heartbeatTimer = null;
  110. }
  111. if (this.heartbeatTimeout) {
  112. clearTimeout(this.heartbeatTimeout);
  113. this.heartbeatTimeout = null;
  114. }
  115. this.missedHeartbeats = 0;
  116. console.log('停止心跳机制');
  117. };
  118. // 设置心跳超时检测
  119. this.setHeartbeatTimeout = function() {
  120. if (this.heartbeatTimeout) {
  121. clearTimeout(this.heartbeatTimeout);
  122. }
  123. this.heartbeatTimeout = setTimeout(() => {
  124. this.missedHeartbeats++;
  125. console.log(`心跳超时,丢失次数: ${this.missedHeartbeats}/${this.heartbeatConfig.maxMissed}`);
  126. if (this.missedHeartbeats >= this.heartbeatConfig.maxMissed) {
  127. console.log('心跳超时次数过多,主动断开连接');
  128. if (app.socket) {
  129. app.socket.close();
  130. }
  131. }
  132. }, this.heartbeatConfig.timeout);
  133. };
  134. // 处理心跳响应
  135. this.handleHeartbeatResponse = function() {
  136. this.missedHeartbeats = 0;
  137. if (this.heartbeatTimeout) {
  138. clearTimeout(this.heartbeatTimeout);
  139. this.heartbeatTimeout = null;
  140. }
  141. console.log('收到心跳响应');
  142. };
  143. // 重连逻辑函数
  144. this.attemptReconnect = async function() {
  145. if (!this.shouldReconnect || this.isReconnecting) {
  146. return;
  147. }
  148. if (this.reconnectAttempts >= this.reconnectConfig.maxRetries) {
  149. Log.info('达到最大重连次数,停止重连');
  150. this.isReconnecting = false;
  151. this.reconnectAttempts = 0;
  152. return;
  153. }
  154. this.isReconnecting = true;
  155. this.reconnectAttempts++;
  156. // 计算重连间隔(指数退避)
  157. const interval = Math.min(
  158. this.reconnectConfig.retryInterval * Math.pow(this.reconnectConfig.retryMultiplier, this.reconnectAttempts - 1),
  159. this.reconnectConfig.maxRetryInterval
  160. );
  161. Log.info(`第${this.reconnectAttempts}次重连尝试,${interval}ms后开始...`);
  162. setTimeout(async () => {
  163. try {
  164. Log.info('开始重连...');
  165. await this.init();
  166. Log.info('重连成功');
  167. this.isReconnecting = false;
  168. this.reconnectAttempts = 0;
  169. } catch (error) {
  170. Log.info('重连失败:', error);
  171. this.isReconnecting = false;
  172. // 继续尝试重连
  173. this.attemptReconnect();
  174. }
  175. }, interval);
  176. };
  177. this.init = async function (this_app) {
  178. if(this_app) this.app = this_app;
  179. await new Promise(async (resolve,reject) => {
  180. const win = CoreWindow.getMainWindow()
  181. if(app.socket){
  182. resolve(true);
  183. win.webContents.send('controller.socket.connect_open', true);
  184. return;
  185. }
  186. // 重置重连状态
  187. this.shouldReconnect = true;
  188. this.isReconnecting = false;
  189. app.socket = new WebSocket('ws://'+pyapp+':7074/ws');
  190. // 监听连接成功事件
  191. app.socket.on('open', () => {
  192. Log.info('socket open')
  193. resolve(true);
  194. win.webContents.send('controller.socket.connect_open', true);
  195. // 启动心跳机制
  196. this.startHeartbeat();
  197. });
  198. // 监听消息事件
  199. app.socket.on('message', (data) => {
  200. try {
  201. let this_data = JSON.parse(data.toString());
  202. if(!['blue_tooth','smart_shooter_enable_preview','smart_shooter_getinfo'].includes(this_data.msg_type)){
  203. console.log('message');
  204. console.log(this_data);
  205. // Log.info(this_data);
  206. }
  207. if(this_data.msg_type){
  208. let notAllMessage = false
  209. switch (this_data.msg_type){
  210. case 'smart_shooter_enable_preview':
  211. notAllMessage = true;
  212. livePreview(this_data);
  213. break;
  214. case 'pong':
  215. // 处理心跳响应
  216. this.handleHeartbeatResponse();
  217. notAllMessage = true;
  218. break;
  219. case 'print_mcu_error_data':
  220. // 处理 MCU 错误日志
  221. this.handleMcuErrorData(this_data, win);
  222. notAllMessage = true;
  223. break;
  224. }
  225. if(notAllMessage) return;
  226. let channel = 'controller.socket.message_'+this_data.msg_type;
  227. if(typeToMessage[this_data.msg_type]){
  228. if(typeof typeToMessage[this_data.msg_type] === 'object'){
  229. typeToMessage[this_data.msg_type].map(item=>{
  230. if(item === 'default'){
  231. win.webContents.send(channel, this_data);
  232. }else{
  233. if(this.app.electron[item]) {
  234. this.app.electron[item].webContents.send(channel, this_data);
  235. }
  236. }
  237. })
  238. }else{
  239. if(this.app.electron[typeToMessage[this_data.msg_type]]) {
  240. this.app.electron[typeToMessage[this_data.msg_type]].webContents.send(channel, this_data);
  241. }
  242. }
  243. }else{
  244. win.webContents.send(channel, this_data);
  245. }
  246. }
  247. }catch (e){
  248. console.log(e)
  249. }
  250. });
  251. // 监听连接关闭事件
  252. app.socket.on('close', (e) => {
  253. Log.info('socket close');
  254. Log.info(e);
  255. win.webContents.send('controller.socket.disconnect', null);
  256. // 停止心跳机制
  257. this.stopHeartbeat();
  258. app.socket = null;
  259. // 启动重连机制
  260. this.attemptReconnect();
  261. });
  262. // 监听错误事件
  263. app.socket.on('error', (err) => {
  264. Log.info('socket error:', err);
  265. win.webContents.send('controller.socket.disconnect', null);
  266. // 停止心跳机制
  267. this.stopHeartbeat();
  268. app.socket = null;
  269. // 启动重连机制
  270. this.attemptReconnect();
  271. reject(true);
  272. });
  273. })
  274. }
  275. this.sendPing = function () {
  276. const message = JSON.stringify({ data: 'node', type: 'ping' });
  277. this.sendMessage(message);
  278. }
  279. this.sendMessage = async function (message) {
  280. console.log('socket.=========================sendMessage');
  281. console.log('socket.sendMessage');
  282. console.log(message);
  283. console.log(app.socket?.readyState);
  284. if(!app.socket){
  285. await this.init()
  286. }
  287. // 检查连接状态
  288. if (app.socket?.readyState === WebSocket.OPEN) {
  289. console.log('send');
  290. app.socket.send(message); // 使用 send() 发送
  291. }
  292. }
  293. this.disconnect = function () {
  294. // 设置标志,阻止重连
  295. this.shouldReconnect = false;
  296. this.isReconnecting = false;
  297. this.reconnectAttempts = 0;
  298. // 停止心跳机制
  299. this.stopHeartbeat();
  300. if (app.socket) {
  301. app.socket.close(); // 使用 close() 方法
  302. app.socket = null;
  303. }
  304. }
  305. // 重新启用重连功能
  306. this.enableReconnect = function () {
  307. this.shouldReconnect = true;
  308. this.reconnectAttempts = 0;
  309. this.isReconnecting = false;
  310. }
  311. this.onSocketMessage = async function (message_type,callback) { // 监听消息事件
  312. return new Promise(async (resolve,reject) => {
  313. app.socket.on('message', onSocketMessage);
  314. async function onSocketMessage(data){
  315. try {
  316. let this_data = JSON.parse(data.toString());
  317. if(this_data.msg_type === message_type){
  318. app.socket.off('message', onSocketMessage);
  319. callback(this_data)
  320. resolve()
  321. }
  322. }catch (e){
  323. Log.error(e)
  324. reject(e)
  325. }
  326. }
  327. })
  328. }
  329. // 处理 MCU 错误数据
  330. this.handleMcuErrorData = function(data, win) {
  331. const logEntry = {
  332. message: data.data?.message || '',
  333. current_time: data.data?.current_time || new Date().toLocaleString('zh-CN', { hour12: false }).replace(/\//g, '-'),
  334. raw: data // 保留原始数据
  335. };
  336. // 添加到日志数组(限制最大条数)
  337. mcuErrorLogs.unshift(logEntry);
  338. if (mcuErrorLogs.length > mcuErrorLogConfig.maxLogs) {
  339. mcuErrorLogs.pop();
  340. }
  341. // 未读数 +1
  342. mcuErrorUnreadCount++;
  343. // 发送未读状态变更通知
  344. win.webContents.send('controller.mcu.errorLogUnread', { count: mcuErrorUnreadCount });
  345. // 同时将原始消息转发给前端(保持原有功能)
  346. win.webContents.send('controller.socket.message_print_mcu_error_data', data);
  347. };
  348. // 获取 MCU 错误日志列表
  349. this.getMcuErrorLogs = function() {
  350. return [...mcuErrorLogs];
  351. };
  352. // 获取未读数
  353. this.getMcuErrorUnreadCount = function() {
  354. return mcuErrorUnreadCount;
  355. };
  356. // 清除未读状态
  357. this.clearMcuErrorUnread = function() {
  358. mcuErrorUnreadCount = 0;
  359. return true;
  360. };
  361. // 设置最大日志条数(供外部调用)
  362. this.setMcuErrorLogMax = function(max) {
  363. mcuErrorLogConfig.maxLogs = max;
  364. // 如果当前日志超过限制,裁剪
  365. while (mcuErrorLogs.length > mcuErrorLogConfig.maxLogs) {
  366. mcuErrorLogs.pop();
  367. }
  368. return true;
  369. };
  370. return this;
  371. }
  372. module.exports = pySocket;