package com.mes.device; import com.alibaba.fastjson2.JSONObject; import com.mes.util.HttpUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Properties; /** * 工位客户端设备状态上报(按 gw + lineSn) */ public class DeviceStateReporter { public static final Logger log = LoggerFactory.getLogger(DeviceStateReporter.class); /** 正常运行 */ public static final String STATE_RUNNING = "1"; /** 工位退出/收班 */ public static final String STATE_STOP = "7"; private static DeviceStateReporter instance; private String serverIp; private String gw; private String lineSn; private DeviceStateReporter() { } public static DeviceStateReporter getInstance() { if (instance == null) { synchronized (DeviceStateReporter.class) { if (instance == null) { instance = new DeviceStateReporter(); } } } return instance; } /** * 从配置文件初始化 */ public void initFromConfig() { try { InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties"); Properties pro = new Properties(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); pro.load(br); br.close(); is.close(); init( pro.getProperty("mes.server_ip", "").trim(), pro.getProperty("mes.gw", "").trim(), pro.getProperty("mes.line_sn", "").trim() ); } catch (Exception e) { log.error("初始化设备状态上报失败", e); } } public void init(String serverIp, String gw, String lineSn) { this.serverIp = serverIp; this.gw = gw; this.lineSn = lineSn; log.info("设备状态上报初始化: gw={}, lineSn={}", gw, lineSn); } /** * 异步上报 */ public void reportAsync(final String state, final String content) { new Thread(new Runnable() { @Override public void run() { reportSync(state, content); } }, "device-state-report-thread").start(); } /** * 同步上报 */ public boolean reportSync(String state, String content) { if (isBlank(serverIp) || isBlank(gw) || isBlank(lineSn)) { log.warn("设备状态上报跳过:配置不完整 serverIp={}, gw={}, lineSn={}", serverIp, gw, lineSn); return false; } try { String url = "http://" + serverIp + ":8980/js/a/mes/mesDevice/reportState"; JSONObject body = new JSONObject(); body.put("gw", gw); body.put("lineSn", lineSn); body.put("state", state); body.put("content", content == null ? "" : content); String result = HttpUtils.sendPostRequestJson(url, body.toJSONString()); log.info("设备状态上报: state={}, content={}, result={}", state, content, result); if (isBlank(result) || "false".equalsIgnoreCase(result)) { return false; } JSONObject retObj = JSONObject.parseObject(result); return retObj != null && "true".equalsIgnoreCase(String.valueOf(retObj.get("result"))); } catch (Exception e) { log.error("设备状态上报异常: state={}, content={}", state, content, e); return false; } } private boolean isBlank(String value) { return value == null || value.trim().isEmpty(); } }