MesDcApiClient.java 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package com.mes.service;
  2. import com.alibaba.fastjson2.JSONObject;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import java.io.BufferedReader;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.InputStreamReader;
  9. import java.io.OutputStream;
  10. import java.io.UnsupportedEncodingException;
  11. import java.net.HttpURLConnection;
  12. import java.net.URL;
  13. import java.net.URLEncoder;
  14. import java.util.LinkedHashMap;
  15. import java.util.Map;
  16. /**
  17. * 一拖二大冲工控机 HTTP:取批次 / 结案 / 过程参数采样上传。
  18. */
  19. public final class MesDcApiClient {
  20. private static final Logger log = LoggerFactory.getLogger(MesDcApiClient.class);
  21. private MesDcApiClient() {
  22. }
  23. /**
  24. * 取本工位待开批次(PDA 已扫码入通用队列)。
  25. * 路径:{@code /js/a/mes/mesFlexDcYt/nextBatch};期望 data:batchCode。
  26. */
  27. public static JSONObject nextBatch(String serverIp, String stationSn) {
  28. Map<String, String> p = new LinkedHashMap<String, String>();
  29. p.put("stationSn", nvl(stationSn));
  30. return post(serverIp, "/js/a/mes/mesFlexDcYt/nextBatch", p);
  31. }
  32. /**
  33. * 清码:从服务端热表清掉本工位该批次码(待取/已取均可)。
  34. * sn、stationSn 服务端均必填。路径:{@code /js/a/mes/mesFlexQueue/clear}。
  35. */
  36. public static JSONObject clear(String serverIp, String sn, String stationSn, String userCode) {
  37. Map<String, String> p = new LinkedHashMap<String, String>();
  38. p.put("sn", nvl(sn));
  39. p.put("stationSn", nvl(stationSn));
  40. p.put("userCode", nvl(userCode));
  41. return post(serverIp, "/js/a/mes/mesFlexQueue/clear", p);
  42. }
  43. /**
  44. * 周期上传(约 2 分钟一段):qty=本段冲次差,带 clientId 幂等;
  45. * 成功看 data.needScanBatch / sessionEnded / mesAllow。
  46. * 路径:{@code /js/a/mes/mesFlexDcYt/completeBatch}。
  47. */
  48. public static JSONObject completeBatch(String serverIp, Map<String, String> fields) {
  49. return post(serverIp, "/js/a/mes/mesFlexDcYt/completeBatch", fields);
  50. }
  51. /**
  52. * 压机过程参数批量上报(JSON):落 mes_flex_dc_yt_press_param,供曲线。
  53. * 路径:{@code /js/a/mes/mesFlexDcYt/uploadPressParam}。
  54. *
  55. * @param body 含 batchCode、stationSn、pressNo、pressModel、samples[]
  56. */
  57. public static JSONObject uploadPressParam(String serverIp, JSONObject body) {
  58. return postJson(serverIp, "/js/a/mes/mesFlexDcYt/uploadPressParam", body);
  59. }
  60. /**
  61. * 开班点检状态(按当前班次):data.passed=true/false;
  62. * 未配点检项/班次时服务端放行 passed=true。
  63. * 路径:{@code /js/a/mes/mesFlexCheck/status}。
  64. */
  65. public static JSONObject checkStatus(String serverIp, String stationSn) {
  66. Map<String, String> p = new LinkedHashMap<String, String>();
  67. p.put("stationSn", nvl(stationSn));
  68. return post(serverIp, "/js/a/mes/mesFlexCheck/status", p);
  69. }
  70. /** 点检是否放行;请求失败返回 false(宁可卡住也不误放行) */
  71. public static boolean checkPassed(JSONObject result) {
  72. if (!isSuccess(result)) {
  73. return false;
  74. }
  75. return "true".equalsIgnoreCase(dataStr(result, "passed"));
  76. }
  77. /**
  78. * 探活服务端(不取码、不结案):短超时连 8980。
  79. * 须在独立线程调用,勿放进工位 tick,否则不通时会卡住指示灯刷新。
  80. */
  81. public static boolean ping(String serverIp) {
  82. String ip = nvl(serverIp);
  83. if (ip.isEmpty()) {
  84. return false;
  85. }
  86. java.net.HttpURLConnection conn = null;
  87. try {
  88. java.net.URL url = new java.net.URL("http://" + ip + ":8980/js/a/");
  89. conn = (java.net.HttpURLConnection) url.openConnection();
  90. conn.setRequestMethod("GET");
  91. // 短超时:不通时尽快返回,避免顶栏灯半天才变
  92. conn.setConnectTimeout(800);
  93. conn.setReadTimeout(800);
  94. conn.setInstanceFollowRedirects(false);
  95. int code = conn.getResponseCode();
  96. // 任意 HTTP 响应(含 302 登录墙)都说明服务在
  97. return code > 0;
  98. } catch (Exception e) {
  99. log.debug("mes ping 失败: {}", e.getMessage());
  100. return false;
  101. } finally {
  102. if (conn != null) {
  103. conn.disconnect();
  104. }
  105. }
  106. }
  107. public static boolean isSuccess(JSONObject result) {
  108. if (result == null) {
  109. return false;
  110. }
  111. Object r = result.get("result");
  112. return r != null && "true".equalsIgnoreCase(String.valueOf(r).trim());
  113. }
  114. public static String messageOf(JSONObject result) {
  115. if (result == null) {
  116. return "请求失败或无响应(服务端接口可能未上线)";
  117. }
  118. String m = result.getString("message");
  119. return m == null || m.isEmpty() ? "失败" : m;
  120. }
  121. public static String dataStr(JSONObject result, String key) {
  122. if (result == null || key == null) {
  123. return "";
  124. }
  125. JSONObject data = result.getJSONObject("data");
  126. if (data == null) {
  127. return nvl(result.getString(key));
  128. }
  129. return nvl(data.getString(key));
  130. }
  131. public static int dataInt(JSONObject result, String key, int def) {
  132. if (result == null || key == null) {
  133. return def;
  134. }
  135. JSONObject data = result.getJSONObject("data");
  136. Object raw = data != null ? data.get(key) : result.get(key);
  137. if (raw == null) {
  138. return def;
  139. }
  140. try {
  141. return Integer.parseInt(String.valueOf(raw).trim());
  142. } catch (Exception e) {
  143. return def;
  144. }
  145. }
  146. private static JSONObject post(String serverIp, String path, Map<String, String> fields) {
  147. try {
  148. String url = "http://" + nvl(serverIp) + ":8980" + path;
  149. String body = toForm(fields);
  150. log.debug("dc POST {} body={}", path, body);
  151. String raw = MesApiClient.doPost(url, body);
  152. if (raw == null || raw.isEmpty() || "false".equalsIgnoreCase(raw.trim())) {
  153. return null;
  154. }
  155. return JSONObject.parseObject(raw);
  156. } catch (Exception e) {
  157. log.debug("dc 请求异常 path={} err={}", path, e.getMessage());
  158. return null;
  159. }
  160. }
  161. /** JSON POST(过程参数采样) */
  162. private static JSONObject postJson(String serverIp, String path, JSONObject body) {
  163. HttpURLConnection connection = null;
  164. InputStream is = null;
  165. OutputStream os = null;
  166. BufferedReader br = null;
  167. try {
  168. String url = "http://" + nvl(serverIp) + ":8980" + path;
  169. String json = body == null ? "{}" : body.toJSONString();
  170. log.debug("dc JSON POST {} body={}", path, json);
  171. connection = (HttpURLConnection) new URL(url).openConnection();
  172. connection.setRequestMethod("POST");
  173. connection.setConnectTimeout(15000);
  174. connection.setReadTimeout(60000);
  175. connection.setDoOutput(true);
  176. connection.setDoInput(true);
  177. connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
  178. os = connection.getOutputStream();
  179. os.write(json.getBytes("UTF-8"));
  180. if (connection.getResponseCode() != 200) {
  181. log.warn("HTTP {} => {}", url, Integer.valueOf(connection.getResponseCode()));
  182. return null;
  183. }
  184. is = connection.getInputStream();
  185. br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  186. StringBuilder sbf = new StringBuilder();
  187. String temp;
  188. while ((temp = br.readLine()) != null) {
  189. sbf.append(temp);
  190. }
  191. String raw = sbf.toString();
  192. if (raw.isEmpty()) {
  193. return null;
  194. }
  195. return JSONObject.parseObject(raw);
  196. } catch (Exception e) {
  197. log.debug("dc JSON 请求异常 path={} err={}", path, e.getMessage());
  198. return null;
  199. } finally {
  200. if (br != null) {
  201. try {
  202. br.close();
  203. } catch (IOException ignored) {
  204. }
  205. }
  206. if (os != null) {
  207. try {
  208. os.close();
  209. } catch (IOException ignored) {
  210. }
  211. }
  212. if (is != null) {
  213. try {
  214. is.close();
  215. } catch (IOException ignored) {
  216. }
  217. }
  218. if (connection != null) {
  219. connection.disconnect();
  220. }
  221. }
  222. }
  223. private static String toForm(Map<String, String> fields) throws UnsupportedEncodingException {
  224. StringBuilder sb = new StringBuilder();
  225. sb.append("__ajax=json");
  226. if (fields != null) {
  227. for (Map.Entry<String, String> e : fields.entrySet()) {
  228. if (e.getKey() == null) {
  229. continue;
  230. }
  231. sb.append('&').append(URLEncoder.encode(e.getKey(), "UTF-8"));
  232. sb.append('=').append(URLEncoder.encode(nvl(e.getValue()), "UTF-8"));
  233. }
  234. }
  235. return sb.toString();
  236. }
  237. private static String nvl(String s) {
  238. return s == null ? "" : s.trim();
  239. }
  240. }