MesClient.java 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884
  1. package com.mes.ui;
  2. import com.alibaba.fastjson2.JSONObject;
  3. import com.mes.component.MesRadio;
  4. import com.mes.component.MesWebView;
  5. import com.fazecast.jSerialComm.SerialPort;
  6. import com.mes.component.ProductTypePanel;
  7. import com.mes.util.DateLocalUtils;
  8. import com.mes.util.HttpUtils;
  9. import com.mes.util.JdbcUtils;
  10. import com.mes.util.Op310PlcPoint;
  11. import com.mes.util.PlcService;
  12. import com.mes.util.Ut5310ScpiService;
  13. import com.mes.util.Ut5310TestResult;
  14. import org.slf4j.Logger;
  15. import org.slf4j.LoggerFactory;
  16. import javax.swing.*;
  17. import javax.swing.border.EmptyBorder;
  18. import javax.swing.event.ChangeEvent;
  19. import javax.swing.event.ChangeListener;
  20. import java.awt.*;
  21. import java.awt.event.*;
  22. import java.io.*;
  23. import java.net.InetSocketAddress;
  24. import java.net.Socket;
  25. import java.sql.ResultSet;
  26. import java.sql.Statement;
  27. import java.time.LocalDateTime;
  28. import java.util.List;
  29. import java.util.Properties;
  30. import java.util.Timer;
  31. import java.util.TimerTask;
  32. import java.util.concurrent.ExecutorService;
  33. import java.util.concurrent.Executors;
  34. public class MesClient extends JFrame {
  35. public static final Logger log = LoggerFactory.getLogger(MesClient.class);
  36. public static int mes_auth = 0; // 权限级别 0=无权限 1=操作工人 2=管理员
  37. public static String mes_gw = ""; // 工位号
  38. public static String mes_gw_des = ""; // 工位名称
  39. public static String mes_server_ip = ""; // 服务器IP地址
  40. public static int mes_heart_icon_cycle = 1;
  41. public static boolean mes_ut5310_enable = false;
  42. public static String mes_line_sn = ""; // 产线编号
  43. public static String mes_plc_ip = "192.168.0.3"; // PLC IP地址
  44. public static final int PLC_PHASE_IDLE = 0;
  45. public static final int PLC_PHASE_WAIT_START = 1;
  46. public static final int PLC_PHASE_WAIT_REQUEST = 2;
  47. public static final int PLC_PHASE_WAIT_OPERATOR = 3;
  48. public static final int PLC_PHASE_WAIT_READY = 4;
  49. public static final int PLC_PHASE_WAIT_UT5310 = 5;
  50. //session
  51. public static String sessionid = "";
  52. public static JPanel contentPane;
  53. public static MesClient mesClientFrame;
  54. public static JTabbedPane tabbedPane;
  55. public static JScrollPane indexScrollPaneA;
  56. public static JScrollPane searchScrollPane; // 已弃用,改为使用 WorkRecordPanel
  57. public static JScrollPane searchScrollPaneDj;
  58. //新增字段
  59. public static ProductTypePanel productTypePanel;
  60. public static JLabel productTypeCurrentLabel;
  61. public static final int PRODUCT_SN_LENGTH = 32;
  62. public static final String PREFIX_ZJ = "000020021815-01000016"; //智界
  63. public static final String PREFIX_SJ = "000020022029-01000016"; //尚界
  64. public static final String PRODUCT_TYPE_SWITCH_PASSWORD = "503833";
  65. public static final String PRODUCT_TYPE_ZJ = ProductTypePanel.TYPE_ZJ;
  66. public static final String PRODUCT_TYPE_SJ = ProductTypePanel.TYPE_SJ;
  67. public static Boolean check_quality_result = false;
  68. public static Integer work_status = 0;
  69. public static JButton heart_beat_menu;
  70. public static JButton status_menu;
  71. public static JButton user_menu;
  72. // “软件设置”页签索引(用于判断当前是否切换到该页签)
  73. public static int softwareSettingTabIndex = -1;
  74. // 软件设置页面中的输入控件与操作按钮
  75. private JTextField softwareIpField;
  76. private JTextField softwareOpField;
  77. private JTextField softwareOpNameField;
  78. private static final String APP_CFG_UT5310_PORT = "ut5310_port";
  79. private JComboBox<String> softwarePortCombo;
  80. private JButton softwareEditBtn;
  81. private JButton softwareSaveBtn;
  82. // 记录上一次非“软件设置”页签,用于密码校验失败时回退
  83. private int lastNonSoftwareTabIndex = 0;
  84. // 防止页签回退时触发重复校验导致递归切换
  85. private boolean softwareTabReverting = false;
  86. public static int scan_type = 0;
  87. public static JButton finish_ok_bt;
  88. public static JButton finish_ng_bt;
  89. public static JButton start_bt;
  90. public static JTextField product_sn;
  91. public static JButton f_scan_data_bt_1;
  92. public static String user20 = "";
  93. public static JFrame welcomeWin;
  94. public static JPanel indexPanelB; // 已弃用,改为使用 WorkRecordPanel
  95. public static MesWebView jfxPanel = null;
  96. public static JPanel indexPanelC;
  97. public static MesWebView jfxPanel2 = null;
  98. public static MesRadio mesRadioHj;
  99. public static JTable table;
  100. public static Object[] columnNames = { "物料名称", "绑定批次", "剩余次数", "操作" };
  101. public static Object[][] rowData = null;
  102. public static JLabel fxlabel;
  103. public static JButton plc_status_menu;
  104. public static JLabel remote_mode_menu;
  105. public static Timer plcMonitorTimer;
  106. private static int plcPhase = PLC_PHASE_IDLE;
  107. private static boolean lastRequestResult = false;
  108. private static boolean lastReady = false;
  109. private static boolean lastError = false;
  110. private static int mesBitlifeCounter = 0;
  111. private static final ExecutorService ut5310Executor = Executors.newSingleThreadExecutor();
  112. public static void main(String[] args) {
  113. // if (LockUtil.getInstance().isAppActive() == false){
  114. //// JOptionPane.showMessageDialog(null, "已有一个程序在运行,程序退出");
  115. // return;
  116. // }else{
  117. EventQueue.invokeLater(new Runnable() {
  118. @Override
  119. public void run() {
  120. try{
  121. JdbcUtils.getConn();
  122. //读文件配置
  123. readProperty();
  124. // 显示界面
  125. mesClientFrame = new MesClient();
  126. mesClientFrame.setVisible(false);
  127. welcomeWin = new LoginFarme();
  128. welcomeWin.setVisible(true);
  129. }catch (Exception e){
  130. e.printStackTrace();
  131. }
  132. }
  133. });
  134. }
  135. // }
  136. //读配置文件
  137. private static void readProperty() throws IOException{
  138. String enconding = "UTF-8";
  139. InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
  140. if (is == null) {
  141. mes_gw = "";
  142. mes_line_sn = "";
  143. mes_gw_des = "";
  144. log.info("未找到config/config.properties,工位信息将由登录界面输入");
  145. return;
  146. }
  147. Properties pro = new Properties();
  148. BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding));
  149. pro.load(br);
  150. mes_gw = pro.getProperty("mes.gw");
  151. mes_line_sn = pro.getProperty("mes.line_sn");
  152. String plcIp = pro.getProperty("mes.plc_ip");
  153. mes_ut5310_enable = Boolean.parseBoolean(pro.getProperty("mes.ut5310_enable", "false"));
  154. Ut5310ScpiService.configure(
  155. pro.getProperty("mes.ut5310_port", "COM3"),
  156. getIntProperty(pro, "mes.ut5310_baud_rate", 9600),
  157. getIntProperty(pro, "mes.ut5310_data_bits", 8),
  158. getIntProperty(pro, "mes.ut5310_stop_bits", 1),
  159. pro.getProperty("mes.ut5310_parity", "NONE"),
  160. getIntProperty(pro, "mes.ut5310_read_timeout_ms", 2000),
  161. getIntProperty(pro, "mes.ut5310_test_timeout_ms", 300000),
  162. getIntProperty(pro, "mes.ut5310_fetch_interval_ms", 500),
  163. pro.getProperty("mes.ut5310_protocol", "MODBUS"),
  164. getIntProperty(pro, "mes.ut5310_modbus_slave", 1),
  165. getIntProperty(pro, "mes.ut5310_modbus_max_steps", 4),
  166. Boolean.parseBoolean(pro.getProperty("mes.ut5310_modbus_send_start", "false")),
  167. getIntProperty(pro, "mes.ut5310_modbus_expected_steps", 2));
  168. if (mes_gw == null) {
  169. mes_gw = "";
  170. }
  171. if (mes_line_sn == null) {
  172. mes_line_sn = "";
  173. }
  174. if (plcIp != null && !plcIp.trim().isEmpty()) {
  175. mes_plc_ip = plcIp.trim();
  176. PlcService.setPlcIp(mes_plc_ip);
  177. }
  178. // 页面保存的串口优先于 properties 默认值
  179. String portFromDb = JdbcUtils.getAppConfig(APP_CFG_UT5310_PORT);
  180. if (portFromDb != null && !portFromDb.isEmpty()) {
  181. Ut5310ScpiService.setPortName(portFromDb);
  182. log.info("UT5310 串口使用本地配置: {}", portFromDb);
  183. }
  184. String ipFromDb = JdbcUtils.getServerIpByOp(mes_gw);
  185. if (ipFromDb != null && !ipFromDb.trim().isEmpty()) {
  186. mes_server_ip = ipFromDb.trim();
  187. }
  188. String nameFromDb = JdbcUtils.getOpNameByOp(mes_gw);
  189. if (nameFromDb != null && !nameFromDb.trim().isEmpty()) {
  190. mes_gw_des = nameFromDb.trim();
  191. } else if (!mes_gw.trim().isEmpty() && !mes_line_sn.trim().isEmpty()) {
  192. mes_gw_des = OprnoUtil.getGwDes(mes_line_sn, mes_gw);
  193. } else {
  194. mes_gw_des = "";
  195. }
  196. log.info(mes_gw + ";" + mes_gw_des + ";" + mes_server_ip + ";");
  197. }
  198. private static int getIntProperty(Properties pro, String name, int defaultValue) {
  199. try {
  200. String value = pro.getProperty(name);
  201. if (value == null || value.trim().isEmpty()) {
  202. return defaultValue;
  203. }
  204. return Integer.parseInt(value.trim());
  205. } catch (Exception e) {
  206. return defaultValue;
  207. }
  208. }
  209. public static void applyOpConfig(String op, String opName, String ip) {
  210. if (op != null) {
  211. mes_gw = op.trim();
  212. }
  213. if (opName != null) {
  214. mes_gw_des = opName.trim();
  215. }
  216. if (ip != null) {
  217. mes_server_ip = ip.trim();
  218. }
  219. try {
  220. // 清除旧配置,确保单条记录(本地工位只保留当前配置)
  221. JdbcUtils.clearOpIpConfig();
  222. JdbcUtils.upsertOpIpConfig(mes_gw, mes_gw_des, mes_server_ip);
  223. } catch (Exception e) {
  224. log.info("保存工位配置失败: {}", e.getMessage());
  225. }
  226. if (mesClientFrame != null) {
  227. mesClientFrame.setTitle("MES系统客户端:" + mes_gw + "- " + mes_gw_des);
  228. }
  229. if (welcomeWin != null) {
  230. welcomeWin.setTitle("MES系统客户端:" + mes_gw + " - " + mes_gw_des);
  231. }
  232. }
  233. // 打开并切换到“软件设置”页签(实际访问权限由页签切换监听统一控制)
  234. public static void openSoftwareSettings() {
  235. if (mesClientFrame != null) {
  236. mesClientFrame.setVisible(true);
  237. }
  238. if (tabbedPane != null && softwareSettingTabIndex >= 0 && softwareSettingTabIndex < tabbedPane.getTabCount()) {
  239. tabbedPane.setSelectedIndex(softwareSettingTabIndex);
  240. }
  241. }
  242. public static boolean ensureOpConfig(Component parent) {
  243. // 1) 先尝试从本地SQLite读取一条配置(本地工位一般只会配置一次)
  244. String[] cfg = JdbcUtils.getAnyOpIpConfig();
  245. if (cfg != null && cfg.length >= 3) {
  246. String op = cfg[0];
  247. String opName = cfg[1];
  248. String ip = cfg[2];
  249. if (!ip.isEmpty() && !op.isEmpty()) {
  250. applyOpConfig(op, opName, ip);
  251. }
  252. }
  253. // 2) 如果已有配置则直接放行
  254. boolean missing = (mes_server_ip == null || mes_server_ip.trim().isEmpty())
  255. || (mes_gw == null || mes_gw.trim().isEmpty());
  256. if (!missing) {
  257. return true;
  258. }
  259. // 3) 没有配置才弹窗让用户输入并写入SQLite
  260. return showOpConfigDialog(parent);
  261. }
  262. public static boolean showOpConfigDialog(Component parent) {
  263. String currentOp = mes_gw == null ? "" : mes_gw.trim();
  264. String currentIp = mes_server_ip == null ? "" : mes_server_ip.trim();
  265. String currentName = mes_gw_des == null ? "" : mes_gw_des.trim();
  266. if (!currentOp.isEmpty()) {
  267. if (currentIp.isEmpty()) {
  268. String ipFromDb = JdbcUtils.getServerIpByOp(currentOp);
  269. if (ipFromDb != null && !ipFromDb.trim().isEmpty()) {
  270. currentIp = ipFromDb.trim();
  271. }
  272. }
  273. if (currentName.isEmpty()) {
  274. String nameFromDb = JdbcUtils.getOpNameByOp(currentOp);
  275. if (nameFromDb != null && !nameFromDb.trim().isEmpty()) {
  276. currentName = nameFromDb.trim();
  277. }
  278. }
  279. }
  280. JTextField ipField = new JTextField(currentIp);
  281. JTextField opField = new JTextField(currentOp);
  282. JTextField nameField = new JTextField(currentName);
  283. JPanel panel = new JPanel(new GridLayout(0, 1));
  284. panel.add(new JLabel("服务器IP/域名:"));
  285. panel.add(ipField);
  286. panel.add(new JLabel("工位号:"));
  287. panel.add(opField);
  288. panel.add(new JLabel("工位名称:"));
  289. panel.add(nameField);
  290. while (true) {
  291. int result = JOptionPane.showConfirmDialog(parent, panel, "软件设置", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
  292. if (result != JOptionPane.OK_OPTION) {
  293. return false;
  294. }
  295. String ip = ipField.getText() == null ? "" : ipField.getText().trim();
  296. String op = opField.getText() == null ? "" : opField.getText().trim();
  297. String opName = nameField.getText() == null ? "" : nameField.getText().trim();
  298. if (ip.isEmpty() || op.isEmpty()) {
  299. JOptionPane.showMessageDialog(parent, "服务器IP和工位号不能为空", "提示窗口", JOptionPane.INFORMATION_MESSAGE);
  300. continue;
  301. }
  302. if (opName.isEmpty()) {
  303. opName = OprnoUtil.getGwDes(mes_line_sn, op);
  304. }
  305. if (!testMesServer(ip)) {
  306. JOptionPane.showMessageDialog(parent, "无法连接到MES服务器:" + ip + ":8980", "提示窗口", JOptionPane.INFORMATION_MESSAGE);
  307. continue;
  308. }
  309. applyOpConfig(op, opName, ip);
  310. return true;
  311. }
  312. }
  313. private static void initServerIp() {
  314. String op = mes_gw;
  315. String ip = JdbcUtils.getServerIpByOp(op);
  316. while (true) {
  317. // 1) DB里有IP,先校验连通性(防止历史错误IP导致永远登录不了)
  318. if (ip != null && !ip.trim().isEmpty()) {
  319. ip = ip.trim();
  320. if (testMesServer(ip)) {
  321. break;
  322. }
  323. JOptionPane.showMessageDialog(null,
  324. "当前工位已配置的MES服务器IP/域名无法连接:" + ip + "\n请重新输入正确的IP/域名",
  325. "MES服务器设置",
  326. JOptionPane.WARNING_MESSAGE);
  327. }
  328. // 2) 让用户输入
  329. String input = JOptionPane.showInputDialog(null, "请输入MES服务器IP/域名", "MES服务器设置", JOptionPane.QUESTION_MESSAGE);
  330. if (input == null) {
  331. System.exit(0);
  332. return;
  333. }
  334. input = input.trim();
  335. if (input.isEmpty()) {
  336. continue;
  337. }
  338. // 3) 校验输入可连通,再写库
  339. if (!testMesServer(input)) {
  340. JOptionPane.showMessageDialog(null,
  341. "无法连接到MES服务器:" + input + ":8980\n请检查IP/域名是否正确,或网络是否可达",
  342. "MES服务器设置",
  343. JOptionPane.WARNING_MESSAGE);
  344. continue;
  345. }
  346. boolean ok = JdbcUtils.upsertOpIpConfig(op, mes_gw_des, input);
  347. if (ok) {
  348. ip = input;
  349. break;
  350. } else {
  351. JOptionPane.showMessageDialog(null, "保存失败,请重试", "提示窗口", JOptionPane.INFORMATION_MESSAGE);
  352. }
  353. }
  354. mes_server_ip = ip;
  355. log.info(mes_gw + ";" + mes_gw_des + ";" + mes_server_ip + ";");
  356. }
  357. public static boolean testMesServer(String host) {
  358. if (host == null || host.trim().isEmpty()) {
  359. return false;
  360. }
  361. try (Socket socket = new Socket()) {
  362. socket.connect(new InetSocketAddress(host.trim(), 8980), 2500);
  363. return true;
  364. } catch (Exception e) {
  365. return false;
  366. }
  367. }
  368. //启动心跳包程序
  369. public static java.util.Timer heartBeatTimer;
  370. public static java.util.Timer heartBeatIconTimer;
  371. public static boolean iconREDFlag = true;
  372. public static void startHeartBeatTimer() {
  373. if(heartBeatTimer!=null) {
  374. heartBeatTimer.cancel();
  375. }
  376. //心跳显示图标
  377. if(heartBeatIconTimer!=null) {
  378. heartBeatIconTimer.cancel();
  379. }
  380. heartBeatIconTimer = new Timer();
  381. heartBeatIconTimer.schedule(new TimerTask() {
  382. public void run() {
  383. if(iconREDFlag) {
  384. heart_beat_menu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/grey_dot.png")));
  385. iconREDFlag = false;
  386. }else {
  387. heart_beat_menu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/green_dot.png")));
  388. iconREDFlag = true;
  389. }
  390. heart_beat_menu.setText(DateLocalUtils.getCurrentTime());
  391. heart_beat_menu.repaint();
  392. }
  393. }, 100,mes_heart_icon_cycle*1000);
  394. }
  395. //设置tcp连接状态显示
  396. public static void setTcpStatus() {
  397. status_menu.setText("已连接MES服务器");
  398. heart_beat_menu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/grey_dot.png")));
  399. heart_beat_menu.repaint();
  400. }
  401. public static void initWarehouseData(){
  402. loadProductTypeFromDb(); //新增
  403. resetScanA();
  404. }
  405. public static void resetScanA() {
  406. work_status = 0;
  407. check_quality_result = false;
  408. plcPhase = PLC_PHASE_IDLE;
  409. lastRequestResult = false;
  410. lastReady = false;
  411. PlcService.clearAllMesSignals();
  412. if (MesClient.finish_ok_bt != null) {
  413. MesClient.finish_ok_bt.setEnabled(false);
  414. }
  415. if (MesClient.finish_ng_bt != null) {
  416. MesClient.finish_ng_bt.setEnabled(false);
  417. }
  418. if (MesClient.start_bt != null) {
  419. MesClient.start_bt.setEnabled(false);
  420. }
  421. if (product_sn != null) {
  422. product_sn.setText("");
  423. }
  424. if (MesClient.fxlabel != null) {
  425. MesClient.fxlabel.setVisible(false);
  426. }
  427. if (MesClient.f_scan_data_bt_1 != null) {
  428. MesClient.f_scan_data_bt_1.setEnabled(true);
  429. }
  430. updateProductTypePanelEnabled(true);
  431. MesClient.setMenuStatus("当前生产类型:" + getProductTypeName() + ",请扫工件码",0); //修改
  432. // MesClient.setMenuStatus("开班点检,请先进行OKNG样件测试",-1);
  433. updateMaterailData();
  434. // shiftUserCheck();
  435. }
  436. public static int userLoginHours;//用户登录所处小时
  437. //换班用户信息检查
  438. private static void shiftUserCheck() {
  439. LocalDateTime now = LocalDateTime.now();
  440. // 判断时间范围
  441. if (userLoginHours >= 8 && userLoginHours < 20) {
  442. int hour = now.getHour();
  443. if (hour >= 20 || hour < 8) {
  444. logoff();
  445. }
  446. } else {
  447. int hour = now.getHour();
  448. if (hour >= 8 && hour < 20) {
  449. logoff();
  450. }
  451. }
  452. }
  453. public static void resetScanB() {
  454. }
  455. public static void connectPlc() {
  456. PlcService.setPlcIp(mes_plc_ip);
  457. boolean ok = PlcService.connect();
  458. updatePlcStatus(ok);
  459. if (!ok) {
  460. PlcService.clearAllMesSignals();
  461. }
  462. }
  463. public static void updatePlcStatus(boolean ok) {
  464. if (plc_status_menu == null) {
  465. return;
  466. }
  467. if (ok) {
  468. plc_status_menu.setText("PLC已连接");
  469. plc_status_menu.setForeground(Color.GREEN);
  470. } else {
  471. plc_status_menu.setText("PLC未连接");
  472. plc_status_menu.setForeground(Color.RED);
  473. }
  474. plc_status_menu.repaint();
  475. }
  476. public static void updateRemoteModeStatus(boolean remote) {
  477. if (remote_mode_menu == null) {
  478. return;
  479. }
  480. if (remote) {
  481. remote_mode_menu.setText("远程模式");
  482. remote_mode_menu.setForeground(Color.GREEN);
  483. } else {
  484. remote_mode_menu.setText("本地模式");
  485. remote_mode_menu.setForeground(Color.ORANGE);
  486. }
  487. remote_mode_menu.repaint();
  488. }
  489. private static void updateStartButtonEnabled(boolean remote, boolean ready) {
  490. if (start_bt == null || plcPhase != PLC_PHASE_WAIT_START || !check_quality_result) {
  491. return;
  492. }
  493. start_bt.setEnabled(remote && ready);
  494. }
  495. public static void startWork() {
  496. if (plcPhase != PLC_PHASE_WAIT_START || !check_quality_result) {
  497. setMenuStatus("当前状态不允许启动", -1);
  498. return;
  499. }
  500. String sn = product_sn.getText().trim();
  501. if (sn.isEmpty()) {
  502. setMenuStatus("工件码为空,请重试", -1);
  503. return;
  504. }
  505. if (!PlcService.ensureConnected()) {
  506. setMenuStatus("PLC未连接,请检查网络", -1);
  507. updatePlcStatus(false);
  508. return;
  509. }
  510. updatePlcStatus(true);
  511. byte[] plcData = PlcService.readSignalBlock();
  512. if (!Op310PlcPoint.isRemote(plcData)) {
  513. setMenuStatus("设备处于本地模式,MES无法控制", -1);
  514. updateRemoteModeStatus(false);
  515. updateStartButtonEnabled(false, Op310PlcPoint.isReady(plcData));
  516. return;
  517. }
  518. if (!Op310PlcPoint.isReady(plcData)) {
  519. setMenuStatus("设备未Ready,请等待", -1);
  520. updateStartButtonEnabled(true, false);
  521. return;
  522. }
  523. if (!PlcService.setStart(true)) {
  524. setMenuStatus("发送启动信号失败", -1);
  525. return;
  526. }
  527. plcPhase = PLC_PHASE_WAIT_REQUEST;
  528. lastRequestResult = Op310PlcPoint.isRequestResult(plcData);
  529. lastReady = Op310PlcPoint.isReady(plcData);
  530. start_bt.setEnabled(false);
  531. setMenuStatus("已发送启动信号,等待设备加工", 0);
  532. }
  533. public static void startPlcMonitorTimer() {
  534. if (plcMonitorTimer != null) {
  535. plcMonitorTimer.cancel();
  536. }
  537. connectPlc();
  538. plcMonitorTimer = new Timer();
  539. plcMonitorTimer.schedule(new TimerTask() {
  540. @Override
  541. public void run() {
  542. pollPlcSignals();
  543. }
  544. }, 500, 300);
  545. }
  546. private static void pollPlcSignals() {
  547. try {
  548. if (!PlcService.ensureConnected()) {
  549. SwingUtilities.invokeLater(() -> updatePlcStatus(false));
  550. return;
  551. }
  552. SwingUtilities.invokeLater(() -> updatePlcStatus(true));
  553. mesBitlifeCounter++;
  554. if (mesBitlifeCounter >= 3) {
  555. mesBitlifeCounter = 0;
  556. PlcService.toggleMesBitlife();
  557. }
  558. byte[] data = PlcService.readSignalBlock();
  559. boolean remote = Op310PlcPoint.isRemote(data);
  560. boolean ready = Op310PlcPoint.isReady(data);
  561. boolean error = Op310PlcPoint.isError(data);
  562. boolean requestResult = Op310PlcPoint.isRequestResult(data);
  563. SwingUtilities.invokeLater(() -> updateRemoteModeStatus(remote));
  564. if (error && !lastError) {
  565. PlcService.pulseErrorReset();
  566. SwingUtilities.invokeLater(() -> setMenuStatus("设备报警,请检查", -1));
  567. }
  568. lastError = error;
  569. if (plcPhase == PLC_PHASE_WAIT_START && check_quality_result) {
  570. if (ready && !lastReady && remote) {
  571. SwingUtilities.invokeLater(() -> setMenuStatus("设备已Ready,请点击启动", 0));
  572. }
  573. SwingUtilities.invokeLater(() -> updateStartButtonEnabled(remote, ready));
  574. }
  575. if (work_status != 1) {
  576. lastRequestResult = requestResult;
  577. lastReady = ready;
  578. return;
  579. }
  580. if (plcPhase == PLC_PHASE_WAIT_START) {
  581. lastRequestResult = requestResult;
  582. lastReady = ready;
  583. return;
  584. }
  585. if (plcPhase == PLC_PHASE_WAIT_REQUEST) {
  586. if (requestResult && !lastRequestResult) {
  587. PlcService.setStart(false);
  588. if (mes_ut5310_enable) {
  589. plcPhase = PLC_PHASE_WAIT_UT5310;
  590. String sn = product_sn == null ? "" : product_sn.getText().trim();
  591. SwingUtilities.invokeLater(() -> {
  592. finish_ok_bt.setEnabled(false);
  593. finish_ng_bt.setEnabled(false);
  594. setMenuStatus("工装到位,开始绝缘耐压测试", 0);
  595. });
  596. startUt5310TestAsync(sn);
  597. } else {
  598. plcPhase = PLC_PHASE_WAIT_OPERATOR;
  599. SwingUtilities.invokeLater(() -> {
  600. finish_ok_bt.setEnabled(true);
  601. finish_ng_bt.setEnabled(true);
  602. setMenuStatus("设备加工完成,请确认OK/NG", 0);
  603. });
  604. }
  605. }
  606. } else if (plcPhase == PLC_PHASE_WAIT_READY) {
  607. if (ready && !lastReady) {
  608. PlcService.clearTestResult();
  609. SwingUtilities.invokeLater(() -> {
  610. resetScanA();
  611. setMenuStatus("结果提交成功,请扫下一件", 0);
  612. scan_type = 1;
  613. scanBarcode();
  614. });
  615. }
  616. }
  617. lastRequestResult = requestResult;
  618. lastReady = ready;
  619. } catch (Exception e) {
  620. log.info("PLC轮询异常: {}", e.getMessage());
  621. PlcService.disconnect();
  622. SwingUtilities.invokeLater(() -> updatePlcStatus(false));
  623. }
  624. }
  625. private static void startUt5310TestAsync(String sn) {
  626. ut5310Executor.submit(() -> {
  627. if (sn == null || sn.trim().isEmpty()) {
  628. submitUt5310Result("", new Ut5310TestResult(false, "ERROR", "empty sn"));
  629. return;
  630. }
  631. try {
  632. SwingUtilities.invokeLater(() -> setMenuStatus("绝缘耐压测试中...", 0));
  633. Ut5310TestResult result = Ut5310ScpiService.startAndFetchResult();
  634. submitUt5310Result(sn, result);
  635. } catch (Exception e) {
  636. log.info("UT5310测试异常: {}", e.getMessage());
  637. submitUt5310Result(sn, new Ut5310TestResult(false, "ERROR", e.getMessage()));
  638. }
  639. });
  640. }
  641. private static boolean submitUt5310Result(String sn, Ut5310TestResult testResult) {
  642. if (plcPhase != PLC_PHASE_WAIT_UT5310) {
  643. SwingUtilities.invokeLater(() -> setMenuStatus("当前状态不允许提交绝缘耐压结果", -1));
  644. return false;
  645. }
  646. if (testResult != null && "ERROR".equalsIgnoreCase(testResult.getJudge())) {
  647. plcPhase = PLC_PHASE_WAIT_REQUEST;
  648. SwingUtilities.invokeLater(() -> {
  649. setMenuStatus("UT5310通信失败: " + testResult.getRawResponse(), -1);
  650. finish_ok_bt.setEnabled(true);
  651. finish_ng_bt.setEnabled(true);
  652. });
  653. return false;
  654. }
  655. if (testResult != null && "STOP".equalsIgnoreCase(testResult.getJudge())) {
  656. plcPhase = PLC_PHASE_WAIT_REQUEST;
  657. SwingUtilities.invokeLater(() -> setMenuStatus("UT5310测试被停止", -1));
  658. return false;
  659. }
  660. if (!PlcService.ensureConnected()) {
  661. SwingUtilities.invokeLater(() -> {
  662. setMenuStatus("PLC未连接,请检查网络", -1);
  663. updatePlcStatus(false);
  664. });
  665. return false;
  666. }
  667. SwingUtilities.invokeLater(() -> updatePlcStatus(true));
  668. boolean isOk = testResult != null && testResult.isOk();
  669. String mesResult = isOk ? "OK" : "NG";
  670. boolean plcWriteOk = isOk ? PlcService.setTestOk(true) : PlcService.setTestNg(true);
  671. if (!plcWriteOk) {
  672. SwingUtilities.invokeLater(() -> setMenuStatus("写入PLC绝缘耐压结果失败", -1));
  673. return false;
  674. }
  675. if (testResult != null) {
  676. testResult.printToConsole();
  677. }
  678. System.out.println("[UT5310] 准备上传 MES: sn=" + sn + ", mesResult=" + mesResult
  679. + ", deviceResult=" + (testResult == null ? "" : testResult.getJudge()));
  680. JSONObject insObj = DataUtil.uploadInsulation2(sn, user20, testResult);
  681. if (insObj == null || insObj.get("result") == null
  682. || !insObj.get("result").toString().equalsIgnoreCase("true")) {
  683. if (isOk) {
  684. PlcService.setTestOk(false);
  685. } else {
  686. PlcService.setTestNg(false);
  687. }
  688. String msg = insObj != null && insObj.get("message") != null
  689. ? insObj.getString("message") : "绝缘耐压明细上传失败,请重试";
  690. SwingUtilities.invokeLater(() -> setMenuStatus(msg, -1));
  691. return false;
  692. }
  693. JSONObject retObj = DataUtil.sendQuality(sn, mesResult, user20,
  694. testResult == null ? "" : testResult.getJudge(),
  695. testResult == null ? "" : testResult.getRawResponse());
  696. if (retObj == null) {
  697. if (isOk) {
  698. PlcService.setTestOk(false);
  699. } else {
  700. PlcService.setTestNg(false);
  701. }
  702. SwingUtilities.invokeLater(() -> setMenuStatus("绝缘耐压结果上传失败,请重试", -1));
  703. return false;
  704. }
  705. if (retObj.get("result") != null && retObj.get("result").toString().equalsIgnoreCase("true")) {
  706. plcPhase = PLC_PHASE_WAIT_READY;
  707. SwingUtilities.invokeLater(() -> {
  708. finish_ok_bt.setEnabled(false);
  709. finish_ng_bt.setEnabled(false);
  710. setMenuStatus("绝缘耐压结果已提交,等待设备复位...", 0);
  711. });
  712. return true;
  713. }
  714. if (isOk) {
  715. PlcService.setTestOk(false);
  716. } else {
  717. PlcService.setTestNg(false);
  718. }
  719. SwingUtilities.invokeLater(() -> {
  720. if (retObj.get("result") == null) {
  721. setMenuStatus("绝缘耐压结果上传失败,请重试", -1);
  722. } else if (retObj.get("result").toString().equalsIgnoreCase("false")) {
  723. setMenuStatus(retObj.getString("message"), -1);
  724. }
  725. });
  726. return false;
  727. }
  728. private static boolean submitPlcResult(String sn, String result, boolean isOk) {
  729. if (plcPhase != PLC_PHASE_WAIT_OPERATOR) {
  730. setMenuStatus("当前状态不允许提交结果", -1);
  731. return false;
  732. }
  733. if (!PlcService.ensureConnected()) {
  734. setMenuStatus("PLC未连接,请检查网络", -1);
  735. updatePlcStatus(false);
  736. return false;
  737. }
  738. updatePlcStatus(true);
  739. boolean plcWriteOk = isOk ? PlcService.setTestOk(true) : PlcService.setTestNg(true);
  740. if (!plcWriteOk) {
  741. setMenuStatus("写入PLC结果信号失败", -1);
  742. return false;
  743. }
  744. JSONObject retObj = DataUtil.sendQuality(sn, result, user20);
  745. if (retObj == null) {
  746. if (isOk) {
  747. PlcService.setTestOk(false);
  748. } else {
  749. PlcService.setTestNg(false);
  750. }
  751. setMenuStatus("请求失败,请重试", -1);
  752. return false;
  753. }
  754. if (retObj.get("result") != null && retObj.get("result").toString().equalsIgnoreCase("true")) {
  755. plcPhase = PLC_PHASE_WAIT_READY;
  756. finish_ok_bt.setEnabled(false);
  757. finish_ng_bt.setEnabled(false);
  758. setMenuStatus("结果已提交,等待设备复位...", 0);
  759. return true;
  760. }
  761. if (isOk) {
  762. PlcService.setTestOk(false);
  763. } else {
  764. PlcService.setTestNg(false);
  765. }
  766. if (retObj.get("result") == null) {
  767. setMenuStatus("请求失败,请重试", -1);
  768. } else if (retObj.get("result").toString().equalsIgnoreCase("false")) {
  769. setMenuStatus(retObj.getString("message"), -1);
  770. }
  771. return false;
  772. }
  773. //获取用户20位
  774. public static void getUser() {
  775. user20 = user_menu.getText().toString();
  776. // String space_tmp1 = "";
  777. // if(user20.length()<20) {
  778. // for(int i=0;i<20-user20.length();i++) {
  779. // space_tmp1 = space_tmp1 + " ";
  780. // }
  781. // }
  782. // user20 = user20 + space_tmp1;
  783. }
  784. //获取barcode内容36位
  785. public static String getBarcode(String barcodeTmp) {
  786. String barcodeRet = barcodeTmp;
  787. if(barcodeTmp.equalsIgnoreCase("")) {
  788. return "";
  789. }else {
  790. if(barcodeTmp.length()<36) {
  791. String space = "";
  792. for(int i=0;i<36-barcodeTmp.length();i++) {
  793. space = space + " ";
  794. }
  795. barcodeRet = barcodeTmp + space;
  796. }
  797. }
  798. return barcodeRet;
  799. }
  800. public static void scanBarcode() {
  801. if(work_status == 1){
  802. JOptionPane.showMessageDialog(mesClientFrame,"工作中,勿扫码","提示窗口", JOptionPane.INFORMATION_MESSAGE);
  803. return;
  804. }
  805. String scanBarcodeTitle = "";
  806. switch(scan_type) {
  807. case 1:
  808. product_sn.setText("");
  809. scanBarcodeTitle = "请扫工件码";
  810. break;
  811. }
  812. //弹窗扫工件码
  813. String scanBarcode = JOptionPane.showInputDialog(null, scanBarcodeTitle);
  814. if(scanBarcode!=null&&!scanBarcode.equalsIgnoreCase("")) {
  815. scanBarcode = scanBarcode.trim(); //生产类型新增
  816. //获取用户
  817. getUser();
  818. //获取扫码内容36位
  819. String barcode36 = getBarcode(scanBarcode);//处理36为码
  820. //工位号
  821. String gw = "";
  822. switch(scan_type) {
  823. case 1:
  824. product_sn.setText(scanBarcode);
  825. break;
  826. }
  827. //刷新界面
  828. mesClientFrame.repaint();
  829. //生产类型新增
  830. String validateMsg = validateProductSnMessage(scanBarcode);
  831. if (validateMsg != null) {
  832. check_quality_result = false;
  833. work_status = 0;
  834. MesClient.finish_ok_bt.setEnabled(false);
  835. MesClient.finish_ng_bt.setEnabled(false);
  836. MesClient.f_scan_data_bt_1.setEnabled(true);
  837. updateProductTypePanelEnabled(true);
  838. MesClient.setMenuStatus(validateMsg, -1);
  839. return;
  840. }
  841. updateProductTypePanelEnabled(false);
  842. // 查询工件质量
  843. JSONObject retObj = DataUtil.checkQuality(scanBarcode,user20);
  844. if(retObj == null){
  845. MesClient.check_quality_result = false;
  846. MesClient.work_status = 0;
  847. MesClient.setMenuStatus("请求失败,请重试",-1);
  848. return;
  849. }
  850. if(retObj.get("result")!=null&&retObj.get("result").toString().equalsIgnoreCase("true")) {
  851. if (!PlcService.ensureConnected()) {
  852. MesClient.check_quality_result = false;
  853. MesClient.work_status = 0;
  854. MesClient.setMenuStatus("PLC未连接,请检查网络", -1);
  855. updatePlcStatus(false);
  856. return;
  857. }
  858. updatePlcStatus(true);
  859. byte[] plcData = PlcService.readSignalBlock();
  860. if (!Op310PlcPoint.isRemote(plcData)) {
  861. MesClient.check_quality_result = false;
  862. MesClient.work_status = 0;
  863. MesClient.setMenuStatus("设备处于本地模式,MES无法控制", -1);
  864. updateRemoteModeStatus(false);
  865. return;
  866. }
  867. MesClient.status_menu.setForeground(Color.GREEN);
  868. MesClient.check_quality_result = true;
  869. MesClient.work_status = 1;
  870. plcPhase = PLC_PHASE_WAIT_START;
  871. lastRequestResult = Op310PlcPoint.isRequestResult(plcData);
  872. lastReady = Op310PlcPoint.isReady(plcData);
  873. MesClient.f_scan_data_bt_1.setEnabled(false);
  874. MesClient.finish_ok_bt.setEnabled(false);
  875. MesClient.finish_ng_bt.setEnabled(false);
  876. updateStartButtonEnabled(Op310PlcPoint.isRemote(plcData), Op310PlcPoint.isReady(plcData));
  877. if (Op310PlcPoint.isReady(plcData)) {
  878. MesClient.setMenuStatus("质量合格,设备已Ready,请点击启动", 0);
  879. } else {
  880. MesClient.setMenuStatus("质量合格,等待设备Ready后点击启动", 0);
  881. }
  882. }else{
  883. MesClient.check_quality_result = false;
  884. MesClient.work_status = 0;
  885. if(retObj.get("result")==null){
  886. MesClient.setMenuStatus("请求失败,请重试",-1);
  887. }else{
  888. if(retObj.get("result").toString().equalsIgnoreCase("false")){
  889. MesClient.setMenuStatus(retObj.getString("message"),-1);
  890. }
  891. }
  892. }
  893. }else {
  894. MesClient.setMenuStatus("请扫工件码,请重试",-1);
  895. // JOptionPane.showMessageDialog(mesClientFrame,"请扫工件码","提示窗口", JOptionPane.INFORMATION_MESSAGE);
  896. return;
  897. }
  898. }
  899. public static void logoff() {
  900. welcomeWin.setVisible(true);
  901. mesClientFrame.setVisible(false);
  902. }
  903. public MesClient() {
  904. setIconImage(Toolkit.getDefaultToolkit().getImage(MesClient.class.getResource("/bg/logo.png")));
  905. setTitle("MES系统客户端:"+mes_gw + "- " + mes_gw_des);
  906. // setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  907. setBounds(0, 0, 1024, 768);
  908. setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
  909. // 添加窗口监听器
  910. addWindowListener(new WindowAdapter() {
  911. @Override
  912. public void windowClosing(WindowEvent e) {
  913. int choice = JOptionPane.showConfirmDialog(null, "确定要关闭窗口吗?", "关闭确认", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
  914. if (choice == JOptionPane.YES_OPTION) {
  915. // 如果用户点击“是”,则关闭窗口
  916. dispose(); // 释放窗口资源并关闭窗口
  917. System.exit(0);
  918. }
  919. }
  920. });
  921. JMenuBar menuBar = new JMenuBar();
  922. menuBar.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 26));
  923. setJMenuBar(menuBar);
  924. JMenu fileMenu = new JMenu("用户");
  925. fileMenu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/user.png")));
  926. fileMenu.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  927. menuBar.add(fileMenu);
  928. JMenuItem exitMenuItem = new JMenuItem("退出");
  929. exitMenuItem.setIcon(new ImageIcon(MesClient.class.getResource("/bg/logoff.png")));
  930. exitMenuItem.setFont(new Font("微软雅黑", Font.PLAIN, 22));
  931. fileMenu.add(exitMenuItem);
  932. exitMenuItem.addMouseListener(new MouseAdapter() {
  933. @Override
  934. public void mousePressed(MouseEvent e) {//只能检测到mousePressed事件
  935. super.mouseClicked(e);
  936. //dispose();
  937. logoff();
  938. }
  939. });
  940. JMenu settingMenu = new JMenu("设置");
  941. //settingMenu.setVisible(false);
  942. settingMenu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/menu_setting.png")));
  943. settingMenu.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  944. menuBar.add(settingMenu);
  945. JMenuItem resetTcpMenu = new JMenuItem("\u91CD\u8FDEMES");
  946. resetTcpMenu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/reset_logo.png")));
  947. resetTcpMenu.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  948. resetTcpMenu.addMouseListener(new MouseAdapter() {
  949. @Override
  950. public void mousePressed(MouseEvent e) {
  951. super.mouseClicked(e);
  952. }
  953. });
  954. // settingMenu.add(resetTcpMenu);
  955. JMenuItem resetTcpMenu_1 = new JMenuItem("刷新工件");
  956. resetTcpMenu_1.setIcon(new ImageIcon(MesClient.class.getResource("/bg/reset_logo.png")));
  957. resetTcpMenu_1.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  958. resetTcpMenu_1.addMouseListener(new MouseAdapter() {
  959. @Override
  960. public void mousePressed(MouseEvent e) {
  961. super.mouseClicked(e);
  962. resetScanA();
  963. }
  964. });
  965. settingMenu.add(resetTcpMenu_1);
  966. contentPane = new JPanel();
  967. contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  968. setContentPane(contentPane);
  969. contentPane.setLayout(new BorderLayout(0, 0));
  970. JToolBar toolBar = new JToolBar();
  971. contentPane.add(toolBar, BorderLayout.NORTH);
  972. JLabel equipment_statu_label = new JLabel("状态:");
  973. equipment_statu_label.setHorizontalAlignment(SwingConstants.CENTER);
  974. equipment_statu_label.setForeground(Color.BLACK);
  975. equipment_statu_label.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  976. equipment_statu_label.setBackground(Color.LIGHT_GRAY);
  977. toolBar.add(equipment_statu_label);
  978. status_menu = new JButton("设备未连接MES服务器");
  979. status_menu.setText("已连接MES服务器");
  980. status_menu.setForeground(Color.GREEN);
  981. status_menu.addActionListener(new ActionListener() {
  982. public void actionPerformed(ActionEvent e) {
  983. }
  984. });
  985. status_menu.setForeground(Color.GREEN);
  986. status_menu.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  987. status_menu.setBackground(Color.BLACK);
  988. toolBar.add(status_menu);
  989. JLabel space_1 = new JLabel(" ");
  990. toolBar.add(space_1);
  991. JLabel heart_beat_status_label = new JLabel("心跳:");
  992. heart_beat_status_label.setHorizontalAlignment(SwingConstants.CENTER);
  993. heart_beat_status_label.setForeground(Color.BLACK);
  994. heart_beat_status_label.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  995. heart_beat_status_label.setBackground(Color.LIGHT_GRAY);
  996. toolBar.add(heart_beat_status_label);
  997. heart_beat_menu = new JButton("2024-02-20 23:20:10");
  998. heart_beat_menu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/green_dot.png")));
  999. heart_beat_menu.setForeground(Color.GREEN);
  1000. heart_beat_menu.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  1001. heart_beat_menu.setBackground(Color.BLACK);
  1002. toolBar.add(heart_beat_menu);
  1003. JLabel space_2 = new JLabel(" ");
  1004. toolBar.add(space_2);
  1005. JLabel user_status_label = new JLabel("登录用户:");
  1006. user_status_label.setHorizontalAlignment(SwingConstants.CENTER);
  1007. user_status_label.setForeground(Color.BLACK);
  1008. user_status_label.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  1009. user_status_label.setBackground(Color.LIGHT_GRAY);
  1010. toolBar.add(user_status_label);
  1011. user_menu = new JButton("JinJuShi");
  1012. user_menu.setForeground(Color.GREEN);
  1013. user_menu.setFont(new Font("微软雅黑", Font.PLAIN, 22));
  1014. user_menu.setBackground(Color.BLACK);
  1015. toolBar.add(user_menu);
  1016. JLabel space_3 = new JLabel(" ");
  1017. toolBar.add(space_3);
  1018. JLabel plc_status_label = new JLabel("PLC:");
  1019. plc_status_label.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  1020. toolBar.add(plc_status_label);
  1021. plc_status_menu = new JButton("PLC未连接");
  1022. plc_status_menu.setForeground(Color.RED);
  1023. plc_status_menu.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  1024. plc_status_menu.addActionListener(e -> connectPlc());
  1025. toolBar.add(plc_status_menu);
  1026. tabbedPane = new JTabbedPane(JTabbedPane.TOP);
  1027. tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
  1028. tabbedPane.setMinimumSize(new Dimension(400, 50));
  1029. tabbedPane.setFont(new Font("宋体", Font.BOLD, 22));
  1030. contentPane.add(tabbedPane, BorderLayout.CENTER);
  1031. JPanel bottomStatusPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 12, 6));
  1032. bottomStatusPanel.setBorder(new EmptyBorder(0, 5, 4, 12));
  1033. JLabel remoteModeTitle = new JLabel("控制模式:");
  1034. remoteModeTitle.setFont(new Font("微软雅黑", Font.PLAIN, 16));
  1035. remote_mode_menu = new JLabel("未知");
  1036. remote_mode_menu.setFont(new Font("微软雅黑", Font.BOLD, 16));
  1037. remote_mode_menu.setForeground(Color.GRAY);
  1038. bottomStatusPanel.add(remoteModeTitle);
  1039. bottomStatusPanel.add(remote_mode_menu);
  1040. contentPane.add(bottomStatusPanel, BorderLayout.SOUTH);
  1041. //首页
  1042. JPanel indexPanelA = new JPanel();
  1043. indexScrollPaneA = new JScrollPane(indexPanelA);
  1044. indexPanelA.setLayout(null);
  1045. product_sn = new JTextField();
  1046. product_sn.setHorizontalAlignment(SwingConstants.CENTER);
  1047. product_sn.setEditable(false);
  1048. product_sn.setFont(new Font("微软雅黑", Font.PLAIN, 28));
  1049. product_sn.setBounds(81, 70, 602, 70);
  1050. indexPanelA.add(product_sn);
  1051. product_sn.setColumns(10);
  1052. f_scan_data_bt_1 = new JButton("扫码");
  1053. f_scan_data_bt_1.addActionListener(new ActionListener() {
  1054. public void actionPerformed(ActionEvent e) {
  1055. scan_type = 1;
  1056. scanBarcode();
  1057. }
  1058. });
  1059. f_scan_data_bt_1.setIcon(new ImageIcon(MesClient.class.getResource("/bg/scan_barcode.png")));
  1060. f_scan_data_bt_1.setFont(new Font("微软雅黑", Font.PLAIN, 32));
  1061. f_scan_data_bt_1.setBounds(693, 70, 198, 70);
  1062. indexPanelA.add(f_scan_data_bt_1);
  1063. // String[] hjtitles = new String[]{"焊机1","焊机2","焊机3"};
  1064. // String[] hjvals = new String[]{"HJ001","HJ002","HJ003"};
  1065. // mesRadioHj = new MesRadio(hjtitles,hjvals);
  1066. // mesRadioHj.setSize(500,50);
  1067. // mesRadioHj.setBounds(190,170,500,50);
  1068. // indexPanelA.add(mesRadioHj);
  1069. fxlabel = new JLabel("该工件为返修件,请仔细检查");
  1070. fxlabel.setFont(new Font("微软雅黑", Font.PLAIN, 38));
  1071. fxlabel.setBounds(81, 330, 810, 70);
  1072. fxlabel.setForeground(Color.RED);
  1073. fxlabel.setHorizontalAlignment(SwingConstants.CENTER);
  1074. fxlabel.setVisible(false);
  1075. indexPanelA.add(fxlabel);
  1076. start_bt = new JButton("启动");
  1077. start_bt.setEnabled(false);
  1078. start_bt.addActionListener(new ActionListener() {
  1079. public void actionPerformed(ActionEvent e) {
  1080. startWork();
  1081. }
  1082. });
  1083. start_bt.setFont(new Font("微软雅黑", Font.PLAIN, 32));
  1084. start_bt.setBounds(347, 180, 280, 70);
  1085. indexPanelA.add(start_bt);
  1086. finish_ok_bt = new JButton("OK");
  1087. finish_ok_bt.setEnabled(false);
  1088. finish_ok_bt.addActionListener(new ActionListener() {
  1089. public void actionPerformed(ActionEvent e) {
  1090. if(work_status == 1 && check_quality_result){
  1091. getUser();
  1092. String sn = MesClient.product_sn.getText().trim();
  1093. if(sn.isEmpty()){
  1094. MesClient.setMenuStatus("工件码为空,请重试",-1);
  1095. return;
  1096. }
  1097. //生产类型新增
  1098. String validateMsg = validateProductSnMessage(sn);
  1099. if (validateMsg != null) {
  1100. MesClient.setMenuStatus(validateMsg, -1);
  1101. return;
  1102. }
  1103. submitPlcResult(sn, "OK", true);
  1104. }
  1105. }
  1106. });
  1107. finish_ok_bt.setIcon(new ImageIcon(MesClient.class.getResource("/bg/ok_bg.png")));
  1108. finish_ok_bt.setFont(new Font("微软雅黑", Font.PLAIN, 32));
  1109. finish_ok_bt.setBounds(185, 420, 240, 80);
  1110. finish_ok_bt.setEnabled(false);
  1111. indexPanelA.add(finish_ok_bt);
  1112. finish_ng_bt = new JButton("NG");
  1113. finish_ng_bt.setEnabled(false);
  1114. finish_ng_bt.addActionListener(new ActionListener() {
  1115. public void actionPerformed(ActionEvent e) {
  1116. if(work_status == 1 && check_quality_result){
  1117. getUser();
  1118. String sn = MesClient.product_sn.getText().trim();
  1119. if(sn.isEmpty()){
  1120. MesClient.setMenuStatus("工件码为空,请重试",-1);
  1121. return;
  1122. }
  1123. String validateMsg = validateProductSnMessage(sn);
  1124. if (validateMsg != null) {
  1125. MesClient.setMenuStatus(validateMsg, -1);
  1126. return;
  1127. }
  1128. submitPlcResult(sn, "NG", false);
  1129. }
  1130. }
  1131. });
  1132. finish_ng_bt.setIcon(new ImageIcon(MesClient.class.getResource("/bg/ng_bg.png")));
  1133. finish_ng_bt.setFont(new Font("微软雅黑", Font.PLAIN, 32));
  1134. finish_ng_bt.setBounds(508, 420, 240, 80);
  1135. finish_ng_bt.setEnabled(false);
  1136. indexPanelA.add(finish_ng_bt);
  1137. tabbedPane.addTab("工作面板", new ImageIcon(MesClient.class.getResource("/bg/a_side.png")), indexScrollPaneA, null);
  1138. tabbedPane.setEnabledAt(0, true);
  1139. // searchScrollPane = new JScrollPane((Component) null);
  1140. indexPanelC = new JPanel(new BorderLayout());
  1141. //新增的面板
  1142. JPanel indexPanelProductType = new JPanel();
  1143. indexPanelProductType.setLayout(null);
  1144. JScrollPane productTypeScrollPane = new JScrollPane(indexPanelProductType);
  1145. JLabel productTypeTitle = new JLabel("生产类型设置");
  1146. productTypeTitle.setFont(new Font("微软雅黑", Font.BOLD, 28));
  1147. productTypeTitle.setForeground(new Color(64, 64, 64));
  1148. productTypeTitle.setHorizontalAlignment(SwingConstants.CENTER);
  1149. productTypeTitle.setBounds(81, 80, 810, 50);
  1150. indexPanelProductType.add(productTypeTitle);
  1151. JLabel productTypeHint = new JLabel("请选择当前生产的工件类型,切换后将保存到本地并用于扫码校验");
  1152. productTypeHint.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  1153. productTypeHint.setForeground(new Color(140, 140, 140));
  1154. productTypeHint.setHorizontalAlignment(SwingConstants.CENTER);
  1155. productTypeHint.setBounds(81, 140, 810, 40);
  1156. indexPanelProductType.add(productTypeHint);
  1157. productTypePanel = new ProductTypePanel(PRODUCT_TYPE_SWITCH_PASSWORD);
  1158. productTypePanel.setBounds(276, 210, 420, 72);
  1159. productTypePanel.setOnChangeListener(() -> {
  1160. if (work_status == 0) {
  1161. saveProductTypeToDb();
  1162. setMenuStatus("当前生产类型:" + getProductTypeName() + ",请扫工件码", 0);
  1163. }
  1164. refreshProductTypeCurrentLabel();
  1165. });
  1166. indexPanelProductType.add(productTypePanel);
  1167. productTypeCurrentLabel = new JLabel();
  1168. productTypeCurrentLabel.setFont(new Font("微软雅黑", Font.PLAIN, 22));
  1169. productTypeCurrentLabel.setForeground(new Color(64, 64, 64));
  1170. productTypeCurrentLabel.setHorizontalAlignment(SwingConstants.CENTER);
  1171. productTypeCurrentLabel.setBounds(81, 310, 810, 40);
  1172. refreshProductTypeCurrentLabel();
  1173. indexPanelProductType.add(productTypeCurrentLabel);
  1174. tabbedPane.addTab("生产类型", new ImageIcon(MesClient.class.getResource("/bg/menu_setting.png")), productTypeScrollPane, null);
  1175. tabbedPane.addTab("开班点检", new ImageIcon(MesClient.class.getResource("/bg/menu_data_preprocess.png")), indexPanelC, null);
  1176. // ========== 工作记录 Tab(改造:当前工位Tab + 所有工位Tab) ==========
  1177. // 旧代码已注释:
  1178. indexPanelB = new JPanel();
  1179. searchScrollPane = new JScrollPane(indexPanelB);
  1180. indexPanelB.setLayout(null);
  1181. tabbedPane.addTab("工作记录", new ImageIcon(MesClient.class.getResource("/bg/menu_data_preprocess.png")), searchScrollPane, null);
  1182. // 创建“软件设置”页面,并加入主Tab页签
  1183. JPanel softwareSettingPanel = buildSoftwareSettingPanel();
  1184. JScrollPane softwareSettingScrollPane = new JScrollPane(softwareSettingPanel);
  1185. tabbedPane.addTab("软件设置", new ImageIcon(MesClient.class.getResource("/bg/menu_setting.png")), softwareSettingScrollPane, null);
  1186. softwareSettingTabIndex = tabbedPane.getTabCount() - 1;
  1187. // 页面初始化时先从本地配置加载软件设置
  1188. loadSoftwareSettingsFromDb();
  1189. // // 创建工作记录的子 TabbedPane
  1190. // JTabbedPane workRecordTabbedPane = new JTabbedPane(JTabbedPane.TOP);
  1191. // workRecordTabbedPane.setFont(new Font("微软雅黑", Font.PLAIN, 14));
  1192. //
  1193. // // OKNG 工位:当前工位 + 所有工位
  1194. // WorkRecordPanel[] workRecordPanels = new WorkRecordPanel[2];
  1195. //
  1196. // // 当前工位Tab(使用配置文件中的 mes.gw)
  1197. // workRecordPanels[0] = new WorkRecordPanel(mes_gw, mes_line_sn);
  1198. // workRecordTabbedPane.addTab(mes_gw, null, workRecordPanels[0], "查询" + mes_gw + "的工作记录");
  1199. //
  1200. // // 所有工位Tab(查询整条产线所有工位)
  1201. // workRecordPanels[1] = new WorkRecordPanel(null, mes_line_sn);
  1202. // workRecordTabbedPane.addTab("所有工位", null, workRecordPanels[1], "查询整条产线所有工位的工作记录");
  1203. //
  1204. // // 切换子Tab时自动刷新数据
  1205. // workRecordTabbedPane.addChangeListener(e -> {
  1206. // int selectedIndex = workRecordTabbedPane.getSelectedIndex();
  1207. // if (selectedIndex >= 0 && selectedIndex < workRecordPanels.length) {
  1208. // workRecordPanels[selectedIndex].refreshData();
  1209. // }
  1210. // });
  1211. //
  1212. // // 将子 TabbedPane 添加到主 TabbedPane
  1213. // tabbedPane.addTab("工作记录", new ImageIcon(MesClient.class.getResource("/bg/menu_data_preprocess.png")), workRecordTabbedPane, null);
  1214. //
  1215. tabbedPane.addChangeListener(new ChangeListener() {
  1216. @Override
  1217. public void stateChanged(ChangeEvent e) {
  1218. JTabbedPane tabbedPane = (JTabbedPane) e.getSource();
  1219. int selectedIndex = tabbedPane.getSelectedIndex();
  1220. System.out.println("selectedIndex:"+selectedIndex);
  1221. if (softwareTabReverting) {
  1222. return;
  1223. }
  1224. if (selectedIndex == softwareSettingTabIndex) {
  1225. // 每次点击进入“软件设置”页签都进行密码验证(固定密码:mes)
  1226. if (!verifySoftwareSettingPassword()) {
  1227. softwareTabReverting = true;
  1228. tabbedPane.setSelectedIndex(lastNonSoftwareTabIndex);
  1229. softwareTabReverting = false;
  1230. return;
  1231. }
  1232. loadSoftwareSettingsFromDb();
  1233. } else {
  1234. // 只记录非“软件设置”页签,便于校验失败时回退
  1235. lastNonSoftwareTabIndex = selectedIndex;
  1236. }
  1237. }
  1238. });
  1239. }
  1240. private static String validateProductSnMessage(String sn) {
  1241. if (sn == null || sn.isEmpty()) {
  1242. return "工件码为空,请重试";
  1243. }
  1244. if (sn.length() != PRODUCT_SN_LENGTH) {
  1245. return "工件码长度须为32位,当前" + sn.length() + "位";
  1246. }
  1247. String prefix = getProductSnPrefix();
  1248. if (!sn.startsWith(prefix)) {
  1249. return "工件码前缀与当前类型(" + getProductTypeName() + ")不匹配,当前工件码为" + getProductTypeNameBySn(sn);
  1250. }
  1251. return null;
  1252. }
  1253. private static void updateProductTypePanelEnabled(boolean enabled) {
  1254. if (productTypePanel != null) {
  1255. productTypePanel.setEnabled(enabled);
  1256. }
  1257. }
  1258. public static void loadProductTypeFromDb() {
  1259. if (productTypePanel == null) {
  1260. return;
  1261. }
  1262. String savedType = JdbcUtils.getClientConfig(
  1263. JdbcUtils.getProductTypeConfigKey(mes_gw),
  1264. PRODUCT_TYPE_ZJ
  1265. );
  1266. if (PRODUCT_TYPE_SJ.equals(savedType)) {
  1267. productTypePanel.setResult(PRODUCT_TYPE_SJ);
  1268. } else {
  1269. productTypePanel.setResult(PRODUCT_TYPE_ZJ);
  1270. }
  1271. refreshProductTypeCurrentLabel();
  1272. }
  1273. public static void refreshProductTypeCurrentLabel() {
  1274. if (productTypeCurrentLabel != null) {
  1275. productTypeCurrentLabel.setText("当前选择:" + getProductTypeName() + "(前缀 " + getProductSnPrefix() + ")");
  1276. }
  1277. }
  1278. public static void saveProductTypeToDb() {
  1279. if (productTypePanel == null) {
  1280. return;
  1281. }
  1282. JdbcUtils.saveClientConfig(
  1283. JdbcUtils.getProductTypeConfigKey(mes_gw),
  1284. productTypePanel.getResult()
  1285. );
  1286. }
  1287. public static String getProductSnPrefix() {
  1288. if (productTypePanel != null && PRODUCT_TYPE_SJ.equals(productTypePanel.getResult())) {
  1289. return PREFIX_SJ;
  1290. }
  1291. return PREFIX_ZJ;
  1292. }
  1293. public static String getProductTypeName() {
  1294. if (productTypePanel != null) {
  1295. return productTypePanel.getTypeName();
  1296. }
  1297. return "智界";
  1298. }
  1299. private static String getProductTypeNameBySn(String sn) {
  1300. if (sn.startsWith(PREFIX_SJ)) {
  1301. return "尚界";
  1302. }
  1303. if (sn.startsWith(PREFIX_ZJ)) {
  1304. return "智界";
  1305. }
  1306. return "未知";
  1307. }
  1308. // 软件设置页面UI构建(含编辑/保存/重载按钮)
  1309. private JPanel buildSoftwareSettingPanel() {
  1310. JPanel panel = new JPanel();
  1311. panel.setLayout(null);
  1312. JLabel title = new JLabel("软件设置");
  1313. title.setFont(new Font("微软雅黑", Font.BOLD, 26));
  1314. title.setBounds(40, 30, 300, 40);
  1315. panel.add(title);
  1316. JLabel ipLabel = new JLabel("服务器IP/域名:");
  1317. ipLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));
  1318. ipLabel.setBounds(40, 100, 200, 30);
  1319. panel.add(ipLabel);
  1320. softwareIpField = new JTextField("");
  1321. softwareIpField.setFont(new Font("微软雅黑", Font.PLAIN, 18));
  1322. softwareIpField.setBounds(220, 100, 360, 34);
  1323. softwareIpField.setEditable(false);
  1324. panel.add(softwareIpField);
  1325. JLabel opLabel = new JLabel("工位号:");
  1326. opLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));
  1327. opLabel.setBounds(40, 150, 200, 30);
  1328. panel.add(opLabel);
  1329. softwareOpField = new JTextField("");
  1330. softwareOpField.setFont(new Font("微软雅黑", Font.PLAIN, 18));
  1331. softwareOpField.setBounds(220, 150, 360, 34);
  1332. softwareOpField.setEditable(false);
  1333. panel.add(softwareOpField);
  1334. JLabel nameLabel = new JLabel("工位名称:");
  1335. nameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));
  1336. nameLabel.setBounds(40, 200, 200, 30);
  1337. panel.add(nameLabel);
  1338. softwareOpNameField = new JTextField("");
  1339. softwareOpNameField.setFont(new Font("微软雅黑", Font.PLAIN, 18));
  1340. softwareOpNameField.setBounds(220, 200, 360, 34);
  1341. softwareOpNameField.setEditable(false);
  1342. panel.add(softwareOpNameField);
  1343. JLabel portLabel = new JLabel("耐压仪串口:");
  1344. portLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));
  1345. portLabel.setBounds(40, 250, 200, 30);
  1346. panel.add(portLabel);
  1347. softwarePortCombo = new JComboBox<String>();
  1348. softwarePortCombo.setFont(new Font("微软雅黑", Font.PLAIN, 18));
  1349. softwarePortCombo.setBounds(220, 250, 360, 34);
  1350. softwarePortCombo.setEditable(true);
  1351. softwarePortCombo.setEnabled(false);
  1352. refreshSerialPortCombo();
  1353. panel.add(softwarePortCombo);
  1354. softwareEditBtn = new JButton("编辑");
  1355. softwareEditBtn.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  1356. softwareEditBtn.setBounds(220, 320, 140, 44);
  1357. softwareEditBtn.addActionListener(new ActionListener() {
  1358. @Override
  1359. public void actionPerformed(ActionEvent e) {
  1360. // 点击“编辑”后允许修改输入框,并开放保存按钮
  1361. softwareIpField.setEditable(true);
  1362. softwareOpField.setEditable(true);
  1363. softwareOpNameField.setEditable(true);
  1364. refreshSerialPortCombo();
  1365. if (softwarePortCombo != null) {
  1366. softwarePortCombo.setEnabled(true);
  1367. }
  1368. if (softwareSaveBtn != null) {
  1369. softwareSaveBtn.setEnabled(true);
  1370. }
  1371. }
  1372. });
  1373. panel.add(softwareEditBtn);
  1374. softwareSaveBtn = new JButton("保存");
  1375. softwareSaveBtn.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  1376. softwareSaveBtn.setBounds(380, 320, 140, 44);
  1377. softwareSaveBtn.setEnabled(false);
  1378. softwareSaveBtn.addActionListener(new ActionListener() {
  1379. @Override
  1380. public void actionPerformed(ActionEvent e) {
  1381. // 保存前读取并校验输入内容
  1382. String ip = softwareIpField.getText() == null ? "" : softwareIpField.getText().trim();
  1383. String op = softwareOpField.getText() == null ? "" : softwareOpField.getText().trim();
  1384. String opName = softwareOpNameField.getText() == null ? "" : softwareOpNameField.getText().trim();
  1385. String port = getSelectedSerialPort();
  1386. if (ip.isEmpty() || op.isEmpty()) {
  1387. JOptionPane.showMessageDialog(mesClientFrame, "服务器IP和工位号不能为空", "提示窗口", JOptionPane.INFORMATION_MESSAGE);
  1388. return;
  1389. }
  1390. if (port.isEmpty()) {
  1391. JOptionPane.showMessageDialog(mesClientFrame, "耐压仪串口不能为空", "提示窗口", JOptionPane.INFORMATION_MESSAGE);
  1392. return;
  1393. }
  1394. if (opName.isEmpty()) {
  1395. opName = OprnoUtil.getGwDes(mes_line_sn, op);
  1396. }
  1397. if (!testMesServer(ip)) {
  1398. JOptionPane.showMessageDialog(mesClientFrame, "无法连接到MES服务器:" + ip + ":8980", "提示窗口", JOptionPane.INFORMATION_MESSAGE);
  1399. return;
  1400. }
  1401. // 写入本地配置并刷新显示
  1402. applyOpConfig(op, opName, ip);
  1403. applyUt5310PortConfig(port);
  1404. loadSoftwareSettingsFromDb();
  1405. softwareIpField.setEditable(false);
  1406. softwareOpField.setEditable(false);
  1407. softwareOpNameField.setEditable(false);
  1408. if (softwarePortCombo != null) {
  1409. softwarePortCombo.setEnabled(false);
  1410. }
  1411. softwareSaveBtn.setEnabled(false);
  1412. JOptionPane.showMessageDialog(mesClientFrame, "保存成功", "提示窗口", JOptionPane.INFORMATION_MESSAGE);
  1413. }
  1414. });
  1415. panel.add(softwareSaveBtn);
  1416. JButton reloadBtn = new JButton("从本地配置读取");
  1417. reloadBtn.setFont(new Font("微软雅黑", Font.PLAIN, 18));
  1418. reloadBtn.setBounds(540, 320, 200, 44);
  1419. reloadBtn.addActionListener(new ActionListener() {
  1420. @Override
  1421. public void actionPerformed(ActionEvent e) {
  1422. // 从本地数据库读取配置并回填页面
  1423. loadSoftwareSettingsFromDb();
  1424. }
  1425. });
  1426. panel.add(reloadBtn);
  1427. panel.setPreferredSize(new Dimension(990, 550));
  1428. return panel;
  1429. }
  1430. private void refreshSerialPortCombo() {
  1431. if (softwarePortCombo == null) {
  1432. return;
  1433. }
  1434. String current = getSelectedSerialPort();
  1435. if (current.isEmpty()) {
  1436. current = Ut5310ScpiService.getPortName();
  1437. }
  1438. softwarePortCombo.removeAllItems();
  1439. SerialPort[] ports = SerialPort.getCommPorts();
  1440. if (ports != null) {
  1441. for (SerialPort p : ports) {
  1442. if (p != null && p.getSystemPortName() != null) {
  1443. softwarePortCombo.addItem(p.getSystemPortName());
  1444. }
  1445. }
  1446. }
  1447. if (current != null && !current.isEmpty()) {
  1448. boolean found = false;
  1449. for (int i = 0; i < softwarePortCombo.getItemCount(); i++) {
  1450. if (current.equalsIgnoreCase(softwarePortCombo.getItemAt(i))) {
  1451. softwarePortCombo.setSelectedIndex(i);
  1452. found = true;
  1453. break;
  1454. }
  1455. }
  1456. if (!found) {
  1457. softwarePortCombo.addItem(current);
  1458. softwarePortCombo.setSelectedItem(current);
  1459. }
  1460. }
  1461. }
  1462. private String getSelectedSerialPort() {
  1463. if (softwarePortCombo == null) {
  1464. return "";
  1465. }
  1466. Object selected = softwarePortCombo.getEditor().getItem();
  1467. if (selected == null) {
  1468. selected = softwarePortCombo.getSelectedItem();
  1469. }
  1470. return selected == null ? "" : selected.toString().trim();
  1471. }
  1472. private void applyUt5310PortConfig(String port) {
  1473. if (port == null || port.trim().isEmpty()) {
  1474. return;
  1475. }
  1476. String next = port.trim();
  1477. Ut5310ScpiService.setPortName(next);
  1478. JdbcUtils.setAppConfig(APP_CFG_UT5310_PORT, next);
  1479. log.info("保存耐压仪串口配置: {}", next);
  1480. }
  1481. // 读取并回填“软件设置”页面数据
  1482. private void loadSoftwareSettingsFromDb() {
  1483. String[] cfg = JdbcUtils.getAnyOpIpConfig();
  1484. if (cfg != null && cfg.length >= 3) {
  1485. applyOpConfig(cfg[0], cfg[1], cfg[2]);
  1486. softwareOpField.setText(cfg[0]);
  1487. softwareOpNameField.setText(cfg[1]);
  1488. softwareIpField.setText(cfg[2]);
  1489. } else {
  1490. softwareOpField.setText(mes_gw == null ? "" : mes_gw);
  1491. softwareOpNameField.setText(mes_gw_des == null ? "" : mes_gw_des);
  1492. softwareIpField.setText(mes_server_ip == null ? "" : mes_server_ip);
  1493. }
  1494. String portFromDb = JdbcUtils.getAppConfig(APP_CFG_UT5310_PORT);
  1495. if (portFromDb != null && !portFromDb.isEmpty()) {
  1496. Ut5310ScpiService.setPortName(portFromDb);
  1497. }
  1498. refreshSerialPortCombo();
  1499. if (softwareSaveBtn != null) {
  1500. softwareSaveBtn.setEnabled(false);
  1501. }
  1502. if (softwareIpField != null) {
  1503. softwareIpField.setEditable(false);
  1504. }
  1505. if (softwareOpField != null) {
  1506. softwareOpField.setEditable(false);
  1507. }
  1508. if (softwareOpNameField != null) {
  1509. softwareOpNameField.setEditable(false);
  1510. }
  1511. if (softwarePortCombo != null) {
  1512. softwarePortCombo.setEnabled(false);
  1513. }
  1514. }
  1515. // 进入“软件设置”页签前的密码校验(固定密码:mes)
  1516. private boolean verifySoftwareSettingPassword() {
  1517. String input = JOptionPane.showInputDialog(this, "请输入软件设置密码:", "软件设置权限验证", JOptionPane.QUESTION_MESSAGE);
  1518. if (input == null) {
  1519. return false;
  1520. }
  1521. if ("mes".equals(input.trim())) {
  1522. return true;
  1523. }
  1524. JOptionPane.showMessageDialog(this, "密码错误,无法进入软件设置页面", "提示窗口", JOptionPane.WARNING_MESSAGE);
  1525. return false;
  1526. }
  1527. public static void setMenuStatus(String msg,int error){
  1528. if(error == 0){
  1529. MesClient.status_menu.setForeground(Color.GREEN);
  1530. }else{
  1531. MesClient.status_menu.setForeground(Color.RED);
  1532. }
  1533. MesClient.status_menu.setText(msg);
  1534. }
  1535. public static void getMaterailData(){
  1536. try{
  1537. JSONObject retObj = DataUtil.getBindMaterail();
  1538. if(retObj == null){
  1539. return;
  1540. }
  1541. if(retObj.get("result")!=null&&retObj.get("result").toString().equalsIgnoreCase("true")) {
  1542. java.util.List<BindMaterialResp> arrs = retObj.getList("data",BindMaterialResp.class);
  1543. int i = 0;
  1544. rowData = new Object[arrs.size()][7];
  1545. for (BindMaterialResp bindMaterialResp:arrs){
  1546. rowData[i][0] = bindMaterialResp.getMaterialTitle();
  1547. rowData[i][1] = bindMaterialResp.getBatchSn();
  1548. rowData[i][2] = bindMaterialResp.getLastTimes();
  1549. rowData[i][3] = "";
  1550. rowData[i][4] = bindMaterialResp.getCraft();
  1551. rowData[i][5] = bindMaterialResp.getMaterialId();
  1552. rowData[i][6] = bindMaterialResp.getType();
  1553. i++;
  1554. }
  1555. bindBatchPanel();
  1556. }
  1557. }catch (Exception e){
  1558. log.info(e.getMessage());
  1559. }
  1560. }
  1561. public static void updateMaterailData(){
  1562. try{
  1563. JSONObject retObj = DataUtil.getBindMaterail();
  1564. if(retObj == null){
  1565. return;
  1566. }
  1567. if(retObj.get("result")!=null&&retObj.get("result").toString().equalsIgnoreCase("true")) {
  1568. List<BindMaterialResp> arrs = retObj.getList("data",BindMaterialResp.class);
  1569. int i = 0;
  1570. for (BindMaterialResp bindMaterialResp:arrs){
  1571. rowData[i][0] = bindMaterialResp.getMaterialTitle();
  1572. rowData[i][1] = bindMaterialResp.getBatchSn();
  1573. rowData[i][2] = bindMaterialResp.getLastTimes();
  1574. rowData[i][3] = "";
  1575. rowData[i][4] = bindMaterialResp.getCraft();
  1576. rowData[i][5] = bindMaterialResp.getMaterialId();
  1577. rowData[i][6] = bindMaterialResp.getType();
  1578. i++;
  1579. }
  1580. MesClient.table.repaint();
  1581. }
  1582. }catch (Exception e){
  1583. log.info(e.getMessage());
  1584. }
  1585. }
  1586. // 绑定物料批次码
  1587. public static void scanBatchSn(BindMaterialResp bindMaterialResp) {
  1588. //弹窗扫工件码
  1589. String scanBarcodeTitle = "请扫物料:"+bindMaterialResp.getMaterialTitle();
  1590. String scanBarcode = JOptionPane.showInputDialog(null, scanBarcodeTitle);
  1591. if(scanBarcode!=null&&!scanBarcode.equalsIgnoreCase("")) {
  1592. JSONObject retObj = DataUtil.saveBindMaterail(scanBarcode,bindMaterialResp.getCraft(),bindMaterialResp.getMaterialId(),bindMaterialResp.getType());
  1593. if(retObj.get("result")!=null&&retObj.get("result").toString().equalsIgnoreCase("true")) {
  1594. MesClient.setMenuStatus("扫物料:"+bindMaterialResp.getMaterialTitle()+"成功",0);
  1595. updateMaterailData();
  1596. }else{
  1597. if(retObj.get("result")==null){
  1598. MesClient.setMenuStatus("请求失败,请重试",-1);
  1599. }else{
  1600. if(retObj.get("result").toString().equalsIgnoreCase("false")){
  1601. MesClient.setMenuStatus(retObj.getString("message"),-1);
  1602. }
  1603. }
  1604. }
  1605. }
  1606. }
  1607. public static void bindBatchPanel(){
  1608. JPanel indexPanelBB = new JPanel();
  1609. JPanel panel = new JPanel();
  1610. panel.setBounds(0, 0, 990, 550);
  1611. // panel.setBounds(81, 50, 810, 479);
  1612. indexPanelBB.add(panel);
  1613. panel.setLayout(new GridLayout(0, 1, 0, 0));
  1614. table = new JTable(rowData, columnNames){
  1615. public boolean isCellEditable(int row, int column) {
  1616. if(column == 3){
  1617. return true;
  1618. }
  1619. return false;
  1620. }
  1621. };
  1622. table.setRowHeight(40);
  1623. table.setEnabled(true);
  1624. table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
  1625. table.getColumnModel().getColumn(3).setCellRenderer(new TableCellRendererButton());
  1626. table.getColumnModel().getColumn(3).setCellEditor(new TableCellEditorButton());
  1627. JScrollPane scrollPane = new JScrollPane(table);
  1628. panel.add(scrollPane);
  1629. JScrollPane indexScrollPaneB = new JScrollPane(indexPanelBB);
  1630. indexPanelBB.setLayout(null);
  1631. tabbedPane.addTab("绑定物料", new ImageIcon(MesClient.class.getResource("/bg/menu_data_preprocess.png")), indexScrollPaneB, null);
  1632. }
  1633. // 开启发送结果定时任务
  1634. public static void startUpdateQualityTimer(){
  1635. // 创建异步线程池
  1636. ExecutorService executorService = Executors.newSingleThreadExecutor();
  1637. // 提交任务
  1638. executorService.submit(() -> {
  1639. log.info("异步任务执行中...");
  1640. // 模拟耗时操作
  1641. try {
  1642. while (true){
  1643. try {
  1644. // 确保连接已经打开
  1645. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  1646. JdbcUtils.openConnection();
  1647. }
  1648. Statement statement = JdbcUtils.conn.createStatement();
  1649. String selectSql = "SELECT id, bw FROM submit_record\n" +
  1650. "WHERE state = 0 ORDER BY id DESC LIMIT 10";
  1651. String updateSql = "UPDATE submit_record \n" +
  1652. "SET state = '1'\n" +
  1653. "WHERE id = ";
  1654. ResultSet rs = statement.executeQuery(selectSql);
  1655. while(rs.next()){
  1656. int id = rs.getInt("id");
  1657. String bw = rs.getString("bw");
  1658. // 发送请求
  1659. String url = "http://"+MesClient.mes_server_ip+":8980/js/a/mes/mesProductRecord/updateQualityByTiming";
  1660. log.info("质量:"+bw);
  1661. String s = HttpUtils.sendPostRequestJson(url, bw );
  1662. log.info("结果:"+s);
  1663. Boolean result = JSONObject.parseObject(s).getBoolean("result");
  1664. if(result) {
  1665. // 更改状态为 1
  1666. statement.executeUpdate(updateSql + id);
  1667. }
  1668. }
  1669. rs.close();
  1670. statement.close();
  1671. } catch (Exception e) {
  1672. log.info(e.getMessage());
  1673. }
  1674. try {
  1675. Thread.sleep(2000);
  1676. }catch (Exception e){
  1677. log.info(e.getMessage());
  1678. }
  1679. }
  1680. } catch (Exception e) {
  1681. log.info(e.getMessage());
  1682. }
  1683. log.info("异步任务执行完毕");
  1684. });
  1685. }
  1686. }