package com.mes.service; import com.alibaba.fastjson2.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.LinkedHashMap; import java.util.Map; /** * 一拖二大冲工控机 HTTP:取批次 / 结案 / 过程参数采样上传。 */ public final class MesDcApiClient { private static final Logger log = LoggerFactory.getLogger(MesDcApiClient.class); private MesDcApiClient() { } /** * 取本工位待开批次(PDA 已扫码入通用队列)。 * 路径:{@code /js/a/mes/mesFlexDcYt/nextBatch};期望 data:batchCode。 */ public static JSONObject nextBatch(String serverIp, String stationSn) { Map p = new LinkedHashMap(); p.put("stationSn", nvl(stationSn)); return post(serverIp, "/js/a/mes/mesFlexDcYt/nextBatch", p); } /** * 清码:从服务端热表清掉本工位该批次码(待取/已取均可)。 * sn、stationSn 服务端均必填。路径:{@code /js/a/mes/mesFlexQueue/clear}。 */ public static JSONObject clear(String serverIp, String sn, String stationSn, String userCode) { Map p = new LinkedHashMap(); p.put("sn", nvl(sn)); p.put("stationSn", nvl(stationSn)); p.put("userCode", nvl(userCode)); return post(serverIp, "/js/a/mes/mesFlexQueue/clear", p); } /** * 周期上传(约 2 分钟一段):qty=本段冲次差,带 clientId 幂等; * 成功看 data.needScanBatch / sessionEnded / mesAllow。 * 路径:{@code /js/a/mes/mesFlexDcYt/completeBatch}。 */ public static JSONObject completeBatch(String serverIp, Map fields) { return post(serverIp, "/js/a/mes/mesFlexDcYt/completeBatch", fields); } /** * 压机过程参数批量上报(JSON):落 mes_flex_dc_yt_press_param,供曲线。 * 路径:{@code /js/a/mes/mesFlexDcYt/uploadPressParam}。 * * @param body 含 batchCode、stationSn、pressNo、pressModel、samples[] */ public static JSONObject uploadPressParam(String serverIp, JSONObject body) { return postJson(serverIp, "/js/a/mes/mesFlexDcYt/uploadPressParam", body); } /** * 开班点检状态(按当前班次):data.passed=true/false; * 未配点检项/班次时服务端放行 passed=true。 * 路径:{@code /js/a/mes/mesFlexCheck/status}。 */ public static JSONObject checkStatus(String serverIp, String stationSn) { Map p = new LinkedHashMap(); p.put("stationSn", nvl(stationSn)); return post(serverIp, "/js/a/mes/mesFlexCheck/status", p); } /** 点检是否放行;请求失败返回 false(宁可卡住也不误放行) */ public static boolean checkPassed(JSONObject result) { if (!isSuccess(result)) { return false; } return "true".equalsIgnoreCase(dataStr(result, "passed")); } /** * 探活服务端(不取码、不结案):短超时连 8980。 * 须在独立线程调用,勿放进工位 tick,否则不通时会卡住指示灯刷新。 */ public static boolean ping(String serverIp) { String ip = nvl(serverIp); if (ip.isEmpty()) { return false; } java.net.HttpURLConnection conn = null; try { java.net.URL url = new java.net.URL("http://" + ip + ":8980/js/a/"); conn = (java.net.HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // 短超时:不通时尽快返回,避免顶栏灯半天才变 conn.setConnectTimeout(800); conn.setReadTimeout(800); conn.setInstanceFollowRedirects(false); int code = conn.getResponseCode(); // 任意 HTTP 响应(含 302 登录墙)都说明服务在 return code > 0; } catch (Exception e) { log.debug("mes ping 失败: {}", e.getMessage()); return false; } finally { if (conn != null) { conn.disconnect(); } } } public static boolean isSuccess(JSONObject result) { if (result == null) { return false; } Object r = result.get("result"); return r != null && "true".equalsIgnoreCase(String.valueOf(r).trim()); } public static String messageOf(JSONObject result) { if (result == null) { return "请求失败或无响应(服务端接口可能未上线)"; } String m = result.getString("message"); return m == null || m.isEmpty() ? "失败" : m; } public static String dataStr(JSONObject result, String key) { if (result == null || key == null) { return ""; } JSONObject data = result.getJSONObject("data"); if (data == null) { return nvl(result.getString(key)); } return nvl(data.getString(key)); } public static int dataInt(JSONObject result, String key, int def) { if (result == null || key == null) { return def; } JSONObject data = result.getJSONObject("data"); Object raw = data != null ? data.get(key) : result.get(key); if (raw == null) { return def; } try { return Integer.parseInt(String.valueOf(raw).trim()); } catch (Exception e) { return def; } } private static JSONObject post(String serverIp, String path, Map fields) { try { String url = "http://" + nvl(serverIp) + ":8980" + path; String body = toForm(fields); log.debug("dc POST {} body={}", path, body); String raw = MesApiClient.doPost(url, body); if (raw == null || raw.isEmpty() || "false".equalsIgnoreCase(raw.trim())) { return null; } return JSONObject.parseObject(raw); } catch (Exception e) { log.debug("dc 请求异常 path={} err={}", path, e.getMessage()); return null; } } /** JSON POST(过程参数采样) */ private static JSONObject postJson(String serverIp, String path, JSONObject body) { HttpURLConnection connection = null; InputStream is = null; OutputStream os = null; BufferedReader br = null; try { String url = "http://" + nvl(serverIp) + ":8980" + path; String json = body == null ? "{}" : body.toJSONString(); log.debug("dc JSON POST {} body={}", path, json); connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("POST"); connection.setConnectTimeout(15000); connection.setReadTimeout(60000); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); os = connection.getOutputStream(); os.write(json.getBytes("UTF-8")); if (connection.getResponseCode() != 200) { log.warn("HTTP {} => {}", url, Integer.valueOf(connection.getResponseCode())); return null; } is = connection.getInputStream(); br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuilder sbf = new StringBuilder(); String temp; while ((temp = br.readLine()) != null) { sbf.append(temp); } String raw = sbf.toString(); if (raw.isEmpty()) { return null; } return JSONObject.parseObject(raw); } catch (Exception e) { log.debug("dc JSON 请求异常 path={} err={}", path, e.getMessage()); return null; } finally { if (br != null) { try { br.close(); } catch (IOException ignored) { } } if (os != null) { try { os.close(); } catch (IOException ignored) { } } if (is != null) { try { is.close(); } catch (IOException ignored) { } } if (connection != null) { connection.disconnect(); } } } private static String toForm(Map fields) throws UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); sb.append("__ajax=json"); if (fields != null) { for (Map.Entry e : fields.entrySet()) { if (e.getKey() == null) { continue; } sb.append('&').append(URLEncoder.encode(e.getKey(), "UTF-8")); sb.append('=').append(URLEncoder.encode(nvl(e.getValue()), "UTF-8")); } } return sb.toString(); } private static String nvl(String s) { return s == null ? "" : s.trim(); } }