socket.js 13 KB

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