package top.haijunit.train.service; import cn.hutool.core.convert.Convert; import cn.hutool.core.util.StrUtil; import cn.hutool.http.HttpStatus; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import top.haijunit.common.exception.ServiceException; import top.haijunit.train.device.entity.DeviceEntity; import top.haijunit.train.device.repository.DeviceRepository; import top.haijunit.train.socket.CommandEnum; import top.haijunit.train.socket.SocketDevice; import java.lang.reflect.InvocationTargetException; import java.util.List; /** * @author zhanghaijun * @date 2023/11/27 17:11 * @description [一句话描述该类的功能] */ @Slf4j @Service @RequiredArgsConstructor public class DeviceService { private final DeviceRepository deviceRepository; public DeviceEntity updateDevice(String msgStr) { JSONObject message = JSONUtil.parseObj(msgStr); if (!message.containsKey("cmd")) { throw new ServiceException(500, String.format("cmd指令解析失败,message:%s", msgStr)); } CommandEnum commandEnum = CommandEnum.getByCode(Convert.toInt(message.get("cmd"), 0)); if (null != commandEnum && null != commandEnum.getClassType()) { try { JSONObject data = JSONUtil.parseObj(message.get("data")); SocketDevice.DeviceBase deviceBase = commandEnum.getClassType().getDeclaredConstructor().newInstance(); String code = Convert.toStr(data.get(deviceBase.getCodeName()), ""); String status = Convert.toStr(data.get(deviceBase.getStatusName()), ""); String other = Convert.toStr(data.get(deviceBase.getOtherName()), ""); if (!StrUtil.isAllNotBlank(code, status)) { throw new ServiceException(HttpStatus.HTTP_INTERNAL_ERROR, String.format("缺少字段: message:%s, code: %s, status: %s", msgStr, deviceBase.getCodeName(), deviceBase.getStatusName())); } return updateDevice(commandEnum, code, status, other); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new ServiceException(HttpStatus.HTTP_INTERNAL_ERROR, String.format("设备信息解析失败,原因:%s", e.getMessage())); } } else { throw new ServiceException(HttpStatus.HTTP_INTERNAL_ERROR, String.format("未能解析消息内容,message:%s", message)); } } public DeviceEntity updateDevice(CommandEnum command, String code, String status, String other) { List list = deviceRepository.findByCode(code); deviceRepository.deleteAll(list); DeviceEntity device = new DeviceEntity(); device.setCommand(command); device.setCode(code); device.setStatus(status); device.setOther(other); deviceRepository.save(device); return device; } }