| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587 |
- 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.DcPackCode;
- import com.mes.service.DcPlcClient;
- 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.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允许=true → 读 DB260 盯产量 → 结案再允许=false → 打印。
- */
- public class StationPanel extends JPanel {
- private static final Logger log = LoggerFactory.getLogger(StationPanel.class);
- /** 空闲时拉取 PDA 批次的最小间隔 */
- 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);
- private volatile Phase phase = Phase.IDLE;
- private volatile String batchCode = "";
- private volatile int targetQty;
- private volatile int baseActualQty;
- private volatile int producedQty;
- private volatile String batchStartTime = "";
- private volatile long lastPollBatchAtMs;
- /** 最近一次 DB260 快照,结案时一并上传(只传一次,不采样堆) */
- private volatile DcRunSnapshot lastSnap = new DcRunSnapshot();
- private final JLabel lblStation;
- /** 顶栏 PLC 地址文案(不含连接状态) */
- private final JLabel lblPlc;
- 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;
- /** 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;
- public StationPanel(MesClientProperties.StationConfig cfg, String serverIp) {
- this.cfg = cfg;
- this.serverIp = serverIp == null ? "" : serverIp.trim();
- this.plc = new DcPlcClient(cfg.getStationSn(), cfg.getPlcIp(), cfg.getPlcPort(),
- cfg.getMesAllowAddr());
- 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);
- lampPlc = new StatusLight();
- lblPlcState = headerStateLabel("未连接");
- lampLineState = new StatusLight();
- lblLineState = headerStateLabel("待机");
- lampMesAllow = new StatusLight();
- lblMesAllowState = headerStateLabel("关");
- lblPlc = new JLabel(plcAddrText());
- lblPlc.setFont(new Font("Consolas", Font.PLAIN, 12));
- lblPlc.setForeground(new Color(160, 210, 220));
- JPanel east = new JPanel(new FlowLayout(FlowLayout.RIGHT, 14, 0));
- east.setOpaque(false);
- east.add(headerLampItem("PLC", lampPlc, lblPlcState));
- east.add(headerLampItem("产线", lampLineState, lblLineState));
- east.add(headerLampItem("MES允许", lampMesAllow, lblMesAllowState));
- // 有 IP 时才跟地址
- if (!plcAddrText().isEmpty()) {
- east.add(lblPlc);
- }
- 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);
- JPanel main = new JPanel(new BorderLayout(0, 14));
- 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));
- 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(2, 3, 14, 14));
- grid.setOpaque(false);
- txtCurrentPart = roField();
- txtNextPart = roField();
- txtActualQty = roField();
- txtProduced = roField();
- txtProduced.setFont(UiTheme.FONT_SN);
- txtDowntime = roField();
- txtTakt = 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("本批已产", txtProduced, UiTheme.STRIPE_SIDE));
- grid.add(UiTheme.paramTile("停机时间", txtDowntime, UiTheme.STRIPE_SIDE));
- grid.add(UiTheme.paramTile("生产节拍", txtTakt, UiTheme.STRIPE_SIDE));
- runCard.add(grid, BorderLayout.CENTER);
- main.add(batchCard, BorderLayout.NORTH);
- main.add(runCard, BorderLayout.CENTER);
- add(main, BorderLayout.CENTER);
- }
- public String getStationSn() {
- return nvl(cfg.getStationSn());
- }
- /** 单设备客户端:页签名固定为工作面板 */
- public String tabTitle() {
- return "工作面板";
- }
- public void initPlc() {
- plc.connect();
- uiPlcLabel();
- refreshSnapshotUi(plc.readSnapshot());
- }
- /**
- * 周期:重连、刷 DB260;空闲拉 PDA 批次;RUN 算产量差达标结案。
- */
- public void tick() {
- if (busy.get()) {
- return;
- }
- try {
- plc.maintainConnection();
- uiPlcLabel();
- DcRunSnapshot snap = plc.readSnapshot();
- if (snap != null) {
- lastSnap = snap;
- }
- refreshSnapshotUi(snap);
- if (phase == Phase.IDLE) {
- pollPdaBatchIfDue();
- return;
- }
- if (phase == Phase.RUN) {
- int produced = snap.actualQty - baseActualQty;
- if (produced < 0) {
- produced = 0;
- }
- producedQty = produced;
- setText(txtProduced, String.valueOf(producedQty));
- setStatusUi("生产中 批次=" + batchCode + " 已产 " + producedQty + " / 目标 " + targetQty);
- if (producedQty >= targetQty) {
- finishBatch(producedQty, false);
- }
- }
- } catch (Exception e) {
- log.warn("工位[{}] tick 异常: {}", cfg.getStationSn(), e.getMessage());
- }
- }
- /** 空闲:向服务端要 PDA 已扫的待开批次 */
- private void pollPdaBatchIfDue() {
- long now = System.currentTimeMillis();
- if (now - lastPollBatchAtMs < POLL_BATCH_INTERVAL_MS) {
- return;
- }
- lastPollBatchAtMs = now;
- if (serverIp.isEmpty()) {
- setStatusUi("空闲:等待扫码(server-ip 未配,仅可联调模拟)");
- return;
- }
- JSONObject ret = MesDcApiClient.nextBatch(serverIp, cfg.getStationSn());
- if (!MesDcApiClient.isSuccess(ret)) {
- setStatusUi("空闲:等待扫码下发批次…");
- 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) {
- log.warn("工位[{}] nextBatch 成功但缺 batchCode/targetQty: {}", cfg.getStationSn(), ret);
- return;
- }
- startBatchFromPda(code, target);
- }
- /**
- * 批次到位:记起点产量 → MES允许=true → 进入 RUN;本批做完再写 false。
- */
- private void startBatchFromPda(String code, int target) {
- if (phase == Phase.RUN) {
- return;
- }
- if (!busy.compareAndSet(false, true)) {
- return;
- }
- try {
- if (!plc.isConnected()) {
- plc.connect();
- }
- Integer base = plc.readActualQty();
- if (base == null) {
- setStatusUi("收到批次,但读实际产量失败,请检查 PLC");
- MainFrame.setMenuStatus(cfg.getStationSn() + " 开批失败:读产量", -1);
- return;
- }
- batchCode = code;
- targetQty = target;
- baseActualQty = base.intValue();
- producedQty = 0;
- batchStartTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
- boolean wrote = plc.setMesAllow(true);
- phase = Phase.RUN;
- setText(txtBatch, batchCode);
- setText(txtTarget, String.valueOf(targetQty));
- setText(txtProduced, "0");
- setMesAllowLamp(wrote);
- setStatusUi((wrote ? "批次已开,MES允许已写" : "批次已开(允许点未配/写失败,本地仍盯产量)")
- + " 起始产量=" + baseActualQty);
- MainFrame.setMenuStatus(cfg.getStationSn() + " 开批 " + batchCode + " 目标" + targetQty, 0);
- log.info("工位[{}] 开批 batch={} target={} baseQty={}",
- cfg.getStationSn(), batchCode, Integer.valueOf(targetQty), Integer.valueOf(baseActualQty));
- } finally {
- busy.set(false);
- }
- }
- /**
- * 手动提交:校验密码 mes 后,按当前已产数量结案(过站结果 OK)。
- * 由主窗页签左侧「设置」菜单调用。
- */
- public void onManualSubmitClick() {
- if (phase != Phase.RUN) {
- setStatusUi("当前无进行中的批次,无法手动提交");
- return;
- }
- if (!askMesPassword()) {
- return;
- }
- finishBatch(producedQty, false, true);
- }
- /**
- * 弹出密码框;正确密码为 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(this, 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(this, "密码错误", "手动提交", JOptionPane.WARNING_MESSAGE);
- return false;
- }
- return true;
- }
- /** 产量达标结案 */
- private void finishBatch(final int qty, final boolean aborted) {
- finishBatch(qty, aborted, false);
- }
- /**
- * 结案。
- *
- * @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() {
- try {
- // 本批做完:MES允许改回 false
- plc.setMesAllow(false);
- String time = timeSnap;
- if (time == null || time.isEmpty()) {
- time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
- }
- // 包装码:年月日 + 随机6位,打印与上传都用它做批量追溯
- final String packCode = DcPackCode.next();
- boolean printed = DcBatchPrinter.printPack(packCode, time, qty);
- // 过站结果:中断 NG,否则 OK(含手动提交)
- String passResult = aborted ? "NG" : "OK";
- DcWorkRecordStore.add(packCode, codeSnap, time, qty, passResult);
- MainFrame.refreshWorkRecords();
- // 结案只上传一次:包装码 + 批次码 + 本批数量 + DB260 过程参数
- DcRunSnapshot snap = lastSnap == null ? new DcRunSnapshot() : lastSnap;
- Map<String, String> fields = new LinkedHashMap<String, String>();
- fields.put("stationSn", cfg.getStationSn());
- fields.put("batchCode", codeSnap);
- fields.put("packCode", packCode);
- 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);
- 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));
- MesDcApiClient.completeBatch(serverIp, fields);
- String how = aborted ? "已强制结束" : (manual ? "手动提交" : "本批达标");
- final String tip = how + " 包装码=" + packCode + " 数量=" + qty
- + (printed ? " 已送打印" : " 打印失败/无打印机");
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- resetToIdle(tip);
- MainFrame.setMenuStatus(cfg.getStationSn() + " 结案 " + packCode + " x" + qty, 0);
- }
- });
- log.info("工位[{}] 结案 batch={} pack={} qty={} aborted={} manual={} printed={}",
- cfg.getStationSn(), codeSnap, packCode, Integer.valueOf(qty),
- Boolean.valueOf(aborted), Boolean.valueOf(manual), Boolean.valueOf(printed));
- } finally {
- busy.set(false);
- }
- }
- }, "dc-finish-" + cfg.getStationSn()).start();
- }
- private void resetToIdle(String msg) {
- phase = Phase.IDLE;
- batchCode = "";
- targetQty = 0;
- baseActualQty = 0;
- producedQty = 0;
- batchStartTime = "";
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- setText(txtBatch, "");
- setText(txtTarget, "");
- setText(txtProduced, "");
- setMesAllowLamp(false);
- setStatusUi(msg == null || msg.isEmpty()
- ? "空闲:等待扫码下发批次…" : msg + " → 等待下一笔");
- }
- });
- }
- 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));
- 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() {
- lblPlc.setText(plcAddrText());
- lampPlc.setLevel(ok ? StatusLight.Level.ON : StatusLight.Level.FAULT);
- lblPlcState.setText(ok ? "已连接" : "未连接");
- }
- });
- }
- /** PLC 地址;IP 未配返回空 */
- private String plcAddrText() {
- String ip = nvl(cfg.getPlcIp());
- if (ip.isEmpty()) {
- return "";
- }
- return ip + ":" + cfg.getPlcPort();
- }
- /** 顶栏状态说明(灯正下方) */
- 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;
- }
- 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("故障")) {
- 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();
- }
- }
|