| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310 |
- package com.usky.sas.mqtt;
- import cn.hutool.core.bean.BeanUtil;
- import cn.hutool.core.collection.CollUtil;
- import cn.hutool.core.util.IdUtil;
- import cn.hutool.core.util.StrUtil;
- import cn.hutool.http.HttpUtil;
- import cn.hutool.json.JSONUtil;
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.fasterxml.jackson.databind.DeserializationFeature;
- import com.fasterxml.jackson.databind.JsonNode;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.usky.sas.common.enums.SystemTypeCodeEnum;
- import com.usky.sas.common.global.SasWebSocket;
- import com.usky.sas.domain.*;
- import com.usky.sas.mapper.*;
- import com.usky.sas.mqtt.dto.*;
- import com.usky.sas.service.*;
- import com.usky.sas.service.dto.agbox.JsonRpcRequest;
- import com.usky.sas.service.vo.*;
- import lombok.extern.slf4j.Slf4j;
- import org.eclipse.paho.client.mqttv3.*;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import javax.annotation.PostConstruct;
- import javax.annotation.PreDestroy;
- import java.time.LocalDateTime;
- import java.time.format.DateTimeFormatter;
- import java.util.Arrays;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.stream.Collectors;
- @Slf4j
- @Service
- public class MqttService {
- @Value("${mqtt.client-id:sas-client-${random.uuid}}")
- private String clientId;
- @Value("${mqtt.topics:}")
- private String topics;
- private MqttClient client;
- private volatile boolean isListening = true;
- private final ObjectMapper mapper = new ObjectMapper()
- .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
- @Autowired
- private SasUsbEventService usbEventService;
- @Autowired
- private SasSnapEventService snapEventService;
- @Autowired
- private SasEntranceEventService entranceEventService;
- @Autowired
- private SasParkingEventService parkingEventService;
- @Autowired
- private SasRoadblockEventService roadblockEventService;
- @Autowired
- private SasAlarsasEventService alarsasEventService;
- @Autowired
- private SasPatrolEventService patrolEventService;
- @Autowired
- private SasAcquisitionEventService acquisitionEventService;
- @Autowired
- private SasPerceptionEventService perceptionEventService;
- @Autowired
- private SasCollectionEventService collectionEventService;
- @Autowired
- private SasConfigService sasConfigService;
- @Autowired
- private SasDeviceService deviceService;
- @Autowired
- private SasEventTypeGroupService eventTypeGroupService;
- @Autowired
- private SasPatrolUserParamService sasPatrolUserParamService;
- @Autowired
- private SasGisMapper gisMapper;
-
- @Autowired
- private SasPicMapper sasPicMapper;
- // Event Code Mappers
- @Autowired
- private SasUsbEventCodeMapper usbEventCodeMapper;
- @Autowired
- private SasSnapTypeCodeMapper snapTypeCodeMapper;
- @Autowired
- private SasEntranceEventCodeMapper entranceEventCodeMapper;
- @Autowired
- private SasParkingEventCodeMapper parkingEventCodeMapper;
- @Autowired
- private SasRoadblockEventCodeMapper roadblockEventCodeMapper;
- @Autowired
- private SasAlarsasEventCodeMapper alarsasEventCodeMapper;
- @Autowired
- private SasPatrolEventCodeMapper patrolEventCodeMapper;
- @Autowired
- private SasAcquisitionEventCodeMapper acquisitionEventCodeMapper;
- @Autowired
- private SasPerceptionEventCodeMapper perceptionEventCodeMapper;
- @Autowired
- private SasCollectionEventCodeMapper collectionEventCodeMapper;
- @PostConstruct
- public void init() {
- SasConfig config = sasConfigService.getConfig();
- if (config == null || config.getHost() == null || config.getHost().isEmpty()) {
- log.warn("sas_config 中无 MQTT 配置或 host 为空,跳过 MQTT 连接");
- isListening = false;
- return;
- }
- try {
- String host = config.getHost();
- int port = parsePort(config.getPort(), 1883);
- String username = config.getUsername() != null ? config.getUsername() : "";
- String password = config.getPassword() != null ? config.getPassword() : "";
- String brokerUrl = "tcp://" + host + ":" + port;
- client = new MqttClient(brokerUrl, clientId);
- MqttConnectOptions options = new MqttConnectOptions();
- options.setCleanSession(true);
- if (!username.isEmpty()) {
- options.setUserName(username);
- options.setPassword(password.toCharArray());
- }
- options.setConnectionTimeout(60);
- options.setKeepAliveInterval(60);
- options.setAutomaticReconnect(true);
- client.setCallback(new MqttCallbackExtended() {
- @Override
- public void connectComplete(boolean reconnect, String serverURI) {
- log.info("MQTT连接成功, reconnect={}", reconnect);
- parseTopics().forEach(MqttService.this::subscribe);
- isListening = true;
- }
- @Override
- public void connectionLost(Throwable cause) {
- log.error("MQTT连接丢失: {}", cause.getMessage());
- isListening = false;
- scheduleReconnect();
- }
- @Override
- public void messageArrived(String topic, MqttMessage message) throws Exception {
- if (isListening) {
- processMessage(topic, message);
- }
- }
- @Override
- public void deliveryComplete(IMqttDeliveryToken token) {
- }
- });
- client.connect(options);
- log.info("MQTT客户端初始化完成, clientId={}", clientId);
- isListening = true;
- } catch (MqttException e) {
- log.error("MQTT初始化失败: {}", e.getMessage(), e);
- isListening = false;
- }
- }
- private static int parsePort(String portStr, int defaultPort) {
- if (portStr == null || portStr.isEmpty()) {
- return defaultPort;
- }
- try {
- return Integer.parseInt(portStr.trim());
- } catch (NumberFormatException e) {
- return defaultPort;
- }
- }
- private void scheduleReconnect() {
- Thread t = new Thread(() -> {
- try {
- Thread.sleep(5000L);
- if (client != null && !client.isConnected()) {
- log.info("尝试主动重连MQTT...");
- client.reconnect();
- }
- } catch (Exception e) {
- log.error("MQTT主动重连失败", e);
- }
- }, "mqtt-reconnect");
- t.setDaemon(true);
- t.start();
- }
- private List<String> parseTopics() {
- return Arrays.asList(topics.split(","));
- }
- private void processMessage(String topic, MqttMessage message) {
- String payload = new String(message.getPayload());
- log.debug("收到MQTT消息, topic={}, payload={}", topic, payload);
- try {
- String[] parts = topic.split("/");
- if (parts.length < 2) {
- log.warn("未知的topic格式: {}", topic);
- return;
- }
- String eventType = null;
- for (int i = 0; i < parts.length - 1; i++) {
- if ("event".equals(parts[i]) && i + 1 < parts.length) {
- eventType = parts[i + 1];
- break;
- }
- }
- if (eventType == null) {
- log.warn("无法从topic解析事件类型: {}", topic);
- return;
- }
- switch (eventType) {
- case "usbalarm":
- handleUsbEvent(payload, topic);
- break;
- case "snap":
- handleSnapEvent(payload, topic);
- break;
- case "entrance":
- handleEntranceEvent(payload, topic);
- break;
- case "parking":
- handleParkingEvent(payload, topic);
- break;
- case "roadblock":
- handleRoadblockEvent(payload, topic);
- break;
- case "alarm":
- handleAlarsasEvent(payload, topic);
- break;
- case "patrol":
- handlePatrolEvent(payload, topic);
- break;
- case "acquisition":
- handleAcquisitionEvent(payload, topic);
- break;
- case "perception":
- handlePerceptionEvent(payload, topic);
- break;
- case "collection":
- handleCollectionEvent(payload, topic);
- break;
- default:
- log.warn("未知的事件类型: {}, topic={}", eventType, topic);
- }
- } catch (Exception e) {
- log.error("处理MQTT消息失败, topic={}", topic, e);
- }
- }
- /**
- * 【已修改】只根据 deviceId + deviceTypeCode 查询,不判断 channel
- */
- private SasDevice findDevice(String deviceId, Integer deviceTypeCode) {
- return deviceService.getOne(new LambdaQueryWrapper<SasDevice>()
- .eq(SasDevice::getDeviceId, deviceId)
- .eq(SasDevice::getDeviceType, deviceTypeCode)
- .last("limit 1"));
- }
- /**
- * 兼容旧调用(自动忽略 channel)
- */
- private SasDevice findDevice(String deviceId, Integer channel, Integer deviceTypeCode) {
- return findDevice(deviceId, deviceTypeCode);
- }
- /**
- * 查询事件类型分组信息
- */
- private SasEventTypeGroup findEventTypeGroup(Integer deviceTypeCode) {
- return eventTypeGroupService.getOne(new LambdaQueryWrapper<SasEventTypeGroup>()
- .eq(SasEventTypeGroup::getDeviceType, deviceTypeCode)
- .last("limit 1"));
- }
- @Transactional(rollbackFor = Exception.class)
- public void handleUsbEvent(String payload, String topic) {
- try {
- JsonNode root = mapper.readTree(payload);
- String method = root.path("method").asText();
- if ("event".equals(method)) {
- UsbEventMessage message = mapper.readValue(payload, UsbEventMessage.class);
- if(message.getEventCode() == null && root.get("code") != null) {
- message.setEventCode(root.get("code").asInt());
- }
- SasDevice device = findDevice(message.getDeviceId(), SystemTypeCodeEnum.usb.getCode());
- if (device == null) {
- log.warn("设备不存在,丢弃USB事件: deviceId={}", message.getDeviceId());
- return;
- }
- SasUsbEvent event = new SasUsbEvent();
- String eventId = message.getId() != null && !message.getId().isEmpty()
- ? message.getId()
- : IdUtil.randomUUID();
- if (usbEventService.getById(eventId) != null) {
- log.info("USB事件已存在, 跳过保存, eventId={}", eventId);
- return;
- }
- event.setEventId(eventId);
- BeanUtil.copyProperties(message, event, "eventId");
- event.setCardId(message.getIcId());
- event.setTriggerTime(parseTime(message.getTriggerTime()));
- event.setCreateTime(LocalDateTime.now());
- event.setUpdateTime(LocalDateTime.now());
- if (message.getEventPic() != null) {
- UsbEventMessage.PicInfo picInfo = message.getEventPic();
- if (picInfo != null && StrUtil.isNotBlank(picInfo.getUrl()) && StrUtil.isNotBlank(picInfo.getPath())) {
- SasPic pic = new SasPic();
- pic.setId(IdUtil.randomUUID());
- pic.setUrl(picInfo.getUrl());
- pic.setPath(picInfo.getPath());
- pic.setCreateTime(LocalDateTime.now());
- pic.setUpdateTime(LocalDateTime.now());
- sasPicMapper.insert(pic);
- event.setPicId(pic.getId());
- }
- }
- usbEventService.save(event);
- BrieflyEventInfo info = BeanUtil.toBean(event, BrieflyEventInfo.class);
- info.setTriggerTime(message.getTriggerTime());
- info.setCreateTime(LocalDateTime.now().format(formatter));
- if (event.getPicId() != null) {
- SasPic pic = sasPicMapper.selectById(event.getPicId());
- if (pic != null && StrUtil.isNotBlank(pic.getUrl()) && StrUtil.isNotBlank(pic.getPath())) {
- info.setEventUrl(pic.getUrl() + pic.getPath());
- }
- }
- SasUsbEventCode code = usbEventCodeMapper.selectById(event.getEventCode());
- if (code != null) {
- info.setEventTypeName(code.getName());
- }
- enrichDeviceInfo(info, device);
- SasEventTypeGroup eventTypeGroup = findEventTypeGroup(SystemTypeCodeEnum.usb.getCode());
- if (eventTypeGroup != null) {
- info.setEventLevelId(eventTypeGroup.getEventLevel());
- }
- info.setDeviceType(SystemTypeCodeEnum.usb.getCode());
- SasWebSocket.sendAll(info);
- log.info("USB事件保存并推送成功, eventId={}", event.getEventId());
- } else if ("heart".equals(method)) {
- handleHeartbeat(payload, SystemTypeCodeEnum.usb.getCode());
- }
- } catch (Exception e) {
- log.error("处理USB事件失败", e);
- }
- }
- @Transactional(rollbackFor = Exception.class)
- public void handleSnapEvent(String payload, String topic) {
- try {
- JsonNode root = mapper.readTree(payload);
- String method = root.path("method").asText();
- if ("event".equals(method)) {
- SnapEventResult eventResult = (SnapEventResult)this.mapper.readValue(payload, SnapEventResult.class);
- log.info("实时智能分析");
- Map<String, Object> map = new HashMap();
- map.put("eventId", eventResult.getId());
- JsonRpcRequest getEventInfoJson = new JsonRpcRequest("getEvent", map, (Long)null);
- Map<String, Object> getEventInfo = new HashMap();
- getEventInfo.put("key", this.sasConfigService.getConfig().getKeyds());
- getEventInfo.put("json", getEventInfoJson.toString());
- log.info("请求AG报文:{}", JSONUtil.toJsonStr(getEventInfo));
- String resultEvent = HttpUtil.post(this.sasConfigService.getConfig().getHost() + "/agbox/device/snap", getEventInfo);
- log.info("请求AG响应:{}", resultEvent);
- SnapEventInfoVo eventInfoVo = (SnapEventInfoVo)this.mapper.readValue(resultEvent, SnapEventInfoVo.class);
- SnapEventInfoResult result = eventInfoVo.getResult();
- SnapEventInfo eventInfo = result.getEventInfo();
- SasSnapEvent bean = (SasSnapEvent)BeanUtil.toBean(eventInfo, SasSnapEvent.class);
- String eventId = eventResult.getId() != null && !eventResult.getId().isEmpty()
- ? eventResult.getId()
- : IdUtil.randomUUID();
- if (snapEventService.getById(eventId) != null) {
- log.info("抓拍事件已存在, 跳过保存, eventId={}", eventId);
- return;
- }
- bean.setEventId(eventId);
- BrieflyEventInfo info = (BrieflyEventInfo)BeanUtil.toBeanIgnoreError(bean, BrieflyEventInfo.class);
- if (eventInfo.getEventPic() != null) {
- SasPic pic = (SasPic)BeanUtil.toBean(eventInfo.getEventPic(), SasPic.class);
- pic.setId(IdUtil.randomUUID());
- this.sasPicMapper.insert(pic);
- bean.setEventPicId(pic.getId());
- info.setEventUrl(pic.getUrl() + pic.getPath());
- }
- if (eventInfo.getScenePic() != null) {
- SasPic pic = (SasPic)BeanUtil.toBean(eventInfo.getScenePic(), SasPic.class);
- pic.setId(IdUtil.randomUUID());
- this.sasPicMapper.insert(pic);
- bean.setScenePicId(pic.getId());
- info.setSceneUrl(pic.getUrl() + pic.getPath());
- }
- if(eventInfo.getEventCode() == null && root.get("code") != null) {
- eventInfo.setEventCode(root.get("code").asInt());
- }
- SasDevice device = findDevice(eventInfo.getDeviceId(), SystemTypeCodeEnum.snap.getCode());
- if (device == null) {
- log.warn("设备不存在,丢弃抓拍事件: deviceId={}", eventInfo.getDeviceId());
- return;
- }
- BeanUtil.copyProperties(eventInfo, bean, "eventId");
- bean.setTriggerTime(parseTime(eventInfo.getTriggerTime()));
- bean.setCreateTime(LocalDateTime.now());
- bean.setUpdateTime(LocalDateTime.now());
- snapEventService.save(bean);
- info.setTriggerTime(eventInfo.getTriggerTime());
- info.setCreateTime(LocalDateTime.now().format(formatter));
- SasSnapTypeCode code = snapTypeCodeMapper.selectById(bean.getEventCode());
- if (code != null) {
- info.setEventTypeName(code.getName());
- }
- enrichDeviceInfo(info, device);
- SasEventTypeGroup eventTypeGroup = findEventTypeGroup(SystemTypeCodeEnum.snap.getCode());
- if (eventTypeGroup != null) {
- info.setEventLevelId(eventTypeGroup.getEventLevel());
- }
- info.setDeviceType(SystemTypeCodeEnum.snap.getCode());
- SasWebSocket.sendAll(info);
- log.info("抓拍事件保存并推送成功, eventId={}", bean.getEventId());
- } else if ("heart".equals(method)) {
- handleHeartbeat(payload, SystemTypeCodeEnum.snap.getCode());
- }
- } catch (Exception e) {
- log.error("处理抓拍事件失败", e);
- }
- }
- @Transactional(rollbackFor = Exception.class)
- public void handleEntranceEvent(String payload, String topic) {
- try {
- JsonNode root = mapper.readTree(payload);
- String method = root.path("method").asText();
- if ("event".equals(method)) {
- EntranceEventMessage message = mapper.readValue(payload, EntranceEventMessage.class);
- if(message.getEventCode() == null && root.get("code") != null) {
- message.setEventCode(root.get("code").asInt());
- }
- SasDevice device = findDevice(message.getDeviceId(), SystemTypeCodeEnum.entrance.getCode());
- if (device == null) {
- log.warn("设备不存在,丢弃门禁事件: deviceId={}", message.getDeviceId());
- return;
- }
- SasEntranceEvent event = new SasEntranceEvent();
- String eventId = message.getId() != null && !message.getId().isEmpty()
- ? message.getId()
- : IdUtil.randomUUID();
- // 如果该事件已存在(设备重发/重复消息),避免主键冲突,直接跳过
- if (entranceEventService.getById(eventId) != null) {
- log.info("门禁事件已存在, 跳过保存, eventId={}", eventId);
- return;
- }
- event.setEventId(eventId);
- BeanUtil.copyProperties(message, event, "eventId");
- event.setCardId(message.getIcId());
- event.setTriggerTime(parseTime(message.getTriggerTime()));
- event.setCreateTime(LocalDateTime.now());
- event.setUpdateTime(LocalDateTime.now());
- // 处理图片信息
- if (message.getEntrancePic() != null) {
- EntranceEventMessage.PicInfo picInfo = message.getEntrancePic();
- if (picInfo != null && StrUtil.isNotBlank(picInfo.getUrl()) && StrUtil.isNotBlank(picInfo.getPath())) {
- SasPic pic = new SasPic();
- pic.setId(IdUtil.randomUUID());
- pic.setUrl(picInfo.getUrl());
- pic.setPath(picInfo.getPath());
- pic.setCreateTime(LocalDateTime.now());
- pic.setUpdateTime(LocalDateTime.now());
- sasPicMapper.insert(pic);
-
- // 设置事件图片ID
- event.setPicId(pic.getId());
- }
- }
- entranceEventService.save(event);
- BrieflyEventInfo info = BeanUtil.toBean(event, BrieflyEventInfo.class);
- info.setTriggerTime(message.getTriggerTime());
- info.setCreateTime(LocalDateTime.now().format(formatter));
-
- // 设置图片URL(如果有)
- if (event.getPicId() != null) {
- SasPic pic = sasPicMapper.selectById(event.getPicId());
- if (pic != null && StrUtil.isNotBlank(pic.getUrl()) && StrUtil.isNotBlank(pic.getPath())) {
- info.setEventUrl(pic.getUrl() + pic.getPath());
- }
- }
-
- SasEntranceEventCode code = entranceEventCodeMapper.selectById(event.getEventCode());
- if (code != null) {
- info.setEventTypeName(code.getName());
- }
- enrichDeviceInfo(info, device);
- SasEventTypeGroup eventTypeGroup = findEventTypeGroup(SystemTypeCodeEnum.entrance.getCode());
- if (eventTypeGroup != null) {
- info.setEventLevelId(eventTypeGroup.getEventLevel());
- }
- info.setDeviceType(SystemTypeCodeEnum.entrance.getCode());
- SasWebSocket.sendAll(info);
- log.info("门禁事件保存并推送成功, eventId={}", event.getEventId());
- } else if ("heart".equals(method)) {
- handleHeartbeat(payload, SystemTypeCodeEnum.entrance.getCode());
- }
- } catch (Exception e) {
- log.error("处理门禁事件失败", e);
- }
- }
- @Transactional(rollbackFor = Exception.class)
- public void handleParkingEvent(String payload, String topic) {
- try {
- JsonNode root = mapper.readTree(payload);
- String method = root.path("method").asText();
- if ("event".equals(method)) {
- ParkingEventResult eventResult = this.mapper.readValue(payload, ParkingEventResult.class);
- SasConfig config = sasConfigService.getConfig();
- if (config == null || StrUtil.isBlank(config.getHost()) || StrUtil.isBlank(config.getKeyds())) {
- log.error("停车场事件处理失败:系统配置未初始化或host/keyds为空");
- return;
- }
- Map<String, Object> map = new HashMap<>();
- map.put("eventId", eventResult.getId());
- JsonRpcRequest getParkingEventInfoJson = new JsonRpcRequest("getEvent", map, (Long)null);
- Map<String, Object> getParkingEventInfo = new HashMap<>();
- getParkingEventInfo.put("key", config.getKeyds());
- getParkingEventInfo.put("json", getParkingEventInfoJson.toString());
- log.info("请求AG报文:{}", JSONUtil.toJsonStr(getParkingEventInfo));
- String resultEvent = HttpUtil.post(config.getHost() + "/agbox/device/parking", getParkingEventInfo);
- log.info("请求AG响应:{}", resultEvent);
- if (StrUtil.isBlank(resultEvent)) {
- log.error("停车场事件:AG接口返回空字符串,终止处理");
- return;
- }
- ParkingEventInfoVo parkingEventInfoVo = this.mapper.readValue(resultEvent, ParkingEventInfoVo.class);
- if (parkingEventInfoVo == null) {
- log.error("停车场事件:解析返回结果为null,响应:{}", resultEvent);
- return;
- }
- ParkingEventInfoResult result = parkingEventInfoVo.getResult();
- if (result == null) {
- log.error("停车场事件:返回结果result为null,响应:{}", resultEvent);
- return;
- }
- ParkingEventInfo eventInfo = result.getEventInfo();
- if (eventInfo == null) {
- log.error("停车场事件:eventInfo为null,响应:{}", resultEvent);
- return;
- }
- SasParkingEvent bean = BeanUtil.toBean(eventInfo, SasParkingEvent.class);
- bean.setCreateTime(LocalDateTime.parse(eventInfo.getReceivingTime(), this.formatter));
- bean.setTriggerTime(LocalDateTime.parse(eventInfo.getTriggerTime(), this.formatter));
- bean.setEventId(eventResult.getId());
- bean.setAccessType(eventInfo.getIo());
- bean.setCarType(eventInfo.getCarCode());
- bean.setPlateType(eventInfo.getPlateCode());
- if (eventInfo.getEventPic() != null) {
- SasPic pic = BeanUtil.toBean(eventInfo.getEventPic(), SasPic.class);
- pic.setId(IdUtil.randomUUID());
- this.sasPicMapper.insert(pic);
- bean.setEventPicId(pic.getId());
- }
- if (eventInfo.getPlacePic() != null) {
- SasPic pic = BeanUtil.toBean(eventInfo.getPlacePic(), SasPic.class);
- pic.setId(IdUtil.randomUUID());
- this.sasPicMapper.insert(pic);
- bean.setPlatePicId(pic.getId());
- }
- if (eventInfo.getEventCode() == null && root.get("code") != null) {
- eventInfo.setEventCode(root.get("code").asInt());
- }
- SasDevice device = findDevice(eventInfo.getDeviceId(), SystemTypeCodeEnum.parking.getCode());
- if (device == null) {
- log.warn("设备不存在,丢弃停车场事件: deviceId={}", eventInfo.getDeviceId());
- return;
- }
- SasParkingEvent event = new SasParkingEvent();
- String eventId = StrUtil.isNotBlank(eventResult.getId()) ? eventResult.getId() : IdUtil.randomUUID();
- if (parkingEventService.getById(eventId) != null) {
- log.info("停车场事件已存在, 跳过保存, eventId={}", eventId);
- return;
- }
- event.setEventId(eventId);
- BeanUtil.copyProperties(eventInfo, event, "eventId");
- event.setTriggerTime(parseTime(eventInfo.getTriggerTime()));
- event.setCreateTime(LocalDateTime.now());
- event.setUpdateTime(LocalDateTime.now());
- parkingEventService.save(event);
- BrieflyEventInfo info = BeanUtil.toBean(event, BrieflyEventInfo.class);
- info.setTriggerTime(eventInfo.getTriggerTime());
- info.setCreateTime(LocalDateTime.now().format(formatter));
- if (eventInfo.getEventPic() != null) {
- info.setEventUrl(eventInfo.getEventPic().getUrl() + eventInfo.getEventPic().getPath());
- }
- if (eventInfo.getPlacePic() != null) {
- info.setEventUrl(eventInfo.getPlacePic().getUrl() + eventInfo.getPlacePic().getPath());
- }
- SasParkingEventCode code = parkingEventCodeMapper.selectById(event.getEventCode());
- if (code != null) {
- info.setEventTypeName(code.getName());
- }
- enrichDeviceInfo(info, device);
- SasEventTypeGroup eventTypeGroup = findEventTypeGroup(SystemTypeCodeEnum.parking.getCode());
- if (eventTypeGroup != null) {
- info.setEventLevelId(eventTypeGroup.getEventLevel());
- }
- info.setDeviceType(SystemTypeCodeEnum.parking.getCode());
- SasWebSocket.sendAll(info);
- log.info("停车场事件保存并推送成功, eventId={}", event.getEventId());
- } else if ("heart".equals(method)) {
- handleHeartbeat(payload, SystemTypeCodeEnum.parking.getCode());
- }
- } catch (Exception e) {
- log.error("处理停车场事件失败", e);
- }
- }
- @Transactional(rollbackFor = Exception.class)
- public void handleRoadblockEvent(String payload, String topic) {
- try {
- JsonNode root = mapper.readTree(payload);
- String method = root.path("method").asText();
- if ("event".equals(method)) {
- RoadblockEventMessage message = mapper.readValue(payload, RoadblockEventMessage.class);
- if(message.getEventCode() == null && root.get("code") != null) {
- message.setEventCode(root.get("code").asInt());
- }
- SasDevice device = findDevice(message.getDeviceId(), SystemTypeCodeEnum.roadblock.getCode());
- if (device == null) {
- log.warn("设备不存在,丢弃阻车路障事件: deviceId={}", message.getDeviceId());
- return;
- }
- SasRoadblockEvent event = new SasRoadblockEvent();
- String eventId = message.getId() != null && !message.getId().isEmpty()
- ? message.getId()
- : IdUtil.randomUUID();
- if (roadblockEventService.getById(eventId) != null) {
- log.info("阻车路障事件已存在, 跳过保存, eventId={}", eventId);
- return;
- }
- event.setEventId(eventId);
- BeanUtil.copyProperties(message, event, "eventId");
- event.setTriggerTime(parseTime(message.getTriggerTime()));
- event.setCreateTime(LocalDateTime.now());
- event.setUpdateTime(LocalDateTime.now());
- if (message.getRoadblockPic() != null) {
- RoadblockEventMessage.PicInfo picInfo = message.getRoadblockPic();
- if (picInfo != null && StrUtil.isNotBlank(picInfo.getUrl()) && StrUtil.isNotBlank(picInfo.getPath())) {
- SasPic pic = new SasPic();
- pic.setId(IdUtil.randomUUID());
- pic.setUrl(picInfo.getUrl());
- pic.setPath(picInfo.getPath());
- pic.setCreateTime(LocalDateTime.now());
- pic.setUpdateTime(LocalDateTime.now());
- sasPicMapper.insert(pic);
- event.setPicId(pic.getId());
- }
- }
- roadblockEventService.save(event);
- BrieflyEventInfo info = BeanUtil.toBean(event, BrieflyEventInfo.class);
- info.setTriggerTime(message.getTriggerTime());
- info.setCreateTime(LocalDateTime.now().format(formatter));
- if (event.getPicId() != null) {
- SasPic pic = sasPicMapper.selectById(event.getPicId());
- if (pic != null && StrUtil.isNotBlank(pic.getUrl()) && StrUtil.isNotBlank(pic.getPath())) {
- info.setEventUrl(pic.getUrl() + pic.getPath());
- }
- }
- SasRoadblockEventCode code = roadblockEventCodeMapper.selectById(event.getEventCode());
- if (code != null) {
- info.setEventTypeName(code.getName());
- }
- enrichDeviceInfo(info, device);
- SasEventTypeGroup eventTypeGroup = findEventTypeGroup(SystemTypeCodeEnum.roadblock.getCode());
- if (eventTypeGroup != null) {
- info.setEventLevelId(eventTypeGroup.getEventLevel());
- }
- info.setDeviceType(SystemTypeCodeEnum.roadblock.getCode());
- SasWebSocket.sendAll(info);
- log.info("阻车路障事件保存并推送成功, eventId={}", event.getEventId());
- } else if ("heart".equals(method)) {
- handleHeartbeat(payload, SystemTypeCodeEnum.roadblock.getCode());
- }
- } catch (Exception e) {
- log.error("处理阻车路障事件失败", e);
- }
- }
- @Transactional(rollbackFor = Exception.class)
- public void handleAlarsasEvent(String payload, String topic) {
- try {
- JsonNode root = mapper.readTree(payload);
- String method = root.path("method").asText();
- // 【核心修复】匹配真实设备的 method: "event"
- if ("event".equals(method)) {
- // 直接从根节点读取所有字段,完全适配你真实的消息格式
- String deviceId = root.path("deviceId").asText();
- Integer channel = root.path("channel").asInt();
- Integer eventCode = root.path("code").asInt(); // 真实消息里是 code 字段!
- String id = root.path("id").asText();
- String triggerTime = root.path("triggerTime").asText();
- String note = root.path("note").asText();
- Integer eventSystem = root.path("eventSystem").asInt();
- // 打印日志,确认字段都读到了
- log.info("【入侵告警】收到消息:deviceId={}, channel={}, eventCode={}, id={}",
- deviceId, channel, eventCode, id);
- // 设备校验
- SasDevice device = findDevice(deviceId, SystemTypeCodeEnum.alarm.getCode());
- if (device == null) {
- log.warn("【入侵告警】设备不存在,丢弃消息:deviceId={}", deviceId);
- return;
- }
- // 构建事件实体
- SasAlarsasEvent event = new SasAlarsasEvent();
- String eventId = StrUtil.isNotBlank(id) ? id : IdUtil.randomUUID();
- // 防重复
- if (alarsasEventService.getById(eventId) != null) {
- log.info("【入侵告警】事件已存在,跳过保存:eventId={}", eventId);
- return;
- }
- // 手动赋值,100% 不会丢字段
- event.setEventId(eventId);
- event.setDeviceId(deviceId);
- event.setChannel(channel);
- event.setEventCode(eventCode);
- event.setNote(note);
- event.setEventSystem(eventSystem);
- event.setTriggerTime(parseTime(triggerTime));
- event.setCreateTime(LocalDateTime.now());
- event.setUpdateTime(LocalDateTime.now());
- // 保存到数据库
- alarsasEventService.save(event);
- log.info("【入侵告警】保存成功!eventId={}, deviceId={}, eventCode={}",
- eventId, deviceId, eventCode);
- // 后续的 WebSocket 推送逻辑(保持不变)
- BrieflyEventInfo info = BeanUtil.toBean(event, BrieflyEventInfo.class);
- info.setTriggerTime(triggerTime);
- info.setCreateTime(LocalDateTime.now().format(formatter));
- SasAlarsasEventCode code = alarsasEventCodeMapper.selectById(eventCode);
- if (code != null) {
- info.setEventTypeName(code.getName());
- }
- enrichDeviceInfo(info, device);
- SasEventTypeGroup eventTypeGroup = findEventTypeGroup(SystemTypeCodeEnum.alarm.getCode());
- if (eventTypeGroup != null) {
- info.setEventLevelId(eventTypeGroup.getEventLevel());
- }
- info.setDeviceType(SystemTypeCodeEnum.alarm.getCode());
- SasWebSocket.sendAll(info);
- } else if ("heart".equals(method)) {
- handleHeartbeat(payload, SystemTypeCodeEnum.alarm.getCode());
- }
- } catch (Exception e) {
- log.error("【入侵告警】处理失败,payload={}", payload, e);
- }
- }
- @Transactional(rollbackFor = Exception.class)
- public void handlePatrolEvent(String payload, String topic) {
- try {
- JsonNode root = mapper.readTree(payload);
- String method = root.path("method").asText();
- if ("event".equals(method)) {
- PatrolEventResult eventResult = (PatrolEventResult)this.mapper.readValue(payload, PatrolEventResult.class);
- Map<String, Object> map = new HashMap();
- map.put("eventId", eventResult.getId());
- JsonRpcRequest getPatrolEventInfoJson = new JsonRpcRequest("getEvent", map, (Long)null);
- Map<String, Object> getPatrolEventInfo = new HashMap();
- getPatrolEventInfo.put("key", this.sasConfigService.getConfig().getKeyds());
- getPatrolEventInfo.put("json", getPatrolEventInfoJson.toString());
- log.info("请求AG报文:{}", JSONUtil.toJsonStr(getPatrolEventInfo));
- String resultEvent = HttpUtil.post(this.sasConfigService.getConfig().getHost() + "/agbox/device/patrol", getPatrolEventInfo);
- log.info("请求AG响应:{}", resultEvent);
- PatrolEventInfoVo patrolEventInfoVo = (PatrolEventInfoVo)this.mapper.readValue(resultEvent, PatrolEventInfoVo.class);
- PatrolEventInfoResult result = patrolEventInfoVo.getResult();
- PatrolEventInfo eventInfo = result.getEventInfo();
- SasDevice device = findDevice(eventInfo.getDeviceId(), SystemTypeCodeEnum.patrol.getCode());
- if (device == null) {
- log.warn("设备不存在,丢弃巡检事件: deviceId={}", eventInfo.getDeviceId());
- return;
- }
- SasPatrolEvent event = new SasPatrolEvent();
- String eventId = patrolEventInfoVo.getId() != null && !patrolEventInfoVo.getId().isEmpty()
- ? patrolEventInfoVo.getId()
- : IdUtil.randomUUID();
- if (patrolEventService.getById(eventId) != null) {
- log.info("巡检事件已存在, 跳过保存, eventId={}", eventId);
- return;
- }
- event.setEventId(eventId);
- BeanUtil.copyProperties(eventInfo, event, "eventId");
- String triggerTimeStr = eventInfo.getTriggerTime().replaceAll("\\s", " ");
- event.setTriggerTime(LocalDateTime.parse(triggerTimeStr, formatter));
- event.setCreateTime(LocalDateTime.now());
- event.setUpdateTime(LocalDateTime.now());
- if (eventInfo.getEventPic() != null) {
- SasPic pic = (SasPic) BeanUtil.toBean(eventInfo.getEventPic(), SasPic.class);
- pic.setId(IdUtil.randomUUID());
- this.sasPicMapper.insert(pic);
- event.setPicId(pic.getId());
- }
- if (eventInfo.getUserParams() != null) {
- SasPatrolUserParam userParam = (SasPatrolUserParam)BeanUtil.toBean(eventInfo.getUserParams(), SasPatrolUserParam.class);
- userParam.setId(IdUtil.randomUUID());
- LocalDateTime now = LocalDateTime.now();
- userParam.setCreateTime(now);
- userParam.setUpdateTime(now);
- this.sasPatrolUserParamService.save(userParam);
- event.setUserParasasId(userParam.getId());
- }
- patrolEventService.save(event);
- BrieflyEventInfo info = BeanUtil.toBean(event, BrieflyEventInfo.class);
- info.setTriggerTime(eventInfo.getTriggerTime());
- info.setCreateTime(LocalDateTime.now().format(formatter));
- if (event.getPicId() != null) {
- SasPic pic = sasPicMapper.selectById(event.getPicId());
- if (pic != null && StrUtil.isNotBlank(pic.getUrl()) && StrUtil.isNotBlank(pic.getPath())) {
- info.setEventUrl(pic.getUrl() + pic.getPath());
- }
- }
- SasPatrolEventCode code = patrolEventCodeMapper.selectById(event.getEventCode());
- if (code != null) {
- info.setEventTypeName(code.getName());
- }
- enrichDeviceInfo(info, device);
- SasEventTypeGroup eventTypeGroup = findEventTypeGroup(SystemTypeCodeEnum.patrol.getCode());
- if (eventTypeGroup != null) {
- info.setEventLevelId(eventTypeGroup.getEventLevel());
- }
- info.setDeviceType(SystemTypeCodeEnum.patrol.getCode());
- SasWebSocket.sendAll(info);
- log.info("巡检事件保存并推送成功, eventId={}", event.getEventId());
- } else if ("heart".equals(method)) {
- handleHeartbeat(payload, SystemTypeCodeEnum.patrol.getCode());
- }
- } catch (Exception e) {
- log.error("处理巡检事件失败", e);
- }
- }
- @Transactional(rollbackFor = Exception.class)
- public void handleAcquisitionEvent(String payload, String topic) {
- try {
- JsonNode root = mapper.readTree(payload);
- String method = root.path("method").asText();
- if ("event".equals(method)) {
- AcquisitionEventMessage message = mapper.readValue(payload, AcquisitionEventMessage.class);
- if(message.getEventCode() == null && root.get("code") != null) {
- message.setEventCode(root.get("code").asInt());
- }
- SasDevice device = findDevice(message.getDeviceId(), SystemTypeCodeEnum.acquisition.getCode());
- if (device == null) {
- log.warn("设备不存在,丢弃数据采集事件: deviceId={}", message.getDeviceId());
- return;
- }
- SasAcquisitionEvent event = new SasAcquisitionEvent();
- String eventId = message.getId() != null && !message.getId().isEmpty()
- ? message.getId()
- : IdUtil.randomUUID();
- if (acquisitionEventService.getById(eventId) != null) {
- log.info("数据采集事件已存在, 跳过保存, eventId={}", eventId);
- return;
- }
- event.setEventId(eventId);
- BeanUtil.copyProperties(message, event, "eventId");
- event.setTriggerTime(parseTime(message.getTriggerTime()));
- event.setCreateTime(LocalDateTime.now());
- event.setUpdateTime(LocalDateTime.now());
- if (message.getAcquisitionPic() != null) {
- AcquisitionEventMessage.PicInfo picInfo = message.getAcquisitionPic();
- if (picInfo != null && StrUtil.isNotBlank(picInfo.getUrl()) && StrUtil.isNotBlank(picInfo.getPath())) {
- SasPic pic = new SasPic();
- pic.setId(IdUtil.randomUUID());
- pic.setUrl(picInfo.getUrl());
- pic.setPath(picInfo.getPath());
- pic.setCreateTime(LocalDateTime.now());
- pic.setUpdateTime(LocalDateTime.now());
- sasPicMapper.insert(pic);
- event.setPicId(pic.getId());
- }
- }
- acquisitionEventService.save(event);
- BrieflyEventInfo info = BeanUtil.toBean(event, BrieflyEventInfo.class);
- info.setTriggerTime(message.getTriggerTime());
- info.setCreateTime(LocalDateTime.now().format(formatter));
- if (event.getPicId() != null) {
- SasPic pic = sasPicMapper.selectById(event.getPicId());
- if (pic != null && StrUtil.isNotBlank(pic.getUrl()) && StrUtil.isNotBlank(pic.getPath())) {
- info.setEventUrl(pic.getUrl() + pic.getPath());
- }
- }
- SasAcquisitionEventCode code = acquisitionEventCodeMapper.selectById(event.getEventCode());
- if (code != null) {
- info.setEventTypeName(code.getName());
- }
- enrichDeviceInfo(info, device);
- SasEventTypeGroup eventTypeGroup = findEventTypeGroup(SystemTypeCodeEnum.acquisition.getCode());
- if (eventTypeGroup != null) {
- info.setEventLevelId(eventTypeGroup.getEventLevel());
- }
- info.setDeviceType(SystemTypeCodeEnum.acquisition.getCode());
- SasWebSocket.sendAll(info);
- log.info("数据采集事件保存并推送成功, eventId={}", event.getEventId());
- } else if ("heart".equals(method)) {
- handleHeartbeat(payload, SystemTypeCodeEnum.acquisition.getCode());
- }
- } catch (Exception e) {
- log.error("处理数据采集事件失败", e);
- }
- }
- @Transactional(rollbackFor = Exception.class)
- public void handlePerceptionEvent(String payload, String topic) {
- try {
- JsonNode root = mapper.readTree(payload);
- String method = root.path("method").asText();
- if ("event".equals(method)) {
- PerceptionEventMessage message = mapper.readValue(payload, PerceptionEventMessage.class);
- if(message.getEventCode() == null && root.get("code") != null) {
- message.setEventCode(root.get("code").asInt());
- }
- SasDevice device = findDevice(message.getDeviceId(), SystemTypeCodeEnum.perception.getCode());
- if (device == null) {
- log.warn("设备不存在,丢弃状态感知事件: deviceId={}", message.getDeviceId());
- return;
- }
- SasPerceptionEvent event = new SasPerceptionEvent();
- String eventId = message.getId() != null && !message.getId().isEmpty()
- ? message.getId()
- : IdUtil.randomUUID();
- if (perceptionEventService.getById(eventId) != null) {
- log.info("状态感知事件已存在, 跳过保存, eventId={}", eventId);
- return;
- }
- event.setEventId(eventId);
- BeanUtil.copyProperties(message, event, "eventId");
- event.setTriggerTime(parseTime(message.getTriggerTime()));
- event.setCreateTime(LocalDateTime.now());
- event.setUpdateTime(LocalDateTime.now());
- if (message.getPerceptionPic() != null) {
- PerceptionEventMessage.PicInfo picInfo = message.getPerceptionPic();
- if (picInfo != null && StrUtil.isNotBlank(picInfo.getUrl()) && StrUtil.isNotBlank(picInfo.getPath())) {
- SasPic pic = new SasPic();
- pic.setId(IdUtil.randomUUID());
- pic.setUrl(picInfo.getUrl());
- pic.setPath(picInfo.getPath());
- pic.setCreateTime(LocalDateTime.now());
- pic.setUpdateTime(LocalDateTime.now());
- sasPicMapper.insert(pic);
- event.setPicId(pic.getId());
- }
- }
- perceptionEventService.save(event);
- BrieflyEventInfo info = BeanUtil.toBean(event, BrieflyEventInfo.class);
- info.setTriggerTime(message.getTriggerTime());
- info.setCreateTime(LocalDateTime.now().format(formatter));
- if (event.getPicId() != null) {
- SasPic pic = sasPicMapper.selectById(event.getPicId());
- if (pic != null && StrUtil.isNotBlank(pic.getUrl()) && StrUtil.isNotBlank(pic.getPath())) {
- info.setEventUrl(pic.getUrl() + pic.getPath());
- }
- }
- SasPerceptionEventCode code = perceptionEventCodeMapper.selectById(event.getEventCode());
- if (code != null) {
- info.setEventTypeName(code.getName());
- }
- enrichDeviceInfo(info, device);
- SasEventTypeGroup eventTypeGroup = findEventTypeGroup(SystemTypeCodeEnum.perception.getCode());
- if (eventTypeGroup != null) {
- info.setEventLevelId(eventTypeGroup.getEventLevel());
- }
- info.setDeviceType(SystemTypeCodeEnum.perception.getCode());
- SasWebSocket.sendAll(info);
- log.info("状态感知事件保存并推送成功, eventId={}", event.getEventId());
- } else if ("heart".equals(method)) {
- handleHeartbeat(payload, SystemTypeCodeEnum.perception.getCode());
- }
- } catch (Exception e) {
- log.error("处理状态感知事件失败", e);
- }
- }
- @Transactional(rollbackFor = Exception.class)
- public void handleCollectionEvent(String payload, String topic) {
- try {
- JsonNode root = mapper.readTree(payload);
- String method = root.path("method").asText();
- if ("event".equals(method)) {
- CollectionEventMessage message = mapper.readValue(payload, CollectionEventMessage.class);
- if(message.getEventCode() == null && root.get("code") != null) {
- message.setEventCode(root.get("code").asInt());
- }
- SasDevice device = findDevice(message.getDeviceId(), SystemTypeCodeEnum.collection.getCode());
- if (device == null) {
- log.warn("设备不存在,丢弃状态采集事件: deviceId={}", message.getDeviceId());
- return;
- }
- SasCollectionEvent event = new SasCollectionEvent();
- String eventId = message.getId() != null && !message.getId().isEmpty()
- ? message.getId()
- : IdUtil.randomUUID();
- if (collectionEventService.getById(eventId) != null) {
- log.info("状态采集事件已存在, 跳过保存, eventId={}", eventId);
- return;
- }
- event.setEventId(eventId);
- BeanUtil.copyProperties(message, event, "eventId");
- event.setTriggerTime(parseTime(message.getTriggerTime()));
- event.setCreateTime(LocalDateTime.now());
- event.setUpdateTime(LocalDateTime.now());
- if (message.getScenePicInfo() != null) {
- SasPic bean = (SasPic)BeanUtil.toBean(message.getScenePicInfo(), SasPic.class);
- bean.setId(IdUtil.randomUUID());
- this.sasPicMapper.insert(bean);
- event.setScenePicId(bean.getId());
- }
- if (message.getEventPicInfo() != null) {
- SasPic bean = (SasPic)BeanUtil.toBean(message.getEventPicInfo(), SasPic.class);
- bean.setId(IdUtil.randomUUID());
- this.sasPicMapper.insert(bean);
- event.setPicId(bean.getId());
- }
- collectionEventService.save(event);
- BrieflyEventInfo info = BeanUtil.toBean(event, BrieflyEventInfo.class);
- info.setTriggerTime(message.getTriggerTime());
- info.setCreateTime(LocalDateTime.now().format(formatter));
- if (message.getEventPicInfo() != null) {
- info.setEventUrl(message.getEventPicInfo().getUrl() + message.getEventPicInfo().getPath());
- }
- if (message.getScenePicInfo() != null) {
- info.setEventUrl(message.getScenePicInfo().getUrl() + message.getScenePicInfo().getPath());
- }
- SasCollectionEventCode code = collectionEventCodeMapper.selectById(event.getEventCode());
- if (code != null) {
- info.setEventTypeName(code.getName());
- }
- enrichDeviceInfo(info, device);
- SasEventTypeGroup eventTypeGroup = findEventTypeGroup(SystemTypeCodeEnum.collection.getCode());
- if (eventTypeGroup != null) {
- info.setEventLevelId(eventTypeGroup.getEventLevel());
- }
- info.setDeviceType(SystemTypeCodeEnum.collection.getCode());
- SasWebSocket.sendAll(info);
- log.info("状态采集事件保存并推送成功, eventId={}", event.getEventId());
- } else if ("heart".equals(method)) {
- handleHeartbeat(payload, SystemTypeCodeEnum.collection.getCode());
- }
- } catch (Exception e) {
- log.error("处理状态采集事件失败", e);
- }
- }
- private void handleHeartbeat(String payload, int deviceTypeCode) {
- try {
- GlobalDeviceHeartInfo heartInfo = mapper.readValue(payload, GlobalDeviceHeartInfo.class);
- List<SasDevice> devices = deviceService.list(new LambdaQueryWrapper<SasDevice>()
- .eq(SasDevice::getDeviceId, heartInfo.getDeviceId())
- .eq(SasDevice::getDeviceType, deviceTypeCode));
- if (CollUtil.isNotEmpty(devices)) {
- GisHeartInfo heartInfoGis = heartInfo.getGis();
- List<SasDevice> updateList = devices.stream().map(device -> {
- device.setTriggerTime(LocalDateTime.now());
- device.setUpdateTime(LocalDateTime.now());
- if (heartInfoGis != null && StrUtil.isNotBlank(device.getGisId())) {
- SasGis gis = gisMapper.selectById(device.getGisId());
- if (gis != null) {
- if (heartInfoGis.getLongitude() != null) gis.setLon(heartInfoGis.getLongitude());
- if (heartInfoGis.getLatitude() != null) gis.setLat(heartInfoGis.getLatitude());
- if (heartInfoGis.getAltitude() != null) gis.setAlt(heartInfoGis.getAltitude());
- gisMapper.updateById(gis);
- }
- }
- return device;
- }).collect(Collectors.toList());
- deviceService.updateBatchById(updateList);
- log.debug("更新设备心跳成功, deviceId={}, count={}", heartInfo.getDeviceId(), updateList.size());
- }
- } catch (Exception e) {
- log.error("处理设备心跳失败", e);
- }
- }
- private void enrichDeviceInfo(BrieflyEventInfo info, SasDevice device) {
- if (device != null) {
- info.setAddress(device.getAddress());
- if (StrUtil.isBlank(info.getNote())) {
- info.setNote(device.getNote());
- }
- }
- }
- private void enrichDeviceInfo(BrieflyEventInfo info, String deviceId, Integer channel, Integer deviceTypeCode) {
- SasDevice device = findDevice(deviceId, deviceTypeCode);
- enrichDeviceInfo(info, device);
- }
- private String extractDeviceId(String topic) {
- String[] parts = topic.split("/");
- return parts.length > 0 ? parts[parts.length - 1] : "unknown";
- }
- private LocalDateTime parseTime(String timeStr) {
- if (timeStr == null || timeStr.isEmpty()) {
- return LocalDateTime.now();
- }
- try {
- return LocalDateTime.parse(timeStr, formatter);
- } catch (Exception e) {
- log.warn("时间解析失败: {}, 使用当前时间", timeStr);
- return LocalDateTime.now();
- }
- }
- public void subscribe(String topic) {
- try {
- if (client != null && client.isConnected()) {
- client.subscribe(topic);
- log.info("订阅主题成功: {}", topic);
- }
- } catch (MqttException e) {
- log.error("订阅主题失败: {}", topic, e);
- }
- }
- public void pauseListening() {
- this.isListening = false;
- log.info("MQTT监听已暂停");
- }
- public void resumeListening() {
- this.isListening = true;
- log.info("MQTT监听已恢复");
- }
- public boolean getConnectionStatus() {
- return client != null && client.isConnected();
- }
- public boolean getListeningStatus() {
- return isListening;
- }
- public void reconnect() {
- try {
- if (client != null) {
- if (client.isConnected()) {
- client.disconnect();
- }
- client.close();
- client = null;
- }
- isListening = true;
- init();
- } catch (Exception e) {
- log.error("MQTT重连失败", e);
- isListening = false;
- }
- }
- @PreDestroy
- public void disconnect() {
- try {
- if (client != null) {
- if (client.isConnected()) {
- client.disconnect();
- log.info("MQTT连接已断开");
- }
- client.close();
- client = null;
- }
- } catch (MqttException e) {
- log.error("断开MQTT连接失败", e);
- }
- }
- }
|