package com.mes.ui; import com.alibaba.fastjson2.JSONObject; import com.mes.component.MesRadio; import com.mes.component.MesWebView; import com.fazecast.jSerialComm.SerialPort; import com.mes.component.ProductTypePanel; import com.mes.util.DateLocalUtils; import com.mes.util.HttpUtils; import com.mes.util.JdbcUtils; import com.mes.util.Op310PlcPoint; import com.mes.util.PlcService; import com.mes.util.Ut5310ScpiService; import com.mes.util.Ut5310TestResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.InetSocketAddress; import java.net.Socket; import java.sql.ResultSet; import java.sql.Statement; import java.time.LocalDateTime; import java.util.List; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MesClient extends JFrame { public static final Logger log = LoggerFactory.getLogger(MesClient.class); public static int mes_auth = 0; // 权限级别 0=无权限 1=操作工人 2=管理员 public static String mes_gw = ""; // 工位号 public static String mes_gw_des = ""; // 工位名称 public static String mes_server_ip = ""; // 服务器IP地址 public static int mes_heart_icon_cycle = 1; public static boolean mes_ut5310_enable = false; public static String mes_line_sn = ""; // 产线编号 public static String mes_plc_ip = "192.168.0.3"; // PLC IP地址 public static final int PLC_PHASE_IDLE = 0; public static final int PLC_PHASE_WAIT_START = 1; public static final int PLC_PHASE_WAIT_REQUEST = 2; public static final int PLC_PHASE_WAIT_OPERATOR = 3; public static final int PLC_PHASE_WAIT_READY = 4; public static final int PLC_PHASE_WAIT_UT5310 = 5; //session public static String sessionid = ""; public static JPanel contentPane; public static MesClient mesClientFrame; public static JTabbedPane tabbedPane; public static JScrollPane indexScrollPaneA; public static JScrollPane searchScrollPane; // 已弃用,改为使用 WorkRecordPanel public static JScrollPane searchScrollPaneDj; //新增字段 public static ProductTypePanel productTypePanel; public static JLabel productTypeCurrentLabel; public static final int PRODUCT_SN_LENGTH = 32; public static final String PREFIX_ZJ = "000020021815-01000016"; //智界 public static final String PREFIX_SJ = "000020022029-01000016"; //尚界 public static final String PRODUCT_TYPE_SWITCH_PASSWORD = "503833"; public static final String PRODUCT_TYPE_ZJ = ProductTypePanel.TYPE_ZJ; public static final String PRODUCT_TYPE_SJ = ProductTypePanel.TYPE_SJ; public static Boolean check_quality_result = false; public static Integer work_status = 0; public static JButton heart_beat_menu; public static JButton status_menu; public static JButton user_menu; // “软件设置”页签索引(用于判断当前是否切换到该页签) public static int softwareSettingTabIndex = -1; // 软件设置页面中的输入控件与操作按钮 private JTextField softwareIpField; private JTextField softwareOpField; private JTextField softwareOpNameField; private static final String APP_CFG_UT5310_PORT = "ut5310_port"; private JComboBox softwarePortCombo; private JButton softwareEditBtn; private JButton softwareSaveBtn; // 记录上一次非“软件设置”页签,用于密码校验失败时回退 private int lastNonSoftwareTabIndex = 0; // 防止页签回退时触发重复校验导致递归切换 private boolean softwareTabReverting = false; public static int scan_type = 0; public static JButton finish_ok_bt; public static JButton finish_ng_bt; public static JButton start_bt; public static JTextField product_sn; public static JButton f_scan_data_bt_1; public static String user20 = ""; public static JFrame welcomeWin; public static JPanel indexPanelB; // 已弃用,改为使用 WorkRecordPanel public static MesWebView jfxPanel = null; public static JPanel indexPanelC; public static MesWebView jfxPanel2 = null; public static MesRadio mesRadioHj; public static JTable table; public static Object[] columnNames = { "物料名称", "绑定批次", "剩余次数", "操作" }; public static Object[][] rowData = null; public static JLabel fxlabel; public static JButton plc_status_menu; public static JLabel remote_mode_menu; public static Timer plcMonitorTimer; private static int plcPhase = PLC_PHASE_IDLE; private static boolean lastRequestResult = false; private static boolean lastReady = false; private static boolean lastError = false; private static int mesBitlifeCounter = 0; private static final ExecutorService ut5310Executor = Executors.newSingleThreadExecutor(); public static void main(String[] args) { // if (LockUtil.getInstance().isAppActive() == false){ //// JOptionPane.showMessageDialog(null, "已有一个程序在运行,程序退出"); // return; // }else{ EventQueue.invokeLater(new Runnable() { @Override public void run() { try{ JdbcUtils.getConn(); //读文件配置 readProperty(); // 显示界面 mesClientFrame = new MesClient(); mesClientFrame.setVisible(false); welcomeWin = new LoginFarme(); welcomeWin.setVisible(true); }catch (Exception e){ e.printStackTrace(); } } }); } // } //读配置文件 private static void readProperty() throws IOException{ String enconding = "UTF-8"; InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties"); if (is == null) { mes_gw = ""; mes_line_sn = ""; mes_gw_des = ""; log.info("未找到config/config.properties,工位信息将由登录界面输入"); return; } Properties pro = new Properties(); BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding)); pro.load(br); mes_gw = pro.getProperty("mes.gw"); mes_line_sn = pro.getProperty("mes.line_sn"); String plcIp = pro.getProperty("mes.plc_ip"); mes_ut5310_enable = Boolean.parseBoolean(pro.getProperty("mes.ut5310_enable", "false")); Ut5310ScpiService.configure( pro.getProperty("mes.ut5310_port", "COM3"), getIntProperty(pro, "mes.ut5310_baud_rate", 9600), getIntProperty(pro, "mes.ut5310_data_bits", 8), getIntProperty(pro, "mes.ut5310_stop_bits", 1), pro.getProperty("mes.ut5310_parity", "NONE"), getIntProperty(pro, "mes.ut5310_read_timeout_ms", 2000), getIntProperty(pro, "mes.ut5310_test_timeout_ms", 300000), getIntProperty(pro, "mes.ut5310_fetch_interval_ms", 500), pro.getProperty("mes.ut5310_protocol", "MODBUS"), getIntProperty(pro, "mes.ut5310_modbus_slave", 1), getIntProperty(pro, "mes.ut5310_modbus_max_steps", 4), Boolean.parseBoolean(pro.getProperty("mes.ut5310_modbus_send_start", "false")), getIntProperty(pro, "mes.ut5310_modbus_expected_steps", 2)); if (mes_gw == null) { mes_gw = ""; } if (mes_line_sn == null) { mes_line_sn = ""; } if (plcIp != null && !plcIp.trim().isEmpty()) { mes_plc_ip = plcIp.trim(); PlcService.setPlcIp(mes_plc_ip); } // 页面保存的串口优先于 properties 默认值 String portFromDb = JdbcUtils.getAppConfig(APP_CFG_UT5310_PORT); if (portFromDb != null && !portFromDb.isEmpty()) { Ut5310ScpiService.setPortName(portFromDb); log.info("UT5310 串口使用本地配置: {}", portFromDb); } String ipFromDb = JdbcUtils.getServerIpByOp(mes_gw); if (ipFromDb != null && !ipFromDb.trim().isEmpty()) { mes_server_ip = ipFromDb.trim(); } String nameFromDb = JdbcUtils.getOpNameByOp(mes_gw); if (nameFromDb != null && !nameFromDb.trim().isEmpty()) { mes_gw_des = nameFromDb.trim(); } else if (!mes_gw.trim().isEmpty() && !mes_line_sn.trim().isEmpty()) { mes_gw_des = OprnoUtil.getGwDes(mes_line_sn, mes_gw); } else { mes_gw_des = ""; } log.info(mes_gw + ";" + mes_gw_des + ";" + mes_server_ip + ";"); } private static int getIntProperty(Properties pro, String name, int defaultValue) { try { String value = pro.getProperty(name); if (value == null || value.trim().isEmpty()) { return defaultValue; } return Integer.parseInt(value.trim()); } catch (Exception e) { return defaultValue; } } public static void applyOpConfig(String op, String opName, String ip) { if (op != null) { mes_gw = op.trim(); } if (opName != null) { mes_gw_des = opName.trim(); } if (ip != null) { mes_server_ip = ip.trim(); } try { // 清除旧配置,确保单条记录(本地工位只保留当前配置) JdbcUtils.clearOpIpConfig(); JdbcUtils.upsertOpIpConfig(mes_gw, mes_gw_des, mes_server_ip); } catch (Exception e) { log.info("保存工位配置失败: {}", e.getMessage()); } if (mesClientFrame != null) { mesClientFrame.setTitle("MES系统客户端:" + mes_gw + "- " + mes_gw_des); } if (welcomeWin != null) { welcomeWin.setTitle("MES系统客户端:" + mes_gw + " - " + mes_gw_des); } } // 打开并切换到“软件设置”页签(实际访问权限由页签切换监听统一控制) public static void openSoftwareSettings() { if (mesClientFrame != null) { mesClientFrame.setVisible(true); } if (tabbedPane != null && softwareSettingTabIndex >= 0 && softwareSettingTabIndex < tabbedPane.getTabCount()) { tabbedPane.setSelectedIndex(softwareSettingTabIndex); } } public static boolean ensureOpConfig(Component parent) { // 1) 先尝试从本地SQLite读取一条配置(本地工位一般只会配置一次) String[] cfg = JdbcUtils.getAnyOpIpConfig(); if (cfg != null && cfg.length >= 3) { String op = cfg[0]; String opName = cfg[1]; String ip = cfg[2]; if (!ip.isEmpty() && !op.isEmpty()) { applyOpConfig(op, opName, ip); } } // 2) 如果已有配置则直接放行 boolean missing = (mes_server_ip == null || mes_server_ip.trim().isEmpty()) || (mes_gw == null || mes_gw.trim().isEmpty()); if (!missing) { return true; } // 3) 没有配置才弹窗让用户输入并写入SQLite return showOpConfigDialog(parent); } public static boolean showOpConfigDialog(Component parent) { String currentOp = mes_gw == null ? "" : mes_gw.trim(); String currentIp = mes_server_ip == null ? "" : mes_server_ip.trim(); String currentName = mes_gw_des == null ? "" : mes_gw_des.trim(); if (!currentOp.isEmpty()) { if (currentIp.isEmpty()) { String ipFromDb = JdbcUtils.getServerIpByOp(currentOp); if (ipFromDb != null && !ipFromDb.trim().isEmpty()) { currentIp = ipFromDb.trim(); } } if (currentName.isEmpty()) { String nameFromDb = JdbcUtils.getOpNameByOp(currentOp); if (nameFromDb != null && !nameFromDb.trim().isEmpty()) { currentName = nameFromDb.trim(); } } } JTextField ipField = new JTextField(currentIp); JTextField opField = new JTextField(currentOp); JTextField nameField = new JTextField(currentName); JPanel panel = new JPanel(new GridLayout(0, 1)); panel.add(new JLabel("服务器IP/域名:")); panel.add(ipField); panel.add(new JLabel("工位号:")); panel.add(opField); panel.add(new JLabel("工位名称:")); panel.add(nameField); while (true) { int result = JOptionPane.showConfirmDialog(parent, panel, "软件设置", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result != JOptionPane.OK_OPTION) { return false; } String ip = ipField.getText() == null ? "" : ipField.getText().trim(); String op = opField.getText() == null ? "" : opField.getText().trim(); String opName = nameField.getText() == null ? "" : nameField.getText().trim(); if (ip.isEmpty() || op.isEmpty()) { JOptionPane.showMessageDialog(parent, "服务器IP和工位号不能为空", "提示窗口", JOptionPane.INFORMATION_MESSAGE); continue; } if (opName.isEmpty()) { opName = OprnoUtil.getGwDes(mes_line_sn, op); } if (!testMesServer(ip)) { JOptionPane.showMessageDialog(parent, "无法连接到MES服务器:" + ip + ":8980", "提示窗口", JOptionPane.INFORMATION_MESSAGE); continue; } applyOpConfig(op, opName, ip); return true; } } private static void initServerIp() { String op = mes_gw; String ip = JdbcUtils.getServerIpByOp(op); while (true) { // 1) DB里有IP,先校验连通性(防止历史错误IP导致永远登录不了) if (ip != null && !ip.trim().isEmpty()) { ip = ip.trim(); if (testMesServer(ip)) { break; } JOptionPane.showMessageDialog(null, "当前工位已配置的MES服务器IP/域名无法连接:" + ip + "\n请重新输入正确的IP/域名", "MES服务器设置", JOptionPane.WARNING_MESSAGE); } // 2) 让用户输入 String input = JOptionPane.showInputDialog(null, "请输入MES服务器IP/域名", "MES服务器设置", JOptionPane.QUESTION_MESSAGE); if (input == null) { System.exit(0); return; } input = input.trim(); if (input.isEmpty()) { continue; } // 3) 校验输入可连通,再写库 if (!testMesServer(input)) { JOptionPane.showMessageDialog(null, "无法连接到MES服务器:" + input + ":8980\n请检查IP/域名是否正确,或网络是否可达", "MES服务器设置", JOptionPane.WARNING_MESSAGE); continue; } boolean ok = JdbcUtils.upsertOpIpConfig(op, mes_gw_des, input); if (ok) { ip = input; break; } else { JOptionPane.showMessageDialog(null, "保存失败,请重试", "提示窗口", JOptionPane.INFORMATION_MESSAGE); } } mes_server_ip = ip; log.info(mes_gw + ";" + mes_gw_des + ";" + mes_server_ip + ";"); } public static boolean testMesServer(String host) { if (host == null || host.trim().isEmpty()) { return false; } try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(host.trim(), 8980), 2500); return true; } catch (Exception e) { return false; } } //启动心跳包程序 public static java.util.Timer heartBeatTimer; public static java.util.Timer heartBeatIconTimer; public static boolean iconREDFlag = true; public static void startHeartBeatTimer() { if(heartBeatTimer!=null) { heartBeatTimer.cancel(); } //心跳显示图标 if(heartBeatIconTimer!=null) { heartBeatIconTimer.cancel(); } heartBeatIconTimer = new Timer(); heartBeatIconTimer.schedule(new TimerTask() { public void run() { if(iconREDFlag) { heart_beat_menu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/grey_dot.png"))); iconREDFlag = false; }else { heart_beat_menu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/green_dot.png"))); iconREDFlag = true; } heart_beat_menu.setText(DateLocalUtils.getCurrentTime()); heart_beat_menu.repaint(); } }, 100,mes_heart_icon_cycle*1000); } //设置tcp连接状态显示 public static void setTcpStatus() { status_menu.setText("已连接MES服务器"); heart_beat_menu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/grey_dot.png"))); heart_beat_menu.repaint(); } public static void initWarehouseData(){ loadProductTypeFromDb(); //新增 resetScanA(); } public static void resetScanA() { work_status = 0; check_quality_result = false; plcPhase = PLC_PHASE_IDLE; lastRequestResult = false; lastReady = false; PlcService.clearAllMesSignals(); if (MesClient.finish_ok_bt != null) { MesClient.finish_ok_bt.setEnabled(false); } if (MesClient.finish_ng_bt != null) { MesClient.finish_ng_bt.setEnabled(false); } if (MesClient.start_bt != null) { MesClient.start_bt.setEnabled(false); } if (product_sn != null) { product_sn.setText(""); } if (MesClient.fxlabel != null) { MesClient.fxlabel.setVisible(false); } if (MesClient.f_scan_data_bt_1 != null) { MesClient.f_scan_data_bt_1.setEnabled(true); } updateProductTypePanelEnabled(true); MesClient.setMenuStatus("当前生产类型:" + getProductTypeName() + ",请扫工件码",0); //修改 // MesClient.setMenuStatus("开班点检,请先进行OKNG样件测试",-1); updateMaterailData(); // shiftUserCheck(); } public static int userLoginHours;//用户登录所处小时 //换班用户信息检查 private static void shiftUserCheck() { LocalDateTime now = LocalDateTime.now(); // 判断时间范围 if (userLoginHours >= 8 && userLoginHours < 20) { int hour = now.getHour(); if (hour >= 20 || hour < 8) { logoff(); } } else { int hour = now.getHour(); if (hour >= 8 && hour < 20) { logoff(); } } } public static void resetScanB() { } public static void connectPlc() { PlcService.setPlcIp(mes_plc_ip); boolean ok = PlcService.connect(); updatePlcStatus(ok); if (!ok) { PlcService.clearAllMesSignals(); } } public static void updatePlcStatus(boolean ok) { if (plc_status_menu == null) { return; } if (ok) { plc_status_menu.setText("PLC已连接"); plc_status_menu.setForeground(Color.GREEN); } else { plc_status_menu.setText("PLC未连接"); plc_status_menu.setForeground(Color.RED); } plc_status_menu.repaint(); } public static void updateRemoteModeStatus(boolean remote) { if (remote_mode_menu == null) { return; } if (remote) { remote_mode_menu.setText("远程模式"); remote_mode_menu.setForeground(Color.GREEN); } else { remote_mode_menu.setText("本地模式"); remote_mode_menu.setForeground(Color.ORANGE); } remote_mode_menu.repaint(); } private static void updateStartButtonEnabled(boolean remote, boolean ready) { if (start_bt == null || plcPhase != PLC_PHASE_WAIT_START || !check_quality_result) { return; } start_bt.setEnabled(remote && ready); } public static void startWork() { if (plcPhase != PLC_PHASE_WAIT_START || !check_quality_result) { setMenuStatus("当前状态不允许启动", -1); return; } String sn = product_sn.getText().trim(); if (sn.isEmpty()) { setMenuStatus("工件码为空,请重试", -1); return; } if (!PlcService.ensureConnected()) { setMenuStatus("PLC未连接,请检查网络", -1); updatePlcStatus(false); return; } updatePlcStatus(true); byte[] plcData = PlcService.readSignalBlock(); if (!Op310PlcPoint.isRemote(plcData)) { setMenuStatus("设备处于本地模式,MES无法控制", -1); updateRemoteModeStatus(false); updateStartButtonEnabled(false, Op310PlcPoint.isReady(plcData)); return; } if (!Op310PlcPoint.isReady(plcData)) { setMenuStatus("设备未Ready,请等待", -1); updateStartButtonEnabled(true, false); return; } if (!PlcService.setStart(true)) { setMenuStatus("发送启动信号失败", -1); return; } plcPhase = PLC_PHASE_WAIT_REQUEST; lastRequestResult = Op310PlcPoint.isRequestResult(plcData); lastReady = Op310PlcPoint.isReady(plcData); start_bt.setEnabled(false); setMenuStatus("已发送启动信号,等待设备加工", 0); } public static void startPlcMonitorTimer() { if (plcMonitorTimer != null) { plcMonitorTimer.cancel(); } connectPlc(); plcMonitorTimer = new Timer(); plcMonitorTimer.schedule(new TimerTask() { @Override public void run() { pollPlcSignals(); } }, 500, 300); } private static void pollPlcSignals() { try { if (!PlcService.ensureConnected()) { SwingUtilities.invokeLater(() -> updatePlcStatus(false)); return; } SwingUtilities.invokeLater(() -> updatePlcStatus(true)); mesBitlifeCounter++; if (mesBitlifeCounter >= 3) { mesBitlifeCounter = 0; PlcService.toggleMesBitlife(); } byte[] data = PlcService.readSignalBlock(); boolean remote = Op310PlcPoint.isRemote(data); boolean ready = Op310PlcPoint.isReady(data); boolean error = Op310PlcPoint.isError(data); boolean requestResult = Op310PlcPoint.isRequestResult(data); SwingUtilities.invokeLater(() -> updateRemoteModeStatus(remote)); if (error && !lastError) { PlcService.pulseErrorReset(); SwingUtilities.invokeLater(() -> setMenuStatus("设备报警,请检查", -1)); } lastError = error; if (plcPhase == PLC_PHASE_WAIT_START && check_quality_result) { if (ready && !lastReady && remote) { SwingUtilities.invokeLater(() -> setMenuStatus("设备已Ready,请点击启动", 0)); } SwingUtilities.invokeLater(() -> updateStartButtonEnabled(remote, ready)); } if (work_status != 1) { lastRequestResult = requestResult; lastReady = ready; return; } if (plcPhase == PLC_PHASE_WAIT_START) { lastRequestResult = requestResult; lastReady = ready; return; } if (plcPhase == PLC_PHASE_WAIT_REQUEST) { if (requestResult && !lastRequestResult) { PlcService.setStart(false); if (mes_ut5310_enable) { plcPhase = PLC_PHASE_WAIT_UT5310; String sn = product_sn == null ? "" : product_sn.getText().trim(); SwingUtilities.invokeLater(() -> { finish_ok_bt.setEnabled(false); finish_ng_bt.setEnabled(false); setMenuStatus("工装到位,开始绝缘耐压测试", 0); }); startUt5310TestAsync(sn); } else { plcPhase = PLC_PHASE_WAIT_OPERATOR; SwingUtilities.invokeLater(() -> { finish_ok_bt.setEnabled(true); finish_ng_bt.setEnabled(true); setMenuStatus("设备加工完成,请确认OK/NG", 0); }); } } } else if (plcPhase == PLC_PHASE_WAIT_READY) { if (ready && !lastReady) { PlcService.clearTestResult(); SwingUtilities.invokeLater(() -> { resetScanA(); setMenuStatus("结果提交成功,请扫下一件", 0); scan_type = 1; scanBarcode(); }); } } lastRequestResult = requestResult; lastReady = ready; } catch (Exception e) { log.info("PLC轮询异常: {}", e.getMessage()); PlcService.disconnect(); SwingUtilities.invokeLater(() -> updatePlcStatus(false)); } } private static void startUt5310TestAsync(String sn) { ut5310Executor.submit(() -> { if (sn == null || sn.trim().isEmpty()) { submitUt5310Result("", new Ut5310TestResult(false, "ERROR", "empty sn")); return; } try { SwingUtilities.invokeLater(() -> setMenuStatus("绝缘耐压测试中...", 0)); Ut5310TestResult result = Ut5310ScpiService.startAndFetchResult(); submitUt5310Result(sn, result); } catch (Exception e) { log.info("UT5310测试异常: {}", e.getMessage()); submitUt5310Result(sn, new Ut5310TestResult(false, "ERROR", e.getMessage())); } }); } private static boolean submitUt5310Result(String sn, Ut5310TestResult testResult) { if (plcPhase != PLC_PHASE_WAIT_UT5310) { SwingUtilities.invokeLater(() -> setMenuStatus("当前状态不允许提交绝缘耐压结果", -1)); return false; } if (testResult != null && "ERROR".equalsIgnoreCase(testResult.getJudge())) { plcPhase = PLC_PHASE_WAIT_REQUEST; SwingUtilities.invokeLater(() -> { setMenuStatus("UT5310通信失败: " + testResult.getRawResponse(), -1); finish_ok_bt.setEnabled(true); finish_ng_bt.setEnabled(true); }); return false; } if (testResult != null && "STOP".equalsIgnoreCase(testResult.getJudge())) { plcPhase = PLC_PHASE_WAIT_REQUEST; SwingUtilities.invokeLater(() -> setMenuStatus("UT5310测试被停止", -1)); return false; } if (!PlcService.ensureConnected()) { SwingUtilities.invokeLater(() -> { setMenuStatus("PLC未连接,请检查网络", -1); updatePlcStatus(false); }); return false; } SwingUtilities.invokeLater(() -> updatePlcStatus(true)); boolean isOk = testResult != null && testResult.isOk(); String mesResult = isOk ? "OK" : "NG"; boolean plcWriteOk = isOk ? PlcService.setTestOk(true) : PlcService.setTestNg(true); if (!plcWriteOk) { SwingUtilities.invokeLater(() -> setMenuStatus("写入PLC绝缘耐压结果失败", -1)); return false; } if (testResult != null) { testResult.printToConsole(); } System.out.println("[UT5310] 准备上传 MES: sn=" + sn + ", mesResult=" + mesResult + ", deviceResult=" + (testResult == null ? "" : testResult.getJudge())); JSONObject insObj = DataUtil.uploadInsulation2(sn, user20, testResult); if (insObj == null || insObj.get("result") == null || !insObj.get("result").toString().equalsIgnoreCase("true")) { if (isOk) { PlcService.setTestOk(false); } else { PlcService.setTestNg(false); } String msg = insObj != null && insObj.get("message") != null ? insObj.getString("message") : "绝缘耐压明细上传失败,请重试"; SwingUtilities.invokeLater(() -> setMenuStatus(msg, -1)); return false; } JSONObject retObj = DataUtil.sendQuality(sn, mesResult, user20, testResult == null ? "" : testResult.getJudge(), testResult == null ? "" : testResult.getRawResponse()); if (retObj == null) { if (isOk) { PlcService.setTestOk(false); } else { PlcService.setTestNg(false); } SwingUtilities.invokeLater(() -> setMenuStatus("绝缘耐压结果上传失败,请重试", -1)); return false; } if (retObj.get("result") != null && retObj.get("result").toString().equalsIgnoreCase("true")) { plcPhase = PLC_PHASE_WAIT_READY; SwingUtilities.invokeLater(() -> { finish_ok_bt.setEnabled(false); finish_ng_bt.setEnabled(false); setMenuStatus("绝缘耐压结果已提交,等待设备复位...", 0); }); return true; } if (isOk) { PlcService.setTestOk(false); } else { PlcService.setTestNg(false); } SwingUtilities.invokeLater(() -> { if (retObj.get("result") == null) { setMenuStatus("绝缘耐压结果上传失败,请重试", -1); } else if (retObj.get("result").toString().equalsIgnoreCase("false")) { setMenuStatus(retObj.getString("message"), -1); } }); return false; } private static boolean submitPlcResult(String sn, String result, boolean isOk) { if (plcPhase != PLC_PHASE_WAIT_OPERATOR) { setMenuStatus("当前状态不允许提交结果", -1); return false; } if (!PlcService.ensureConnected()) { setMenuStatus("PLC未连接,请检查网络", -1); updatePlcStatus(false); return false; } updatePlcStatus(true); boolean plcWriteOk = isOk ? PlcService.setTestOk(true) : PlcService.setTestNg(true); if (!plcWriteOk) { setMenuStatus("写入PLC结果信号失败", -1); return false; } JSONObject retObj = DataUtil.sendQuality(sn, result, user20); if (retObj == null) { if (isOk) { PlcService.setTestOk(false); } else { PlcService.setTestNg(false); } setMenuStatus("请求失败,请重试", -1); return false; } if (retObj.get("result") != null && retObj.get("result").toString().equalsIgnoreCase("true")) { plcPhase = PLC_PHASE_WAIT_READY; finish_ok_bt.setEnabled(false); finish_ng_bt.setEnabled(false); setMenuStatus("结果已提交,等待设备复位...", 0); return true; } if (isOk) { PlcService.setTestOk(false); } else { PlcService.setTestNg(false); } if (retObj.get("result") == null) { setMenuStatus("请求失败,请重试", -1); } else if (retObj.get("result").toString().equalsIgnoreCase("false")) { setMenuStatus(retObj.getString("message"), -1); } return false; } //获取用户20位 public static void getUser() { user20 = user_menu.getText().toString(); // String space_tmp1 = ""; // if(user20.length()<20) { // for(int i=0;i<20-user20.length();i++) { // space_tmp1 = space_tmp1 + " "; // } // } // user20 = user20 + space_tmp1; } //获取barcode内容36位 public static String getBarcode(String barcodeTmp) { String barcodeRet = barcodeTmp; if(barcodeTmp.equalsIgnoreCase("")) { return ""; }else { if(barcodeTmp.length()<36) { String space = ""; for(int i=0;i<36-barcodeTmp.length();i++) { space = space + " "; } barcodeRet = barcodeTmp + space; } } return barcodeRet; } public static void scanBarcode() { if(work_status == 1){ JOptionPane.showMessageDialog(mesClientFrame,"工作中,勿扫码","提示窗口", JOptionPane.INFORMATION_MESSAGE); return; } String scanBarcodeTitle = ""; switch(scan_type) { case 1: product_sn.setText(""); scanBarcodeTitle = "请扫工件码"; break; } //弹窗扫工件码 String scanBarcode = JOptionPane.showInputDialog(null, scanBarcodeTitle); if(scanBarcode!=null&&!scanBarcode.equalsIgnoreCase("")) { scanBarcode = scanBarcode.trim(); //生产类型新增 //获取用户 getUser(); //获取扫码内容36位 String barcode36 = getBarcode(scanBarcode);//处理36为码 //工位号 String gw = ""; switch(scan_type) { case 1: product_sn.setText(scanBarcode); break; } //刷新界面 mesClientFrame.repaint(); //生产类型新增 String validateMsg = validateProductSnMessage(scanBarcode); if (validateMsg != null) { check_quality_result = false; work_status = 0; MesClient.finish_ok_bt.setEnabled(false); MesClient.finish_ng_bt.setEnabled(false); MesClient.f_scan_data_bt_1.setEnabled(true); updateProductTypePanelEnabled(true); MesClient.setMenuStatus(validateMsg, -1); return; } updateProductTypePanelEnabled(false); // 查询工件质量 JSONObject retObj = DataUtil.checkQuality(scanBarcode,user20); if(retObj == null){ MesClient.check_quality_result = false; MesClient.work_status = 0; MesClient.setMenuStatus("请求失败,请重试",-1); return; } if(retObj.get("result")!=null&&retObj.get("result").toString().equalsIgnoreCase("true")) { if (!PlcService.ensureConnected()) { MesClient.check_quality_result = false; MesClient.work_status = 0; MesClient.setMenuStatus("PLC未连接,请检查网络", -1); updatePlcStatus(false); return; } updatePlcStatus(true); byte[] plcData = PlcService.readSignalBlock(); if (!Op310PlcPoint.isRemote(plcData)) { MesClient.check_quality_result = false; MesClient.work_status = 0; MesClient.setMenuStatus("设备处于本地模式,MES无法控制", -1); updateRemoteModeStatus(false); return; } MesClient.status_menu.setForeground(Color.GREEN); MesClient.check_quality_result = true; MesClient.work_status = 1; plcPhase = PLC_PHASE_WAIT_START; lastRequestResult = Op310PlcPoint.isRequestResult(plcData); lastReady = Op310PlcPoint.isReady(plcData); MesClient.f_scan_data_bt_1.setEnabled(false); MesClient.finish_ok_bt.setEnabled(false); MesClient.finish_ng_bt.setEnabled(false); updateStartButtonEnabled(Op310PlcPoint.isRemote(plcData), Op310PlcPoint.isReady(plcData)); if (Op310PlcPoint.isReady(plcData)) { MesClient.setMenuStatus("质量合格,设备已Ready,请点击启动", 0); } else { MesClient.setMenuStatus("质量合格,等待设备Ready后点击启动", 0); } }else{ MesClient.check_quality_result = false; MesClient.work_status = 0; if(retObj.get("result")==null){ MesClient.setMenuStatus("请求失败,请重试",-1); }else{ if(retObj.get("result").toString().equalsIgnoreCase("false")){ MesClient.setMenuStatus(retObj.getString("message"),-1); } } } }else { MesClient.setMenuStatus("请扫工件码,请重试",-1); // JOptionPane.showMessageDialog(mesClientFrame,"请扫工件码","提示窗口", JOptionPane.INFORMATION_MESSAGE); return; } } public static void logoff() { welcomeWin.setVisible(true); mesClientFrame.setVisible(false); } public MesClient() { setIconImage(Toolkit.getDefaultToolkit().getImage(MesClient.class.getResource("/bg/logo.png"))); setTitle("MES系统客户端:"+mes_gw + "- " + mes_gw_des); // setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(0, 0, 1024, 768); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); // 添加窗口监听器 addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { int choice = JOptionPane.showConfirmDialog(null, "确定要关闭窗口吗?", "关闭确认", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (choice == JOptionPane.YES_OPTION) { // 如果用户点击“是”,则关闭窗口 dispose(); // 释放窗口资源并关闭窗口 System.exit(0); } } }); JMenuBar menuBar = new JMenuBar(); menuBar.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 26)); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("用户"); fileMenu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/user.png"))); fileMenu.setFont(new Font("微软雅黑", Font.PLAIN, 20)); menuBar.add(fileMenu); JMenuItem exitMenuItem = new JMenuItem("退出"); exitMenuItem.setIcon(new ImageIcon(MesClient.class.getResource("/bg/logoff.png"))); exitMenuItem.setFont(new Font("微软雅黑", Font.PLAIN, 22)); fileMenu.add(exitMenuItem); exitMenuItem.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) {//只能检测到mousePressed事件 super.mouseClicked(e); //dispose(); logoff(); } }); JMenu settingMenu = new JMenu("设置"); //settingMenu.setVisible(false); settingMenu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/menu_setting.png"))); settingMenu.setFont(new Font("微软雅黑", Font.PLAIN, 20)); menuBar.add(settingMenu); JMenuItem resetTcpMenu = new JMenuItem("\u91CD\u8FDEMES"); resetTcpMenu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/reset_logo.png"))); resetTcpMenu.setFont(new Font("微软雅黑", Font.PLAIN, 20)); resetTcpMenu.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { super.mouseClicked(e); } }); // settingMenu.add(resetTcpMenu); JMenuItem resetTcpMenu_1 = new JMenuItem("刷新工件"); resetTcpMenu_1.setIcon(new ImageIcon(MesClient.class.getResource("/bg/reset_logo.png"))); resetTcpMenu_1.setFont(new Font("微软雅黑", Font.PLAIN, 20)); resetTcpMenu_1.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { super.mouseClicked(e); resetScanA(); } }); settingMenu.add(resetTcpMenu_1); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); JToolBar toolBar = new JToolBar(); contentPane.add(toolBar, BorderLayout.NORTH); JLabel equipment_statu_label = new JLabel("状态:"); equipment_statu_label.setHorizontalAlignment(SwingConstants.CENTER); equipment_statu_label.setForeground(Color.BLACK); equipment_statu_label.setFont(new Font("微软雅黑", Font.PLAIN, 20)); equipment_statu_label.setBackground(Color.LIGHT_GRAY); toolBar.add(equipment_statu_label); status_menu = new JButton("设备未连接MES服务器"); status_menu.setText("已连接MES服务器"); status_menu.setForeground(Color.GREEN); status_menu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); status_menu.setForeground(Color.GREEN); status_menu.setFont(new Font("微软雅黑", Font.PLAIN, 20)); status_menu.setBackground(Color.BLACK); toolBar.add(status_menu); JLabel space_1 = new JLabel(" "); toolBar.add(space_1); JLabel heart_beat_status_label = new JLabel("心跳:"); heart_beat_status_label.setHorizontalAlignment(SwingConstants.CENTER); heart_beat_status_label.setForeground(Color.BLACK); heart_beat_status_label.setFont(new Font("微软雅黑", Font.PLAIN, 20)); heart_beat_status_label.setBackground(Color.LIGHT_GRAY); toolBar.add(heart_beat_status_label); heart_beat_menu = new JButton("2024-02-20 23:20:10"); heart_beat_menu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/green_dot.png"))); heart_beat_menu.setForeground(Color.GREEN); heart_beat_menu.setFont(new Font("微软雅黑", Font.PLAIN, 20)); heart_beat_menu.setBackground(Color.BLACK); toolBar.add(heart_beat_menu); JLabel space_2 = new JLabel(" "); toolBar.add(space_2); JLabel user_status_label = new JLabel("登录用户:"); user_status_label.setHorizontalAlignment(SwingConstants.CENTER); user_status_label.setForeground(Color.BLACK); user_status_label.setFont(new Font("微软雅黑", Font.PLAIN, 20)); user_status_label.setBackground(Color.LIGHT_GRAY); toolBar.add(user_status_label); user_menu = new JButton("JinJuShi"); user_menu.setForeground(Color.GREEN); user_menu.setFont(new Font("微软雅黑", Font.PLAIN, 22)); user_menu.setBackground(Color.BLACK); toolBar.add(user_menu); JLabel space_3 = new JLabel(" "); toolBar.add(space_3); JLabel plc_status_label = new JLabel("PLC:"); plc_status_label.setFont(new Font("微软雅黑", Font.PLAIN, 20)); toolBar.add(plc_status_label); plc_status_menu = new JButton("PLC未连接"); plc_status_menu.setForeground(Color.RED); plc_status_menu.setFont(new Font("微软雅黑", Font.PLAIN, 20)); plc_status_menu.addActionListener(e -> connectPlc()); toolBar.add(plc_status_menu); tabbedPane = new JTabbedPane(JTabbedPane.TOP); tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); tabbedPane.setMinimumSize(new Dimension(400, 50)); tabbedPane.setFont(new Font("宋体", Font.BOLD, 22)); contentPane.add(tabbedPane, BorderLayout.CENTER); JPanel bottomStatusPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 12, 6)); bottomStatusPanel.setBorder(new EmptyBorder(0, 5, 4, 12)); JLabel remoteModeTitle = new JLabel("控制模式:"); remoteModeTitle.setFont(new Font("微软雅黑", Font.PLAIN, 16)); remote_mode_menu = new JLabel("未知"); remote_mode_menu.setFont(new Font("微软雅黑", Font.BOLD, 16)); remote_mode_menu.setForeground(Color.GRAY); bottomStatusPanel.add(remoteModeTitle); bottomStatusPanel.add(remote_mode_menu); contentPane.add(bottomStatusPanel, BorderLayout.SOUTH); //首页 JPanel indexPanelA = new JPanel(); indexScrollPaneA = new JScrollPane(indexPanelA); indexPanelA.setLayout(null); product_sn = new JTextField(); product_sn.setHorizontalAlignment(SwingConstants.CENTER); product_sn.setEditable(false); product_sn.setFont(new Font("微软雅黑", Font.PLAIN, 28)); product_sn.setBounds(81, 70, 602, 70); indexPanelA.add(product_sn); product_sn.setColumns(10); f_scan_data_bt_1 = new JButton("扫码"); f_scan_data_bt_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { scan_type = 1; scanBarcode(); } }); f_scan_data_bt_1.setIcon(new ImageIcon(MesClient.class.getResource("/bg/scan_barcode.png"))); f_scan_data_bt_1.setFont(new Font("微软雅黑", Font.PLAIN, 32)); f_scan_data_bt_1.setBounds(693, 70, 198, 70); indexPanelA.add(f_scan_data_bt_1); // String[] hjtitles = new String[]{"焊机1","焊机2","焊机3"}; // String[] hjvals = new String[]{"HJ001","HJ002","HJ003"}; // mesRadioHj = new MesRadio(hjtitles,hjvals); // mesRadioHj.setSize(500,50); // mesRadioHj.setBounds(190,170,500,50); // indexPanelA.add(mesRadioHj); fxlabel = new JLabel("该工件为返修件,请仔细检查"); fxlabel.setFont(new Font("微软雅黑", Font.PLAIN, 38)); fxlabel.setBounds(81, 330, 810, 70); fxlabel.setForeground(Color.RED); fxlabel.setHorizontalAlignment(SwingConstants.CENTER); fxlabel.setVisible(false); indexPanelA.add(fxlabel); start_bt = new JButton("启动"); start_bt.setEnabled(false); start_bt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { startWork(); } }); start_bt.setFont(new Font("微软雅黑", Font.PLAIN, 32)); start_bt.setBounds(347, 180, 280, 70); indexPanelA.add(start_bt); finish_ok_bt = new JButton("OK"); finish_ok_bt.setEnabled(false); finish_ok_bt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(work_status == 1 && check_quality_result){ getUser(); String sn = MesClient.product_sn.getText().trim(); if(sn.isEmpty()){ MesClient.setMenuStatus("工件码为空,请重试",-1); return; } //生产类型新增 String validateMsg = validateProductSnMessage(sn); if (validateMsg != null) { MesClient.setMenuStatus(validateMsg, -1); return; } submitPlcResult(sn, "OK", true); } } }); finish_ok_bt.setIcon(new ImageIcon(MesClient.class.getResource("/bg/ok_bg.png"))); finish_ok_bt.setFont(new Font("微软雅黑", Font.PLAIN, 32)); finish_ok_bt.setBounds(185, 420, 240, 80); finish_ok_bt.setEnabled(false); indexPanelA.add(finish_ok_bt); finish_ng_bt = new JButton("NG"); finish_ng_bt.setEnabled(false); finish_ng_bt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(work_status == 1 && check_quality_result){ getUser(); String sn = MesClient.product_sn.getText().trim(); if(sn.isEmpty()){ MesClient.setMenuStatus("工件码为空,请重试",-1); return; } String validateMsg = validateProductSnMessage(sn); if (validateMsg != null) { MesClient.setMenuStatus(validateMsg, -1); return; } submitPlcResult(sn, "NG", false); } } }); finish_ng_bt.setIcon(new ImageIcon(MesClient.class.getResource("/bg/ng_bg.png"))); finish_ng_bt.setFont(new Font("微软雅黑", Font.PLAIN, 32)); finish_ng_bt.setBounds(508, 420, 240, 80); finish_ng_bt.setEnabled(false); indexPanelA.add(finish_ng_bt); tabbedPane.addTab("工作面板", new ImageIcon(MesClient.class.getResource("/bg/a_side.png")), indexScrollPaneA, null); tabbedPane.setEnabledAt(0, true); // searchScrollPane = new JScrollPane((Component) null); indexPanelC = new JPanel(new BorderLayout()); //新增的面板 JPanel indexPanelProductType = new JPanel(); indexPanelProductType.setLayout(null); JScrollPane productTypeScrollPane = new JScrollPane(indexPanelProductType); JLabel productTypeTitle = new JLabel("生产类型设置"); productTypeTitle.setFont(new Font("微软雅黑", Font.BOLD, 28)); productTypeTitle.setForeground(new Color(64, 64, 64)); productTypeTitle.setHorizontalAlignment(SwingConstants.CENTER); productTypeTitle.setBounds(81, 80, 810, 50); indexPanelProductType.add(productTypeTitle); JLabel productTypeHint = new JLabel("请选择当前生产的工件类型,切换后将保存到本地并用于扫码校验"); productTypeHint.setFont(new Font("微软雅黑", Font.PLAIN, 20)); productTypeHint.setForeground(new Color(140, 140, 140)); productTypeHint.setHorizontalAlignment(SwingConstants.CENTER); productTypeHint.setBounds(81, 140, 810, 40); indexPanelProductType.add(productTypeHint); productTypePanel = new ProductTypePanel(PRODUCT_TYPE_SWITCH_PASSWORD); productTypePanel.setBounds(276, 210, 420, 72); productTypePanel.setOnChangeListener(() -> { if (work_status == 0) { saveProductTypeToDb(); setMenuStatus("当前生产类型:" + getProductTypeName() + ",请扫工件码", 0); } refreshProductTypeCurrentLabel(); }); indexPanelProductType.add(productTypePanel); productTypeCurrentLabel = new JLabel(); productTypeCurrentLabel.setFont(new Font("微软雅黑", Font.PLAIN, 22)); productTypeCurrentLabel.setForeground(new Color(64, 64, 64)); productTypeCurrentLabel.setHorizontalAlignment(SwingConstants.CENTER); productTypeCurrentLabel.setBounds(81, 310, 810, 40); refreshProductTypeCurrentLabel(); indexPanelProductType.add(productTypeCurrentLabel); tabbedPane.addTab("生产类型", new ImageIcon(MesClient.class.getResource("/bg/menu_setting.png")), productTypeScrollPane, null); tabbedPane.addTab("开班点检", new ImageIcon(MesClient.class.getResource("/bg/menu_data_preprocess.png")), indexPanelC, null); // ========== 工作记录 Tab(改造:当前工位Tab + 所有工位Tab) ========== // 旧代码已注释: indexPanelB = new JPanel(); searchScrollPane = new JScrollPane(indexPanelB); indexPanelB.setLayout(null); tabbedPane.addTab("工作记录", new ImageIcon(MesClient.class.getResource("/bg/menu_data_preprocess.png")), searchScrollPane, null); // 创建“软件设置”页面,并加入主Tab页签 JPanel softwareSettingPanel = buildSoftwareSettingPanel(); JScrollPane softwareSettingScrollPane = new JScrollPane(softwareSettingPanel); tabbedPane.addTab("软件设置", new ImageIcon(MesClient.class.getResource("/bg/menu_setting.png")), softwareSettingScrollPane, null); softwareSettingTabIndex = tabbedPane.getTabCount() - 1; // 页面初始化时先从本地配置加载软件设置 loadSoftwareSettingsFromDb(); // // 创建工作记录的子 TabbedPane // JTabbedPane workRecordTabbedPane = new JTabbedPane(JTabbedPane.TOP); // workRecordTabbedPane.setFont(new Font("微软雅黑", Font.PLAIN, 14)); // // // OKNG 工位:当前工位 + 所有工位 // WorkRecordPanel[] workRecordPanels = new WorkRecordPanel[2]; // // // 当前工位Tab(使用配置文件中的 mes.gw) // workRecordPanels[0] = new WorkRecordPanel(mes_gw, mes_line_sn); // workRecordTabbedPane.addTab(mes_gw, null, workRecordPanels[0], "查询" + mes_gw + "的工作记录"); // // // 所有工位Tab(查询整条产线所有工位) // workRecordPanels[1] = new WorkRecordPanel(null, mes_line_sn); // workRecordTabbedPane.addTab("所有工位", null, workRecordPanels[1], "查询整条产线所有工位的工作记录"); // // // 切换子Tab时自动刷新数据 // workRecordTabbedPane.addChangeListener(e -> { // int selectedIndex = workRecordTabbedPane.getSelectedIndex(); // if (selectedIndex >= 0 && selectedIndex < workRecordPanels.length) { // workRecordPanels[selectedIndex].refreshData(); // } // }); // // // 将子 TabbedPane 添加到主 TabbedPane // tabbedPane.addTab("工作记录", new ImageIcon(MesClient.class.getResource("/bg/menu_data_preprocess.png")), workRecordTabbedPane, null); // tabbedPane.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { JTabbedPane tabbedPane = (JTabbedPane) e.getSource(); int selectedIndex = tabbedPane.getSelectedIndex(); System.out.println("selectedIndex:"+selectedIndex); if (softwareTabReverting) { return; } if (selectedIndex == softwareSettingTabIndex) { // 每次点击进入“软件设置”页签都进行密码验证(固定密码:mes) if (!verifySoftwareSettingPassword()) { softwareTabReverting = true; tabbedPane.setSelectedIndex(lastNonSoftwareTabIndex); softwareTabReverting = false; return; } loadSoftwareSettingsFromDb(); } else { // 只记录非“软件设置”页签,便于校验失败时回退 lastNonSoftwareTabIndex = selectedIndex; } } }); } private static String validateProductSnMessage(String sn) { if (sn == null || sn.isEmpty()) { return "工件码为空,请重试"; } if (sn.length() != PRODUCT_SN_LENGTH) { return "工件码长度须为32位,当前" + sn.length() + "位"; } String prefix = getProductSnPrefix(); if (!sn.startsWith(prefix)) { return "工件码前缀与当前类型(" + getProductTypeName() + ")不匹配,当前工件码为" + getProductTypeNameBySn(sn); } return null; } private static void updateProductTypePanelEnabled(boolean enabled) { if (productTypePanel != null) { productTypePanel.setEnabled(enabled); } } public static void loadProductTypeFromDb() { if (productTypePanel == null) { return; } String savedType = JdbcUtils.getClientConfig( JdbcUtils.getProductTypeConfigKey(mes_gw), PRODUCT_TYPE_ZJ ); if (PRODUCT_TYPE_SJ.equals(savedType)) { productTypePanel.setResult(PRODUCT_TYPE_SJ); } else { productTypePanel.setResult(PRODUCT_TYPE_ZJ); } refreshProductTypeCurrentLabel(); } public static void refreshProductTypeCurrentLabel() { if (productTypeCurrentLabel != null) { productTypeCurrentLabel.setText("当前选择:" + getProductTypeName() + "(前缀 " + getProductSnPrefix() + ")"); } } public static void saveProductTypeToDb() { if (productTypePanel == null) { return; } JdbcUtils.saveClientConfig( JdbcUtils.getProductTypeConfigKey(mes_gw), productTypePanel.getResult() ); } public static String getProductSnPrefix() { if (productTypePanel != null && PRODUCT_TYPE_SJ.equals(productTypePanel.getResult())) { return PREFIX_SJ; } return PREFIX_ZJ; } public static String getProductTypeName() { if (productTypePanel != null) { return productTypePanel.getTypeName(); } return "智界"; } private static String getProductTypeNameBySn(String sn) { if (sn.startsWith(PREFIX_SJ)) { return "尚界"; } if (sn.startsWith(PREFIX_ZJ)) { return "智界"; } return "未知"; } // 软件设置页面UI构建(含编辑/保存/重载按钮) private JPanel buildSoftwareSettingPanel() { JPanel panel = new JPanel(); panel.setLayout(null); JLabel title = new JLabel("软件设置"); title.setFont(new Font("微软雅黑", Font.BOLD, 26)); title.setBounds(40, 30, 300, 40); panel.add(title); JLabel ipLabel = new JLabel("服务器IP/域名:"); ipLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18)); ipLabel.setBounds(40, 100, 200, 30); panel.add(ipLabel); softwareIpField = new JTextField(""); softwareIpField.setFont(new Font("微软雅黑", Font.PLAIN, 18)); softwareIpField.setBounds(220, 100, 360, 34); softwareIpField.setEditable(false); panel.add(softwareIpField); JLabel opLabel = new JLabel("工位号:"); opLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18)); opLabel.setBounds(40, 150, 200, 30); panel.add(opLabel); softwareOpField = new JTextField(""); softwareOpField.setFont(new Font("微软雅黑", Font.PLAIN, 18)); softwareOpField.setBounds(220, 150, 360, 34); softwareOpField.setEditable(false); panel.add(softwareOpField); JLabel nameLabel = new JLabel("工位名称:"); nameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18)); nameLabel.setBounds(40, 200, 200, 30); panel.add(nameLabel); softwareOpNameField = new JTextField(""); softwareOpNameField.setFont(new Font("微软雅黑", Font.PLAIN, 18)); softwareOpNameField.setBounds(220, 200, 360, 34); softwareOpNameField.setEditable(false); panel.add(softwareOpNameField); JLabel portLabel = new JLabel("耐压仪串口:"); portLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18)); portLabel.setBounds(40, 250, 200, 30); panel.add(portLabel); softwarePortCombo = new JComboBox(); softwarePortCombo.setFont(new Font("微软雅黑", Font.PLAIN, 18)); softwarePortCombo.setBounds(220, 250, 360, 34); softwarePortCombo.setEditable(true); softwarePortCombo.setEnabled(false); refreshSerialPortCombo(); panel.add(softwarePortCombo); softwareEditBtn = new JButton("编辑"); softwareEditBtn.setFont(new Font("微软雅黑", Font.PLAIN, 20)); softwareEditBtn.setBounds(220, 320, 140, 44); softwareEditBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 点击“编辑”后允许修改输入框,并开放保存按钮 softwareIpField.setEditable(true); softwareOpField.setEditable(true); softwareOpNameField.setEditable(true); refreshSerialPortCombo(); if (softwarePortCombo != null) { softwarePortCombo.setEnabled(true); } if (softwareSaveBtn != null) { softwareSaveBtn.setEnabled(true); } } }); panel.add(softwareEditBtn); softwareSaveBtn = new JButton("保存"); softwareSaveBtn.setFont(new Font("微软雅黑", Font.PLAIN, 20)); softwareSaveBtn.setBounds(380, 320, 140, 44); softwareSaveBtn.setEnabled(false); softwareSaveBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 保存前读取并校验输入内容 String ip = softwareIpField.getText() == null ? "" : softwareIpField.getText().trim(); String op = softwareOpField.getText() == null ? "" : softwareOpField.getText().trim(); String opName = softwareOpNameField.getText() == null ? "" : softwareOpNameField.getText().trim(); String port = getSelectedSerialPort(); if (ip.isEmpty() || op.isEmpty()) { JOptionPane.showMessageDialog(mesClientFrame, "服务器IP和工位号不能为空", "提示窗口", JOptionPane.INFORMATION_MESSAGE); return; } if (port.isEmpty()) { JOptionPane.showMessageDialog(mesClientFrame, "耐压仪串口不能为空", "提示窗口", JOptionPane.INFORMATION_MESSAGE); return; } if (opName.isEmpty()) { opName = OprnoUtil.getGwDes(mes_line_sn, op); } if (!testMesServer(ip)) { JOptionPane.showMessageDialog(mesClientFrame, "无法连接到MES服务器:" + ip + ":8980", "提示窗口", JOptionPane.INFORMATION_MESSAGE); return; } // 写入本地配置并刷新显示 applyOpConfig(op, opName, ip); applyUt5310PortConfig(port); loadSoftwareSettingsFromDb(); softwareIpField.setEditable(false); softwareOpField.setEditable(false); softwareOpNameField.setEditable(false); if (softwarePortCombo != null) { softwarePortCombo.setEnabled(false); } softwareSaveBtn.setEnabled(false); JOptionPane.showMessageDialog(mesClientFrame, "保存成功", "提示窗口", JOptionPane.INFORMATION_MESSAGE); } }); panel.add(softwareSaveBtn); JButton reloadBtn = new JButton("从本地配置读取"); reloadBtn.setFont(new Font("微软雅黑", Font.PLAIN, 18)); reloadBtn.setBounds(540, 320, 200, 44); reloadBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 从本地数据库读取配置并回填页面 loadSoftwareSettingsFromDb(); } }); panel.add(reloadBtn); panel.setPreferredSize(new Dimension(990, 550)); return panel; } private void refreshSerialPortCombo() { if (softwarePortCombo == null) { return; } String current = getSelectedSerialPort(); if (current.isEmpty()) { current = Ut5310ScpiService.getPortName(); } softwarePortCombo.removeAllItems(); SerialPort[] ports = SerialPort.getCommPorts(); if (ports != null) { for (SerialPort p : ports) { if (p != null && p.getSystemPortName() != null) { softwarePortCombo.addItem(p.getSystemPortName()); } } } if (current != null && !current.isEmpty()) { boolean found = false; for (int i = 0; i < softwarePortCombo.getItemCount(); i++) { if (current.equalsIgnoreCase(softwarePortCombo.getItemAt(i))) { softwarePortCombo.setSelectedIndex(i); found = true; break; } } if (!found) { softwarePortCombo.addItem(current); softwarePortCombo.setSelectedItem(current); } } } private String getSelectedSerialPort() { if (softwarePortCombo == null) { return ""; } Object selected = softwarePortCombo.getEditor().getItem(); if (selected == null) { selected = softwarePortCombo.getSelectedItem(); } return selected == null ? "" : selected.toString().trim(); } private void applyUt5310PortConfig(String port) { if (port == null || port.trim().isEmpty()) { return; } String next = port.trim(); Ut5310ScpiService.setPortName(next); JdbcUtils.setAppConfig(APP_CFG_UT5310_PORT, next); log.info("保存耐压仪串口配置: {}", next); } // 读取并回填“软件设置”页面数据 private void loadSoftwareSettingsFromDb() { String[] cfg = JdbcUtils.getAnyOpIpConfig(); if (cfg != null && cfg.length >= 3) { applyOpConfig(cfg[0], cfg[1], cfg[2]); softwareOpField.setText(cfg[0]); softwareOpNameField.setText(cfg[1]); softwareIpField.setText(cfg[2]); } else { softwareOpField.setText(mes_gw == null ? "" : mes_gw); softwareOpNameField.setText(mes_gw_des == null ? "" : mes_gw_des); softwareIpField.setText(mes_server_ip == null ? "" : mes_server_ip); } String portFromDb = JdbcUtils.getAppConfig(APP_CFG_UT5310_PORT); if (portFromDb != null && !portFromDb.isEmpty()) { Ut5310ScpiService.setPortName(portFromDb); } refreshSerialPortCombo(); if (softwareSaveBtn != null) { softwareSaveBtn.setEnabled(false); } if (softwareIpField != null) { softwareIpField.setEditable(false); } if (softwareOpField != null) { softwareOpField.setEditable(false); } if (softwareOpNameField != null) { softwareOpNameField.setEditable(false); } if (softwarePortCombo != null) { softwarePortCombo.setEnabled(false); } } // 进入“软件设置”页签前的密码校验(固定密码:mes) private boolean verifySoftwareSettingPassword() { String input = JOptionPane.showInputDialog(this, "请输入软件设置密码:", "软件设置权限验证", JOptionPane.QUESTION_MESSAGE); if (input == null) { return false; } if ("mes".equals(input.trim())) { return true; } JOptionPane.showMessageDialog(this, "密码错误,无法进入软件设置页面", "提示窗口", JOptionPane.WARNING_MESSAGE); return false; } public static void setMenuStatus(String msg,int error){ if(error == 0){ MesClient.status_menu.setForeground(Color.GREEN); }else{ MesClient.status_menu.setForeground(Color.RED); } MesClient.status_menu.setText(msg); } public static void getMaterailData(){ try{ JSONObject retObj = DataUtil.getBindMaterail(); if(retObj == null){ return; } if(retObj.get("result")!=null&&retObj.get("result").toString().equalsIgnoreCase("true")) { java.util.List arrs = retObj.getList("data",BindMaterialResp.class); int i = 0; rowData = new Object[arrs.size()][7]; for (BindMaterialResp bindMaterialResp:arrs){ rowData[i][0] = bindMaterialResp.getMaterialTitle(); rowData[i][1] = bindMaterialResp.getBatchSn(); rowData[i][2] = bindMaterialResp.getLastTimes(); rowData[i][3] = ""; rowData[i][4] = bindMaterialResp.getCraft(); rowData[i][5] = bindMaterialResp.getMaterialId(); rowData[i][6] = bindMaterialResp.getType(); i++; } bindBatchPanel(); } }catch (Exception e){ log.info(e.getMessage()); } } public static void updateMaterailData(){ try{ JSONObject retObj = DataUtil.getBindMaterail(); if(retObj == null){ return; } if(retObj.get("result")!=null&&retObj.get("result").toString().equalsIgnoreCase("true")) { List arrs = retObj.getList("data",BindMaterialResp.class); int i = 0; for (BindMaterialResp bindMaterialResp:arrs){ rowData[i][0] = bindMaterialResp.getMaterialTitle(); rowData[i][1] = bindMaterialResp.getBatchSn(); rowData[i][2] = bindMaterialResp.getLastTimes(); rowData[i][3] = ""; rowData[i][4] = bindMaterialResp.getCraft(); rowData[i][5] = bindMaterialResp.getMaterialId(); rowData[i][6] = bindMaterialResp.getType(); i++; } MesClient.table.repaint(); } }catch (Exception e){ log.info(e.getMessage()); } } // 绑定物料批次码 public static void scanBatchSn(BindMaterialResp bindMaterialResp) { //弹窗扫工件码 String scanBarcodeTitle = "请扫物料:"+bindMaterialResp.getMaterialTitle(); String scanBarcode = JOptionPane.showInputDialog(null, scanBarcodeTitle); if(scanBarcode!=null&&!scanBarcode.equalsIgnoreCase("")) { JSONObject retObj = DataUtil.saveBindMaterail(scanBarcode,bindMaterialResp.getCraft(),bindMaterialResp.getMaterialId(),bindMaterialResp.getType()); if(retObj.get("result")!=null&&retObj.get("result").toString().equalsIgnoreCase("true")) { MesClient.setMenuStatus("扫物料:"+bindMaterialResp.getMaterialTitle()+"成功",0); updateMaterailData(); }else{ if(retObj.get("result")==null){ MesClient.setMenuStatus("请求失败,请重试",-1); }else{ if(retObj.get("result").toString().equalsIgnoreCase("false")){ MesClient.setMenuStatus(retObj.getString("message"),-1); } } } } } public static void bindBatchPanel(){ JPanel indexPanelBB = new JPanel(); JPanel panel = new JPanel(); panel.setBounds(0, 0, 990, 550); // panel.setBounds(81, 50, 810, 479); indexPanelBB.add(panel); panel.setLayout(new GridLayout(0, 1, 0, 0)); table = new JTable(rowData, columnNames){ public boolean isCellEditable(int row, int column) { if(column == 3){ return true; } return false; } }; table.setRowHeight(40); table.setEnabled(true); table.setFont(new Font("微软雅黑", Font.PLAIN, 14)); table.getColumnModel().getColumn(3).setCellRenderer(new TableCellRendererButton()); table.getColumnModel().getColumn(3).setCellEditor(new TableCellEditorButton()); JScrollPane scrollPane = new JScrollPane(table); panel.add(scrollPane); JScrollPane indexScrollPaneB = new JScrollPane(indexPanelBB); indexPanelBB.setLayout(null); tabbedPane.addTab("绑定物料", new ImageIcon(MesClient.class.getResource("/bg/menu_data_preprocess.png")), indexScrollPaneB, null); } // 开启发送结果定时任务 public static void startUpdateQualityTimer(){ // 创建异步线程池 ExecutorService executorService = Executors.newSingleThreadExecutor(); // 提交任务 executorService.submit(() -> { log.info("异步任务执行中..."); // 模拟耗时操作 try { while (true){ try { // 确保连接已经打开 if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) { JdbcUtils.openConnection(); } Statement statement = JdbcUtils.conn.createStatement(); String selectSql = "SELECT id, bw FROM submit_record\n" + "WHERE state = 0 ORDER BY id DESC LIMIT 10"; String updateSql = "UPDATE submit_record \n" + "SET state = '1'\n" + "WHERE id = "; ResultSet rs = statement.executeQuery(selectSql); while(rs.next()){ int id = rs.getInt("id"); String bw = rs.getString("bw"); // 发送请求 String url = "http://"+MesClient.mes_server_ip+":8980/js/a/mes/mesProductRecord/updateQualityByTiming"; log.info("质量:"+bw); String s = HttpUtils.sendPostRequestJson(url, bw ); log.info("结果:"+s); Boolean result = JSONObject.parseObject(s).getBoolean("result"); if(result) { // 更改状态为 1 statement.executeUpdate(updateSql + id); } } rs.close(); statement.close(); } catch (Exception e) { log.info(e.getMessage()); } try { Thread.sleep(2000); }catch (Exception e){ log.info(e.getMessage()); } } } catch (Exception e) { log.info(e.getMessage()); } log.info("异步任务执行完毕"); }); } }