| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076 |
- package com.mes.ui;
- import com.alibaba.fastjson2.JSONObject;
- import com.mes.config.MesClientProperties;
- import com.mes.entity.DcRunSnapshot;
- import com.mes.service.DcBatchPrinter;
- import com.mes.service.DcLineBatchContext;
- import com.mes.service.DcPlcClient;
- import com.mes.service.DcPrintQueueStore;
- import com.mes.service.DcWorkRecordStore;
- import com.mes.service.MesDcApiClient;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import javax.swing.*;
- import javax.swing.border.EmptyBorder;
- import java.awt.*;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.text.SimpleDateFormat;
- import java.util.Arrays;
- import java.util.Date;
- import java.util.LinkedHashMap;
- import java.util.Map;
- import java.util.concurrent.atomic.AtomicBoolean;
- /**
- * 自动化大冲线体主面板:取批次 → MES允许 → 读 DB260 展示;
- * 结案打印由压机5冲次达标触发(本页不再按 DB260 产量自动结案)。
- */
- public class StationPanel extends JPanel {
- private static final Logger log = LoggerFactory.getLogger(StationPanel.class);
- /** 兜底取批最小间隔(SSE 正常时由门铃触发) */
- private static final long POLL_BATCH_INTERVAL_MS = 2000L;
- /** IDLE 等 PDA;RUN 允许运行盯产量;DONE 结案过渡 */
- public enum Phase {
- IDLE, RUN, DONE
- }
- private final MesClientProperties.StationConfig cfg;
- private final String serverIp;
- private final DcPlcClient plc;
- private final AtomicBoolean busy = new AtomicBoolean(false);
- /** 后台 nextBatch 进行中 */
- private final AtomicBoolean nextBusy = new AtomicBoolean(false);
- private volatile Phase phase = Phase.IDLE;
- private volatile String batchCode = "";
- /** 本件结案工号:优先 nextBatch 带回的入队 userCode */
- private volatile String currentUserCode = "";
- private volatile int targetQty;
- /** 开批时 PLC 实际产量起点;中途复位后会按已产重定 */
- private volatile int baseActualQty;
- /** 本批已产件数(中途产量复位不丢进度) */
- private volatile int producedQty;
- /** 上一拍读到的实际产量,用于发现中途被清零/变小 */
- private volatile int lastActualQty;
- private volatile String batchStartTime = "";
- private volatile long lastPollBatchAtMs;
- /** 最近一次 DB260 快照,结案时一并上传(只传一次,不采样堆) */
- private volatile DcRunSnapshot lastSnap = new DcRunSnapshot();
- /** 结案上传未成功时的待重试报文(DONE 态由 tick 续传,避免热队列卡「已取」) */
- private volatile Map<String, String> pendingCompleteFields;
- /** 挂起结案说明文案(达标/手动/强制) */
- private volatile String pendingHow = "";
- /** 挂起结案对应批次码(续传提示用) */
- private volatile String pendingBatchCode = "";
- /** 挂起结案数量 */
- private volatile int pendingQty;
- /** 异步打印是否已成功送出(仅提示,不挡结案) */
- private volatile boolean pendingPrinted;
- /** 结案上传重试互斥,避免 finish 线程与 tick 同时打 completeBatch */
- private final AtomicBoolean completeRetryBusy = new AtomicBoolean(false);
- private final JLabel lblStation;
- private final JLabel lblStatus;
- private final JTextField txtBatch;
- private final JTextField txtTarget;
- private final JTextField txtCurrentPart;
- private final JTextField txtNextPart;
- private final JTextField txtActualQty;
- private final JTextField txtProduced;
- private final JTextField txtDowntime;
- private final JTextField txtTakt;
- /** 产线状态文案示值 */
- private final JTextField txtLineState;
- /** 五台压机本批进度(主界面汇总,结案看压机5) */
- private final JTextField txtPressProgress;
- /** 服务端 SSE 呼吸灯 */
- private final BreathingLight serverHeartbeat;
- /** PLC 连接指示灯:绿=已连,红=未连 */
- private final StatusLight lampPlc;
- /** PLC 连接状态说明 */
- private final JLabel lblPlcState;
- /** 产线状态指示灯:绿=正常,灰=待机,红=故障 */
- private final StatusLight lampLineState;
- /** 产线状态说明 */
- private final JLabel lblLineState;
- /** MES 允许运行指示灯:绿=已开,灰=关 */
- private final StatusLight lampMesAllow;
- /** MES 允许状态说明 */
- private final JLabel lblMesAllowState;
- /** 漏推送时现场可点:强制 nextBatch */
- private final JButton btnNext;
- public StationPanel(MesClientProperties.StationConfig cfg, String serverIp) {
- this.cfg = cfg;
- this.serverIp = serverIp == null ? "" : serverIp.trim();
- // mes-allow-enabled=false 时开批/结案/清码都不写 PLC 允许点
- this.plc = new DcPlcClient(cfg.getStationSn(), cfg.getPlcIp(), cfg.getPlcPort(),
- cfg.getMesAllowAddr(), MainFrame.mes_allow_enabled);
- setLayout(new BorderLayout(0, 0));
- setBackground(UiTheme.BG);
- setBorder(new EmptyBorder(0, 0, 0, 0));
- String titleText = nvl(cfg.getTitle());
- if (titleText.isEmpty()) {
- titleText = "自动化大冲";
- }
- JPanel header = UiTheme.gradientHeader();
- header.setBorder(new EmptyBorder(16, 20, 16, 20));
- lblStation = new JLabel(titleText);
- lblStation.setFont(UiTheme.FONT_TITLE);
- lblStation.setForeground(Color.WHITE);
- // Consolas 不支持中文,副标题只用工位编码,避免乱码方框
- JLabel lblCode = new JLabel(nvl(cfg.getStationSn()));
- lblCode.setFont(new Font("Consolas", Font.BOLD, 13));
- lblCode.setForeground(new Color(140, 210, 220));
- JPanel titleCol = new JPanel();
- titleCol.setOpaque(false);
- titleCol.setLayout(new BoxLayout(titleCol, BoxLayout.Y_AXIS));
- titleCol.add(lblStation);
- titleCol.add(Box.createVerticalStrut(3));
- titleCol.add(lblCode);
- serverHeartbeat = new BreathingLight();
- serverHeartbeat.setOnline(false);
- lampPlc = new StatusLight();
- lblPlcState = headerStateLabel("未连接");
- lampLineState = new StatusLight();
- lblLineState = headerStateLabel("待机");
- lampMesAllow = new StatusLight();
- lblMesAllowState = headerStateLabel("关");
- JPanel east = new JPanel(new FlowLayout(FlowLayout.RIGHT, 14, 0));
- east.setOpaque(false);
- east.add(headerBreathingItem("MES", serverHeartbeat));
- east.add(headerLampItem("PLC", lampPlc, lblPlcState));
- east.add(headerLampItem("产线", lampLineState, lblLineState));
- east.add(headerLampItem("MES允许", lampMesAllow, lblMesAllowState));
- header.add(titleCol, BorderLayout.WEST);
- header.add(east, BorderLayout.EAST);
- // 状态条紧贴顶栏下方,一眼能看到当前阶段
- lblStatus = new JLabel("空闲:等待扫码下发批次…");
- lblStatus.setFont(UiTheme.FONT_BODY);
- lblStatus.setOpaque(true);
- lblStatus.setBackground(UiTheme.OK_BG);
- lblStatus.setForeground(UiTheme.OK_FG);
- lblStatus.setBorder(new EmptyBorder(9, 16, 9, 16));
- JPanel north = new JPanel(new BorderLayout(0, 0));
- north.setOpaque(false);
- north.add(header, BorderLayout.NORTH);
- north.add(lblStatus, BorderLayout.SOUTH);
- add(north, BorderLayout.NORTH);
- // 本批 : 线体过程 按 1:3 等比分高;格子有最小高度,再矮则滚动
- JPanel main = new JPanel(new GridBagLayout());
- main.setOpaque(false);
- main.setBorder(new EmptyBorder(16, 20, 16, 20));
- JPanel batchCard = UiTheme.card();
- batchCard.setLayout(new BorderLayout(0, 10));
- batchCard.add(UiTheme.sectionTitle("本批"), BorderLayout.NORTH);
- JPanel batchGrid = new JPanel(new GridLayout(1, 2, 14, 0));
- batchGrid.setOpaque(false);
- batchGrid.setPreferredSize(new Dimension(10, UiTheme.TILE_PREF_H));
- batchGrid.setMinimumSize(new Dimension(10, UiTheme.TILE_MIN_H));
- txtBatch = roField();
- txtTarget = roField();
- batchGrid.add(UiTheme.paramTile("批次码", txtBatch, UiTheme.STRIPE_SIDE));
- batchGrid.add(UiTheme.paramTile("本批目标数量", txtTarget, UiTheme.STRIPE_SIDE));
- batchCard.add(batchGrid, BorderLayout.CENTER);
- JPanel runCard = UiTheme.card();
- runCard.setLayout(new BorderLayout(0, 10));
- runCard.add(UiTheme.sectionTitle("线体过程"), BorderLayout.NORTH);
- JPanel grid = new JPanel(new GridLayout(3, 3, 14, 14));
- grid.setOpaque(false);
- // 3 行格子最小总高,防止被压成一条线
- grid.setMinimumSize(new Dimension(10, UiTheme.TILE_MIN_H * 3 + 28));
- grid.setPreferredSize(new Dimension(10, UiTheme.TILE_PREF_H * 3 + 28));
- txtCurrentPart = roField();
- txtNextPart = roField();
- txtActualQty = roField();
- txtProduced = roField();
- txtDowntime = roField();
- txtTakt = roField();
- txtPressProgress = roField();
- txtLineState = roField();
- grid.add(UiTheme.paramTile("当前零件名称", txtCurrentPart, UiTheme.STRIPE_SIDE));
- grid.add(UiTheme.paramTile("下一零件名称", txtNextPart, UiTheme.STRIPE_SIDE));
- grid.add(UiTheme.paramTile("实际产量", txtActualQty, UiTheme.STRIPE_SIDE));
- grid.add(UiTheme.paramTile("停机时间", txtDowntime, UiTheme.STRIPE_SIDE));
- grid.add(UiTheme.paramTile("生产节拍", txtTakt, UiTheme.STRIPE_SIDE));
- grid.add(UiTheme.paramTile("产线状态", txtLineState, UiTheme.STRIPE_SIDE));
- grid.add(UiTheme.paramTile("本批已产", txtProduced, UiTheme.STRIPE_SIDE));
- UiTheme.markTileValueBase(txtProduced, UiTheme.FONT_SN.getSize2D());
- grid.add(UiTheme.paramTile("五台冲次数量进度", txtPressProgress, UiTheme.STRIPE_SIDE));
- UiTheme.markTileValueBase(txtPressProgress, UiTheme.FONT_BODY.getSize2D());
- runCard.add(grid, BorderLayout.CENTER);
- GridBagConstraints gc = new GridBagConstraints();
- gc.gridx = 0;
- gc.fill = GridBagConstraints.BOTH;
- gc.weightx = 1;
- gc.gridy = 0;
- gc.weighty = 1; // 本批约 1 行
- main.add(batchCard, gc);
- gc.gridy = 1;
- gc.weighty = 3; // 线体过程约 3 行,与本批等比分高
- gc.insets = new Insets(14, 0, 0, 0);
- main.add(runCard, gc);
- JScrollPane scroll = new JScrollPane(main);
- scroll.setBorder(BorderFactory.createEmptyBorder());
- scroll.setOpaque(false);
- scroll.getViewport().setOpaque(false);
- scroll.getVerticalScrollBar().setUnitIncrement(16);
- add(scroll, BorderLayout.CENTER);
- // 底部操作区:只保留「取批次」按钮
- JPanel actions = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 0));
- actions.setOpaque(false);
- actions.setBorder(new EmptyBorder(0, 20, 16, 20));
- btnNext = UiTheme.primaryBtn("取批次");
- btnNext.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- onManualNextClick();
- }
- });
- actions.add(btnNext);
- add(actions, BorderLayout.SOUTH);
- }
- public String getStationSn() {
- return nvl(cfg.getStationSn());
- }
- /** 单设备客户端:页签名固定为工作面板 */
- public String tabTitle() {
- return "工作面板";
- }
- public void initPlc() {
- plc.connect();
- uiPlcLabel();
- refreshSnapshotUi(plc.readSnapshot());
- }
- /**
- * 周期:重连、刷 DB260;RUN 只展示线体产量差,不按 DB260 自动结案。
- * 结案由压机5冲次达标触发 {@link #finishFromPress5(int)}。
- */
- public void tick() {
- if (busy.get()) {
- return;
- }
- try {
- plc.maintainConnection();
- uiPlcLabel();
- uiServerHeartbeat();
- DcRunSnapshot snap = plc.readSnapshot();
- if (snap != null) {
- lastSnap = snap;
- }
- refreshSnapshotUi(snap);
- refreshPressProgressUi();
- if (phase == Phase.IDLE) {
- if (!MainFrame.isMesServerOnline()) {
- setStatusUi("空闲:MES/SSE 未连接,等待服务端…");
- } else {
- setStatusUi("空闲:等待扫码下发批次…");
- }
- return;
- }
- if (phase == Phase.DONE) {
- // 上传曾失败:用挂起报文续传,成功前不重新开批、不回空闲
- retryPendingCompleteIfAny();
- return;
- }
- if (phase == Phase.RUN) {
- // 线体产量差仅展示;结案看压机5
- updateProducedAgainstActual(snap.actualQty);
- setText(txtProduced, String.valueOf(producedQty));
- int p5 = DcLineBatchContext.getPressProduced(5);
- setStatusUi("生产中 批次=" + batchCode
- + " 压机5 " + p5 + " / " + targetQty
- + " (达标后打印结案)");
- }
- } catch (Exception e) {
- log.warn("工位[{}] tick 异常: {}", cfg.getStationSn(), e.getMessage());
- }
- }
- /** SSE / 兜底:空闲则 nextBatch */
- public void tryAutoNextFromPush() {
- if (phase != Phase.IDLE) {
- return;
- }
- requestNextAsync();
- }
- public void tryAutoNextFromPush(String enqueueStationSn) {
- if (enqueueStationSn == null || !enqueueStationSn.trim().equalsIgnoreCase(getStationSn())) {
- return;
- }
- tryAutoNextFromPush();
- }
- /**
- * SSE 清码:本机正占用同一批次码则关允许并回空闲。
- * 结案上传中(DONE+挂起报文)不打断,避免丢续传导致热队列卡「已取」。
- */
- public void applyClearedFromPush(String clearedSn) {
- String local = nvl(batchCode);
- String remote = nvl(clearedSn);
- if (local.isEmpty() || remote.isEmpty() || !local.equalsIgnoreCase(remote)) {
- return;
- }
- if (phase == Phase.IDLE) {
- return;
- }
- if (phase == Phase.DONE && pendingCompleteFields != null) {
- log.info("工位[{}] 结案上传中收到清码 sn={},不打断", cfg.getStationSn(), local);
- return;
- }
- if (!busy.compareAndSet(false, true)) {
- return;
- }
- try {
- log.info("工位[{}] 收到清码推送,复位本地 batch={}", cfg.getStationSn(), local);
- plc.setMesAllow(false);
- pendingCompleteFields = null;
- // resetToIdle 内会关闭共享批次并通知压机页冲刷
- resetToIdle("服务端已清码 " + local);
- MainFrame.setMenuStatus(cfg.getStationSn() + " 已清码 " + local, 0);
- } finally {
- busy.set(false);
- }
- }
- /** 异步 nextBatch,不堵 PLC tick(自动门铃/兜底,带 2s 节流) */
- public void requestNextAsync() {
- requestNextAsync(false);
- }
- /**
- * 异步 nextBatch。
- *
- * @param forceManual true=手动按钮:跳过节流,必打日志,失败把服务端文案顶到状态条
- */
- public void requestNextAsync(final boolean forceManual) {
- if (phase != Phase.IDLE) {
- if (forceManual) {
- log.info("工位[{}] 手动取批次忽略:当前 phase={}", cfg.getStationSn(), phase);
- }
- return;
- }
- long now = System.currentTimeMillis();
- if (!forceManual && now - lastPollBatchAtMs < POLL_BATCH_INTERVAL_MS) {
- return;
- }
- lastPollBatchAtMs = now;
- if (serverIp.isEmpty()) {
- setStatusUi("空闲:等待扫码(server-ip 未配,仅可联调模拟)");
- log.warn("工位[{}] 取批次中止:server-ip 未配置", cfg.getStationSn());
- return;
- }
- if (!nextBusy.compareAndSet(false, true)) {
- if (forceManual) {
- setStatusUi("取批次进行中,请稍候…");
- log.info("工位[{}] 手动取批次:已有请求在飞,跳过重复点击", cfg.getStationSn());
- }
- return;
- }
- log.info("工位[{}] 开始 nextBatch{}", cfg.getStationSn(), forceManual ? "(手动)" : "");
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- JSONObject ret = MesDcApiClient.nextBatch(serverIp, cfg.getStationSn());
- if (phase != Phase.IDLE) {
- log.info("工位[{}] nextBatch 返回时已非空闲 phase={},丢弃结果",
- cfg.getStationSn(), phase);
- return;
- }
- if (ret == null) {
- setStatusUi("取批次无响应(检查服务端/网络)");
- log.warn("工位[{}] nextBatch 无响应 server={}", cfg.getStationSn(), serverIp);
- return;
- }
- if (!MesDcApiClient.isSuccess(ret)) {
- String msg = MesDcApiClient.messageOf(ret);
- // 模具寿命:状态栏必显;弹窗仅手动取批,避免 SSE/轮询反复弹窗
- if (msg != null && msg.indexOf("模具寿命已到") >= 0) {
- setStatusUi(msg);
- if (forceManual) {
- showMoldLifeDialog(msg);
- }
- } else {
- setStatusUi("取批次:" + msg);
- }
- log.info("工位[{}] nextBatch 未取到:{}", cfg.getStationSn(), msg);
- return;
- }
- String code = MesDcApiClient.dataStr(ret, "batchCode");
- if (code.isEmpty()) {
- code = MesDcApiClient.dataStr(ret, "sn");
- }
- int target = MesDcApiClient.dataInt(ret, "targetQty", 0);
- if (target <= 0) {
- target = MesDcApiClient.dataInt(ret, "qty", 0);
- }
- if (code.isEmpty() || target <= 0) {
- setStatusUi("取批次成功但缺批次码/目标数量");
- log.warn("工位[{}] nextBatch 成功但缺 batchCode/targetQty: {}", cfg.getStationSn(), ret);
- return;
- }
- String queueUser = MesDcApiClient.dataStr(ret, "userCode");
- if (queueUser.isEmpty()) {
- queueUser = MesDcApiClient.dataStr(ret, "ucode");
- }
- log.info("工位[{}] nextBatch 成功 batch={} target={} userCode={}",
- cfg.getStationSn(), code, Integer.valueOf(target), queueUser);
- startBatchFromPda(code, target, queueUser);
- } finally {
- nextBusy.set(false);
- }
- }
- }, "dc-next-" + cfg.getStationSn()).start();
- }
- /**
- * 批次到位:记起点产量 → MES允许=true → 进入 RUN;本批做完再写 false。
- *
- * @param queueUserCode PDA 入队工号(可空)
- */
- private void startBatchFromPda(String code, int target, String queueUserCode) {
- // DONE 挂起续传中禁止再开批,避免冲掉待上传结案
- if (phase == Phase.RUN || phase == Phase.DONE) {
- return;
- }
- if (!busy.compareAndSet(false, true)) {
- return;
- }
- try {
- if (!plc.isConnected()) {
- plc.connect();
- }
- // 服务端 next 后队列已是「已取」:PLC 读不到也不能丢弃,否则热表卡住、界面像没反应
- Integer base = plc.readActualQty();
- int baseQty = 0;
- if (base == null) {
- log.warn("工位[{}] 开批时读实际产量失败(PLC 未连/点位异常),起点按 0,batch={}",
- cfg.getStationSn(), code);
- } else {
- baseQty = base.intValue();
- }
- batchCode = code;
- currentUserCode = queueUserCode == null ? "" : queueUserCode.trim();
- targetQty = target;
- baseActualQty = baseQty;
- lastActualQty = baseActualQty;
- producedQty = 0;
- batchStartTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
- // 共享给五台压机页:只主界面持有批次码
- DcLineBatchContext.open(batchCode, targetQty, batchStartTime);
- MainFrame.notifyPressesBatchOpened();
- boolean wrote = plc.setMesAllow(true);
- phase = Phase.RUN;
- setText(txtBatch, batchCode);
- setText(txtTarget, String.valueOf(targetQty));
- setText(txtProduced, "0");
- setMesAllowLamp(wrote);
- // 开批提示:区分开关关 / 点未配或写失败
- String tip;
- if (wrote) {
- tip = "批次已开,MES允许已写";
- } else if (!plc.isMesAllowEnabled()) {
- tip = "批次已开(MES允许开关已关,未写PLC)";
- } else {
- tip = "批次已开(允许点未配/写失败)";
- }
- if (base == null) {
- tip = tip + " PLC产量未读到,起点=0";
- } else {
- tip = tip + " 起始产量=" + baseActualQty;
- }
- tip = tip + " 结案看压机5";
- setStatusUi(tip);
- MainFrame.setMenuStatus(cfg.getStationSn() + " 开批 " + batchCode + " 目标" + targetQty, 0);
- log.info("工位[{}] 开批 batch={} target={} baseQty={} plcOk={}(结案条件=压机5达标)",
- cfg.getStationSn(), batchCode, Integer.valueOf(targetQty),
- Integer.valueOf(baseActualQty), Boolean.valueOf(base != null));
- } finally {
- busy.set(false);
- }
- }
- /**
- * 手动取批次:SSE 漏推时立刻 nextBatch(跳过节流,必打日志)。
- * 仅空闲可用。
- */
- public void onManualNextClick() {
- log.info("工位[{}] 点击「取批次」 phase={}", cfg.getStationSn(), phase);
- if (phase != Phase.IDLE) {
- setStatusUi("当前非空闲,无法取批次(进行中请用手动提交结案)");
- return;
- }
- setStatusUi("正在手动取批次…");
- requestNextAsync(true);
- }
- /**
- * 手动提交:设置菜单入口。
- * RUN:密码 mes → 确认批次/数量 → 结案(走挂起续传)。
- * DONE+挂起:可立即再打一次上传;其它态弹窗说明。
- */
- public void onManualSubmitClick() {
- log.info("工位[{}] 点击「手动提交」 phase={} batch={}",
- cfg.getStationSn(), phase, batchCode);
- if (phase == Phase.DONE && pendingCompleteFields != null) {
- int opt = JOptionPane.showConfirmDialog(dialogParent(),
- "批次 " + pendingBatchCode + " 结案上传未成功,是否立即重试?",
- "手动提交", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
- if (opt == JOptionPane.YES_OPTION) {
- setStatusUi("手动触发结案续传…");
- new Thread(new Runnable() {
- @Override
- public void run() {
- uploadPendingComplete(false);
- }
- }, "dc-manual-retry-" + cfg.getStationSn()).start();
- }
- return;
- }
- if (phase != Phase.RUN) {
- JOptionPane.showMessageDialog(dialogParent(),
- "当前无进行中的批次,无法手动提交。\n请先取批次并开批后再试。",
- "手动提交", JOptionPane.INFORMATION_MESSAGE);
- return;
- }
- if (!askMesPassword()) {
- return;
- }
- int qty = DcLineBatchContext.getPressProduced(5);
- if (qty <= 0) {
- qty = producedQty;
- }
- String confirm = "确认手动结案?\n"
- + "批次码:" + batchCode + "\n"
- + "压机5已产:" + DcLineBatchContext.getPressProduced(5) + "\n"
- + "线体已产:" + producedQty + "\n"
- + "计划产量:" + targetQty + "\n"
- + "本次上报数量:" + qty;
- int ok = JOptionPane.showConfirmDialog(dialogParent(), confirm, "手动提交",
- JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
- if (ok != JOptionPane.OK_OPTION) {
- return;
- }
- finishBatch(qty, false, true);
- }
- /**
- * 压机5冲次达标回调:按压机5已产数量结案并打印。
- *
- * @param press5Qty 压机5本批已产
- */
- public void finishFromPress5(int press5Qty) {
- if (phase != Phase.RUN) {
- return;
- }
- int qty = press5Qty > 0 ? press5Qty : DcLineBatchContext.getPressProduced(5);
- if (qty <= 0) {
- qty = producedQty;
- }
- log.info("工位[{}] 收到压机5达标结案 qty={} batch={}",
- cfg.getStationSn(), Integer.valueOf(qty), batchCode);
- finishBatch(qty, false, false);
- }
- /**
- * 弹出密码框;正确密码为 mes。
- *
- * @return true=校验通过
- */
- private boolean askMesPassword() {
- JPasswordField pf = new JPasswordField(12);
- JPanel box = new JPanel(new BorderLayout(8, 8));
- box.add(new JLabel("请输入密码"), BorderLayout.NORTH);
- box.add(pf, BorderLayout.CENTER);
- int opt = JOptionPane.showConfirmDialog(dialogParent(), box, "手动提交",
- JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
- if (opt != JOptionPane.OK_OPTION) {
- return false;
- }
- char[] input = pf.getPassword();
- boolean ok = Arrays.equals(input, "mes".toCharArray());
- Arrays.fill(input, '\0');
- if (!ok) {
- JOptionPane.showMessageDialog(dialogParent(), "密码错误", "手动提交", JOptionPane.WARNING_MESSAGE);
- return false;
- }
- return true;
- }
- /** 弹窗挂到主窗,避免工作面板未显示时对话框位置异常 */
- private Component dialogParent() {
- Window w = SwingUtilities.getWindowAncestor(this);
- return w != null ? w : this;
- }
- /** 产量达标结案 */
- private void finishBatch(final int qty, final boolean aborted) {
- finishBatch(qty, aborted, false);
- }
- /**
- * 结案:关 MES允许 → 本机记录 → 异步打印 → 挂起报文上传;
- * 仅 completeBatch 成功才回空闲,失败留 DONE 由 tick 续传。
- *
- * @param qty 本批数量
- * @param aborted 是否强制中断(结果 NG)
- * @param manual 是否手动提交
- */
- private void finishBatch(final int qty, final boolean aborted, final boolean manual) {
- if (!busy.compareAndSet(false, true)) {
- return;
- }
- phase = Phase.DONE;
- final String codeSnap = batchCode;
- final String timeSnap = batchStartTime;
- new Thread(new Runnable() {
- @Override
- public void run() {
- boolean fieldsReady = false;
- try {
- // 本批做完:MES允许改回 false
- plc.setMesAllow(false);
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- setMesAllowLamp(false);
- }
- });
- String time = timeSnap;
- if (time == null || time.isEmpty()) {
- time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
- }
- // 过站结果:中断 NG,否则 OK(含手动提交)
- String passResult = aborted ? "NG" : "OK";
- DcRunSnapshot snap = lastSnap == null ? new DcRunSnapshot() : lastSnap;
- final Map<String, String> fields = new LinkedHashMap<String, String>();
- fields.put("stationSn", cfg.getStationSn());
- fields.put("batchCode", codeSnap);
- fields.put("qty", String.valueOf(qty));
- fields.put("produceTime", time);
- fields.put("aborted", aborted ? "1" : "0");
- fields.put("manual", manual ? "1" : "0");
- fields.put("result", passResult);
- // 结案工号:取批时队列带回的入队工号;空则 system
- String jobUser = currentUserCode == null ? "" : currentUserCode.trim();
- fields.put("userCode", jobUser.isEmpty() ? "system" : jobUser);
- fields.put("currentPart", nvl(snap.currentPart));
- fields.put("nextPart", nvl(snap.nextPart));
- fields.put("actualQty", String.valueOf(snap.actualQty));
- fields.put("downtime", String.valueOf(snap.downtime));
- fields.put("takt", String.valueOf(snap.takt));
- fields.put("lineState", String.valueOf(snap.lineState));
- fields.put("lineStateText", nvl(snap.lineStateText));
- // 本机记录先落;挂起报文供 DONE 续传(按批次码幂等)
- DcWorkRecordStore.add(codeSnap, time, qty, passResult);
- MainFrame.refreshWorkRecords();
- String how = aborted ? "已强制结束" : (manual ? "手动提交" : "压机5达标");
- pendingCompleteFields = fields;
- pendingHow = how;
- pendingBatchCode = codeSnap;
- pendingQty = qty;
- pendingPrinted = false;
- fieldsReady = true;
- // 手动打印:只入列表不自动打;自动模式:异步送打(卡死不能挡结案)
- final String printTime = time;
- final String printBatch = codeSnap;
- final int printQty = qty;
- if (DcBatchPrinter.isManualPrintMode()) {
- DcPrintQueueStore.addPending(printBatch, printTime, printQty);
- MainFrame.refreshPrintList();
- pendingPrinted = false;
- log.info("工位[{}] 手动打印模式:批次已入打印列表 batch={}", cfg.getStationSn(), printBatch);
- setStatusUi("已入打印列表,请到「打印列表」确认送打");
- } else {
- new Thread(new Runnable() {
- @Override
- public void run() {
- boolean ok = DcBatchPrinter.printBatch(printBatch, printTime, printQty);
- pendingPrinted = ok;
- if (ok) {
- // 自动打成功也记一笔已打印,便于打印列表追溯
- DcPrintQueueStore.addPending(printBatch, printTime, printQty);
- DcPrintQueueStore.markPrinted(printBatch);
- MainFrame.refreshPrintList();
- } else {
- log.warn("工位[{}] 异步打印失败/无打印机 batch={}", cfg.getStationSn(), printBatch);
- }
- }
- }, "dc-print-" + cfg.getStationSn()).start();
- }
- // 先放 busy:phase=DONE,tick 可刷灯并可走续传
- busy.set(false);
- uploadPendingComplete(true);
- } catch (Exception ex) {
- log.error("工位[{}] 结案异常: {}", cfg.getStationSn(), ex.getMessage(), ex);
- setStatusUi("结案异常:" + ex.getMessage());
- if (!fieldsReady) {
- // 报文未备好:回到 RUN,可手动再提交
- phase = Phase.RUN;
- }
- } finally {
- busy.set(false);
- }
- }
- }, "dc-finish-" + cfg.getStationSn()).start();
- }
- /** DONE 态 tick 触发:有挂起结案则续传 */
- private void retryPendingCompleteIfAny() {
- if (pendingCompleteFields == null) {
- return;
- }
- uploadPendingComplete(false);
- }
- /**
- * 上传挂起的结案报文;成功才回空闲(关共享批次、通知压机)。
- *
- * @param fromFinishThread true=结案线程内首轮(可多等几轮);false=tick 续传单次
- */
- private void uploadPendingComplete(boolean fromFinishThread) {
- final Map<String, String> fields = pendingCompleteFields;
- if (fields == null) {
- return;
- }
- if (!completeRetryBusy.compareAndSet(false, true)) {
- return;
- }
- final String how = pendingHow;
- final String batch = pendingBatchCode;
- final int qty = pendingQty;
- try {
- int maxAttempts = fromFinishThread ? 12 : 1;
- boolean uploaded = false;
- for (int attempt = 1; attempt <= maxAttempts; attempt++) {
- JSONObject ret = MesDcApiClient.completeBatch(serverIp, fields);
- uploaded = MesDcApiClient.isSuccess(ret);
- if (uploaded) {
- break;
- }
- setStatusUi(how + " 批次码=" + batch + " 上传失败,重试中…(#" + attempt + ")");
- MainFrame.setMenuStatus(cfg.getStationSn() + " 上传失败重试 #" + attempt, -1);
- log.warn("工位[{}] 结案上传失败 batch={} attempt={} msg={}",
- cfg.getStationSn(), batch, Integer.valueOf(attempt),
- MesDcApiClient.messageOf(ret));
- if (attempt < maxAttempts) {
- try {
- Thread.sleep(5000L);
- } catch (InterruptedException ie) {
- Thread.currentThread().interrupt();
- break;
- }
- }
- }
- if (uploaded) {
- pendingCompleteFields = null;
- // 手动模式:未自动送打,提示去打印列表;自动模式按是否真正送打成功区分
- String printTip;
- if (DcBatchPrinter.isManualPrintMode()) {
- printTip = " 待手动打印";
- } else if (pendingPrinted) {
- printTip = " 已送打印";
- } else {
- printTip = " 打印已提交/待确认";
- }
- final String tip = how + " 批次码=" + batch + " 数量=" + qty
- + printTip + " 已上传";
- resetToIdle(tip);
- MainFrame.setMenuStatus(cfg.getStationSn() + " 结案 " + batch + " x" + qty, 0);
- log.info("工位[{}] 结案成功 batch={} qty={}", cfg.getStationSn(), batch, Integer.valueOf(qty));
- } else {
- setStatusUi(how + " 批次码=" + batch + " 等待续传…");
- }
- } finally {
- completeRetryBusy.set(false);
- }
- }
- /**
- * 按 PLC 实际产量累计本批已产。
- * 若实际产量比上一拍变小(人为复位/清零),保留已产件数,把起点挪到「当前值 − 已产」,
- * 避免差值为负导致进度归零、永远达不到目标。
- *
- * @param actualQty 当前 PLC 实际产量示值
- */
- private void updateProducedAgainstActual(int actualQty) {
- if (actualQty < lastActualQty) {
- int kept = producedQty;
- baseActualQty = actualQty - kept;
- log.warn("工位[{}] 检测到实际产量复位/变小:上次={} 本次={},保留已产={},重定起点={}",
- cfg.getStationSn(),
- Integer.valueOf(lastActualQty),
- Integer.valueOf(actualQty),
- Integer.valueOf(kept),
- Integer.valueOf(baseActualQty));
- setStatusUi("检测到产量复位,已保留本批进度 " + kept + " / " + targetQty);
- }
- int produced = actualQty - baseActualQty;
- if (produced < 0) {
- produced = 0;
- }
- // 本批内已产只增不减,防止抖动回退
- if (produced > producedQty) {
- producedQty = produced;
- }
- lastActualQty = actualQty;
- }
- private void resetToIdle(String msg) {
- phase = Phase.IDLE;
- batchCode = "";
- currentUserCode = "";
- targetQty = 0;
- baseActualQty = 0;
- producedQty = 0;
- lastActualQty = 0;
- batchStartTime = "";
- pendingCompleteFields = null;
- pendingHow = "";
- pendingBatchCode = "";
- pendingQty = 0;
- pendingPrinted = false;
- // 上传成功或清码后才关共享批次,挂起续传期间压机仍能看见本批
- DcLineBatchContext.close();
- MainFrame.notifyPressesBatchClosed();
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- setText(txtBatch, "");
- setText(txtTarget, "");
- setText(txtProduced, "");
- setText(txtPressProgress, "");
- setMesAllowLamp(false);
- setStatusUi(msg == null || msg.isEmpty()
- ? "空闲:等待扫码下发批次…" : msg + " → 等待下一笔");
- }
- });
- }
- /** 刷新主界面「五台冲次进度」汇总 */
- private void refreshPressProgressUi() {
- if (phase != Phase.RUN) {
- return;
- }
- final int target = targetQty;
- final StringBuilder sb = new StringBuilder();
- for (int i = 1; i <= 5; i++) {
- if (i > 1) {
- sb.append(" ");
- }
- sb.append(i).append('#').append(DcLineBatchContext.getPressProduced(i));
- if (target > 0) {
- sb.append('/').append(target);
- }
- }
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- setText(txtPressProgress, sb.toString());
- }
- });
- }
- private void refreshSnapshotUi(final DcRunSnapshot s) {
- if (s == null) {
- return;
- }
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- setText(txtCurrentPart, s.currentPart);
- setText(txtNextPart, s.nextPart);
- setText(txtActualQty, String.valueOf(s.actualQty));
- setText(txtDowntime, String.valueOf(s.downtime));
- setText(txtTakt, String.valueOf(s.takt));
- setText(txtLineState, nvl(s.lineStateText).isEmpty()
- ? String.valueOf(s.lineState) : s.lineStateText);
- setLineStateLamp(s.lineState);
- setMesAllowLamp(phase == Phase.RUN);
- }
- });
- }
- /**
- * 产线状态灯 + 说明:2 正常;3 故障;0/1 待机。
- */
- private void setLineStateLamp(final int lineState) {
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- StatusLight.Level lv = StatusLight.Level.OFF;
- String tip = "待机";
- if (lineState == 2) {
- lv = StatusLight.Level.ON;
- tip = "正常";
- } else if (lineState == 3) {
- lv = StatusLight.Level.FAULT;
- tip = "故障";
- }
- lampLineState.setLevel(lv);
- lblLineState.setText(tip);
- }
- });
- }
- /** 刷新 MES 允许指示灯 + 说明 */
- private void setMesAllowLamp(final boolean on) {
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- lampMesAllow.setOn(on);
- lblMesAllowState.setText(on ? "开" : "关");
- }
- });
- }
- /** 顶栏刷新:连接灯 + 状态说明 */
- private void uiPlcLabel() {
- final boolean ok = plc.isConnected();
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- lampPlc.setLevel(ok ? StatusLight.Level.ON : StatusLight.Level.FAULT);
- lblPlcState.setText(ok ? "已连接" : "未连接");
- }
- });
- }
- /** 按 SSE 连接态刷新 MES 呼吸灯 */
- private void uiServerHeartbeat() {
- final boolean online = MainFrame.isMesServerOnline();
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- serverHeartbeat.setOnline(online);
- serverHeartbeat.setToolTipText(online
- ? "服务端已连接(SSE 正常)"
- : "服务端已断开(SSE 未连)");
- }
- });
- }
- /** 顶栏状态说明(灯正下方) */
- private static JLabel headerStateLabel(String text) {
- JLabel lb = new JLabel(text, SwingConstants.CENTER);
- lb.setFont(new Font("微软雅黑", Font.PLAIN, 11));
- lb.setForeground(new Color(200, 230, 235));
- lb.setAlignmentX(Component.CENTER_ALIGNMENT);
- return lb;
- }
- /**
- * 顶栏一组:名称在上、灯居中、状态说明在灯下方。
- */
- private static JPanel headerLampItem(String name, StatusLight lamp, JLabel stateLbl) {
- JPanel p = new JPanel();
- p.setOpaque(false);
- p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
- JLabel lb = new JLabel(name, SwingConstants.CENTER);
- lb.setFont(new Font("微软雅黑", Font.PLAIN, 12));
- lb.setForeground(new Color(160, 210, 220));
- lb.setAlignmentX(Component.CENTER_ALIGNMENT);
- lamp.setAlignmentX(Component.CENTER_ALIGNMENT);
- stateLbl.setAlignmentX(Component.CENTER_ALIGNMENT);
- p.add(lb);
- p.add(Box.createVerticalStrut(2));
- p.add(lamp);
- p.add(Box.createVerticalStrut(2));
- p.add(stateLbl);
- return p;
- }
- /** 顶栏 MES 呼吸灯一组 */
- private static JPanel headerBreathingItem(String name, BreathingLight lamp) {
- JPanel p = new JPanel();
- p.setOpaque(false);
- p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
- JLabel lb = new JLabel(name, SwingConstants.CENTER);
- lb.setFont(new Font("微软雅黑", Font.PLAIN, 12));
- lb.setForeground(new Color(160, 210, 220));
- lb.setAlignmentX(Component.CENTER_ALIGNMENT);
- lamp.setAlignmentX(Component.CENTER_ALIGNMENT);
- p.add(lb);
- p.add(Box.createVerticalStrut(4));
- p.add(lamp);
- return p;
- }
- /**
- * 模具寿命卡关弹窗(取批线程回调,切回 EDT)。
- *
- * @param msg 服务端失败文案
- */
- private void showMoldLifeDialog(final String msg) {
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- JOptionPane.showMessageDialog(dialogParent(),
- msg == null || msg.isEmpty() ? "模具寿命已到,请更换模具" : msg,
- "模具寿命", JOptionPane.WARNING_MESSAGE);
- }
- });
- }
- private void setStatusUi(final String text) {
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- lblStatus.setText(text == null ? "" : text);
- String t = text == null ? "" : text;
- if (t.contains("失败") || t.contains("故障") || t.contains("模具寿命已到")) {
- lblStatus.setBackground(UiTheme.ERR_BG);
- lblStatus.setForeground(UiTheme.ERR_FG);
- } else if (t.contains("生产中") || t.contains("已开") || t.contains("开批")) {
- lblStatus.setBackground(UiTheme.RUN_BG);
- lblStatus.setForeground(UiTheme.RUN_FG);
- } else {
- lblStatus.setBackground(UiTheme.OK_BG);
- lblStatus.setForeground(UiTheme.OK_FG);
- }
- }
- });
- }
- private static JTextField roField() {
- JTextField t = new JTextField();
- t.setEditable(false);
- t.setFont(UiTheme.FONT_VALUE);
- return t;
- }
- private static void setText(JTextField t, String v) {
- if (t != null) {
- t.setText(v == null ? "" : v);
- }
- }
- private static String nvl(String s) {
- return s == null ? "" : s.trim();
- }
- }
|