| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256 |
- package com.mes.ui;
- import com.alibaba.fastjson2.JSONObject;
- import com.github.xingshuangs.iot.protocol.s7.enums.EPlcType;
- import com.github.xingshuangs.iot.protocol.s7.service.S7PLC;
- import com.mes.component.MesRadio;
- import com.mes.component.MesWebView;
- import com.mes.netty.NettyClient;
- import com.mes.netty.ProtocolParam;
- import com.mes.util.*;
- import javafx.embed.swing.JFXPanel;
- 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.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.MouseAdapter;
- import java.awt.event.MouseEvent;
- import java.io.*;
- import java.lang.reflect.Field;
- import java.nio.channels.FileChannel;
- import java.nio.channels.FileLock;
- import java.nio.channels.OverlappingFileLockException;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.time.LocalDateTime;
- import java.util.*;
- import java.util.List;
- import java.util.Timer;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.ScheduledFuture;
- import java.util.concurrent.TimeUnit;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- 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_tcp_port = 3000; // TCP服务端口
- public static int mes_heart_beat_cycle = 10; // 心跳周期
- public static int mes_heart_icon_cycle = 1;
- public static String mes_line_sn = ""; // 产线编号
- //TCP连接
- public static NettyClient nettyClient;
- //TCP连接状态
- public static boolean tcp_connect_flag = false;
- //TCP连接请求
- public static boolean connect_request_flag = false;
- //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;
- public static JScrollPane searchScrollPaneDj;
- 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 scan_type = 0;
- public static JButton finish_ok_bt;
- public static JButton finish_ng_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;
- 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;
- /**
- * 业务字段
- *
- */
- // 存储工位信息的 Map:key=工位号,value=Oprno 对象
- public static Map<String, Oprno> oprnoMap = new HashMap<>();
- // 正则表达式:匹配 mes.oprno.${工位号}.${属性名}
- private static final Pattern OPRNO_PATTERN = Pattern.compile("mes\\.oprno\\.(\\w+)\\.(\\w+)");
- // 需要跳过的属性名(不读入 Map)
- private static final String[] SKIP_PROPERTIES = {"hgA_qr_code", "hgB_qr_code"};
- // 新增:存储动态生成的工位输入框(key=工位号,value=输入框)
- private static Map<String, JTextField> oprnoTextFieldMap = new HashMap<>();
- // 输入框相关配置(可调整)
- private static final int TEXT_FIELD_WIDTH = 602; // 输入框宽度
- private static final int TEXT_FIELD_HEIGHT = 50; // 输入框高度
- private static final int TEXT_FIELD_X = 81; // 输入框X坐标(与原有工件码输入框对齐)
- private static final int TEXT_FIELD_MARGIN = 20; // 输入框之间的间距
- private static final Font TEXT_FIELD_FONT = new Font("微软雅黑", Font.PLAIN, 22); // 输入框字体
-
- // 定时任务池
- private static ScheduledExecutorService schedulerPool;
- // 存储每个工位的定时任务,用于后续管理和取消
- private static Map<String, ScheduledFuture<?>> taskMap = new HashMap<>();
- // 定时任务执行间隔(毫秒)
- // 定时任务开关状态
- public static boolean scheduledTasksEnabled = false;
- private static final long TASK_INTERVAL = 1000;
- // 时间打印任务间隔(毫秒)
- private static final long TIME_PRINT_INTERVAL = 500; // 0.5秒
- // 时间打印任务的引用
- private static ScheduledFuture<?> timePrintTask = null;
- //点检字段
- public static Boolean check_info = false;
- public static S7PLC s7PLC = new S7PLC(EPlcType.S1200,"10.88.10.80");
- public static void main(String[] args) {
- if (LockUtil.getInstance().isAppActive() == true){
- // JOptionPane.showMessageDialog(null, "已有一个程序在运行,程序退出");
- return;
- }else{
- EventQueue.invokeLater(new Runnable() {
- @Override
- public void run() {
- try{
- //读文件配置
- readProperty();
- // 显示界面
- mesClientFrame = new MesClient();
- mesClientFrame.setVisible(false);
- JdbcUtils.getConn();
- welcomeWin = new LoginFarme();
- welcomeWin.setVisible(true);
- getMaterailData();
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- });
- }
- }
- //读配置文件
- private static void readProperty() throws IOException{
- String enconding = "UTF-8";
- InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
- Properties pro = new Properties();
- BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding));
- pro.load(br);
- mes_gw = pro.getProperty("mes.gw");
- mes_server_ip = pro.getProperty("mes.server_ip");
- mes_tcp_port = Integer.parseInt(pro.getProperty("mes.tcp_port"));
- mes_heart_beat_cycle = Integer.parseInt(pro.getProperty("mes.heart_beat_cycle"));
- mes_line_sn = pro.getProperty("mes.line_sn");
- mes_gw_des = OprnoUtil.getGwDes(mes_line_sn,mes_gw);
- log.info(mes_gw + ";" + mes_gw_des + ";" + mes_server_ip + ";" + mes_tcp_port + ";" + mes_heart_beat_cycle);
- // 2. 读取工位信息并填充到 oprnoMap(自动跳过二维码字段)
- loadOprnoMap(pro);
- // 循环打印工位信息
- for (Map.Entry<String, Oprno> entry : oprnoMap.entrySet()) {
- Oprno oprno = entry.getValue();
- log.info("工位信息" + oprno.toString());
- }
- DataUtil.getCheckInfo();
- }
- // 初始化TCP
- public static void initTcpConnection() {
- try {
- if(nettyClient==null) {
- //初始化TCP连接
- nettyClient = new NettyClient();
- //TCP连接状态
- tcp_connect_flag = false;
- //设置TCP请求状态
- connect_request_flag = true;
- DataUtil.synrTcp(nettyClient,mes_gw);
- }
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- /**
- * 为指定工位创建定时任务
- * @param oprnoCode 工位号
- * @param textField 对应的输入框
- */
- private void createScheduledTask(final String oprnoCode, final JTextField textField) {
- // 先取消可能存在的旧任务
- if (taskMap.containsKey(oprnoCode)) {
- ScheduledFuture<?> oldTask = taskMap.get(oprnoCode);
- if (!oldTask.isCancelled()) {
- oldTask.cancel(false);
- }
- }
-
- // 只有当定时任务开关开启时才创建任务
- if (scheduledTasksEnabled) {
- // 创建新的定时任务
- ScheduledFuture<?> task = schedulerPool.scheduleAtFixedRate(() -> {
- // 在每次执行前检查开关状态
- if (scheduledTasksEnabled) {
- try {
- // 从PLC读取数据(这里是示例,实际使用时需要根据工位号确定对应的PLC地址)
- String sn = S7PLCUtils.getSnInOprno(oprnoMap.get(oprnoCode), s7PLC).trim();
- // 使用SwingUtilities确保在事件调度线程中更新UI
- SwingUtilities.invokeLater(() -> {
- // 更新输入框内容
- // System.out.println(sn + "加工完成情况" + s7PLC.readBoolean(oprnoMap.get(oprnoCode).process_ok));
- textField.setText(sn);
- });
- // 当从对应plc中取到加工完成时执行
- if (s7PLC.readBoolean(oprnoMap.get(oprnoCode).process_ok)){
- textField.setText(oprnoCode+"加工完成");
- System.out.println("工位号:"+oprnoCode);
- System.out.println("工位dizhi:"+oprnoMap.get(oprnoCode).process_ok);
- System.out.println("sn:"+sn);
- System.out.println("加工完成:---------------"+sn);
- String qret = "OK";
- if (!S7PLCUtils.getResultInOprno(oprnoMap.get(oprnoCode),s7PLC)){
- qret = "NG";
- }
- System.out.println("加工结果:---------------"+qret);
- Boolean sendret = DataUtil.sendQualityByGW(nettyClient,sn,qret,user20,oprnoCode);
- if (!sendret){
- log.error("发送数据失败");
- }
- }
- } catch (Exception e) {
- log.error("定时任务执行异常,工位号: " + oprnoCode, e);
- // 在异常情况下,也在事件调度线程中更新UI显示错误信息
- SwingUtilities.invokeLater(() -> {
- textField.setText("读取错误");
- });
- }
- }
- }, 0, TASK_INTERVAL, TimeUnit.MILLISECONDS);
-
- // 保存任务引用以便后续管理
- taskMap.put(oprnoCode, task);
- } else {
- log.info("定时任务已关闭,未为工位 " + oprnoCode + " 创建定时任务");
- }
- }
-
-
- /**
- * 新增:动态生成工位输入框(根据 oprnoMap 的 key 数量)
- * @param parentPanel 父面板(indexPanelA)
- */
- private void generateOprnoTextFields(JPanel parentPanel) {
- // 输入框起始Y坐标(在返修件提示标签下方,避免与OK/NG按钮重叠)
- int startY = 80; // 整体上移,减少顶部空白空间
- // 标签宽度设置
- int labelWidth = 120;
- // 按钮宽度
- int buttonWidth = 100;
- // 输入框和按钮之间的间距
- int gapBetweenFieldAndButton = 5;
- // 调整后的输入框宽度(为按钮腾出空间)
- int adjustedTextFieldWidth = TEXT_FIELD_WIDTH - labelWidth - buttonWidth - gapBetweenFieldAndButton;
- // 初始化定时任务池(如果尚未初始化)
- if (schedulerPool == null || schedulerPool.isShutdown()) {
- schedulerPool = Executors.newScheduledThreadPool(oprnoMap.size());
- }
- // 创建一个子面板来容纳所有输入框和标签,便于管理和滚动
- JPanel textFieldsPanel = new JPanel();
- textFieldsPanel.setLayout(null);
- textFieldsPanel.setBounds(TEXT_FIELD_X, startY, TEXT_FIELD_WIDTH, 100 + oprnoMap.size() * (TEXT_FIELD_HEIGHT + TEXT_FIELD_MARGIN));
- textFieldsPanel.setVisible(true); // 确保工位输入框和标签面板可见
-
- // 遍历 oprnoMap,生成输入框和标签(按工位号排序)
- List<String> oprnoCodes = new ArrayList<>(oprnoMap.keySet());
- Collections.sort(oprnoCodes); // 排序,确保输入框顺序固定
- int fieldY = 0;
- for (String oprnoCode : oprnoCodes) {
- // 1. 创建工位号标签
- JLabel label = new JLabel(oprnoCode + ":");
- label.setFont(TEXT_FIELD_FONT); // 使用与输入框相同的字体,保持一致性
- label.setHorizontalAlignment(SwingConstants.RIGHT); // 右对齐,便于与输入框对齐
- label.setVerticalAlignment(SwingConstants.CENTER);
- label.setBounds(0, fieldY, labelWidth, TEXT_FIELD_HEIGHT);
- label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); // 右侧添加一些边距
- textFieldsPanel.add(label);
-
- // 2. 创建输入框
- JTextField textField = new JTextField();
- textField.setHorizontalAlignment(SwingConstants.CENTER);
- textField.setEditable(false); // 设为不可编辑(与工件码输入框一致)
- textField.setFont(TEXT_FIELD_FONT);
- textField.setToolTipText("工位:" + oprnoCode); // 鼠标悬浮提示工位号
- // 设置输入框位置和大小(调整宽度和X坐标,为按钮腾出空间)
- textField.setBounds(labelWidth, fieldY, adjustedTextFieldWidth, TEXT_FIELD_HEIGHT);
- // 设置输入框默认文本(只显示状态信息,不包含工位号)
- textField.setText("");
- // 3. 存储输入框到Map(后续可通过工位号获取/修改输入框内容)
- oprnoTextFieldMap.put(oprnoCode, textField);
- // 4. 创建刷新按钮
- JButton refreshButton = new JButton("手动上料");
- refreshButton.setFont(new Font("SimHei", Font.PLAIN, 12));
- refreshButton.setBounds(labelWidth + adjustedTextFieldWidth + gapBetweenFieldAndButton, fieldY, buttonWidth, TEXT_FIELD_HEIGHT);
- refreshButton.setToolTipText("刷新工位:" + oprnoCode);
-
- // 5. 为按钮添加点击事件监听器
- final String currentOprnoCode = oprnoCode; // 必须使用final变量在匿名内部类中访问
- refreshButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- // 获取输入框内容
- String inputValue = textField.getText();
- // 打印工位号和输入框内容
- System.out.println("工位号:" + currentOprnoCode + ", 输入内容:" + inputValue);
- s7PLC.writeBoolean(oprnoMap.get(currentOprnoCode).getMes_in(),true);
- }
- });
- // 6. 添加到子面板
- textFieldsPanel.add(textField);
- textFieldsPanel.add(refreshButton);
- // 7. 为当前工位创建定时任务
- createScheduledTask(oprnoCode, textField);
- // 8. 计算下一个输入框的Y坐标
- fieldY += TEXT_FIELD_HEIGHT + TEXT_FIELD_MARGIN;
- }
-
- // 添加子面板到父面板
- parentPanel.add(textFieldsPanel);
-
- // 调整父面板的首选大小,确保滚动条正常工作
- parentPanel.setPreferredSize(new Dimension(parentPanel.getWidth(), Math.max(700, startY + textFieldsPanel.getHeight() + 100)));
- log.info("动态生成 {} 个工位输入框和标签", oprnoTextFieldMap.size());
- }
- //启动心跳包程序
- 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();
- }
- heartBeatTimer = new java.util.Timer();
- heartBeatTimer.schedule(new TimerTask() {
- public void run() {
- if(nettyClient!=null&&tcp_connect_flag) {
- //System.out.println("发送心跳报文");
- DataUtil.heartBeat(nettyClient,mes_gw);
- heart_beat_menu.setText(DateLocalUtils.getCurrentTime());
- }
- }
- }, 100,mes_heart_beat_cycle*1000);
- //心跳显示图标
- if(heartBeatIconTimer!=null) {
- heartBeatIconTimer.cancel();
- }
- heartBeatIconTimer = new Timer();
- heartBeatIconTimer.schedule(new TimerTask() {
- public void run() {
- if(tcp_connect_flag) {
- 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();
- }else {
- heart_beat_menu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/grey_dot.png")));
- heart_beat_menu.setText(DateLocalUtils.getCurrentTime());
- heart_beat_menu.repaint();
- //若未连接则尝试连接
- if(nettyClient!=null&&!tcp_connect_flag){
- System.out.println("TCP已断开");
- //TCP重新同步连接
- if(!connect_request_flag) {
- //System.out.println("TCP重新同步连接");
- //设置TCP请求状态,只重新同步连接一次
- connect_request_flag = true;
- DataUtil.synrTcp(nettyClient,mes_gw);
- }
- }
- }
- }
- }, 100,mes_heart_icon_cycle*1000);
- }
- //设置tcp连接状态显示
- public static void setTcpStatus() {
- if(tcp_connect_flag) {
- status_menu.setText("已连接MES服务器");
- heart_beat_menu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/grey_dot.png")));
- heart_beat_menu.repaint();
- }else {
- 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(){
- resetScanA();
- }
- public static void resetScanA() {
- work_status = 0;
- check_quality_result = false;
- MesClient.finish_ok_bt.setEnabled(false);
- MesClient.finish_ng_bt.setEnabled(false);
- product_sn.setText("");
- MesClient.fxlabel.setVisible(false);
- MesClient.f_scan_data_bt_1.setEnabled(true);
- MesClient.status_menu.setText("请扫工件码");
- 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();
- }
- }
- }
- //获取用户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("")) {
- //获取用户
- getUser();
- //获取扫码内容36位
- String barcode36 = getBarcode(scanBarcode);//处理36为码
- //工位号
- String gw = "";
- switch(scan_type) {
- case 1:
- product_sn.setText(scanBarcode);
- break;
- }
- //刷新界面
- mesClientFrame.repaint();
- if(!tcp_connect_flag) {
- MesClient.setMenuStatus("设备未连接Mes服务器",-1);
- // JOptionPane.showMessageDialog(mesClientFrame,"设备未连接Mes服务器","提示窗口", JOptionPane.INFORMATION_MESSAGE);
- return;
- }
- // 查询工件质量
- Boolean sendret = DataUtil.checkQuality(nettyClient,barcode36,user20);
- if(!sendret){
- MesClient.setMenuStatus("消息发送失败,请重试",-1);
- return;
- }
- }else {
- MesClient.setMenuStatus("请扫工件码,请重试",-1);
- return;
- }
- }
- public static void logoff() {
- welcomeWin.setVisible(true);
- mesClientFrame.setVisible(false);
- // 关闭定时任务池
- shutdownSchedulerPool();
-
- nettyClient = null;
- // if(heartBeatTimer!=null) {
- // heartBeatTimer.cancel();
- // }
- // if(heartBeatIconTimer!=null) {
- // heartBeatIconTimer.cancel();
- // }
- tcp_connect_flag = false;
- connect_request_flag = false;
- }
-
- /**
- * 创建时间打印定时任务
- */
- private void createTimePrintTask() {
- // 先取消可能存在的旧任务
- if (timePrintTask != null && !timePrintTask.isCancelled()) {
- timePrintTask.cancel(false);
- }
-
- // 初始化定时任务池(如果尚未初始化)
- if (schedulerPool == null || schedulerPool.isShutdown()) {
- schedulerPool = Executors.newScheduledThreadPool(oprnoMap.size() + 1); // +1 为时间打印任务
- }
-
- // 创建时间打印定时任务
- timePrintTask = schedulerPool.scheduleAtFixedRate(() -> {
- // 在每次执行前检查开关状态
- if (scheduledTasksEnabled) {
- try {
- // 获取所有工位对象并转换为数组
- Oprno[] oprnos = oprnoMap.values().toArray(new Oprno[0]);
- // 调用S7PLCUtils.isStart方法检查工位上料状态
- Oprno startOprno = S7PLCUtils.isStart(s7PLC, oprnos);
- // 处理返回结果
- if (startOprno != null) {
- // 判断这个工件码的位置是A面还是B面
- System.out.println("上料的工位号码:"+ startOprno.getOprno());
- String sn = S7PLCUtils.getSnInJXB(startOprno, s7PLC);
- if (sn != null && !sn.isEmpty()) {
- // 检查质量
- Boolean checkQualityResult = DataUtil.checkQualityByGw(nettyClient, sn, user20,startOprno.getOprno());
- if (!checkQualityResult) {
- MesClient.setMenuStatus("消息发送失败,请重试",-1);
- }
- }else {
- MesClient.setMenuStatus(startOprno.getOprno()+"获取工件码为空",-1);
- }
- }
- } catch (Exception e) {
- log.error("时间打印任务执行异常", e);
- }
- }
- }, 0, TIME_PRINT_INTERVAL, TimeUnit.MILLISECONDS);
- }
-
- /**
- * 关闭定时任务池的方法
- */
- private static void shutdownSchedulerPool() {
- try {
- if (schedulerPool != null && !schedulerPool.isShutdown()) {
- // 取消时间打印任务
- if (timePrintTask != null && !timePrintTask.isCancelled()) {
- timePrintTask.cancel(false);
- timePrintTask = null;
- }
-
- // 取消所有工位定时任务
- for (ScheduledFuture<?> future : taskMap.values()) {
- if (future != null && !future.isCancelled()) {
- future.cancel(false);
- }
- }
- // 清空任务映射
- taskMap.clear();
- // 关闭调度器池
- schedulerPool.shutdown();
- // 等待任务池关闭,最多等待3秒
- if (!schedulerPool.awaitTermination(3, TimeUnit.SECONDS)) {
- // 如果超时,强制关闭
- schedulerPool.shutdownNow();
- }
- log.info("定时任务池已成功关闭");
- }
- } catch (Exception e) {
- log.error("关闭定时任务池时发生异常", e);
- // 发生异常时强制关闭
- if (schedulerPool != null && !schedulerPool.isTerminated()) {
- schedulerPool.shutdownNow();
- }
- }
- }
- public MesClient() {
- setIconImage(Toolkit.getDefaultToolkit().getImage(MesClient.class.getResource("/bg/logo.png")));
- setTitle("MES系统客户端:"+mes_gw + "- " + mes_gw_des);
- setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
- // 添加窗口关闭监听器,确保定时任务池正确关闭
- addWindowListener(new java.awt.event.WindowAdapter() {
- @Override
- public void windowClosing(java.awt.event.WindowEvent windowEvent) {
- // 关闭定时任务池
- shutdownSchedulerPool();
- // 退出程序
- System.exit(0);
- }
- });
- setBounds(0, 0, 1024, 768);
- 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);
-
- JMenu mesMenu = new JMenu("MES");
- mesMenu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/menu_data_analysis.png")));
- mesMenu.setFont(new Font("微软雅黑", Font.PLAIN, 20));
- menuBar.add(mesMenu);
-
- JMenuItem taskToggleMenuItem = new JMenuItem("启动 (关闭)");
- taskToggleMenuItem.setIcon(new ImageIcon(MesClient.class.getResource("/bg/grey_dot.png")));
- taskToggleMenuItem.setFont(new Font("微软雅黑", Font.PLAIN, 20));
- taskToggleMenuItem.addMouseListener(new MouseAdapter() {
- @Override
- public void mousePressed(MouseEvent e) {
- // 如果当前是关闭状态,用户点击想要开启
- if (!scheduledTasksEnabled) {
- DataUtil.getCheckInfo();
- // 先检查开班点检是否完成
- if (!check_info) {
- // 未完成点检,显示提示并阻止操作
- MesClient.setMenuStatus("请先完成开班点检", -1);
- return;
- }
- }
-
- // 切换定时任务状态
- scheduledTasksEnabled = !scheduledTasksEnabled;
-
- // 更新菜单项文本和图标
- if (scheduledTasksEnabled) {
- taskToggleMenuItem.setText("启动 (开启)");
- taskToggleMenuItem.setIcon(new ImageIcon(MesClient.class.getResource("/bg/green_dot.png")));
- // 启动定时任务逻辑将在定时任务执行时检查状态
- MesClient.setMenuStatus("定时任务已开启", 1);
- } else {
- taskToggleMenuItem.setText("启动 (关闭)");
- taskToggleMenuItem.setIcon(new ImageIcon(MesClient.class.getResource("/bg/grey_dot.png")));
- MesClient.setMenuStatus("定时任务已关闭", -1);
- }
-
- // 重新创建时间打印任务,确保其与定时任务开关状态同步
- createTimePrintTask();
-
- // 当定时任务开启时,为所有工位重新创建读码定时任务
- if (scheduledTasksEnabled) {
- for (Map.Entry<String, JTextField> entry : oprnoTextFieldMap.entrySet()) {
- String oprnoCode = entry.getKey();
- JTextField textField = entry.getValue();
- createScheduledTask(oprnoCode, textField);
- }
- }
- }
- });
- mesMenu.add(taskToggleMenuItem);
- 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);
- //重连mes
- nettyClient.future.channel().close();
- }
- });
- 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服务器");
- if(tcp_connect_flag) {
- status_menu.setText("已连接MES服务器");
- status_menu.setForeground(Color.GREEN);
- }else {
- status_menu.setText("未连接MES服务器");
- status_menu.setForeground(Color.DARK_GRAY);
- }
- 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 space_4 = new JLabel(" ");
- toolBar.add(space_4);
- tabbedPane = new JTabbedPane(JTabbedPane.TOP);
- tabbedPane.setMinimumSize(new Dimension(400, 50));
- tabbedPane.setFont(new Font("宋体", Font.BOLD, 22));
- contentPane.add(tabbedPane);
- //首页
- 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);
- product_sn.setVisible(false); // 隐藏工件码输入框
- 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);
- f_scan_data_bt_1.setVisible(false); // 隐藏扫码按钮
- 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, 170, 810, 70);
- fxlabel.setForeground(Color.RED);
- fxlabel.setHorizontalAlignment(SwingConstants.CENTER);
- fxlabel.setVisible(false);
- indexPanelA.add(fxlabel);
- generateOprnoTextFields(indexPanelA);
-
- // 创建时间打印定时任务
- createTimePrintTask();
- 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){
- String sn = getBarcode(product_sn.getText());
- if(sn.isEmpty()){
- MesClient.setMenuStatus("工件码为空,请重试",-1);
- return;
- }
- getUser();
- String qret = "OK";
- Boolean sendret = DataUtil.sendQuality(nettyClient,sn,qret,user20);
- if(!sendret){
- MesClient.setMenuStatus("消息发送失败,请重试",-1);
- return;
- }else{
- // MesClient.resetScanA();
- // MesClient.scan_type = 1;
- // MesClient.scanBarcode();
- // MesClient.setMenuStatus("结果提交成功,请扫下一件",0);
- }
- }
- }
- });
- 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, 291, 240, 80);
- finish_ok_bt.setEnabled(false);
- finish_ok_bt.setVisible(false); // 隐藏OK按钮
- 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){
- String sn = getBarcode(product_sn.getText());
- if(sn.isEmpty()){
- MesClient.setMenuStatus("工件码为空,请重试",-1);
- return;
- }
- getUser();
- String qret = "NG";
- Boolean sendret = DataUtil.sendQuality(nettyClient,sn,qret,user20);
- if(!sendret){
- MesClient.setMenuStatus("消息发送失败,请重试",-1);
- return;
- }else{
- // MesClient.resetScanA();
- // MesClient.scan_type = 1;
- // MesClient.scanBarcode();
- // MesClient.setMenuStatus("结果提交成功,请扫下一件",0);
- }
- }
- }
- });
- 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, 291, 240, 80);
- finish_ng_bt.setEnabled(false);
- finish_ng_bt.setVisible(false); // 隐藏NG按钮
- 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();
- searchScrollPaneDj = new JScrollPane(indexPanelC);
- indexPanelC.setLayout(null);
- tabbedPane.addTab("开班点检", new ImageIcon(MesClient.class.getResource("/bg/menu_data_preprocess.png")), searchScrollPaneDj, null);
- indexPanelB = new JPanel();
- searchScrollPane = new JScrollPane(indexPanelB);
- indexPanelB.setLayout(null);
- tabbedPane.addTab("工作记录", new ImageIcon(MesClient.class.getResource("/bg/menu_data_preprocess.png")), searchScrollPane, 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(selectedIndex == 1){
- }
- }
- });
- }
- //页面菜单状态
- 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.get("result")!=null&&retObj.get("result").toString().equalsIgnoreCase("true")) {
- java.util.List<BindMaterialResp> 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.get("result")!=null&&retObj.get("result").toString().equalsIgnoreCase("true")) {
- List<BindMaterialResp> 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("异步任务执行完毕");
- });
- }
- /**
- * 从 Properties 中提取所有工位信息,填充到 oprnoMap(跳过指定属性)
- */
- private static void loadOprnoMap(Properties pro) {
- Enumeration<?> keys = pro.propertyNames();
- while (keys.hasMoreElements()) {
- String key = (String) keys.nextElement();
- Matcher matcher = OPRNO_PATTERN.matcher(key);
- if (matcher.find()) {
- String oprnoCode = matcher.group(1); // 工位号(如 OP090A、HSB)
- String propertyName = matcher.group(2); // 属性名(如 hgA_out、hgA_qr_code)
- // 跳过需要忽略的属性(hgA_qr_code、hgB_qr_code)
- if (isSkipProperty(propertyName)) {
- log.debug("跳过忽略的属性:{}(工位:{})", propertyName, oprnoCode);
- continue;
- }
- String propertyValue = pro.getProperty(key); // 属性值
- // 从 Map 中获取或创建 Oprno 对象
- Oprno oprno = oprnoMap.get(oprnoCode);
- if (oprno == null) {
- oprno = new Oprno();
- oprno.setOprno(oprnoCode);
- oprnoMap.put(oprnoCode, oprno);
- }
- // 反射注入属性值
- setOprnoProperty(oprno, propertyName, propertyValue);
- }
- }
- // log.info("成功加载 {} 个工位配置:{}", oprnoMap.size(), oprnoMap.keySet());
- }
- /**
- * 判断属性是否需要跳过
- */
- private static boolean isSkipProperty(String propertyName) {
- for (String skipProp : SKIP_PROPERTIES) {
- if (skipProp.equals(propertyName)) {
- return true;
- }
- }
- return false;
- }
- /**
- * 反射给 Oprno 对象设置属性值
- */
- private static void setOprnoProperty(Oprno oprno, String propertyName, String propertyValue) {
- try {
- Field field = Oprno.class.getDeclaredField(propertyName);
- field.setAccessible(true);
- field.set(oprno, propertyValue);
- } catch (NoSuchFieldException e) {
- // log.warn("Oprno 类不存在字段:{},该属性值未注入", propertyName);
- } catch (IllegalAccessException e) {
- // log.error("设置 Oprno 属性失败:{}", propertyName, e);
- }
- }
- }
|