MainFrame.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. package com.mes.ui;
  2. import com.mes.config.MesClientProperties;
  3. import com.mes.service.MesFlexQueuePushClient;
  4. import com.mes.util.SingleInstanceLock;
  5. import com.mes.util.UiImages;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import javax.swing.*;
  9. import javax.swing.border.EmptyBorder;
  10. import java.awt.*;
  11. import java.awt.event.ActionEvent;
  12. import java.awt.event.ActionListener;
  13. import java.awt.event.WindowAdapter;
  14. import java.awt.event.WindowEvent;
  15. import java.util.ArrayList;
  16. import java.util.List;
  17. import java.util.Timer;
  18. import java.util.TimerTask;
  19. import java.util.concurrent.atomic.AtomicBoolean;
  20. /**
  21. * 柔性线一拖五主窗:免登录,按配置多 Tab,每工位独立 PLC + 取码/上传/过站。
  22. * 弧焊/小冲/大冲/点焊/凸焊共用此壳,差异在 application.yml。
  23. * 启动后订阅 mesFlexQueue SSE;断线时对 IDLE 工位 15s 慢轮询 next 兜底。
  24. */
  25. public class MainFrame extends JFrame {
  26. /** 日志 */
  27. public static final Logger log = LoggerFactory.getLogger(MainFrame.class);
  28. /** 当前主窗单例引用 */
  29. public static MainFrame mesClientFrame;
  30. /** MES 服务 IP */
  31. public static String mes_server_ip = "";
  32. /** 窗口标题前缀 */
  33. public static String mes_app_title = "MES 凸焊客户端";
  34. /** 过程参数 upload 路径 */
  35. public static String mes_upload_path = "/js/a/mes/mesFlexHg/upload";
  36. /** 参数档,凸焊为 tuhan */
  37. public static String mes_param_profile = "tuhan";
  38. /** 默认设备类型 */
  39. public static String mes_device_type = "";
  40. /** 过站工号;默认 system 跳过绑员工 */
  41. public static String mes_user_code = "system";
  42. /** 收到入队推送后是否自动 next */
  43. public static boolean mes_auto_next_on_push = true;
  44. /** 隐藏状态钮,供 setMenuStatus 写文案 */
  45. public static JButton status_menu;
  46. /** Spring 注入的 mes.* 配置快照 */
  47. private static MesClientProperties props;
  48. /** 各工位面板(与 Tab 一一对应) */
  49. private static final List<StationPanel> stationPanels = new ArrayList<StationPanel>();
  50. /** 工位状态机轮询定时器(约 500ms) */
  51. private static Timer tickTimer;
  52. /** SSE 入队推送客户端 */
  53. private static MesFlexQueuePushClient pushClient;
  54. /** SSE 断线时 IDLE 慢轮询 */
  55. private static Timer fallbackNextTimer;
  56. /** 正在退出:避免连点标题栏 X 叠多个「确定退出」或重复 System.exit */
  57. private static final AtomicBoolean exiting = new AtomicBoolean(false);
  58. /**
  59. * 免登录启动主窗。
  60. * 同一客户端只允许一个进程/窗口;重复启动会提示并返回 false。
  61. *
  62. * @return false=单实例冲突
  63. */
  64. public static boolean launch() {
  65. if (SingleInstanceLock.getInstance().isAppActive(SingleInstanceLock.DEFAULT_LOCK_NAME)) {
  66. log.warn("已有客户端实例在运行,本次启动取消");
  67. try {
  68. // 必须在可见提示后由调用方 exit,避免用户以为没反应又连点开多个
  69. JOptionPane.showMessageDialog(null,
  70. "凸焊客户端已在运行,不能重复打开。\n请使用已打开的窗口。",
  71. "提示",
  72. JOptionPane.WARNING_MESSAGE);
  73. } catch (Exception ex) {
  74. log.warn("弹窗提示失败: {}", ex.getMessage());
  75. }
  76. return false;
  77. }
  78. EventQueue.invokeLater(new Runnable() {
  79. @Override
  80. public void run() {
  81. try {
  82. // 已有主窗则前置,禁止再 new 第二个 JFrame
  83. if (mesClientFrame != null && mesClientFrame.isDisplayable()) {
  84. mesClientFrame.setExtendedState(JFrame.NORMAL);
  85. mesClientFrame.toFront();
  86. mesClientFrame.requestFocus();
  87. log.warn("主窗已存在,忽略重复创建");
  88. return;
  89. }
  90. UiTheme.applyLookAndFeel();
  91. mesClientFrame = new MainFrame();
  92. mesClientFrame.setVisible(true);
  93. startTickTimer();
  94. startPush();
  95. // PLC 在后台连:假 IP/离线时不卡 EDT
  96. new Thread(new Runnable() {
  97. @Override
  98. public void run() {
  99. for (StationPanel p : stationPanels) {
  100. try {
  101. p.initPlc();
  102. } catch (Exception ex) {
  103. log.warn("PLC 初始化异常: {}", ex.getMessage());
  104. }
  105. }
  106. }
  107. }, "tuhan-plc-init").start();
  108. } catch (Exception e) {
  109. log.error("启动主界面失败", e);
  110. e.printStackTrace();
  111. }
  112. }
  113. });
  114. return true;
  115. }
  116. /**
  117. * 应用 yml 配置;由 Spring Runner 在弹窗前调用。
  118. */
  119. public static void applyConfig(MesClientProperties p) {
  120. if (p == null) {
  121. throw new IllegalStateException("MesClientProperties 为空,请检查 application.yml 中 mes 配置");
  122. }
  123. props = p;
  124. mes_server_ip = trim(p.getServerIp());
  125. mes_app_title = trim(p.getAppTitle());
  126. if (mes_app_title.isEmpty()) {
  127. mes_app_title = "MES 柔性线客户端";
  128. }
  129. mes_upload_path = trim(p.getUploadPath());
  130. if (mes_upload_path.isEmpty()) {
  131. mes_upload_path = "/js/a/mes/mesFlexHg/upload";
  132. }
  133. mes_param_profile = trim(p.getParamProfile());
  134. if (mes_param_profile.isEmpty()) {
  135. mes_param_profile = "hg";
  136. }
  137. mes_device_type = trim(p.getDeviceType());
  138. mes_user_code = trim(p.getUserCode());
  139. if (mes_user_code.isEmpty()) {
  140. // system:服务端 assertBound 放行
  141. mes_user_code = "system";
  142. }
  143. mes_auto_next_on_push = p.isAutoNextOnPush();
  144. List<MesClientProperties.StationConfig> list = p.getStations();
  145. if (list == null || list.isEmpty()) {
  146. log.warn("mes.stations 为空,请在 application.yml 配置五工位");
  147. } else {
  148. log.info("加载工位数={} upload={} profile={}", list.size(), mes_upload_path, mes_param_profile);
  149. for (MesClientProperties.StationConfig s : list) {
  150. log.info("工位 id={} sn={} plc={}/{}", s.getId(), s.getStationSn(),
  151. s.getPlcIp(), s.getPlcType());
  152. }
  153. }
  154. }
  155. public MainFrame() {
  156. setIconImage(Toolkit.getDefaultToolkit().getImage(UiImages.icon("logo.png")));
  157. setTitle(mes_app_title);
  158. setBounds(40, 40, 1120, 860);
  159. setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
  160. addWindowListener(new WindowAdapter() {
  161. @Override
  162. public void windowClosing(WindowEvent e) {
  163. // 已点过确定:忽略后续 X,防止确认框/退出逻辑叠入
  164. if (exiting.get()) {
  165. return;
  166. }
  167. int choice = JOptionPane.showConfirmDialog(MainFrame.this, "确定退出?", "关闭确认",
  168. JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
  169. if (choice != JOptionPane.YES_OPTION) {
  170. return;
  171. }
  172. if (!exiting.compareAndSet(false, true)) {
  173. return;
  174. }
  175. // 先藏窗再清资源:SSE disconnect 若卡在 EDT,窗还在会被连点 X
  176. setVisible(false);
  177. dispose();
  178. new Thread(new Runnable() {
  179. @Override
  180. public void run() {
  181. try {
  182. stopPush();
  183. stopTickTimer();
  184. } catch (Throwable t) {
  185. log.warn("退出清理异常: {}", t.getMessage());
  186. } finally {
  187. System.exit(0);
  188. }
  189. }
  190. }, "mes-client-exit").start();
  191. }
  192. });
  193. JMenuBar menuBar = new JMenuBar();
  194. menuBar.setBackground(UiTheme.HEADER_TOP);
  195. menuBar.setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0, UiTheme.ACCENT));
  196. setJMenuBar(menuBar);
  197. JMenu fileMenu = new JMenu("系统");
  198. fileMenu.setFont(new Font("微软雅黑", Font.PLAIN, 13));
  199. fileMenu.setForeground(Color.WHITE);
  200. menuBar.add(fileMenu);
  201. JMenuItem exitItem = new JMenuItem("退出");
  202. exitItem.setFont(new Font("微软雅黑", Font.PLAIN, 13));
  203. exitItem.addActionListener(new ActionListener() {
  204. @Override
  205. public void actionPerformed(ActionEvent e) {
  206. dispatchEvent(new WindowEvent(MainFrame.this, WindowEvent.WINDOW_CLOSING));
  207. }
  208. });
  209. fileMenu.add(exitItem);
  210. JPanel content = new JPanel(new BorderLayout(0, 0));
  211. content.setBorder(new EmptyBorder(0, 0, 0, 0));
  212. content.setBackground(UiTheme.BG);
  213. setContentPane(content);
  214. // 隐藏状态钮,供 setMenuStatus 写入文案
  215. status_menu = new JButton();
  216. status_menu.setVisible(false);
  217. JTabbedPane tabs = new JTabbedPane(JTabbedPane.TOP);
  218. tabs.setFont(new Font("微软雅黑", Font.PLAIN, 14));
  219. tabs.setBackground(UiTheme.BG);
  220. tabs.setBorder(new EmptyBorder(8, 8, 8, 8));
  221. tabs.setFocusable(false);
  222. stationPanels.clear();
  223. List<MesClientProperties.StationConfig> stations =
  224. props == null ? null : props.getStations();
  225. if (stations == null || stations.isEmpty()) {
  226. JLabel empty = new JLabel("请在 application.yml 配置 mes.stations", SwingConstants.CENTER);
  227. empty.setFont(new Font("微软雅黑", Font.PLAIN, 18));
  228. content.add(empty, BorderLayout.CENTER);
  229. return;
  230. }
  231. List<String> stationSnList = new ArrayList<String>();
  232. for (MesClientProperties.StationConfig sc : stations) {
  233. StationPanel panel = new StationPanel(sc, mes_server_ip, mes_user_code);
  234. stationPanels.add(panel);
  235. tabs.addTab(panel.tabTitle(), panel);
  236. // A/B 面工位都进工作记录查询范围
  237. for (String ssn : panel.allStationSns()) {
  238. if (!ssn.isEmpty() && !stationSnList.contains(ssn)) {
  239. stationSnList.add(ssn);
  240. }
  241. }
  242. }
  243. // 工作记录:本机全部工位已结案 sn + 加工时间
  244. StringBuilder csv = new StringBuilder();
  245. for (int i = 0; i < stationSnList.size(); i++) {
  246. if (i > 0) {
  247. csv.append(',');
  248. }
  249. csv.append(stationSnList.get(i));
  250. }
  251. tabs.addTab("工作记录", new WorkRecordPanel(mes_server_ip, csv.toString()));
  252. content.add(tabs, BorderLayout.CENTER);
  253. }
  254. /**
  255. * 约 500ms 轮询各工位状态机(认面 / 运行结束)。
  256. * 过程参数在 StationPanel 内按每秒节流采入集合,结束后一次性上传。
  257. */
  258. private static void startTickTimer() {
  259. stopTickTimer();
  260. tickTimer = new Timer("hg-station-tick", true);
  261. tickTimer.scheduleAtFixedRate(new TimerTask() {
  262. @Override
  263. public void run() {
  264. for (StationPanel p : stationPanels) {
  265. try {
  266. p.tick();
  267. } catch (Exception ex) {
  268. log.debug("tick skip: {}", ex.getMessage());
  269. }
  270. }
  271. }
  272. }, 800L, 500L);
  273. }
  274. private static void stopTickTimer() {
  275. if (tickTimer != null) {
  276. tickTimer.cancel();
  277. tickTimer = null;
  278. }
  279. }
  280. /**
  281. * 启动 SSE 入队订阅 + 断线 15s 慢轮询兜底。
  282. * 推送只当门铃:真正取码仍走 StationPanel.requestNextAsync → next。
  283. */
  284. private static void startPush() {
  285. stopPush();
  286. if (stationPanels.isEmpty()) {
  287. return;
  288. }
  289. List<String> sns = new ArrayList<String>();
  290. for (StationPanel p : stationPanels) {
  291. for (String sn : p.allStationSns()) {
  292. if (sn != null && !sn.isEmpty() && !sns.contains(sn)) {
  293. sns.add(sn);
  294. }
  295. }
  296. }
  297. pushClient = new MesFlexQueuePushClient(mes_server_ip, sns, new MesFlexQueuePushClient.EnqueuedListener() {
  298. @Override
  299. public void onEnqueued(String stationSn, String sn) {
  300. if (!mes_auto_next_on_push) {
  301. log.info("auto-next-on-push=false,忽略入队推送 stationSn={} sn={}", stationSn, sn);
  302. return;
  303. }
  304. StationPanel panel = findPanel(stationSn);
  305. if (panel == null) {
  306. log.warn("SSE 入队工位[{}] 本机无对应 Tab", stationSn);
  307. return;
  308. }
  309. // 门铃:空闲工位自动取码(A/B 面由客户端读 PLC 识别)
  310. panel.tryAutoNextFromPush(stationSn);
  311. }
  312. @Override
  313. public void onCleared(String stationSn, String sn) {
  314. StationPanel panel = findPanel(stationSn);
  315. if (panel == null) {
  316. return;
  317. }
  318. // PDA/他端清码:本机正占用同一 sn 则复位界面
  319. panel.applyClearedFromPush(sn);
  320. }
  321. });
  322. pushClient.start();
  323. // 断线兜底:SSE 未连接时每 15s 对空闲面慢速 next
  324. fallbackNextTimer = new Timer("mes-flex-fallback-next", true);
  325. fallbackNextTimer.scheduleAtFixedRate(new TimerTask() {
  326. @Override
  327. public void run() {
  328. if (pushClient != null && pushClient.isConnected()) {
  329. return;
  330. }
  331. for (StationPanel p : stationPanels) {
  332. try {
  333. p.tryAutoNextFromPush();
  334. } catch (Exception ex) {
  335. log.debug("fallback next skip: {}", ex.getMessage());
  336. }
  337. }
  338. }
  339. }, 15000L, 15000L);
  340. log.info("已启动取码推送订阅 + 断线兜底轮询");
  341. }
  342. private static void stopPush() {
  343. if (fallbackNextTimer != null) {
  344. fallbackNextTimer.cancel();
  345. fallbackNextTimer = null;
  346. }
  347. if (pushClient != null) {
  348. pushClient.stop();
  349. pushClient = null;
  350. }
  351. }
  352. /**
  353. * 服务端是否在线:以取码队列 SSE 长连接为准(服务端会周期性 ping)。
  354. * 工位顶栏呼吸灯据此绿呼吸 / 红停。
  355. */
  356. public static boolean isMesServerOnline() {
  357. return pushClient != null && pushClient.isConnected();
  358. }
  359. /** 按工位编码找面板 */
  360. private static StationPanel findPanel(String stationSn) {
  361. if (stationSn == null) {
  362. return null;
  363. }
  364. for (StationPanel p : stationPanels) {
  365. if (p.ownsStationSn(stationSn)) {
  366. return p;
  367. }
  368. }
  369. return null;
  370. }
  371. public static void setMenuStatus(final String msg, final int level) {
  372. SwingUtilities.invokeLater(new Runnable() {
  373. @Override
  374. public void run() {
  375. if (status_menu == null) {
  376. return;
  377. }
  378. status_menu.setText(msg == null ? "" : msg);
  379. if (level < 0) {
  380. status_menu.setForeground(Color.RED);
  381. } else {
  382. status_menu.setForeground(new Color(0, 128, 0));
  383. }
  384. }
  385. });
  386. }
  387. private static String trim(String s) {
  388. return s == null ? "" : s.trim();
  389. }
  390. }