socket.js 14 KB

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