package com.mes.ui; import com.mes.config.MesClientProperties; import com.mes.service.MesFlexQueuePushClient; import com.mes.util.SingleInstanceLock; import com.mes.util.UiImages; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicBoolean; /** * 柔性线一拖五主窗:免登录,按配置多 Tab,每工位独立 PLC + 取码/上传/过站。 * 弧焊/小冲/大冲/点焊/凸焊共用此壳,差异在 application.yml。 * 启动后订阅 mesFlexQueue SSE;断线时对 IDLE 工位 15s 慢轮询 next 兜底。 */ public class MainFrame extends JFrame { /** 日志 */ public static final Logger log = LoggerFactory.getLogger(MainFrame.class); /** 当前主窗单例引用 */ public static MainFrame mesClientFrame; /** MES 服务 IP */ public static String mes_server_ip = ""; /** 窗口标题前缀 */ public static String mes_app_title = "MES 凸焊客户端"; /** 过程参数 upload 路径 */ public static String mes_upload_path = "/js/a/mes/mesFlexHg/upload"; /** 参数档,凸焊为 tuhan */ public static String mes_param_profile = "tuhan"; /** 默认设备类型 */ public static String mes_device_type = ""; /** 过站工号;默认 system 跳过绑员工 */ public static String mes_user_code = "system"; /** 收到入队推送后是否自动 next */ public static boolean mes_auto_next_on_push = true; /** 隐藏状态钮,供 setMenuStatus 写文案 */ public static JButton status_menu; /** Spring 注入的 mes.* 配置快照 */ private static MesClientProperties props; /** 各工位面板(与 Tab 一一对应) */ private static final List stationPanels = new ArrayList(); /** 工位状态机轮询定时器(约 500ms) */ private static Timer tickTimer; /** SSE 入队推送客户端 */ private static MesFlexQueuePushClient pushClient; /** SSE 断线时 IDLE 慢轮询 */ private static Timer fallbackNextTimer; /** 正在退出:避免连点标题栏 X 叠多个「确定退出」或重复 System.exit */ private static final AtomicBoolean exiting = new AtomicBoolean(false); /** * 免登录启动主窗。 * 同一客户端只允许一个进程/窗口;重复启动会提示并返回 false。 * * @return false=单实例冲突 */ public static boolean launch() { if (SingleInstanceLock.getInstance().isAppActive(SingleInstanceLock.DEFAULT_LOCK_NAME)) { log.warn("已有客户端实例在运行,本次启动取消"); try { // 必须在可见提示后由调用方 exit,避免用户以为没反应又连点开多个 JOptionPane.showMessageDialog(null, "凸焊客户端已在运行,不能重复打开。\n请使用已打开的窗口。", "提示", JOptionPane.WARNING_MESSAGE); } catch (Exception ex) { log.warn("弹窗提示失败: {}", ex.getMessage()); } return false; } EventQueue.invokeLater(new Runnable() { @Override public void run() { try { // 已有主窗则前置,禁止再 new 第二个 JFrame if (mesClientFrame != null && mesClientFrame.isDisplayable()) { mesClientFrame.setExtendedState(JFrame.NORMAL); mesClientFrame.toFront(); mesClientFrame.requestFocus(); log.warn("主窗已存在,忽略重复创建"); return; } UiTheme.applyLookAndFeel(); mesClientFrame = new MainFrame(); mesClientFrame.setVisible(true); startTickTimer(); startPush(); // PLC 在后台连:假 IP/离线时不卡 EDT new Thread(new Runnable() { @Override public void run() { for (StationPanel p : stationPanels) { try { p.initPlc(); } catch (Exception ex) { log.warn("PLC 初始化异常: {}", ex.getMessage()); } } } }, "tuhan-plc-init").start(); } catch (Exception e) { log.error("启动主界面失败", e); e.printStackTrace(); } } }); return true; } /** * 应用 yml 配置;由 Spring Runner 在弹窗前调用。 */ public static void applyConfig(MesClientProperties p) { if (p == null) { throw new IllegalStateException("MesClientProperties 为空,请检查 application.yml 中 mes 配置"); } props = p; mes_server_ip = trim(p.getServerIp()); mes_app_title = trim(p.getAppTitle()); if (mes_app_title.isEmpty()) { mes_app_title = "MES 柔性线客户端"; } mes_upload_path = trim(p.getUploadPath()); if (mes_upload_path.isEmpty()) { mes_upload_path = "/js/a/mes/mesFlexHg/upload"; } mes_param_profile = trim(p.getParamProfile()); if (mes_param_profile.isEmpty()) { mes_param_profile = "hg"; } mes_device_type = trim(p.getDeviceType()); mes_user_code = trim(p.getUserCode()); if (mes_user_code.isEmpty()) { // system:服务端 assertBound 放行 mes_user_code = "system"; } mes_auto_next_on_push = p.isAutoNextOnPush(); List list = p.getStations(); if (list == null || list.isEmpty()) { log.warn("mes.stations 为空,请在 application.yml 配置五工位"); } else { log.info("加载工位数={} upload={} profile={}", list.size(), mes_upload_path, mes_param_profile); for (MesClientProperties.StationConfig s : list) { log.info("工位 id={} sn={} plc={}/{}", s.getId(), s.getStationSn(), s.getPlcIp(), s.getPlcType()); } } } public MainFrame() { setIconImage(Toolkit.getDefaultToolkit().getImage(UiImages.icon("logo.png"))); setTitle(mes_app_title); setBounds(40, 40, 1120, 860); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // 已点过确定:忽略后续 X,防止确认框/退出逻辑叠入 if (exiting.get()) { return; } int choice = JOptionPane.showConfirmDialog(MainFrame.this, "确定退出?", "关闭确认", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (choice != JOptionPane.YES_OPTION) { return; } if (!exiting.compareAndSet(false, true)) { return; } // 先藏窗再清资源:SSE disconnect 若卡在 EDT,窗还在会被连点 X setVisible(false); dispose(); new Thread(new Runnable() { @Override public void run() { try { stopPush(); stopTickTimer(); } catch (Throwable t) { log.warn("退出清理异常: {}", t.getMessage()); } finally { System.exit(0); } } }, "mes-client-exit").start(); } }); JMenuBar menuBar = new JMenuBar(); menuBar.setBackground(UiTheme.HEADER_TOP); menuBar.setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0, UiTheme.ACCENT)); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("系统"); fileMenu.setFont(new Font("微软雅黑", Font.PLAIN, 13)); fileMenu.setForeground(Color.WHITE); menuBar.add(fileMenu); JMenuItem exitItem = new JMenuItem("退出"); exitItem.setFont(new Font("微软雅黑", Font.PLAIN, 13)); exitItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispatchEvent(new WindowEvent(MainFrame.this, WindowEvent.WINDOW_CLOSING)); } }); fileMenu.add(exitItem); JPanel content = new JPanel(new BorderLayout(0, 0)); content.setBorder(new EmptyBorder(0, 0, 0, 0)); content.setBackground(UiTheme.BG); setContentPane(content); // 隐藏状态钮,供 setMenuStatus 写入文案 status_menu = new JButton(); status_menu.setVisible(false); JTabbedPane tabs = new JTabbedPane(JTabbedPane.TOP); tabs.setFont(new Font("微软雅黑", Font.PLAIN, 14)); tabs.setBackground(UiTheme.BG); tabs.setBorder(new EmptyBorder(8, 8, 8, 8)); tabs.setFocusable(false); stationPanels.clear(); List stations = props == null ? null : props.getStations(); if (stations == null || stations.isEmpty()) { JLabel empty = new JLabel("请在 application.yml 配置 mes.stations", SwingConstants.CENTER); empty.setFont(new Font("微软雅黑", Font.PLAIN, 18)); content.add(empty, BorderLayout.CENTER); return; } List stationSnList = new ArrayList(); for (MesClientProperties.StationConfig sc : stations) { StationPanel panel = new StationPanel(sc, mes_server_ip, mes_user_code); stationPanels.add(panel); tabs.addTab(panel.tabTitle(), panel); // A/B 面工位都进工作记录查询范围 for (String ssn : panel.allStationSns()) { if (!ssn.isEmpty() && !stationSnList.contains(ssn)) { stationSnList.add(ssn); } } } // 工作记录:本机全部工位已结案 sn + 加工时间 StringBuilder csv = new StringBuilder(); for (int i = 0; i < stationSnList.size(); i++) { if (i > 0) { csv.append(','); } csv.append(stationSnList.get(i)); } tabs.addTab("工作记录", new WorkRecordPanel(mes_server_ip, csv.toString())); content.add(tabs, BorderLayout.CENTER); } /** * 约 500ms 轮询各工位状态机(认面 / 运行结束)。 * 过程参数在 StationPanel 内按每秒节流采入集合,结束后一次性上传。 */ private static void startTickTimer() { stopTickTimer(); tickTimer = new Timer("hg-station-tick", true); tickTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { for (StationPanel p : stationPanels) { try { p.tick(); } catch (Exception ex) { log.debug("tick skip: {}", ex.getMessage()); } } } }, 800L, 500L); } private static void stopTickTimer() { if (tickTimer != null) { tickTimer.cancel(); tickTimer = null; } } /** * 启动 SSE 入队订阅 + 断线 15s 慢轮询兜底。 * 推送只当门铃:真正取码仍走 StationPanel.requestNextAsync → next。 */ private static void startPush() { stopPush(); if (stationPanels.isEmpty()) { return; } List sns = new ArrayList(); for (StationPanel p : stationPanels) { for (String sn : p.allStationSns()) { if (sn != null && !sn.isEmpty() && !sns.contains(sn)) { sns.add(sn); } } } pushClient = new MesFlexQueuePushClient(mes_server_ip, sns, new MesFlexQueuePushClient.EnqueuedListener() { @Override public void onEnqueued(String stationSn, String sn) { if (!mes_auto_next_on_push) { log.info("auto-next-on-push=false,忽略入队推送 stationSn={} sn={}", stationSn, sn); return; } StationPanel panel = findPanel(stationSn); if (panel == null) { log.warn("SSE 入队工位[{}] 本机无对应 Tab", stationSn); return; } // 门铃:空闲工位自动取码(A/B 面由客户端读 PLC 识别) panel.tryAutoNextFromPush(stationSn); } @Override public void onCleared(String stationSn, String sn) { StationPanel panel = findPanel(stationSn); if (panel == null) { return; } // PDA/他端清码:本机正占用同一 sn 则复位界面 panel.applyClearedFromPush(sn); } }); pushClient.start(); // 断线兜底:SSE 未连接时每 15s 对空闲面慢速 next fallbackNextTimer = new Timer("mes-flex-fallback-next", true); fallbackNextTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (pushClient != null && pushClient.isConnected()) { return; } for (StationPanel p : stationPanels) { try { p.tryAutoNextFromPush(); } catch (Exception ex) { log.debug("fallback next skip: {}", ex.getMessage()); } } } }, 15000L, 15000L); log.info("已启动取码推送订阅 + 断线兜底轮询"); } private static void stopPush() { if (fallbackNextTimer != null) { fallbackNextTimer.cancel(); fallbackNextTimer = null; } if (pushClient != null) { pushClient.stop(); pushClient = null; } } /** * 服务端是否在线:以取码队列 SSE 长连接为准(服务端会周期性 ping)。 * 工位顶栏呼吸灯据此绿呼吸 / 红停。 */ public static boolean isMesServerOnline() { return pushClient != null && pushClient.isConnected(); } /** 按工位编码找面板 */ private static StationPanel findPanel(String stationSn) { if (stationSn == null) { return null; } for (StationPanel p : stationPanels) { if (p.ownsStationSn(stationSn)) { return p; } } return null; } public static void setMenuStatus(final String msg, final int level) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (status_menu == null) { return; } status_menu.setText(msg == null ? "" : msg); if (level < 0) { status_menu.setForeground(Color.RED); } else { status_menu.setForeground(new Color(0, 128, 0)); } } }); } private static String trim(String s) { return s == null ? "" : s.trim(); } }