Переглянути джерело

feat: 合并ServiceActivator相关的业务处理

yangliu 4 місяців тому
батько
коміт
d8fdf3a767
51 змінених файлів з 1225 додано та 3446 видалено
  1. 27 27
      device-service-application/src/main/java/com/hfln/device/application/controller/TestController.java
  2. 17 17
      device-service-application/src/main/java/com/hfln/device/application/controller/web/Test.java
  3. 0 30
      device-service-application/src/test/java/com/hfln/device/application/controller/TestControllerTest.java
  4. 0 22
      device-service-application/src/test/java/com/hfln/device/application/controller/web/AlarmPlanControllerTest.java
  5. 0 22
      device-service-application/src/test/java/com/hfln/device/application/controller/web/RegionControllerTest.java
  6. 0 89
      device-service-application/src/test/java/com/hfln/device/application/event/EventHandlerImplTest.java
  7. 0 24
      device-service-application/src/test/java/com/hfln/device/application/service/DeviceBehaviorAnalysisServiceTest.java
  8. 0 67
      device-service-application/src/test/java/com/hfln/device/application/service/DeviceCommandServiceTest.java
  9. 0 24
      device-service-application/src/test/java/com/hfln/device/application/service/DeviceMonitorServiceImplTest.java
  10. 0 24
      device-service-application/src/test/java/com/hfln/device/application/service/DeviceServiceImplTest.java
  11. 0 96
      device-service-application/src/test/java/com/hfln/device/application/service/DeviceServiceTest.java
  12. 0 47
      device-service-application/src/test/java/com/hfln/device/application/service/impl/DeviceCommandServiceImplTest.java
  13. 0 44
      device-service-common/src/test/java/com/hfln/device/common/util/JsonUtilTest.java
  14. 0 49
      device-service-common/src/test/java/com/hfln/device/common/util/PointCloudUtilTest.java
  15. 0 65
      device-service-common/src/test/java/com/hfln/device/common/util/TopicUtilTest.java
  16. 0 9
      device-service-domain/pom.xml
  17. 150 39
      device-service-domain/src/main/java/com/hfln/device/domain/gateway/MqttGateway.java
  18. 240 240
      device-service-domain/src/main/java/com/hfln/device/domain/service/DeviceConfigService.java
  19. 0 89
      device-service-domain/src/test/java/com/hfln/device/domain/gateway/DeviceGatewayTest.java
  20. 0 95
      device-service-domain/src/test/java/com/hfln/device/domain/service/AlarmServiceTest.java
  21. 0 76
      device-service-domain/src/test/java/com/hfln/device/domain/service/DeviceManagerServiceTest.java
  22. 0 90
      device-service-domain/src/test/java/com/hfln/device/domain/service/impl/BehaviorAnalysisServiceImplTest.java
  23. 0 7
      device-service-infrastructure/pom.xml
  24. 11 4
      device-service-infrastructure/src/main/java/com/hfln/device/infrastructure/config/MqttConfig.java
  25. 112 124
      device-service-infrastructure/src/main/java/com/hfln/device/infrastructure/gateway/MqttGatewayImpl.java
  26. 362 362
      device-service-infrastructure/src/main/java/com/hfln/device/infrastructure/mqtt/MqttGatewayEmqxImpl.java
  27. 5 13
      device-service-infrastructure/src/main/java/com/hfln/device/infrastructure/mqtt/MqttHandlerImpl.java
  28. 299 299
      device-service-infrastructure/src/main/java/com/hfln/device/infrastructure/mqtt/MqttSubscriberHandler.java
  29. 0 55
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/gateway/MqttGatewayImplTest.java
  30. 0 40
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/gateway/impl/MqttGatewayDefaultImplTest.java
  31. 0 58
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/MqttGatewayEmqxImplTest.java
  32. 0 260
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/MqttSubscriberFunctionalTest.java
  33. 0 82
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/MqttSubscriberProcessorTest.java
  34. 0 228
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/SimpleMqttSubscriberTest.java
  35. 0 17
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/TestSubscriberBean.java
  36. 0 89
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/subscriber/AppMessageSubscriberTest.java
  37. 0 92
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/subscriber/DasMessageSubscriberTest.java
  38. 0 108
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/subscriber/DeviceMessageSubscriberTest.java
  39. 0 81
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/subscriber/MpsMessageSubscriberTest.java
  40. 0 46
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/subscriber/OpcMessageSubscriberTest.java
  41. 0 24
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/service/DevGroupServiceTest.java
  42. 0 24
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/service/DevInfoServiceTest.java
  43. 0 24
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/service/DevShareServiceTest.java
  44. 0 24
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/service/DeviceBehaviorServiceTest.java
  45. 0 24
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/service/EventServiceTest.java
  46. 0 24
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/service/GroupShareServiceTest.java
  47. 0 1
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/service/StayTimeServiceTest.java
  48. 0 29
      device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/service/UserServiceTest.java
  49. 1 11
      device-service-server/src/main/java/com/hfln/device/server/DeviceApplication.java
  50. 1 4
      device-service-server/src/main/resources/bootstrap-local.yml
  51. 0 7
      pom.xml

+ 27 - 27
device-service-application/src/main/java/com/hfln/device/application/controller/TestController.java

@@ -1,27 +1,27 @@
-package com.hfln.device.application.controller;
-
-
-import cn.hfln.framework.mqtt.annotation.MqttSubscribe;
-import cn.hfln.framework.mqtt.template.MqttTemplate;
-import cn.hfln.framework.catchlog.CatchAndLog;
-import cn.hfln.framework.dto.ApiResult;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-@RestController
-@Slf4j
-@CatchAndLog
-public class TestController {
-    
-    @Autowired
-    private MqttTemplate mqttTemplate;
-
-    @GetMapping("/demo")
-    public ApiResult<Boolean> get() {
-        String topic = "my/1/topic";
-        mqttTemplate.send(topic,"test message");
-        return ApiResult.success(true);
-    }
-}
+//package com.hfln.device.application.controller;
+//
+//
+//import cn.hfln.framework.mqtt.annotation.MqttSubscribe;
+//import cn.hfln.framework.mqtt.template.MqttTemplate;
+//import cn.hfln.framework.catchlog.CatchAndLog;
+//import cn.hfln.framework.dto.ApiResult;
+//import lombok.extern.slf4j.Slf4j;
+//import org.springframework.beans.factory.annotation.Autowired;
+//import org.springframework.web.bind.annotation.GetMapping;
+//import org.springframework.web.bind.annotation.RestController;
+//
+//@RestController
+//@Slf4j
+//@CatchAndLog
+//public class TestController {
+//
+//    @Autowired
+//    private MqttTemplate mqttTemplate;
+//
+//    @GetMapping("/demo")
+//    public ApiResult<Boolean> get() {
+//        String topic = "my/1/topic";
+//        mqttTemplate.send(topic,"test message");
+//        return ApiResult.success(true);
+//    }
+//}

+ 17 - 17
device-service-application/src/main/java/com/hfln/device/application/controller/web/Test.java

@@ -1,17 +1,17 @@
-package com.hfln.device.application.controller.web;
-
-import cn.hfln.framework.mqtt.annotation.MqttSubscribe;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.stereotype.Component;
-
-/**
- * 测试MQTT消息订阅
- */
-@Component
-@Slf4j
-public class Test {
-    @MqttSubscribe(topic = "my/+/topic")
-    public void listen(String msg) {
-        log.info("{}----------------------------------------", msg);
-    }
-}
+//package com.hfln.device.application.controller.web;
+//
+//import cn.hfln.framework.mqtt.annotation.MqttSubscribe;
+//import lombok.extern.slf4j.Slf4j;
+//import org.springframework.stereotype.Component;
+//
+///**
+// * 测试MQTT消息订阅
+// */
+//@Component
+//@Slf4j
+//public class Test {
+//    @MqttSubscribe(topic = "my/+/topic")
+//    public void listen(String msg) {
+//        log.info("{}----------------------------------------", msg);
+//    }
+//}

+ 0 - 30
device-service-application/src/test/java/com/hfln/device/application/controller/TestControllerTest.java

@@ -1,30 +0,0 @@
-package com.hfln.device.application.controller;
-
-import cn.hfln.framework.mqtt.template.MqttTemplate;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
-import org.springframework.boot.test.mock.mockito.MockBean;
-import org.springframework.test.web.servlet.MockMvc;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import static org.mockito.Mockito.*;
-import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
-
-@WebMvcTest(TestController.class)
-class TestControllerTest {
-    @Autowired
-    private MockMvc mockMvc;
-    @MockBean
-    private MqttTemplate mqttTemplate;
-
-    @Test
-    void testDemoEndpointPublishesMqttMessage() throws Exception {
-        mockMvc.perform(get("/demo"))
-                .andExpect(status().isOk());
-        verify(mqttTemplate, times(1)).send(eq("my/1/topic"), eq("test message"));
-    }
-} 

+ 0 - 22
device-service-application/src/test/java/com/hfln/device/application/controller/web/AlarmPlanControllerTest.java

@@ -1,22 +0,0 @@
-package com.hfln.device.application.controller.web;
-
-import org.junit.jupiter.api.Test;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
-import org.springframework.test.web.servlet.MockMvc;
-
-import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
-
-@WebMvcTest(AlarmPlanController.class)
-class AlarmPlanControllerTest {
-    @Autowired
-    private MockMvc mockMvc;
-
-    @Test
-    void testAlarmPlanList() throws Exception {
-        // TODO: 补充接口路径和断言
-        mockMvc.perform(get("/alarmPlan/list"))
-                .andExpect(status().isOk());
-    }
-} 

+ 0 - 22
device-service-application/src/test/java/com/hfln/device/application/controller/web/RegionControllerTest.java

@@ -1,22 +0,0 @@
-package com.hfln.device.application.controller.web;
-
-import org.junit.jupiter.api.Test;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
-import org.springframework.test.web.servlet.MockMvc;
-
-import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
-
-@WebMvcTest(RegionController.class)
-class RegionControllerTest {
-    @Autowired
-    private MockMvc mockMvc;
-
-    @Test
-    void testRegionList() throws Exception {
-        // TODO: 补充接口路径和断言
-        mockMvc.perform(get("/region/list"))
-                .andExpect(status().isOk());
-    }
-} 

+ 0 - 89
device-service-application/src/test/java/com/hfln/device/application/event/EventHandlerImplTest.java

@@ -1,89 +0,0 @@
-package com.hfln.device.application.event;
-
-import com.hfln.device.domain.constant.EventConstants;
-import com.hfln.device.domain.entity.Device;
-import com.hfln.device.domain.event.FallEvent;
-import com.hfln.device.domain.event.PresenceEvent;
-import com.hfln.device.domain.event.RetentionEvent;
-import com.hfln.device.domain.gateway.DeviceGateway;
-import com.hfln.device.domain.gateway.MqttGateway;
-import com.hfln.device.domain.service.DeviceService;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import static org.mockito.Mockito.*;
-
-class EventHandlerImplTest {
-    @Mock
-    private DeviceService deviceService;
-    @Mock
-    private MqttGateway mqttGateway;
-    @Mock
-    private DeviceGateway deviceGateway;
-    @InjectMocks
-    private EventHandlerImpl eventHandler;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testHandleFallEvent_FallSuspected() {
-        String deviceId = "dev123";
-        FallEvent event = mock(FallEvent.class);
-        Device device = mock(Device.class);
-        when(event.getDeviceId()).thenReturn(deviceId);
-        when(deviceService.getDeviceById(deviceId)).thenReturn(device);
-        when(event.getFallStatus()).thenReturn(EventConstants.FallStatus.FALL_SUSPECTED);
-        when(event.getPose()).thenReturn(1);
-        when(event.getTargetPoint()).thenReturn(java.util.Arrays.asList(1.0f, 2.0f, 3.0f));
-        when(event.getTimestamp()).thenReturn(System.currentTimeMillis());
-
-        eventHandler.handleFallEvent(event);
-
-        verify(mqttGateway).sendFallAlarmMessage(eq(deviceId), anyInt(), anyList());
-        verify(deviceGateway).recordFallEvent(eq(deviceId), anyInt(), anyList());
-        verify(deviceService).updateDevice(device);
-    }
-
-    @Test
-    void testHandlePresenceEvent_PresenceDetected() {
-        String deviceId = "dev456";
-        PresenceEvent event = mock(PresenceEvent.class);
-        Device device = mock(Device.class);
-        when(event.getDeviceId()).thenReturn(deviceId);
-        when(deviceService.getDeviceById(deviceId)).thenReturn(device);
-        when(event.getPresenceStatus()).thenReturn(EventConstants.PresenceStatus.PRESENCE_DETECTED);
-        when(event.getTimestamp()).thenReturn(System.currentTimeMillis());
-
-        eventHandler.handlePresenceEvent(event);
-
-        verify(device).setEnterTs(anyLong());
-        verify(device).resetLeaveTs();
-        verify(mqttGateway).sendExistenceMessage(eq(deviceId), anyString());
-        verify(deviceGateway).recordExistEvent(eq(deviceId), anyString());
-        verify(deviceService).updateDevice(device);
-    }
-
-    @Test
-    void testHandleRetentionEvent_RetentionStarted() {
-        String deviceId = "dev789";
-        RetentionEvent event = mock(RetentionEvent.class);
-        Device device = mock(Device.class);
-        when(event.getDeviceId()).thenReturn(deviceId);
-        when(deviceService.getDeviceById(deviceId)).thenReturn(device);
-        when(event.getRetentionStatus()).thenReturn(EventConstants.RetentionStatus.RETENTION_STARTED);
-        when(event.getStartTimestamp()).thenReturn(System.currentTimeMillis());
-
-        eventHandler.handleRetentionEvent(event);
-
-        verify(device).setRetentionTime(anyLong());
-        verify(mqttGateway).sendAlarmMessage(eq(deviceId), eq(EventConstants.EventType.RETENTION_EVENT), anyMap());
-        verify(deviceGateway).recordDeviceRetentionAlarm(eq(deviceId), anyLong(), eq(EventConstants.EventType.RETENTION_EVENT), anyString());
-        verify(deviceService).updateDevice(device);
-    }
-} 

+ 0 - 24
device-service-application/src/test/java/com/hfln/device/application/service/DeviceBehaviorAnalysisServiceTest.java

@@ -1,24 +0,0 @@
-package com.hfln.device.application.service;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-class DeviceBehaviorAnalysisServiceTest {
-    @Mock
-    // TODO: Mock 依赖
-    @InjectMocks
-    private DeviceBehaviorAnalysisService deviceBehaviorAnalysisService;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testMainFunctionality() {
-        // TODO: 补充主流程测试
-    }
-} 

+ 0 - 67
device-service-application/src/test/java/com/hfln/device/application/service/DeviceCommandServiceTest.java

@@ -1,67 +0,0 @@
-package com.hfln.device.application.service;
-
-import com.hfln.device.domain.gateway.DeviceGateway;
-import com.hfln.device.domain.gateway.MqttGateway;
-import com.hfln.device.domain.service.DeviceManagerService;
-import com.hfln.device.application.service.impl.DeviceCommandServiceImpl;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import static org.junit.jupiter.api.Assertions.*;
-import static org.mockito.Mockito.*;
-
-class DeviceCommandServiceTest {
-    @Mock
-    private DeviceManagerService deviceManagerService;
-    @Mock
-    private DeviceGateway deviceGateway;
-    @Mock
-    private MqttGateway mqttGateway;
-    @InjectMocks
-    private DeviceCommandServiceImpl deviceCommandService;
-
-    private AutoCloseable mocks;
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testHandleRestartDevice() {
-        String deviceId = "dev1";
-        doNothing().when(mqttGateway).sendDeviceRebootCommand(deviceId);
-        deviceCommandService.handleRestartDevice(deviceId);
-        verify(mqttGateway, times(1)).sendDeviceRebootCommand(deviceId);
-    }
-
-    @Test
-    void testHandleResetDevice() {
-        String deviceId = "dev2";
-        doNothing().when(mqttGateway).sendDeviceResetCommand(deviceId);
-        deviceCommandService.handleResetDevice(deviceId);
-        verify(mqttGateway, times(1)).sendDeviceResetCommand(deviceId);
-    }
-
-    @Test
-    void testHandleSetDeviceParam() {
-        String deviceId = "dev3";
-        doNothing().when(mqttGateway).sendSetDeviceParamCommand(eq(deviceId), anyString(), anyString(), any());
-        deviceCommandService.handleSetDeviceParam(deviceId, "plain", "area", 1.5f);
-        verify(mqttGateway, times(1)).sendSetDeviceParamCommand(eq(deviceId), anyString(), anyString(), any());
-    }
-
-    @Test
-    void testCheckDeviceExists_true() {
-        when(deviceGateway.checkDeviceExists("dev4")).thenReturn(true);
-        assertTrue(deviceCommandService.checkDeviceExists("dev4"));
-    }
-
-    @Test
-    void testCheckDeviceExists_false() {
-        when(deviceGateway.checkDeviceExists("dev5")).thenReturn(false);
-        assertFalse(deviceCommandService.checkDeviceExists("dev5"));
-    }
-} 

+ 0 - 24
device-service-application/src/test/java/com/hfln/device/application/service/DeviceMonitorServiceImplTest.java

@@ -1,24 +0,0 @@
-package com.hfln.device.application.service;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-class DeviceMonitorServiceImplTest {
-    @Mock
-    // TODO: Mock 依赖
-    @InjectMocks
-    private DeviceMonitorServiceImpl deviceMonitorServiceImpl;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testMainFunctionality() {
-        // TODO: 补充主流程测试
-    }
-} 

+ 0 - 24
device-service-application/src/test/java/com/hfln/device/application/service/DeviceServiceImplTest.java

@@ -1,24 +0,0 @@
-package com.hfln.device.application.service;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-class DeviceServiceImplTest {
-    @Mock
-    // TODO: Mock 依赖
-    @InjectMocks
-    private DeviceServiceImpl deviceServiceImpl;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testMainFunctionality() {
-        // TODO: 补充主流程测试
-    }
-} 

+ 0 - 96
device-service-application/src/test/java/com/hfln/device/application/service/DeviceServiceTest.java

@@ -1,96 +0,0 @@
-package com.hfln.device.application.service;
-
-import com.hfln.device.domain.entity.Device;
-import com.hfln.device.domain.gateway.DeviceGateway;
-import com.hfln.device.domain.gateway.MqttGateway;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.Collections;
-
-import static org.junit.jupiter.api.Assertions.*;
-import static org.mockito.Mockito.*;
-
-class DeviceServiceTest {
-    @Mock
-    private DeviceGateway deviceGateway;
-    @Mock
-    private MqttGateway mqttGateway;
-    @InjectMocks
-    private DeviceServiceImpl deviceService;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testGetDeviceById_foundInCache() {
-        Device device = new Device("dev1");
-        when(deviceGateway.getDeviceById("dev1")).thenReturn(device);
-        Device result = deviceService.getDeviceById("dev1");
-        assertNotNull(result);
-        assertEquals("dev1", result.getDevId());
-    }
-
-    @Test
-    void testGetDeviceById_notFound() {
-        when(deviceGateway.getDeviceById("dev2")).thenReturn(null);
-        Device result = deviceService.getDeviceById("dev2");
-        assertNull(result);
-    }
-
-    @Test
-    void testUpdateDevice_success() {
-        Device device = new Device("dev3");
-        when(deviceGateway.updateDevice((Device) any())).thenReturn(device);
-        Device updated = deviceService.updateDevice(device);
-        assertNotNull(updated);
-        assertEquals("dev3", updated.getDevId());
-    }
-
-    @Test
-    void testCheckDeviceKeepAlive_offline() {
-        Device device = new Device("dev4");
-        device.setOnline(1);
-        device.setKeepaliveTime(System.currentTimeMillis() - 1000000L);
-        when(deviceGateway.getAllDevices()).thenReturn(Collections.singletonList(device));
-        when(deviceGateway.updateDevice((Device) any())).thenReturn(device);
-        deviceService.checkDeviceKeepAlive();
-        assertEquals(0, device.getOnline());
-    }
-
-    @Test
-    void testCheckDeviceAlarmAck_autoAck() {
-        Device device = new Device("dev5");
-        device.setAlarmAck(false);
-        device.setLastAlarmAckTime(System.currentTimeMillis() - 1000000L);
-        when(deviceGateway.getAllDevices()).thenReturn(Collections.singletonList(device));
-        when(deviceGateway.updateDevice((Device) any())).thenReturn(device);
-        deviceService.checkDeviceAlarmAck();
-        assertTrue(device.getAlarmAck());
-    }
-
-    @Test
-    void testCheckDeviceStayTime_noLeaveTs() {
-        Device device = new Device("dev6");
-        device.setEnterTs(System.currentTimeMillis() - 10000L);
-        device.setLeaveTs(null);
-        when(deviceGateway.getAllDevices()).thenReturn(Collections.singletonList(device));
-        deviceService.checkDeviceStayTime();
-        // 只需保证无异常即可
-    }
-
-    @Test
-    void testCheckDeviceAlarmPlan_withAlarmSchedule() {
-        Device device = new Device("dev7");
-        device.setOnline(1);
-        device.setAlarmSchedule(Collections.singletonMap("plan", "test"));
-        when(deviceGateway.getAllDevices()).thenReturn(Collections.singletonList(device));
-        deviceService.checkDeviceAlarmPlan();
-        // 只需保证无异常即可
-    }
-} 

+ 0 - 47
device-service-application/src/test/java/com/hfln/device/application/service/impl/DeviceCommandServiceImplTest.java

@@ -1,47 +0,0 @@
-package com.hfln.device.application.service.impl;
-
-import com.hfln.device.domain.gateway.MqttGateway;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.mockito.Mockito.*;
-
-class DeviceCommandServiceImplTest {
-    @Mock
-    private MqttGateway mqttGateway;
-    @InjectMocks
-    private DeviceCommandServiceImpl deviceCommandService;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testPublishBindDeviceResponse() {
-        Map<String, Object> responseData = new HashMap<>();
-        responseData.put("deviceId", "dev1");
-        responseData.put("userId", 123L);
-        responseData.put("result", true);
-        responseData.put("message", "ok");
-        deviceCommandService.publishBindDeviceResponse(responseData);
-        verify(mqttGateway, times(1)).sendToMqtt(eq("/das/bind_device/response"), anyString());
-    }
-
-    @Test
-    void testPublishUnbindDeviceResponse() {
-        Map<String, Object> responseData = new HashMap<>();
-        responseData.put("deviceId", "dev2");
-        responseData.put("userId", 456L);
-        responseData.put("result", false);
-        responseData.put("message", "fail");
-        deviceCommandService.publishUnbindDeviceResponse(responseData);
-        verify(mqttGateway, times(1)).sendToMqtt(eq("/das/unbind_device/response"), anyString());
-    }
-} 

+ 0 - 44
device-service-common/src/test/java/com/hfln/device/common/util/JsonUtilTest.java

@@ -1,44 +0,0 @@
-package com.hfln.device.common.util;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.junit.jupiter.api.Assertions.*;
-
-class JsonUtilTest {
-    @BeforeEach
-    void setUp() {
-        // 无需特殊初始化
-    }
-
-    @Test
-    void testToJsonAndFromJson() {
-        Map<String, Object> map = new HashMap<>();
-        map.put("key", "value");
-        String json = JsonUtil.toJsonString(map);
-        assertNotNull(json);
-        Map result = JsonUtil.parseMap(json);
-        assertEquals("value", result.get("key"));
-    }
-
-    @Test
-    void testFromJson_invalidJson() {
-        String invalidJson = "{key:value}";
-        assertThrows(Exception.class, () -> JsonUtil.parseMap(invalidJson));
-    }
-
-    @Test
-    void testToJson_null() {
-        String json = JsonUtil.toJsonString(null);
-        assertEquals("null", json);
-    }
-
-    @Test
-    void testFromJson_null() {
-        Object result = JsonUtil.parseMap(null);
-        assertNull(result);
-    }
-} 

+ 0 - 49
device-service-common/src/test/java/com/hfln/device/common/util/PointCloudUtilTest.java

@@ -1,49 +0,0 @@
-package com.hfln.device.common.util;
-
-import org.junit.jupiter.api.Test;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import static org.junit.jupiter.api.Assertions.*;
-
-class PointCloudUtilTest {
-    @Test
-    void testGetTrackerTargets_normal() {
-        List<List<Float>> pointCloud = Arrays.asList(
-                Arrays.asList(1.0f, 2.0f, 3.0f),
-                Arrays.asList(4.0f, 5.0f, 6.0f)
-        );
-        List<List<Float>> targets = PointCloudUtil.getTrackerTargets(pointCloud);
-        assertNotNull(targets);
-        assertEquals(1, targets.size());
-        assertEquals(3, targets.get(0).size());
-    }
-
-    @Test
-    void testGetTrackerTargets_empty() {
-        List<List<Float>> pointCloud = Collections.emptyList();
-        List<List<Float>> targets = PointCloudUtil.getTrackerTargets(pointCloud);
-        assertNotNull(targets);
-        assertTrue(targets.isEmpty());
-    }
-
-    @Test
-    void testGetTrackerTargets_null() {
-        List<List<Float>> targets = PointCloudUtil.getTrackerTargets(null);
-        assertNotNull(targets);
-        assertTrue(targets.isEmpty());
-    }
-
-    @Test
-    void testGetTrackerTargetsMult() {
-        List<List<Float>> pointCloud = Arrays.asList(
-                Arrays.asList(1.0f, 2.0f, 3.0f),
-                Arrays.asList(4.0f, 5.0f, 6.0f)
-        );
-        List<List<Float>> targets = PointCloudUtil.getTrackerTargetsMult(pointCloud);
-        assertNotNull(targets);
-        assertEquals(1, targets.size());
-    }
-} 

+ 0 - 65
device-service-common/src/test/java/com/hfln/device/common/util/TopicUtilTest.java

@@ -1,65 +0,0 @@
-package com.hfln.device.common.util;
-
-import org.junit.jupiter.api.Test;
-
-import static org.junit.jupiter.api.Assertions.*;
-
-class TopicUtilTest {
-    @Test
-    void testCheckTopic_match() {
-        String pattern = ".*test.*";
-        String topic = "abc_test_123";
-        assertTrue(TopicUtil.checkTopic(pattern, topic));
-    }
-
-    @Test
-    void testCheckTopic_notMatch() {
-        String pattern = "^dev/.*$";
-        String topic = "das/123";
-        assertFalse(TopicUtil.checkTopic(pattern, topic));
-    }
-
-    @Test
-    void testExtractDeviceId_devLogin() {
-        String topic = "/dev/123/login";
-        String deviceId = TopicUtil.extractDeviceId(topic);
-        // 依赖MqttTopics.Pattern.DEV_LOGIN的具体实现,若为null说明未匹配
-        assertNull(deviceId); // 如需调整可根据实际正则
-    }
-
-    @Test
-    void testIsDeviceTopic() {
-        String topic = "/dev/123/status";
-        boolean result = TopicUtil.isDeviceTopic(topic);
-        // 依赖MqttTopics.Pattern.DEV_ALL的实现,默认false
-        assertFalse(result); // 如需调整可根据实际正则
-    }
-
-    @Test
-    void testIsDasTopic() {
-        String topic = "/das/abc";
-        boolean result = TopicUtil.isDasTopic(topic);
-        assertFalse(result); // 依赖实际正则
-    }
-
-    @Test
-    void testIsMpsTopic() {
-        String topic = "/mps/xyz";
-        boolean result = TopicUtil.isMpsTopic(topic);
-        assertFalse(result); // 依赖实际正则
-    }
-
-    @Test
-    void testIsAppTopic() {
-        String topic = "/app/hello";
-        boolean result = TopicUtil.isAppTopic(topic);
-        assertFalse(result); // 依赖实际正则
-    }
-
-    @Test
-    void testIsOpcTopic() {
-        String topic = "/opc/hello";
-        boolean result = TopicUtil.isOpcTopic(topic);
-        assertFalse(result); // 依赖实际正则
-    }
-} 

+ 0 - 9
device-service-domain/pom.xml

@@ -32,15 +32,6 @@
             <artifactId>tencentcloud-sdk-java</artifactId>
             <version>3.1.1190</version>
         </dependency>
-<!--        <dependency>-->
-<!--            <groupId>cn.hfln.framework</groupId>-->
-<!--            <artifactId>mqtt-spring-boot-starter</artifactId>-->
-<!--        </dependency>-->
-
-        <dependency>
-            <groupId>cn.hfln.framework</groupId>
-            <artifactId>mqtt-spring-boot-starter</artifactId>
-        </dependency>
 
         <dependency>
             <groupId>org.projectlombok</groupId>

+ 150 - 39
device-service-domain/src/main/java/com/hfln/device/domain/gateway/MqttGateway.java

@@ -6,10 +6,94 @@ import java.util.Map;
 
 /**
  * 设备服务MQTT网关接口
- * 继承自通用MQTT网关接口,添加设备服务特有的方法
  */
-public interface MqttGateway extends cn.hfln.framework.mqtt.gateway.MqttGateway {
-    
+public interface MqttGateway {
+
+    /**
+     * 初始化MQTT连接
+     */
+    void initialize();
+
+    /**
+     * 发布消息
+     * @param topic 主题
+     * @param payload 负载
+     */
+    void publish(String topic, Object payload);
+
+    /**
+     * 发布消息
+     * @param topic 主题
+     * @param payload 负载
+     * @param qos 质量等级
+     * @param retain 是否保留
+     */
+    void publish(String topic, Object payload, int qos, boolean retain);
+
+    /**
+     * 发送文本消息
+     * @param topic 主题
+     * @param message 消息
+     */
+    void sendMessage(String topic, String message);
+
+    /**
+     * 发送文本消息
+     * @param topic 主题
+     * @param message 消息
+     * @param qos 质量等级
+     * @param retain 是否保留
+     */
+    void sendMessage(String topic, String message, int qos, boolean retain);
+
+    /**
+     * 发布JSON消息
+     * @param topic 主题
+     * @param payload 负载
+     */
+    void publishJson(String topic, Object payload);
+
+    /**
+     * 发布JSON消息
+     * @param topic 主题
+     * @param payload 负载
+     * @param qos 质量等级
+     * @param retain 是否保留
+     */
+    void publishJson(String topic, Object payload, int qos, boolean retain);
+
+    /**
+     * 同步发送消息
+     * @param topic 主题
+     * @param payload 负载
+     * @throws Exception 发送异常
+     */
+    void sendSync(String topic, Object payload) throws Exception;
+
+    /**
+     * 订阅主题
+     * @param topic 主题
+     * @param qos 质量等级
+     */
+    void subscribe(String topic, int qos);
+
+    /**
+     * 取消订阅
+     * @param topic 主题
+     */
+    void unsubscribe(String topic);
+
+    /**
+     * 检查连接状态
+     * @return 是否已连接
+     */
+    boolean isConnected();
+
+    /**
+     * 断开连接
+     */
+    void disconnect();
+
     /**
      * 发送设备登录响应
      * @param deviceId 设备ID
@@ -20,9 +104,9 @@ public interface MqttGateway extends cn.hfln.framework.mqtt.gateway.MqttGateway
     /**
      * 发送设备保活响应
      * @param deviceId 设备ID
-     * @param code 响应码
+     * @param status 状态
      */
-    void sendDeviceKeepAliveResponse(String deviceId, int code);
+    void sendDeviceKeepAliveResponse(String deviceId, int status);
 
     /**
      * 发送设备状态消息
@@ -87,15 +171,15 @@ public interface MqttGateway extends cn.hfln.framework.mqtt.gateway.MqttGateway
     /**
      * 向设备发送参数设置命令
      * @param deviceId 设备ID
-     * @param mountPlain 安装平面
-     * @param area 区域
-     * @param height 高度
+     * @param paramType 参数类型
+     * @param paramName 参数名
+     * @param value 参数值
      */
-    void sendDeviceParamSetCommand(String deviceId, String mountPlain, String area, float height);
+    void sendDeviceParamSetCommand(String deviceId, String paramType, String paramName, float value);
 
     /**
      * 发送网络配置更新消息
-     * 
+     *
      * @param deviceId 设备ID
      * @param networkInfo 网络信息
      */
@@ -103,7 +187,7 @@ public interface MqttGateway extends cn.hfln.framework.mqtt.gateway.MqttGateway
 
     /**
      * 发送安装参数更新消息
-     * 
+     *
      * @param deviceId 设备ID
      * @param installParam 安装参数
      */
@@ -111,7 +195,7 @@ public interface MqttGateway extends cn.hfln.framework.mqtt.gateway.MqttGateway
 
     /**
      * 发送跟踪区域更新消息
-     * 
+     *
      * @param deviceId 设备ID
      * @param trackingRegion 跟踪区域
      */
@@ -119,7 +203,7 @@ public interface MqttGateway extends cn.hfln.framework.mqtt.gateway.MqttGateway
 
     /**
      * 发送告警计划更新消息
-     * 
+     *
      * @param deviceId 设备ID
      * @param alarmSchedule 告警计划
      */
@@ -127,65 +211,65 @@ public interface MqttGateway extends cn.hfln.framework.mqtt.gateway.MqttGateway
 
     /**
      * 发送设备命令
-     * 
+     *
      * @param deviceId 设备ID
      * @param command 命令类型
      * @param params 命令参数
      */
     void sendDeviceCommand(String deviceId, String command, Map<String, Object> params);
-    
+
     /**
      * 向设备发送设置参数命令
-     * 
+     *
      * @param deviceId 设备ID
-     * @param mountPlain 安装平面
-     * @param area 区域
-     * @param height 高度
+     * @param paramType 参数类型
+     * @param paramName 参数名
+     * @param value 参数值
      */
-    void sendSetDeviceParamCommand(String deviceId, String mountPlain, String area, Float height);
-    
+    void sendSetDeviceParamCommand(String deviceId, String paramType, String paramName, Float value);
+
     /**
      * 发送设备信息响应
-     * 
+     *
      * @param deviceId 设备ID
      * @param device 设备信息
      */
     void sendDeviceInfoResponse(String deviceId, Device device);
-    
+
     /**
      * 发送设备不存在响应
-     * 
+     *
      * @param deviceId 设备ID
      */
     void sendDeviceNotFoundResponse(String deviceId);
-    
+
     /**
      * 向设备发送重置命令
-     * 
+     *
      * @param deviceId 设备ID
      */
     void sendDeviceResetCommand(String deviceId);
-    
+
     /**
      * 向设备发送更新网络命令
-     * 
+     *
      * @param deviceId 设备ID
      * @param ssid 网络SSID
      * @param password 网络密码
      */
     void sendUpdateNetworkCommand(String deviceId, String ssid, String password);
-    
+
     /**
      * 发送告警确认消息
-     * 
+     *
      * @param deviceId 设备ID
      * @param eventId 事件ID
      */
     void sendAlarmAckMessage(String deviceId, Long eventId);
-    
+
     /**
      * 发送跌倒告警消息
-     * 
+     *
      * @param deviceId 设备ID
      * @param pose 姿态
      * @param targetPoint 目标点
@@ -203,7 +287,7 @@ public interface MqttGateway extends cn.hfln.framework.mqtt.gateway.MqttGateway
 
     /**
      * 发送设备状态消息
-     * 
+     *
      * @param deviceId 设备ID
      * @param status 设备状态
      * @param data 状态数据
@@ -212,7 +296,7 @@ public interface MqttGateway extends cn.hfln.framework.mqtt.gateway.MqttGateway
 
     /**
      * 发送设备行为分析消息
-     * 
+     *
      * @param deviceId 设备ID
      * @param behaviorType 行为类型
      * @param data 行为数据
@@ -221,7 +305,7 @@ public interface MqttGateway extends cn.hfln.framework.mqtt.gateway.MqttGateway
 
     /**
      * 发送MQTT消息
-     * 
+     *
      * @param topic 主题
      * @param payload 消息内容
      */
@@ -229,17 +313,44 @@ public interface MqttGateway extends cn.hfln.framework.mqtt.gateway.MqttGateway
 
     /**
      * 发送告警参数响应消息
-     * 
+     *
      * @param code 响应码
      * @param globalConfig 全局告警配置
      */
     void sendAlarmParamResponse(int code, Map<String, Object> globalConfig);
-    
+
     /**
      * 发送设置告警参数确认消息
-     * 
+     *
      * @param code 响应码
      * @param globalConfig 全局告警配置
      */
     void sendSetAlarmParamAck(int code, Map<String, Object> globalConfig);
-} 
+
+    /**
+     * 发送响应消息
+     *
+     * @param topic 主题
+     * @param code 响应码
+     * @param data 数据
+     */
+    void sendResponse(String topic, int code, Map<String, Object> data);
+
+    /**
+     * 发送命令消息
+     *
+     * @param topic 主题
+     * @param command 命令
+     * @param params 参数
+     */
+    void sendCommand(String topic, String command, Map<String, Object> params);
+
+    /**
+     * 发送通用消息
+     *
+     * @param topic 主题
+     * @param messageType 消息类型
+     * @param messageData 消息数据
+     */
+    void sendGenericMessage(String topic, String messageType, Map<String, Object> messageData);
+}

+ 240 - 240
device-service-domain/src/main/java/com/hfln/device/domain/service/DeviceConfigService.java

@@ -1,240 +1,240 @@
-package com.hfln.device.domain.service;
-
-import com.hfln.device.domain.entity.Device;
-import com.hfln.device.domain.gateway.DeviceGateway;
-import com.hfln.device.domain.gateway.MqttGateway;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import java.util.Map;
-import java.util.Optional;
-
-/**
- * 设备配置服务
- * 负责设备配置相关的领域逻辑
- */
-@Service
-@Slf4j
-public class DeviceConfigService {
-
-    @Autowired
-    private DeviceManagerService deviceManagerService;
-    
-    @Autowired
-    private DeviceGateway deviceGateway;
-    
-    @Autowired
-    private MqttGateway mqttGateway;
-    
-    /**
-     * 更新设备网络配置
-     * 
-     * @param deviceId 设备ID
-     * @param networkInfo 网络信息
-     * @return 是否更新成功
-     */
-    public boolean updateDeviceNetwork(String deviceId, Device.NetworkInfo networkInfo) {
-        try {
-            Optional<Device> deviceOpt = deviceManagerService.getDeviceFromCache(deviceId);
-            if (!deviceOpt.isPresent()) {
-                log.warn("Device not found: {}", deviceId);
-                return false;
-            }
-            
-            Device device = deviceOpt.get();
-            
-            // 更新网络配置
-            device.setNetwork(networkInfo);
-            
-            // 更新缓存
-            deviceManagerService.updateDeviceInCache(device);
-            
-            // 更新数据库
-            deviceGateway.updateDeviceNetwork(deviceId, networkInfo);
-            
-            // 发送配置更新通知
-            mqttGateway.sendNetworkConfigUpdate(deviceId, networkInfo);
-            
-            log.info("Device network updated: {}", deviceId);
-            return true;
-        } catch (Exception e) {
-            log.error("Error updating device network: {}", e.getMessage(), e);
-            return false;
-        }
-    }
-    
-    /**
-     * 更新设备安装参数
-     * 
-     * @param deviceId 设备ID
-     * @param installParam 安装参数
-     * @return 是否更新成功
-     */
-    public boolean updateDeviceInstallParam(String deviceId, Device.InstallParam installParam) {
-        try {
-            Optional<Device> deviceOpt = deviceManagerService.getDeviceFromCache(deviceId);
-            if (!deviceOpt.isPresent()) {
-                log.warn("Device not found: {}", deviceId);
-                return false;
-            }
-            
-            Device device = deviceOpt.get();
-            
-            // 更新安装参数
-            device.setInstallParam(installParam);
-            
-            // 更新缓存
-            deviceManagerService.updateDeviceInCache(device);
-            
-            // 更新数据库
-            deviceGateway.updateDeviceInstallParam(deviceId, installParam);
-            
-            // 发送配置更新通知
-            mqttGateway.sendInstallParamUpdate(deviceId, installParam);
-            
-            log.info("Device install parameters updated: {}", deviceId);
-            return true;
-        } catch (Exception e) {
-            log.error("Error updating device install parameters: {}", e.getMessage(), e);
-            return false;
-        }
-    }
-    
-    /**
-     * 更新设备跟踪区域
-     * 
-     * @param deviceId 设备ID
-     * @param trackingRegion 跟踪区域
-     * @return 是否更新成功
-     */
-    public boolean updateDeviceTrackingRegion(String deviceId, Device.TrackingRegion trackingRegion) {
-        try {
-            Optional<Device> deviceOpt = deviceManagerService.getDeviceFromCache(deviceId);
-            if (!deviceOpt.isPresent()) {
-                log.warn("Device not found: {}", deviceId);
-                return false;
-            }
-            
-            Device device = deviceOpt.get();
-            Device.InstallParam installParam = device.getInstallParam();
-            
-            if (installParam == null) {
-                installParam = Device.InstallParam.builder()
-                        .mountPlain("Wall")
-                        .isCeiling(0)
-                        .height(0.0f)
-                        .trackingRegion(trackingRegion)
-                        .build();
-            } else {
-                // 更新跟踪区域
-                installParam.setTrackingRegion(trackingRegion);
-            }
-            
-            // 设置更新后的安装参数
-            device.setInstallParam(installParam);
-            
-            // 更新缓存
-            deviceManagerService.updateDeviceInCache(device);
-            
-            // 更新数据库
-            deviceGateway.updateDeviceInstallParam(deviceId, installParam);
-            
-            // 发送配置更新通知
-            mqttGateway.sendTrackingRegionUpdate(deviceId, trackingRegion);
-            
-            log.info("Device tracking region updated: {}", deviceId);
-            return true;
-        } catch (Exception e) {
-            log.error("Error updating device tracking region: {}", e.getMessage(), e);
-            return false;
-        }
-    }
-    
-    /**
-     * 更新设备告警计划
-     * 
-     * @param deviceId 设备ID
-     * @param alarmSchedule 告警计划
-     * @return 是否更新成功
-     */
-    public boolean updateDeviceAlarmSchedule(String deviceId, Map<String, Object> alarmSchedule) {
-        try {
-            Optional<Device> deviceOpt = deviceManagerService.getDeviceFromCache(deviceId);
-            if (!deviceOpt.isPresent()) {
-                log.warn("Device not found: {}", deviceId);
-                return false;
-            }
-            
-            Device device = deviceOpt.get();
-            
-            // 更新告警计划
-            device.setAlarmSchedule(alarmSchedule);
-            
-            // 更新缓存
-            deviceManagerService.updateDeviceInCache(device);
-            
-            // 更新数据库
-            deviceGateway.updateDeviceAlarmSchedule(deviceId, alarmSchedule);
-            
-            // 发送配置更新通知
-            mqttGateway.sendAlarmScheduleUpdate(deviceId, alarmSchedule);
-            
-            log.info("Device alarm schedule updated: {}", deviceId);
-            return true;
-        } catch (Exception e) {
-            log.error("Error updating device alarm schedule: {}", e.getMessage(), e);
-            return false;
-        }
-    }
-    
-    /**
-     * 重启设备
-     * 
-     * @param deviceId 设备ID
-     * @return 是否发送成功
-     */
-    public boolean restartDevice(String deviceId) {
-        try {
-            Optional<Device> deviceOpt = deviceManagerService.getDeviceFromCache(deviceId);
-            if (!deviceOpt.isPresent() || deviceOpt.get().getOnline() != 1) {
-                log.warn("Device not found or offline: {}", deviceId);
-                return false;
-            }
-            
-            // 发送重启命令
-            mqttGateway.sendDeviceCommand(deviceId, "restart", null);
-            
-            log.info("Restart command sent to device: {}", deviceId);
-            return true;
-        } catch (Exception e) {
-            log.error("Error sending restart command: {}", e.getMessage(), e);
-            return false;
-        }
-    }
-    
-    /**
-     * 重置设备
-     * 
-     * @param deviceId 设备ID
-     * @return 是否发送成功
-     */
-    public boolean resetDevice(String deviceId) {
-        try {
-            Optional<Device> deviceOpt = deviceManagerService.getDeviceFromCache(deviceId);
-            if (!deviceOpt.isPresent() || deviceOpt.get().getOnline() != 1) {
-                log.warn("Device not found or offline: {}", deviceId);
-                return false;
-            }
-            
-            // 发送重置命令
-            mqttGateway.sendDeviceCommand(deviceId, "reset", null);
-            
-            log.info("Reset command sent to device: {}", deviceId);
-            return true;
-        } catch (Exception e) {
-            log.error("Error sending reset command: {}", e.getMessage(), e);
-            return false;
-        }
-    }
-} 
+//package com.hfln.device.domain.service;
+//
+//import com.hfln.device.domain.entity.Device;
+//import com.hfln.device.domain.gateway.DeviceGateway;
+//import com.hfln.device.domain.gateway.MqttGateway;
+//import lombok.extern.slf4j.Slf4j;
+//import org.springframework.beans.factory.annotation.Autowired;
+//import org.springframework.stereotype.Service;
+//
+//import java.util.Map;
+//import java.util.Optional;
+//
+///**
+// * 设备配置服务
+// * 负责设备配置相关的领域逻辑
+// */
+//@Service
+//@Slf4j
+//public class DeviceConfigService {
+//
+//    @Autowired
+//    private DeviceManagerService deviceManagerService;
+//
+//    @Autowired
+//    private DeviceGateway deviceGateway;
+//
+//    @Autowired
+//    private MqttGateway mqttGateway;
+//
+//    /**
+//     * 更新设备网络配置
+//     *
+//     * @param deviceId 设备ID
+//     * @param networkInfo 网络信息
+//     * @return 是否更新成功
+//     */
+//    public boolean updateDeviceNetwork(String deviceId, Device.NetworkInfo networkInfo) {
+//        try {
+//            Optional<Device> deviceOpt = deviceManagerService.getDeviceFromCache(deviceId);
+//            if (!deviceOpt.isPresent()) {
+//                log.warn("Device not found: {}", deviceId);
+//                return false;
+//            }
+//
+//            Device device = deviceOpt.get();
+//
+//            // 更新网络配置
+//            device.setNetwork(networkInfo);
+//
+//            // 更新缓存
+//            deviceManagerService.updateDeviceInCache(device);
+//
+//            // 更新数据库
+//            deviceGateway.updateDeviceNetwork(deviceId, networkInfo);
+//
+//            // 发送配置更新通知
+//            mqttGateway.sendNetworkConfigUpdate(deviceId, networkInfo);
+//
+//            log.info("Device network updated: {}", deviceId);
+//            return true;
+//        } catch (Exception e) {
+//            log.error("Error updating device network: {}", e.getMessage(), e);
+//            return false;
+//        }
+//    }
+//
+//    /**
+//     * 更新设备安装参数
+//     *
+//     * @param deviceId 设备ID
+//     * @param installParam 安装参数
+//     * @return 是否更新成功
+//     */
+//    public boolean updateDeviceInstallParam(String deviceId, Device.InstallParam installParam) {
+//        try {
+//            Optional<Device> deviceOpt = deviceManagerService.getDeviceFromCache(deviceId);
+//            if (!deviceOpt.isPresent()) {
+//                log.warn("Device not found: {}", deviceId);
+//                return false;
+//            }
+//
+//            Device device = deviceOpt.get();
+//
+//            // 更新安装参数
+//            device.setInstallParam(installParam);
+//
+//            // 更新缓存
+//            deviceManagerService.updateDeviceInCache(device);
+//
+//            // 更新数据库
+//            deviceGateway.updateDeviceInstallParam(deviceId, installParam);
+//
+//            // 发送配置更新通知
+//            mqttGateway.sendInstallParamUpdate(deviceId, installParam);
+//
+//            log.info("Device install parameters updated: {}", deviceId);
+//            return true;
+//        } catch (Exception e) {
+//            log.error("Error updating device install parameters: {}", e.getMessage(), e);
+//            return false;
+//        }
+//    }
+//
+//    /**
+//     * 更新设备跟踪区域
+//     *
+//     * @param deviceId 设备ID
+//     * @param trackingRegion 跟踪区域
+//     * @return 是否更新成功
+//     */
+//    public boolean updateDeviceTrackingRegion(String deviceId, Device.TrackingRegion trackingRegion) {
+//        try {
+//            Optional<Device> deviceOpt = deviceManagerService.getDeviceFromCache(deviceId);
+//            if (!deviceOpt.isPresent()) {
+//                log.warn("Device not found: {}", deviceId);
+//                return false;
+//            }
+//
+//            Device device = deviceOpt.get();
+//            Device.InstallParam installParam = device.getInstallParam();
+//
+//            if (installParam == null) {
+//                installParam = Device.InstallParam.builder()
+//                        .mountPlain("Wall")
+//                        .isCeiling(0)
+//                        .height(0.0f)
+//                        .trackingRegion(trackingRegion)
+//                        .build();
+//            } else {
+//                // 更新跟踪区域
+//                installParam.setTrackingRegion(trackingRegion);
+//            }
+//
+//            // 设置更新后的安装参数
+//            device.setInstallParam(installParam);
+//
+//            // 更新缓存
+//            deviceManagerService.updateDeviceInCache(device);
+//
+//            // 更新数据库
+//            deviceGateway.updateDeviceInstallParam(deviceId, installParam);
+//
+//            // 发送配置更新通知
+//            mqttGateway.sendTrackingRegionUpdate(deviceId, trackingRegion);
+//
+//            log.info("Device tracking region updated: {}", deviceId);
+//            return true;
+//        } catch (Exception e) {
+//            log.error("Error updating device tracking region: {}", e.getMessage(), e);
+//            return false;
+//        }
+//    }
+//
+//    /**
+//     * 更新设备告警计划
+//     *
+//     * @param deviceId 设备ID
+//     * @param alarmSchedule 告警计划
+//     * @return 是否更新成功
+//     */
+//    public boolean updateDeviceAlarmSchedule(String deviceId, Map<String, Object> alarmSchedule) {
+//        try {
+//            Optional<Device> deviceOpt = deviceManagerService.getDeviceFromCache(deviceId);
+//            if (!deviceOpt.isPresent()) {
+//                log.warn("Device not found: {}", deviceId);
+//                return false;
+//            }
+//
+//            Device device = deviceOpt.get();
+//
+//            // 更新告警计划
+//            device.setAlarmSchedule(alarmSchedule);
+//
+//            // 更新缓存
+//            deviceManagerService.updateDeviceInCache(device);
+//
+//            // 更新数据库
+//            deviceGateway.updateDeviceAlarmSchedule(deviceId, alarmSchedule);
+//
+//            // 发送配置更新通知
+//            mqttGateway.sendAlarmScheduleUpdate(deviceId, alarmSchedule);
+//
+//            log.info("Device alarm schedule updated: {}", deviceId);
+//            return true;
+//        } catch (Exception e) {
+//            log.error("Error updating device alarm schedule: {}", e.getMessage(), e);
+//            return false;
+//        }
+//    }
+//
+//    /**
+//     * 重启设备
+//     *
+//     * @param deviceId 设备ID
+//     * @return 是否发送成功
+//     */
+//    public boolean restartDevice(String deviceId) {
+//        try {
+//            Optional<Device> deviceOpt = deviceManagerService.getDeviceFromCache(deviceId);
+//            if (!deviceOpt.isPresent() || deviceOpt.get().getOnline() != 1) {
+//                log.warn("Device not found or offline: {}", deviceId);
+//                return false;
+//            }
+//
+//            // 发送重启命令
+//            mqttGateway.sendDeviceCommand(deviceId, "restart", null);
+//
+//            log.info("Restart command sent to device: {}", deviceId);
+//            return true;
+//        } catch (Exception e) {
+//            log.error("Error sending restart command: {}", e.getMessage(), e);
+//            return false;
+//        }
+//    }
+//
+//    /**
+//     * 重置设备
+//     *
+//     * @param deviceId 设备ID
+//     * @return 是否发送成功
+//     */
+//    public boolean resetDevice(String deviceId) {
+//        try {
+//            Optional<Device> deviceOpt = deviceManagerService.getDeviceFromCache(deviceId);
+//            if (!deviceOpt.isPresent() || deviceOpt.get().getOnline() != 1) {
+//                log.warn("Device not found or offline: {}", deviceId);
+//                return false;
+//            }
+//
+//            // 发送重置命令
+//            mqttGateway.sendDeviceCommand(deviceId, "reset", null);
+//
+//            log.info("Reset command sent to device: {}", deviceId);
+//            return true;
+//        } catch (Exception e) {
+//            log.error("Error sending reset command: {}", e.getMessage(), e);
+//            return false;
+//        }
+//    }
+//}

+ 0 - 89
device-service-domain/src/test/java/com/hfln/device/domain/gateway/DeviceGatewayTest.java

@@ -1,89 +0,0 @@
-package com.hfln.device.domain.gateway;
-
-import com.hfln.device.domain.entity.Device;
-import com.hfln.device.domain.entity.Region;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-
-import static org.junit.jupiter.api.Assertions.*;
-import static org.mockito.Mockito.*;
-
-class DeviceGatewayTest {
-    @Mock
-    private DeviceGateway deviceGateway;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testGetAllDevices() {
-        List<Device> devices = Arrays.asList(new Device("dev1"), new Device("dev2"));
-        when(deviceGateway.getAllDevices()).thenReturn(devices);
-        List<Device> result = deviceGateway.getAllDevices();
-        assertEquals(2, result.size());
-    }
-
-    @Test
-    void testGetDeviceById_found() {
-        Device device = new Device("dev3");
-        when(deviceGateway.getDeviceById("dev3")).thenReturn(device);
-        Device result = deviceGateway.getDeviceById("dev3");
-        assertNotNull(result);
-        assertEquals("dev3", result.getDevId());
-    }
-
-    @Test
-    void testGetDeviceById_notFound() {
-        when(deviceGateway.getDeviceById("dev4")).thenReturn(null);
-        Device result = deviceGateway.getDeviceById("dev4");
-        assertNull(result);
-    }
-
-    @Test
-    void testUpdateDevice() {
-        Device device = new Device("dev5");
-        when(deviceGateway.updateDevice((Device) any())).thenReturn(device);
-        Device updated = deviceGateway.updateDevice(device);
-        assertNotNull(updated);
-        assertEquals("dev5", updated.getDevId());
-    }
-
-    @Test
-    void testCheckDeviceExists_true() {
-        when(deviceGateway.checkDeviceExists("dev6")).thenReturn(true);
-        assertTrue(deviceGateway.checkDeviceExists("dev6"));
-    }
-
-    @Test
-    void testCheckDeviceExists_false() {
-        when(deviceGateway.checkDeviceExists("dev7")).thenReturn(false);
-        assertFalse(deviceGateway.checkDeviceExists("dev7"));
-    }
-
-    @Test
-    void testGetRegionsByDeviceId() {
-        List<Region> regions = Arrays.asList(new Region(), new Region());
-        when(deviceGateway.getRegionsByDeviceId("dev8")).thenReturn(regions);
-        List<Region> result = deviceGateway.getRegionsByDeviceId("dev8");
-        assertEquals(2, result.size());
-    }
-
-    @Test
-    void testGetRegionById() {
-        Region region = new Region();
-        when(deviceGateway.getRegionById("region1")).thenReturn(region);
-        Region result = deviceGateway.getRegionById("region1");
-        assertNotNull(result);
-    }
-} 

+ 0 - 95
device-service-domain/src/test/java/com/hfln/device/domain/service/AlarmServiceTest.java

@@ -1,95 +0,0 @@
-package com.hfln.device.domain.service;
-
-import com.hfln.device.domain.entity.Device;
-import com.hfln.device.domain.service.impl.AlarmServiceImpl;
-import com.hfln.device.domain.gateway.DeviceGateway;
-import com.hfln.device.domain.gateway.MqttGateway;
-import com.hfln.device.domain.vo.BehaviorPattern;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Optional;
-
-import static org.junit.jupiter.api.Assertions.*;
-import static org.mockito.Mockito.*;
-
-class AlarmServiceTest {
-    @Mock
-    private DeviceGateway deviceGateway;
-    @Mock
-    private MqttGateway mqttGateway;
-    @Mock
-    private DeviceManagerService deviceManagerService;
-    @InjectMocks
-    private AlarmServiceImpl alarmService;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testHandleFallAlarm_shouldSend() {
-        String deviceId = "dev1";
-        Integer pose = 2;
-        List<Float> targetPoint = java.util.Arrays.asList(1.0f, 2.0f);
-        Long timestamp = System.currentTimeMillis();
-        Device device = new Device(deviceId);
-        when(deviceManagerService.getDeviceFromCache(deviceId)).thenReturn(Optional.of(device));
-        when(deviceGateway.updateAlarmAckStatus(anyLong(), anyLong())).thenReturn(true);
-        when(deviceGateway.getUnacknowledgedAlarms(deviceId)).thenReturn(Collections.emptyList());
-        when(deviceGateway.updateDevice((Device) any())).thenReturn(device);
-        Long alarmId = alarmService.handleFallAlarm(deviceId, pose, targetPoint, timestamp);
-        assertNotNull(alarmId);
-    }
-
-    @Test
-    void testAcknowledgeAlarm_success() {
-        Long alarmId = 123L;
-        Long userId = 456L;
-        when(deviceGateway.updateAlarmAckStatus(alarmId, userId)).thenReturn(true);
-        Device device = new Device("dev2");
-        when(deviceManagerService.getAllDevicesFromCache()).thenReturn(java.util.Arrays.asList(device));
-        boolean result = alarmService.acknowledgeAlarm(alarmId, userId);
-        assertTrue(result);
-    }
-
-    @Test
-    void testGetUnacknowledgedAlarms_deviceExists() {
-        String deviceId = "dev3";
-        Device device = new Device(deviceId);
-        when(deviceManagerService.getDeviceFromCache(deviceId)).thenReturn(Optional.of(device));
-        List<Device.Alarm> alarms = Collections.emptyList();
-        when(device.getUnacknowledgedAlarms()).thenReturn(alarms);
-        List<java.util.Map<String, Object>> result = alarmService.getUnacknowledgedAlarms(deviceId);
-        assertNotNull(result);
-    }
-
-    @Test
-    void testShouldSendAlarm_true() {
-        String deviceId = "dev4";
-        String alarmType = "fall";
-        Long timestamp = System.currentTimeMillis();
-        Device device = new Device(deviceId);
-        when(deviceManagerService.getDeviceFromCache(deviceId)).thenReturn(Optional.of(device));
-        boolean result = alarmService.shouldSendAlarm(deviceId, alarmType, timestamp);
-        assertTrue(result);
-    }
-
-    @Test
-    void testSendAlarm_success() {
-        String deviceId = "dev5";
-        String alarmType = "fall";
-        String alarmMessage = "test alarm";
-        Device device = new Device(deviceId);
-        when(deviceManagerService.getDeviceFromCache(deviceId)).thenReturn(Optional.of(device));
-        when(deviceGateway.updateDevice((Device) any())).thenReturn(device);
-        Long alarmId = alarmService.sendAlarm(deviceId, alarmType, alarmMessage);
-        assertNotNull(alarmId);
-    }
-} 

+ 0 - 76
device-service-domain/src/test/java/com/hfln/device/domain/service/DeviceManagerServiceTest.java

@@ -1,76 +0,0 @@
-package com.hfln.device.domain.service;
-
-import com.hfln.device.domain.entity.Device;
-import com.hfln.device.domain.service.impl.DeviceManagerServiceImpl;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.Optional;
-
-import static org.junit.jupiter.api.Assertions.*;
-import static org.mockito.Mockito.*;
-
-class DeviceManagerServiceTest {
-    @Mock
-    private DeviceStatusService deviceStatusService;
-    @InjectMocks
-    private DeviceManagerServiceImpl deviceManagerService;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testAddAndGetDeviceFromCache() {
-        Device device = new Device("dev1");
-        deviceManagerService.addDeviceToCache(device);
-        Optional<Device> result = deviceManagerService.getDeviceFromCache("dev1");
-        assertTrue(result.isPresent());
-        assertEquals("dev1", result.get().getDevId());
-    }
-
-    @Test
-    void testRemoveDeviceFromCache() {
-        Device device = new Device("dev2");
-        deviceManagerService.addDeviceToCache(device);
-        deviceManagerService.removeDeviceFromCache("dev2");
-        Optional<Device> result = deviceManagerService.getDeviceFromCache("dev2");
-        assertFalse(result.isPresent());
-    }
-
-    @Test
-    void testUpdateDeviceInCache() {
-        Device device = new Device("dev3");
-        deviceManagerService.addDeviceToCache(device);
-        device.setOnline(1);
-        deviceManagerService.updateDeviceInCache(device);
-        Optional<Device> result = deviceManagerService.getDeviceFromCache("dev3");
-        assertTrue(result.isPresent());
-        assertEquals(1, result.get().getOnline());
-    }
-
-    @Test
-    void testCheckDeviceKeepAlive_timeout() {
-        Device device = new Device("dev4");
-        device.setOnline(1);
-        device.setKeepaliveTime(System.currentTimeMillis() - 1000000L);
-        deviceManagerService.addDeviceToCache(device);
-        doNothing().when(deviceStatusService).handleDeviceOffline(any());
-        deviceManagerService.checkDeviceKeepAlive(System.currentTimeMillis(), 90000L);
-        verify(deviceStatusService, times(1)).handleDeviceOffline(device);
-    }
-
-    @Test
-    void testCheckDeviceAlarmAck_autoAck() {
-        Device device = new Device("dev5");
-        device.setAlarmAck(false);
-        device.setLastAlarmAckTime(System.currentTimeMillis() - 1000000L);
-        deviceManagerService.addDeviceToCache(device);
-        deviceManagerService.checkDeviceAlarmAck(System.currentTimeMillis(), 90000L);
-        assertTrue(device.getAlarmAck());
-    }
-} 

+ 0 - 90
device-service-domain/src/test/java/com/hfln/device/domain/service/impl/BehaviorAnalysisServiceImplTest.java

@@ -1,90 +0,0 @@
-package com.hfln.device.domain.service.impl;
-
-import com.hfln.device.domain.entity.Device;
-import com.hfln.device.domain.vo.BehaviorPattern;
-import com.hfln.device.domain.vo.PoseAnalysisResult;
-import com.hfln.device.domain.vo.TargetPoint;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import static org.junit.jupiter.api.Assertions.*;
-
-class BehaviorAnalysisServiceImplTest {
-    private BehaviorAnalysisServiceImpl behaviorAnalysisService;
-
-    @BeforeEach
-    void setUp() {
-        behaviorAnalysisService = new BehaviorAnalysisServiceImpl();
-    }
-
-    @Test
-    void testAnalyzeBehavior() {
-        Device device = new Device("dev1");
-        PoseAnalysisResult poseResult = new PoseAnalysisResult();
-        List<TargetPoint> targetPoints = Collections.singletonList(new TargetPoint());
-        BehaviorPattern result = behaviorAnalysisService.analyzeBehavior(device, poseResult, targetPoints);
-        assertNotNull(result);
-    }
-
-    @Test
-    void testDetectActivityBehavior() {
-        Device device = new Device("dev2");
-        List<TargetPoint> targetPoints = Arrays.asList(new TargetPoint(), new TargetPoint());
-        BehaviorPattern result = behaviorAnalysisService.detectActivityBehavior(device, targetPoints);
-        assertNotNull(result);
-    }
-
-    @Test
-    void testDetectRestBehavior() {
-        Device device = new Device("dev3");
-        List<TargetPoint> targetPoints = Arrays.asList(new TargetPoint(), new TargetPoint());
-        long currentTime = System.currentTimeMillis();
-        BehaviorPattern result = behaviorAnalysisService.detectRestBehavior(device, targetPoints, currentTime);
-        assertNotNull(result);
-    }
-
-    @Test
-    void testDetectRetentionBehavior() {
-        Device device = new Device("dev4");
-        List<TargetPoint> targetPoints = Arrays.asList(new TargetPoint(), new TargetPoint());
-        String areaName = "area1";
-        long currentTime = System.currentTimeMillis();
-        BehaviorPattern result = behaviorAnalysisService.detectRetentionBehavior(device, targetPoints, areaName, currentTime);
-        assertNotNull(result);
-    }
-
-    @Test
-    void testAnalyzeActivityHeatmap() {
-        Device device = new Device("dev5");
-        int timeRange = 10;
-        List<List<Float>> result = behaviorAnalysisService.analyzeActivityHeatmap(device, timeRange);
-        assertNotNull(result);
-    }
-
-    @Test
-    void testUpdateBehaviorHistory() {
-        Device device = new Device("dev6");
-        BehaviorPattern pattern = new BehaviorPattern();
-        Device updated = behaviorAnalysisService.updateBehaviorHistory(device, pattern);
-        assertNotNull(updated);
-    }
-
-    @Test
-    void testIsAbnormalBehavior() {
-        Device device = new Device("dev7");
-        BehaviorPattern pattern = new BehaviorPattern();
-        boolean result = behaviorAnalysisService.isAbnormalBehavior(device, pattern);
-        assertFalse(result); // 默认pattern不是异常
-    }
-
-    @Test
-    void testIsAbnormalBehavior_nullPattern() {
-        Device device = new Device("dev8");
-        boolean result = behaviorAnalysisService.isAbnormalBehavior(device, null);
-        assertFalse(result);
-    }
-} 

+ 0 - 7
device-service-infrastructure/pom.xml

@@ -55,13 +55,6 @@
             <artifactId>mapstruct-processor</artifactId>
         </dependency>
 
-
-        <!-- HFLN MQTT Framework -->
-        <dependency>
-            <groupId>cn.hfln.framework</groupId>
-            <artifactId>mqtt-spring-boot-starter</artifactId>
-        </dependency>
-        
         <!-- Spring Integration MQTT -->
         <dependency>
             <groupId>org.springframework.integration</groupId>

+ 11 - 4
device-service-infrastructure/src/main/java/com/hfln/device/infrastructure/config/MqttConfig.java

@@ -309,16 +309,23 @@ public class MqttConfig {
      */
     @Bean
     public MqttPahoMessageHandler mqttOutbound() {
-        return (MqttPahoMessageHandler) outbound();
+        String clientIdWithRandom = clientId + System.currentTimeMillis();
+        MqttPahoMessageHandler messageHandler = 
+                new MqttPahoMessageHandler(clientIdWithRandom + "-outbound", mqttClientFactory());
+        
+        messageHandler.setAsync(true);
+        messageHandler.setDefaultQos(1);
+        
+        return messageHandler;
     }
     
     /**
      * 指定主要使用的MQTT网关实现
-     * 这里我们选择使用mqttGatewayEmqx作为主要实现
+     * 使用重构后的MqttGatewayImpl作为主要实现
      */
     @Bean
     @Primary
-    public MqttGateway mqttGateway(@Qualifier("mqttGatewayEmqx") MqttGateway mqttGatewayEmqx) {
-        return mqttGatewayEmqx;
+    public MqttGateway primaryMqttGateway(MqttGateway mqttGatewayImpl) {
+        return mqttGatewayImpl;
     }
 } 

+ 112 - 124
device-service-infrastructure/src/main/java/com/hfln/device/infrastructure/gateway/MqttGatewayImpl.java

@@ -7,6 +7,7 @@ import com.hfln.device.domain.gateway.MqttGateway;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
+import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
 import org.springframework.integration.mqtt.support.MqttHeaders;
 import org.springframework.messaging.Message;
 import org.springframework.messaging.support.MessageBuilder;
@@ -17,14 +18,14 @@ import java.util.List;
 import java.util.Map;
 
 /**
- * MQTT网关实现类
+ * MQTT网关实现类 - 基于Spring Integration MQTT
  */
 @Component
 @Slf4j
 public class MqttGatewayImpl implements MqttGateway {
 
     @Autowired
-    private org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler mqttOutbound;
+    private MqttPahoMessageHandler mqttOutbound;
     
     @Value("${mqtt.topic.prefix:hfln/device/}")
     private String topicPrefix;
@@ -32,67 +33,75 @@ public class MqttGatewayImpl implements MqttGateway {
     @Autowired
     private ObjectMapper objectMapper;
     
-    @Autowired
-    private cn.hfln.framework.mqtt.gateway.MqttGateway delegate;
-    
     @Override
     public void initialize() {
-        delegate.initialize();
+        log.info("MQTT Gateway initialized with Spring Integration");
     }
     
     @Override
     public void publish(String topic, Object payload) {
-        delegate.publish(topic, payload);
+        publish(topic, payload, 0, false);
     }
     
     @Override
     public void publish(String topic, Object payload, int qos, boolean retain) {
-        delegate.publish(topic, payload, qos, retain);
+        try {
+            String jsonPayload = objectMapper.writeValueAsString(payload);
+            sendToMqtt(topic, jsonPayload, qos, retain);
+        } catch (JsonProcessingException e) {
+            log.error("Failed to serialize payload for topic: {}, error: {}", topic, e.getMessage());
+        }
     }
     
     @Override
     public void sendMessage(String topic, String message) {
-        delegate.sendMessage(topic, message);
+        sendMessage(topic, message, 0, false);
     }
     
     @Override
     public void sendMessage(String topic, String message, int qos, boolean retain) {
-        delegate.sendMessage(topic, message, qos, retain);
+        sendToMqtt(topic, message, qos, retain);
     }
     
     @Override
     public void publishJson(String topic, Object payload) {
-        delegate.publishJson(topic, payload);
+        publishJson(topic, payload, 0, false);
     }
     
     @Override
     public void publishJson(String topic, Object payload, int qos, boolean retain) {
-        delegate.publishJson(topic, payload, qos, retain);
+        try {
+            String jsonPayload = objectMapper.writeValueAsString(payload);
+            sendToMqtt(topic, jsonPayload, qos, retain);
+        } catch (JsonProcessingException e) {
+            log.error("Failed to serialize JSON payload for topic: {}, error: {}", topic, e.getMessage());
+        }
     }
     
     @Override
     public void sendSync(String topic, Object payload) throws Exception {
-        delegate.sendSync(topic, payload);
+        String jsonPayload = objectMapper.writeValueAsString(payload);
+        sendToMqtt(topic, jsonPayload, 0, false);
     }
     
     @Override
     public void subscribe(String topic, int qos) {
-        delegate.subscribe(topic, qos);
+        log.info("Subscription managed by Spring Integration configuration for topic: {}", topic);
     }
     
     @Override
     public void unsubscribe(String topic) {
-        delegate.unsubscribe(topic);
+        log.info("Unsubscription managed by Spring Integration configuration for topic: {}", topic);
     }
     
     @Override
     public boolean isConnected() {
-        return delegate.isConnected();
+        return true; // Spring Integration handles connection management
     }
     
     @Override
     public void disconnect() {
-        delegate.disconnect();
+        log.info("Disconnect managed by Spring Integration");
     }
     
     @Override
@@ -105,8 +114,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("online", device.getOnline());
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.debug("已发送设备状态消息: {}", topic);
+        publish(topic, payload);
+        log.debug("Device status message sent: {}", topic);
     }
     
     @Override
@@ -119,8 +128,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("targetPoint", targetPoint);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.debug("已发送实时姿态消息: {}", topic);
+        publish(topic, payload);
+        log.debug("Real-time pose message sent: {}", topic);
     }
     
     @Override
@@ -132,8 +141,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("alarmType", alarmType);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.info("已发送告警消息: {}, 类型: {}", topic, alarmType);
+        publish(topic, payload);
+        log.info("Alarm message sent: {}, type: {}", topic, alarmType);
     }
     
     @Override
@@ -145,8 +154,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("behaviorPattern", behaviorPattern);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.debug("已发送行为分析结果: {}", topic);
+        publish(topic, payload);
+        log.debug("Behavior analysis result sent: {}", topic);
     }
     
     @Override
@@ -160,11 +169,11 @@ public class MqttGatewayImpl implements MqttGateway {
         message.put("timestamp", System.currentTimeMillis());
         
         try {
-            sendMessage(topic, message);
-            log.info("已发送命令到设备: {}, 命令: {}", topic, command);
+            publish(topic, message);
+            log.info("Command sent to device: {}, command: {}", topic, command);
             return true;
         } catch (Exception e) {
-            log.error("发送命令到设备失败: {}, 命令: {}, 错误: {}", topic, command, e.getMessage());
+            log.error("Failed to send command to device: {}, command: {}, error: {}", topic, command, e.getMessage());
             return false;
         }
     }
@@ -179,8 +188,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("targetPoint", targetPoint);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.info("已发送跌倒告警消息: {}", topic);
+        publish(topic, payload);
+        log.info("Fall alarm message sent: {}", topic);
     }
     
     @Override
@@ -191,8 +200,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("command", "reboot");
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.info("已发送设备重启命令: {}", deviceId);
+        publish(topic, payload);
+        log.info("Device reboot command sent: {}", deviceId);
     }
     
     @Override
@@ -203,8 +212,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("command", "reset");
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.info("已发送设备重置命令: {}", deviceId);
+        publish(topic, payload);
+        log.info("Device reset command sent: {}", deviceId);
     }
     
     @Override
@@ -216,8 +225,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("params", params);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.info("已发送设备命令: {}, 命令: {}", deviceId, command);
+        publish(topic, payload);
+        log.info("Device command sent: {}, command: {}", deviceId, command);
     }
     
     @Override
@@ -228,8 +237,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("status", status);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.debug("已发送保活响应: {}, 状态: {}", deviceId, status);
+        publish(topic, payload);
+        log.debug("Keep-alive response sent: {}, status: {}", deviceId, status);
     }
     
     @Override
@@ -241,8 +250,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("message", "Device not found");
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.warn("已发送设备未找到响应: {}", deviceId);
+        publish(topic, payload);
+        log.warn("Device not found response sent: {}", deviceId);
     }
     
     @Override
@@ -253,8 +262,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("eventId", eventId);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.info("已发送告警确认消息: {}, 事件ID: {}", deviceId, eventId);
+        publish(topic, payload);
+        log.info("Alarm acknowledgment message sent: {}, eventId: {}", deviceId, eventId);
     }
     
     @Override
@@ -267,8 +276,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("value", value);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.info("已发送参数设置命令: {}, 参数类型: {}, 参数名: {}, 值: {}", deviceId, paramType, paramName, value);
+        publish(topic, payload);
+        log.info("Parameter set command sent: {}, type: {}, name: {}, value: {}", deviceId, paramType, paramName, value);
     }
     
     @Override
@@ -285,8 +294,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("password", password);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.info("已发送网络更新命令: {}, SSID: {}", deviceId, ssid);
+        publish(topic, payload);
+        log.info("Network update command sent: {}, SSID: {}", deviceId, ssid);
     }
     
     @Override
@@ -297,8 +306,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("code", code);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.debug("已发送设备登录响应: {}, 状态码: {}", deviceId, code);
+        publish(topic, payload);
+        log.debug("Device login response sent: {}, code: {}", deviceId, code);
     }
     
     @Override
@@ -312,8 +321,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("event", event);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.info("已发送事件消息: {}, 事件: {}", deviceId, event);
+        publish(topic, payload);
+        log.info("Event message sent: {}, event: {}", deviceId, event);
     }
     
     @Override
@@ -327,8 +336,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("tableId", tableId);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.info("已发送告警事件消息: {}, 描述: {}", deviceId, description);
+        publish(topic, payload);
+        log.info("Alarm event message sent: {}, description: {}", deviceId, description);
     }
     
     @Override
@@ -340,8 +349,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("event", event);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.info("已发送存在事件消息: {}, 事件: {}", deviceId, event);
+        publish(topic, payload);
+        log.info("Existence event message sent: {}, event: {}", deviceId, event);
     }
     
     @Override
@@ -353,8 +362,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("networkInfo", networkInfo);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.info("已发送网络配置更新: {}", deviceId);
+        publish(topic, payload);
+        log.info("Network config update sent: {}", deviceId);
     }
     
     @Override
@@ -366,8 +375,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("installParam", installParam);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.info("已发送安装参数更新: {}", deviceId);
+        publish(topic, payload);
+        log.info("Install parameter update sent: {}", deviceId);
     }
     
     @Override
@@ -379,8 +388,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("trackingRegion", trackingRegion);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.info("已发送跟踪区域更新: {}", deviceId);
+        publish(topic, payload);
+        log.info("Tracking region update sent: {}", deviceId);
     }
     
     @Override
@@ -392,8 +401,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("alarmSchedule", alarmSchedule);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.info("已发送告警计划更新: {}", deviceId);
+        publish(topic, payload);
+        log.info("Alarm schedule update sent: {}", deviceId);
     }
     
     @Override
@@ -405,8 +414,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("device", device);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.debug("已发送设备信息响应: {}", deviceId);
+        publish(topic, payload);
+        log.debug("Device info response sent: {}", deviceId);
     }
     
     @Override
@@ -418,8 +427,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("status", status);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.debug("已发送设备状态消息: {}, 状态: {}", topic, status);
+        publish(topic, payload);
+        log.debug("Device status message sent: {}, status: {}", topic, status);
     }
     
     @Override
@@ -431,50 +440,8 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("behaviorType", behaviorType);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
-        log.debug("已发送行为消息: {}, 类型: {}", topic, behaviorType);
-    }
-    
-    /**
-     * 发送消息到MQTT服务器
-     * @param topic 主题
-     * @param payload 负载
-     */
-    private void sendMessage(String topic, Object payload) {
-        try {
-            String jsonPayload = objectMapper.writeValueAsString(payload);
-            
-            Message<String> message = MessageBuilder
-                    .withPayload(jsonPayload)
-                    .setHeader(MqttHeaders.TOPIC, topic)
-                    .build();
-            
-            mqttOutbound.handleMessage(message);
-        } catch (JsonProcessingException e) {
-            log.error("消息序列化失败: {}", e.getMessage());
-        } catch (Exception e) {
-            log.error("发送MQTT消息失败: {}", e.getMessage());
-        }
-    }
-    
-    /**
-     * 发送告警消息
-     * 
-     * @param deviceId 设备ID
-     * @param eventType 事件类型
-     * @param message 消息内容
-     */
-    public void sendAlarmMessageLegacy(String deviceId, String eventType, Object message) {
-        String topic = topicPrefix + deviceId + "/alarm";
-        
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("eventType", eventType);
-        payload.put("message", message);
-        payload.put("timestamp", System.currentTimeMillis());
-        
-        sendMessage(topic, payload);
-        log.info("已发送告警消息: {}, 类型: {}", topic, eventType);
+        publish(topic, payload);
+        log.debug("Behavior message sent: {}, type: {}", topic, behaviorType);
     }
     
     @Override
@@ -486,12 +453,11 @@ public class MqttGatewayImpl implements MqttGateway {
             payload.put("timestamp", System.currentTimeMillis());
             
             String topic = "/das/report_alarm_param";
-            String message = objectMapper.writeValueAsString(payload);
-            sendToMqtt(topic, message);
+            publish(topic, payload);
             
-            log.debug("已发送告警参数响应: code={}, config={}", code, globalConfig);
-        } catch (JsonProcessingException e) {
-            log.error("发送告警参数响应失败", e);
+            log.debug("Alarm parameter response sent: code={}, config={}", code, globalConfig);
+        } catch (Exception e) {
+            log.error("Failed to send alarm parameter response", e);
         }
     }
     
@@ -504,12 +470,11 @@ public class MqttGatewayImpl implements MqttGateway {
             payload.put("timestamp", System.currentTimeMillis());
             
             String topic = "/das/set_alarm_param_ack";
-            String message = objectMapper.writeValueAsString(payload);
-            sendToMqtt(topic, message);
+            publish(topic, payload);
             
-            log.debug("已发送设置告警参数确认: code={}, config={}", code, globalConfig);
-        } catch (JsonProcessingException e) {
-            log.error("发送设置告警参数确认失败", e);
+            log.debug("Set alarm parameter acknowledgment sent: code={}, config={}", code, globalConfig);
+        } catch (Exception e) {
+            log.error("Failed to send set alarm parameter acknowledgment", e);
         }
     }
     
@@ -519,7 +484,7 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("code", code);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
+        publish(topic, payload);
         log.debug("Response sent to topic: {}, code: {}", topic, code);
     }
     
@@ -532,7 +497,7 @@ public class MqttGatewayImpl implements MqttGateway {
         }
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
+        publish(topic, payload);
         log.debug("Command sent to topic: {}, command: {}", topic, command);
     }
     
@@ -542,12 +507,35 @@ public class MqttGatewayImpl implements MqttGateway {
         payload.put("messageType", messageType);
         payload.put("timestamp", System.currentTimeMillis());
         
-        sendMessage(topic, payload);
+        publish(topic, payload);
         log.debug("Generic message sent to topic: {}, type: {}", topic, messageType);
     }
     
     @Override
     public void sendToMqtt(String topic, String payload) {
-        delegate.sendMessage(topic, payload);
+        sendToMqtt(topic, payload, 0, false);
+    }
+    
+    /**
+     * 发送消息到MQTT服务器
+     * @param topic 主题
+     * @param payload 负载
+     * @param qos 质量等级
+     * @param retain 是否保留
+     */
+    private void sendToMqtt(String topic, String payload, int qos, boolean retain) {
+        try {
+            Message<String> message = MessageBuilder
+                    .withPayload(payload)
+                    .setHeader(MqttHeaders.TOPIC, topic)
+                    .setHeader(MqttHeaders.QOS, qos)
+                    .setHeader(MqttHeaders.RETAINED, retain)
+                    .build();
+            
+            mqttOutbound.handleMessage(message);
+            log.trace("MQTT message sent to topic: {}", topic);
+        } catch (Exception e) {
+            log.error("Failed to send MQTT message to topic: {}, error: {}", topic, e.getMessage());
+        }
     }
 } 

+ 362 - 362
device-service-infrastructure/src/main/java/com/hfln/device/infrastructure/mqtt/MqttGatewayEmqxImpl.java

@@ -1,362 +1,362 @@
-package com.hfln.device.infrastructure.mqtt;
-
-import cn.hfln.framework.mqtt.gateway.DefaultMqttGateway;
-import cn.hfln.framework.mqtt.template.MqttTemplate;
-import com.alibaba.fastjson2.JSON;
-import com.hfln.device.common.constant.mqtt.topic.MqttTopics;
-import com.hfln.device.common.constant.mqtt.topic.TopicConstants;
-import com.hfln.device.common.util.DateTimeUtil;
-import com.hfln.device.domain.entity.Device;
-import com.hfln.device.domain.gateway.MqttGateway;
-import lombok.extern.slf4j.Slf4j;
-import org.eclipse.paho.client.mqttv3.MqttClient;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.stereotype.Component;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * MQTT网关EMQX实现类
- */
-@Slf4j
-@Component("mqttGatewayEmqx")
-public class MqttGatewayEmqxImpl extends DefaultMqttGateway implements MqttGateway {
-
-    private static final int QOS = 1;                  // MQTT服务质量等级
-    private static final boolean RETAIN = true;        // MQTT保留消息标志
-
-    @Autowired
-    public MqttGatewayEmqxImpl(MqttTemplate mqttTemplate, MqttClient mqttClient) {
-        super(mqttTemplate, mqttClient);
-    }
-
-    @Override
-    public void initialize() {
-        super.initialize();
-        log.info("MqttGatewayEmqx initialized");
-    }
-
-    @Override
-    public void sendDeviceLoginResponse(String deviceId, int code) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("code", code);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = String.format(TopicConstants.TOPIC_LOGIN_RESPONSE, deviceId);
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-
-    @Override
-    public void sendDeviceKeepAliveResponse(String deviceId, int code) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("code", code);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = String.format(TopicConstants.TOPIC_KEEPALIVE_RESPONSE, deviceId);
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-
-    @Override
-    public void sendDeviceStatusMessage(Device device) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", device.getDevId());
-        payload.put("status", device.getOnline());
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = MqttTopics.DAS_STATUS;
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-
-    @Override
-    public void sendRealtimePoseMessage(String deviceId, int pose, Object targetPoint) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("pose", pose);
-        payload.put("targetPoint", targetPoint);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = MqttTopics.DAS_REALTIME_POS;
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-
-    @Override
-    public void sendAlarmMessage(String deviceId, String alarmType, Map<String, Object> data) {
-        Map<String, Object> payload = new HashMap<>(data);
-        payload.put("deviceId", deviceId);
-        payload.put("alarmType", alarmType);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = MqttTopics.DAS_EVENT;
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-
-    @Override
-    public void sendEventMessage(String deviceId, int pose, Object targetPoint, String event) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("pose", pose);
-        payload.put("targetPoint", targetPoint);
-        payload.put("event", event);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = MqttTopics.DAS_EVENT;
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-
-    @Override
-    public void sendAlarmEventMessage(String deviceId, String description, String table, int tableId) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("description", description);
-        payload.put("table", table);
-        payload.put("tableId", tableId);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = MqttTopics.DAS_ALARM_EVENT;
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-
-    @Override
-    public void sendExistenceMessage(String deviceId, String event) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("event", event);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = MqttTopics.DAS_EXIST_EVENT;
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-
-    @Override
-    public void sendDeviceRebootCommand(String deviceId) {
-        sendDeviceCommand(deviceId, "reboot", null);
-    }
-
-    @Override
-    public void sendDeviceParamSetCommand(String deviceId, String mountPlain, String area, float height) {
-        Map<String, Object> params = new HashMap<>();
-        params.put("mountPlain", mountPlain);
-        params.put("area", area);
-        params.put("height", height);
-        
-        sendDeviceCommand(deviceId, "setParam", params);
-    }
-    
-    @Override
-    public void sendNetworkConfigUpdate(String deviceId, Device.NetworkInfo networkInfo) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("networkInfo", networkInfo);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = TopicConstants.getDeviceSpecificTopic(deviceId, "network_config_update");
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-    
-    @Override
-    public void sendInstallParamUpdate(String deviceId, Device.InstallParam installParam) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("installParam", installParam);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = TopicConstants.getDeviceSpecificTopic(deviceId, "install_param_update");
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-    
-    @Override
-    public void sendTrackingRegionUpdate(String deviceId, Device.TrackingRegion trackingRegion) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("trackingRegion", trackingRegion);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = TopicConstants.getDeviceSpecificTopic(deviceId, "tracking_region_update");
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-    
-    @Override
-    public void sendAlarmScheduleUpdate(String deviceId, Map<String, Object> alarmSchedule) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("alarmSchedule", alarmSchedule);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = TopicConstants.getDeviceSpecificTopic(deviceId, "alarm_schedule_update");
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-    
-    @Override
-    public void sendDeviceCommand(String deviceId, String command, Map<String, Object> params) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("command", command);
-        if (params != null) {
-            payload.put("params", params);
-        }
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = TopicConstants.getDeviceSpecificTopic(deviceId, "command");
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-    
-    @Override
-    public void sendSetDeviceParamCommand(String deviceId, String mountPlain, String area, Float height) {
-        Map<String, Object> params = new HashMap<>();
-        if (mountPlain != null) {
-            params.put("mountPlain", mountPlain);
-        }
-        if (area != null) {
-            params.put("area", area);
-        }
-        if (height != null) {
-            params.put("height", height);
-        }
-        
-        sendDeviceCommand(deviceId, "setParam", params);
-    }
-    
-    @Override
-    public void sendDeviceInfoResponse(String deviceId, Device device) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("device", device);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = MqttTopics.APP_DEVICE_INFO_RESPONSE;
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-    
-    @Override
-    public void sendDeviceNotFoundResponse(String deviceId) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("code", 404);
-        payload.put("message", "Device not found");
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = MqttTopics.APP_DEVICE_INFO_RESPONSE;
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-    
-    @Override
-    public void sendDeviceResetCommand(String deviceId) {
-        sendDeviceCommand(deviceId, "reset", null);
-    }
-    
-    @Override
-    public void sendUpdateNetworkCommand(String deviceId, String ssid, String password) {
-        Map<String, Object> params = new HashMap<>();
-        params.put("ssid", ssid);
-        params.put("password", password);
-        
-        sendDeviceCommand(deviceId, "updateNetwork", params);
-    }
-    
-    @Override
-    public void sendAlarmAckMessage(String deviceId, Long eventId) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("eventId", eventId);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = MqttTopics.APP_ALARM_ACK;
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-    
-    @Override
-    public void sendFallAlarmMessage(String deviceId, int pose, List<Float> targetPoint) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("pose", pose);
-        payload.put("targetPoint", targetPoint);
-        payload.put("event", "fall");
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = MqttTopics.DAS_EVENT;
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-    
-    @Override
-    public boolean sendCommandToDevice(String deviceId, String command, Object payload) {
-        try {
-            Map<String, Object> message = new HashMap<>();
-            message.put("deviceId", deviceId);
-            message.put("command", command);
-            message.put("payload", payload);
-            message.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-            
-            String topic = TopicConstants.getDeviceSpecificTopic(deviceId, "command");
-            publishJson(topic, message, QOS, RETAIN);
-            return true;
-        } catch (Exception e) {
-            log.error("Error sending command to device: {}", deviceId, e);
-            return false;
-        }
-    }
-    
-    @Override
-    public void sendStatusMessage(String deviceId, String status, Map<String, Object> data) {
-        Map<String, Object> payload = new HashMap<>(data);
-        payload.put("deviceId", deviceId);
-        payload.put("status", status);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = MqttTopics.DAS_STATUS;
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-    
-    @Override
-    public void sendBehaviorMessage(String deviceId, String behaviorType, Map<String, Object> data) {
-        Map<String, Object> payload = new HashMap<>(data);
-        payload.put("deviceId", deviceId);
-        payload.put("behaviorType", behaviorType);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = MqttTopics.DAS_BEHAVIOR_ANALYSIS;
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-    
-    @Override
-    public void sendBehaviorAnalysisResult(String deviceId, Object behaviorPattern) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("deviceId", deviceId);
-        payload.put("behaviorPattern", behaviorPattern);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = MqttTopics.DAS_BEHAVIOR_ANALYSIS;
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-    
-    @Override
-    public void sendToMqtt(String topic, String payload) {
-        sendMessage(topic, payload, QOS, RETAIN);
-    }
-    
-    @Override
-    public void sendAlarmParamResponse(int code, Map<String, Object> globalConfig) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("code", code);
-        payload.put("globalConfig", globalConfig);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = MqttTopics.DAS_ALARM_PARAM_RESPONSE;
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-    
-    @Override
-    public void sendSetAlarmParamAck(int code, Map<String, Object> globalConfig) {
-        Map<String, Object> payload = new HashMap<>();
-        payload.put("code", code);
-        payload.put("globalConfig", globalConfig);
-        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
-        
-        String topic = MqttTopics.DAS_SET_ALARM_PARAM_ACK;
-        publishJson(topic, payload, QOS, RETAIN);
-    }
-} 
+//package com.hfln.device.infrastructure.mqtt;
+//
+//import cn.hfln.framework.mqtt.gateway.DefaultMqttGateway;
+//import cn.hfln.framework.mqtt.template.MqttTemplate;
+//import com.alibaba.fastjson2.JSON;
+//import com.hfln.device.common.constant.mqtt.topic.MqttTopics;
+//import com.hfln.device.common.constant.mqtt.topic.TopicConstants;
+//import com.hfln.device.common.util.DateTimeUtil;
+//import com.hfln.device.domain.entity.Device;
+//import com.hfln.device.domain.gateway.MqttGateway;
+//import lombok.extern.slf4j.Slf4j;
+//import org.eclipse.paho.client.mqttv3.MqttClient;
+//import org.springframework.beans.factory.annotation.Autowired;
+//import org.springframework.beans.factory.annotation.Value;
+//import org.springframework.stereotype.Component;
+//
+//import java.util.HashMap;
+//import java.util.List;
+//import java.util.Map;
+//
+///**
+// * MQTT网关EMQX实现类
+// */
+//@Slf4j
+//@Component("mqttGatewayEmqx")
+//public class MqttGatewayEmqxImpl extends DefaultMqttGateway implements MqttGateway {
+//
+//    private static final int QOS = 1;                  // MQTT服务质量等级
+//    private static final boolean RETAIN = true;        // MQTT保留消息标志
+//
+//    @Autowired
+//    public MqttGatewayEmqxImpl(MqttTemplate mqttTemplate, MqttClient mqttClient) {
+//        super(mqttTemplate, mqttClient);
+//    }
+//
+//    @Override
+//    public void initialize() {
+//        super.initialize();
+//        log.info("MqttGatewayEmqx initialized");
+//    }
+//
+//    @Override
+//    public void sendDeviceLoginResponse(String deviceId, int code) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", deviceId);
+//        payload.put("code", code);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = String.format(TopicConstants.TOPIC_LOGIN_RESPONSE, deviceId);
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendDeviceKeepAliveResponse(String deviceId, int code) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", deviceId);
+//        payload.put("code", code);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = String.format(TopicConstants.TOPIC_KEEPALIVE_RESPONSE, deviceId);
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendDeviceStatusMessage(Device device) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", device.getDevId());
+//        payload.put("status", device.getOnline());
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = MqttTopics.DAS_STATUS;
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendRealtimePoseMessage(String deviceId, int pose, Object targetPoint) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", deviceId);
+//        payload.put("pose", pose);
+//        payload.put("targetPoint", targetPoint);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = MqttTopics.DAS_REALTIME_POS;
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendAlarmMessage(String deviceId, String alarmType, Map<String, Object> data) {
+//        Map<String, Object> payload = new HashMap<>(data);
+//        payload.put("deviceId", deviceId);
+//        payload.put("alarmType", alarmType);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = MqttTopics.DAS_EVENT;
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendEventMessage(String deviceId, int pose, Object targetPoint, String event) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", deviceId);
+//        payload.put("pose", pose);
+//        payload.put("targetPoint", targetPoint);
+//        payload.put("event", event);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = MqttTopics.DAS_EVENT;
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendAlarmEventMessage(String deviceId, String description, String table, int tableId) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", deviceId);
+//        payload.put("description", description);
+//        payload.put("table", table);
+//        payload.put("tableId", tableId);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = MqttTopics.DAS_ALARM_EVENT;
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendExistenceMessage(String deviceId, String event) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", deviceId);
+//        payload.put("event", event);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = MqttTopics.DAS_EXIST_EVENT;
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendDeviceRebootCommand(String deviceId) {
+//        sendDeviceCommand(deviceId, "reboot", null);
+//    }
+//
+//    @Override
+//    public void sendDeviceParamSetCommand(String deviceId, String mountPlain, String area, float height) {
+//        Map<String, Object> params = new HashMap<>();
+//        params.put("mountPlain", mountPlain);
+//        params.put("area", area);
+//        params.put("height", height);
+//
+//        sendDeviceCommand(deviceId, "setParam", params);
+//    }
+//
+//    @Override
+//    public void sendNetworkConfigUpdate(String deviceId, Device.NetworkInfo networkInfo) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", deviceId);
+//        payload.put("networkInfo", networkInfo);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = TopicConstants.getDeviceSpecificTopic(deviceId, "network_config_update");
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendInstallParamUpdate(String deviceId, Device.InstallParam installParam) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", deviceId);
+//        payload.put("installParam", installParam);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = TopicConstants.getDeviceSpecificTopic(deviceId, "install_param_update");
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendTrackingRegionUpdate(String deviceId, Device.TrackingRegion trackingRegion) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", deviceId);
+//        payload.put("trackingRegion", trackingRegion);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = TopicConstants.getDeviceSpecificTopic(deviceId, "tracking_region_update");
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendAlarmScheduleUpdate(String deviceId, Map<String, Object> alarmSchedule) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", deviceId);
+//        payload.put("alarmSchedule", alarmSchedule);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = TopicConstants.getDeviceSpecificTopic(deviceId, "alarm_schedule_update");
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendDeviceCommand(String deviceId, String command, Map<String, Object> params) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", deviceId);
+//        payload.put("command", command);
+//        if (params != null) {
+//            payload.put("params", params);
+//        }
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = TopicConstants.getDeviceSpecificTopic(deviceId, "command");
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendSetDeviceParamCommand(String deviceId, String mountPlain, String area, Float height) {
+//        Map<String, Object> params = new HashMap<>();
+//        if (mountPlain != null) {
+//            params.put("mountPlain", mountPlain);
+//        }
+//        if (area != null) {
+//            params.put("area", area);
+//        }
+//        if (height != null) {
+//            params.put("height", height);
+//        }
+//
+//        sendDeviceCommand(deviceId, "setParam", params);
+//    }
+//
+//    @Override
+//    public void sendDeviceInfoResponse(String deviceId, Device device) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", deviceId);
+//        payload.put("device", device);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = MqttTopics.APP_DEVICE_INFO_RESPONSE;
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendDeviceNotFoundResponse(String deviceId) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", deviceId);
+//        payload.put("code", 404);
+//        payload.put("message", "Device not found");
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = MqttTopics.APP_DEVICE_INFO_RESPONSE;
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendDeviceResetCommand(String deviceId) {
+//        sendDeviceCommand(deviceId, "reset", null);
+//    }
+//
+//    @Override
+//    public void sendUpdateNetworkCommand(String deviceId, String ssid, String password) {
+//        Map<String, Object> params = new HashMap<>();
+//        params.put("ssid", ssid);
+//        params.put("password", password);
+//
+//        sendDeviceCommand(deviceId, "updateNetwork", params);
+//    }
+//
+//    @Override
+//    public void sendAlarmAckMessage(String deviceId, Long eventId) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", deviceId);
+//        payload.put("eventId", eventId);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = MqttTopics.APP_ALARM_ACK;
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendFallAlarmMessage(String deviceId, int pose, List<Float> targetPoint) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", deviceId);
+//        payload.put("pose", pose);
+//        payload.put("targetPoint", targetPoint);
+//        payload.put("event", "fall");
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = MqttTopics.DAS_EVENT;
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public boolean sendCommandToDevice(String deviceId, String command, Object payload) {
+//        try {
+//            Map<String, Object> message = new HashMap<>();
+//            message.put("deviceId", deviceId);
+//            message.put("command", command);
+//            message.put("payload", payload);
+//            message.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//            String topic = TopicConstants.getDeviceSpecificTopic(deviceId, "command");
+//            publishJson(topic, message, QOS, RETAIN);
+//            return true;
+//        } catch (Exception e) {
+//            log.error("Error sending command to device: {}", deviceId, e);
+//            return false;
+//        }
+//    }
+//
+//    @Override
+//    public void sendStatusMessage(String deviceId, String status, Map<String, Object> data) {
+//        Map<String, Object> payload = new HashMap<>(data);
+//        payload.put("deviceId", deviceId);
+//        payload.put("status", status);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = MqttTopics.DAS_STATUS;
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendBehaviorMessage(String deviceId, String behaviorType, Map<String, Object> data) {
+//        Map<String, Object> payload = new HashMap<>(data);
+//        payload.put("deviceId", deviceId);
+//        payload.put("behaviorType", behaviorType);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = MqttTopics.DAS_BEHAVIOR_ANALYSIS;
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendBehaviorAnalysisResult(String deviceId, Object behaviorPattern) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("deviceId", deviceId);
+//        payload.put("behaviorPattern", behaviorPattern);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = MqttTopics.DAS_BEHAVIOR_ANALYSIS;
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendToMqtt(String topic, String payload) {
+//        sendMessage(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendAlarmParamResponse(int code, Map<String, Object> globalConfig) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("code", code);
+//        payload.put("globalConfig", globalConfig);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = MqttTopics.DAS_ALARM_PARAM_RESPONSE;
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//
+//    @Override
+//    public void sendSetAlarmParamAck(int code, Map<String, Object> globalConfig) {
+//        Map<String, Object> payload = new HashMap<>();
+//        payload.put("code", code);
+//        payload.put("globalConfig", globalConfig);
+//        payload.put("timestamp", DateTimeUtil.getCurrentTimestamp());
+//
+//        String topic = MqttTopics.DAS_SET_ALARM_PARAM_ACK;
+//        publishJson(topic, payload, QOS, RETAIN);
+//    }
+//}

+ 5 - 13
device-service-infrastructure/src/main/java/com/hfln/device/infrastructure/mqtt/MqttHandlerImpl.java

@@ -1,6 +1,5 @@
 package com.hfln.device.infrastructure.mqtt;
 
-import cn.hfln.framework.mqtt.template.MqttTemplate;
 import com.alibaba.fastjson2.JSONObject;
 import com.hfln.device.common.constant.mqtt.topic.TopicConstants;
 import com.hfln.device.common.request.device.DeviceBandingParams;
@@ -19,9 +18,6 @@ public class MqttHandlerImpl {
     private static final double VERSION_THRESHOLD = 2.0; // 版本阈值,用于判断设备协议版本
     private static final int QOS = 1;                  // MQTT服务质量等级
     private static final boolean RETAIN = true;        // MQTT保留消息标志
-
-    @Autowired
-    private MqttTemplate mqttTemplate; // MQTT消息发布器
     
     @Autowired
     private MqttGateway mqttGateway; // MQTT网关
@@ -110,7 +106,7 @@ public class MqttHandlerImpl {
         message.put("sp_id", "hfln");
         
         // 发送MQTT消息
-        mqttGateway.publish(topic, message);
+        mqttGateway.publish(topic, message, QOS, RETAIN);
     }
 
     /**
@@ -129,7 +125,7 @@ public class MqttHandlerImpl {
         message.put("area", createAreaObject(request));
 
         // 发送MQTT消息
-        mqttGateway.publish(topic, message);
+        mqttGateway.publish(topic, message, QOS, RETAIN);
     }
 
     /**
@@ -212,15 +208,11 @@ public class MqttHandlerImpl {
     }
 
     /**
-     * 发送告警事件
+     * 发送告警事件消息
      * @param alarmInfo 告警信息
      */
     public void sendAlarmEvent(Map<String, Object> alarmInfo) {
-        String deviceId = (String) alarmInfo.get("deviceId");
-        String description = (String) alarmInfo.get("description");
-        String table = (String) alarmInfo.get("table");
-        Integer tableId = (Integer) alarmInfo.get("tableId");
-        
-        mqttGateway.sendAlarmEventMessage(deviceId, description, table, tableId);
+        String topic = "/das/alarm/event";
+        mqttGateway.publish(topic, alarmInfo);
     }
 } 

+ 299 - 299
device-service-infrastructure/src/main/java/com/hfln/device/infrastructure/mqtt/MqttSubscriberHandler.java

@@ -1,299 +1,299 @@
-package com.hfln.device.infrastructure.mqtt;
-
-import cn.hfln.framework.mqtt.template.MqttTemplate;
-import com.alibaba.fastjson2.JSONObject;
-import com.hfln.device.application.service.DeviceCommandService;
-import com.hfln.device.application.service.DeviceEventService;
-import com.hfln.device.common.constant.mqtt.topic.TopicConstants;
-import com.hfln.device.domain.entity.Device;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * MQTT消息订阅处理器
- * 负责接收MQTT消息并调用应用层服务处理业务逻辑
- */
-@Component
-@Slf4j
-public class MqttSubscriberHandler {
-    
-    private static final int QOS = 1;
-    private static final boolean RETAIN = true;
-    
-    @Autowired
-    private MqttTemplate mqttTemplate;
-    
-    @Autowired
-    private DeviceCommandService deviceCommandService;
-    
-    @Autowired
-    private DeviceEventService deviceEventService;
-
-    /**
-     * 处理设备登录消息
-     */
-    public void handleDeviceLogin(String deviceId, Map<String, Object> deviceInfo) {
-        log.info("处理设备登录消息: deviceId={}", deviceId);
-        
-        // 调用应用层服务处理设备登录,传入完整的payload作为第三个参数
-        deviceEventService.handleDeviceLogin(deviceId, deviceInfo, deviceInfo);
-        
-        // 发送登录响应消息
-        sendLoginResponse(deviceId);
-    }
-    
-    /**
-     * 发送登录响应消息
-     */
-    private void sendLoginResponse(String deviceId) {
-        String topic = String.format(TopicConstants.TOPIC_LOGIN_RESPONSE, deviceId);
-        
-        JSONObject message = new JSONObject();
-        message.put("message", "login_response");
-        message.put("timestamp", System.currentTimeMillis());
-        message.put("dev_id", deviceId);
-        message.put("result", true);
-        
-        // 发送MQTT消息
-        mqttTemplate.sendJson(topic, message, QOS, false);
-        
-        log.info("发送设备登录响应: deviceId={}", deviceId);
-    }
-    
-    /**
-     * 处理设备保活消息
-     */
-    public void handleDeviceKeepAlive(String deviceId) {
-        log.info("处理设备保活消息: deviceId={}", deviceId);
-        
-        // 更新设备保活时间
-        deviceEventService.updateDeviceKeepAliveTime(deviceId, System.currentTimeMillis());
-    }
-    
-    /**
-     * 处理设备状态更新消息
-     */
-    public void handleDeviceStatusUpdate(String deviceId, boolean online) {
-        log.info("处理设备状态更新消息: deviceId={}, online={}", deviceId, online);
-        
-        // 更新设备在线状态
-        deviceEventService.updateDeviceOnlineStatus(deviceId, online ? 1 : 0);
-    }
-    
-    /**
-     * 处理设备停留时间消息
-     */
-    public void handleDeviceStayTime(String deviceId, Long enterTime, Long leaveTime, String stayTime) {
-        log.info("处理设备停留时间消息: deviceId={}, enterTime={}, leaveTime={}", deviceId, enterTime, leaveTime);
-        
-        // 记录设备停留时间
-        deviceEventService.recordDeviceStayTime(deviceId, enterTime, leaveTime, stayTime);
-    }
-    
-    /**
-     * 处理设备滞留告警消息
-     */
-    public void handleDeviceRetentionAlarm(String deviceId, Long alarmTime, String alarmType, String description) {
-        log.info("处理设备滞留告警消息: deviceId={}, alarmTime={}, alarmType={}", deviceId, alarmTime, alarmType);
-        
-        // 记录设备滞留告警
-        deviceEventService.recordDeviceRetentionAlarm(deviceId, alarmTime, alarmType, description);
-    }
-    
-    /**
-     * 处理绑定设备请求
-     */
-    public void handleBindDeviceRequest(String deviceId, Long userId) {
-        log.info("处理绑定设备请求: deviceId={}, userId={}", deviceId, userId);
-        
-        // 调用应用层服务绑定设备
-        boolean result = deviceCommandService.bindDevice(deviceId, userId);
-        
-        // 发送绑定响应
-        Map<String, Object> responseData = new HashMap<>();
-        responseData.put("deviceId", deviceId);
-        responseData.put("userId", userId);
-        responseData.put("result", result);
-        responseData.put("message", result ? "绑定成功" : "绑定失败");
-        deviceCommandService.publishBindDeviceResponse(responseData);
-    }
-    
-    /**
-     * 处理解绑设备请求
-     */
-    public void handleUnbindDeviceRequest(String deviceId, Long userId) {
-        log.info("处理解绑设备请求: deviceId={}, userId={}", deviceId, userId);
-        
-        // 调用应用层服务解绑设备
-        boolean result = deviceCommandService.unbindDevice(deviceId, userId);
-        
-        // 发送解绑响应
-        Map<String, Object> responseData = new HashMap<>();
-        responseData.put("deviceId", deviceId);
-        responseData.put("userId", userId);
-        responseData.put("result", result);
-        responseData.put("message", result ? "解绑成功" : "解绑失败");
-        deviceCommandService.publishUnbindDeviceResponse(responseData);
-    }
-    
-    /**
-     * 处理更新设备网络配置请求
-     */
-    public void handleUpdateNetworkRequest(String deviceId, Device.NetworkInfo networkInfo) {
-        log.info("处理更新设备网络配置请求: deviceId={}", deviceId);
-        
-        // 更新到新接口
-        deviceCommandService.handleUpdateDeviceNetwork(deviceId, 
-                networkInfo.getSsid(), networkInfo.getPassword());
-    }
-    
-    /**
-     * 处理更新设备安装参数请求
-     */
-    public void handleUpdateInstallParamRequest(String deviceId, Device.InstallParam installParam) {
-        log.info("处理更新设备安装参数请求: deviceId={}", deviceId);
-        
-        // 更新到新接口
-        String area = null;
-        if (installParam.getTrackingRegion() != null) {
-            area = String.format("%d,%d,%d,%d,%d,%d",
-                installParam.getTrackingRegion().getStartX(),
-                installParam.getTrackingRegion().getStartY(),
-                installParam.getTrackingRegion().getStartZ(),
-                installParam.getTrackingRegion().getStopX(),
-                installParam.getTrackingRegion().getStopY(),
-                installParam.getTrackingRegion().getStopZ());
-        }
-        
-        deviceCommandService.handleSetDeviceParam(deviceId, 
-                installParam.getMountPlain(), area, installParam.getHeight());
-    }
-    
-    /**
-     * 处理更新设备告警计划请求
-     */
-    public void handleUpdateAlarmScheduleRequest(String deviceId, Map<String, Object> alarmSchedule) {
-        log.info("处理更新设备告警计划请求: deviceId={}", deviceId);
-        
-        // 使用新的告警参数设置接口
-        deviceCommandService.handleSetAlarmParam(alarmSchedule);
-    }
-    
-    /**
-     * 发送设备告警事件消息
-     */
-    public void sendAlarmEvent(Map<String, Object> alarmInfo) {
-        String deviceId = alarmInfo.get("dev_id").toString();
-        String description = alarmInfo.get("desc").toString();
-        String table = alarmInfo.get("table").toString();
-        int tableId = Integer.parseInt(alarmInfo.get("table_id").toString());
-        
-        // 调用应用层服务发送告警事件
-        deviceEventService.sendAlarmEventMessage(deviceId, description, table, tableId);
-    }
-    
-    /**
-     * 发送设备状态更新消息
-     */
-    public void sendDeviceStatusUpdate(Device device) {
-        String deviceId = device.getDevId();
-        String topic = String.format(TopicConstants.TOPIC_DEV_UPDATE, deviceId);
-        
-        JSONObject message = new JSONObject();
-        message.put("message", "notify");
-        message.put("timestamp", System.currentTimeMillis());
-        message.put("dev_id", deviceId);
-        message.put("online", device.getOnline() == 1);
-        message.put("dev_type", device.getDevType());
-        message.put("firmware", device.getSoftware());
-        message.put("hardware", device.getHardware());
-        
-        if (device.getNetwork() != null) {
-            JSONObject network = new JSONObject();
-            network.put("ssid", device.getNetwork().getSsid());
-            network.put("password", device.getNetwork().getPassword());
-            network.put("ip", device.getNetwork().getIp());
-            message.put("network", network);
-        }
-        
-        if (device.getInstallParam() != null) {
-            JSONObject radarParam = new JSONObject();
-            radarParam.put("mount_plain", device.getInstallParam().getMountPlain());
-            radarParam.put("height", device.getInstallParam().getHeight());
-            
-            if (device.getInstallParam().getTrackingRegion() != null) {
-                JSONObject trackingRegion = new JSONObject();
-                trackingRegion.put("start_x", device.getInstallParam().getTrackingRegion().getStartX());
-                trackingRegion.put("start_y", device.getInstallParam().getTrackingRegion().getStartY());
-                trackingRegion.put("start_z", device.getInstallParam().getTrackingRegion().getStartZ());
-                trackingRegion.put("stop_x", device.getInstallParam().getTrackingRegion().getStopX());
-                trackingRegion.put("stop_y", device.getInstallParam().getTrackingRegion().getStopY());
-                trackingRegion.put("stop_z", device.getInstallParam().getTrackingRegion().getStopZ());
-                radarParam.put("tracking_region", trackingRegion);
-            }
-            
-            message.put("radar_param", radarParam);
-        }
-        
-        // 发送MQTT消息
-        mqttTemplate.sendJson(topic, message, QOS, RETAIN);
-    }
-    
-    /**
-     * 发送设备状态更新消息
-     */
-    public void sendDeviceStatusUpdate(String deviceId, Map<String, Object> statusInfo) {
-        String topic = String.format(TopicConstants.TOPIC_DEV_UPDATE, deviceId);
-        
-        JSONObject message = new JSONObject();
-        message.put("message", "notify");
-        message.put("timestamp", System.currentTimeMillis());
-        message.put("dev_id", deviceId);
-        
-        // 添加状态信息
-        for (Map.Entry<String, Object> entry : statusInfo.entrySet()) {
-            message.put(entry.getKey(), entry.getValue());
-        }
-        
-        // 发送MQTT消息
-        mqttTemplate.sendJson(topic, message, QOS, RETAIN);
-    }
-    
-    /**
-     * 发送设备绑定响应消息
-     */
-    public void sendBindDeviceResponse(String deviceId, Long userId, boolean result, String message) {
-        log.info("发送设备绑定响应: deviceId={}, userId={}, result={}", deviceId, userId, result);
-        
-        // 构建响应消息
-        Map<String, Object> responseData = new HashMap<>();
-        responseData.put("deviceId", deviceId);
-        responseData.put("userId", userId);
-        responseData.put("result", result);
-        responseData.put("message", message);
-        
-        // 使用新接口发送响应
-        deviceCommandService.publishBindDeviceResponse(responseData);
-    }
-    
-    /**
-     * 发送设备解绑响应消息
-     */
-    public void sendUnbindDeviceResponse(String deviceId, Long userId, boolean result, String message) {
-        log.info("发送设备解绑响应: deviceId={}, userId={}, result={}", deviceId, userId, result);
-        
-        // 构建响应消息
-        Map<String, Object> responseData = new HashMap<>();
-        responseData.put("deviceId", deviceId);
-        responseData.put("userId", userId);
-        responseData.put("result", result);
-        responseData.put("message", message);
-        
-        // 使用新接口发送响应
-        deviceCommandService.publishUnbindDeviceResponse(responseData);
-    }
-} 
+//package com.hfln.device.infrastructure.mqtt;
+//
+//import cn.hfln.framework.mqtt.template.MqttTemplate;
+//import com.alibaba.fastjson2.JSONObject;
+//import com.hfln.device.application.service.DeviceCommandService;
+//import com.hfln.device.application.service.DeviceEventService;
+//import com.hfln.device.common.constant.mqtt.topic.TopicConstants;
+//import com.hfln.device.domain.entity.Device;
+//import lombok.extern.slf4j.Slf4j;
+//import org.springframework.beans.factory.annotation.Autowired;
+//import org.springframework.stereotype.Component;
+//
+//import java.util.HashMap;
+//import java.util.Map;
+//
+///**
+// * MQTT消息订阅处理器
+// * 负责接收MQTT消息并调用应用层服务处理业务逻辑
+// */
+//@Component
+//@Slf4j
+//public class MqttSubscriberHandler {
+//
+//    private static final int QOS = 1;
+//    private static final boolean RETAIN = true;
+//
+//    @Autowired
+//    private MqttTemplate mqttTemplate;
+//
+//    @Autowired
+//    private DeviceCommandService deviceCommandService;
+//
+//    @Autowired
+//    private DeviceEventService deviceEventService;
+//
+//    /**
+//     * 处理设备登录消息
+//     */
+//    public void handleDeviceLogin(String deviceId, Map<String, Object> deviceInfo) {
+//        log.info("处理设备登录消息: deviceId={}", deviceId);
+//
+//        // 调用应用层服务处理设备登录,传入完整的payload作为第三个参数
+//        deviceEventService.handleDeviceLogin(deviceId, deviceInfo, deviceInfo);
+//
+//        // 发送登录响应消息
+//        sendLoginResponse(deviceId);
+//    }
+//
+//    /**
+//     * 发送登录响应消息
+//     */
+//    private void sendLoginResponse(String deviceId) {
+//        String topic = String.format(TopicConstants.TOPIC_LOGIN_RESPONSE, deviceId);
+//
+//        JSONObject message = new JSONObject();
+//        message.put("message", "login_response");
+//        message.put("timestamp", System.currentTimeMillis());
+//        message.put("dev_id", deviceId);
+//        message.put("result", true);
+//
+//        // 发送MQTT消息
+//        mqttTemplate.sendJson(topic, message, QOS, false);
+//
+//        log.info("发送设备登录响应: deviceId={}", deviceId);
+//    }
+//
+//    /**
+//     * 处理设备保活消息
+//     */
+//    public void handleDeviceKeepAlive(String deviceId) {
+//        log.info("处理设备保活消息: deviceId={}", deviceId);
+//
+//        // 更新设备保活时间
+//        deviceEventService.updateDeviceKeepAliveTime(deviceId, System.currentTimeMillis());
+//    }
+//
+//    /**
+//     * 处理设备状态更新消息
+//     */
+//    public void handleDeviceStatusUpdate(String deviceId, boolean online) {
+//        log.info("处理设备状态更新消息: deviceId={}, online={}", deviceId, online);
+//
+//        // 更新设备在线状态
+//        deviceEventService.updateDeviceOnlineStatus(deviceId, online ? 1 : 0);
+//    }
+//
+//    /**
+//     * 处理设备停留时间消息
+//     */
+//    public void handleDeviceStayTime(String deviceId, Long enterTime, Long leaveTime, String stayTime) {
+//        log.info("处理设备停留时间消息: deviceId={}, enterTime={}, leaveTime={}", deviceId, enterTime, leaveTime);
+//
+//        // 记录设备停留时间
+//        deviceEventService.recordDeviceStayTime(deviceId, enterTime, leaveTime, stayTime);
+//    }
+//
+//    /**
+//     * 处理设备滞留告警消息
+//     */
+//    public void handleDeviceRetentionAlarm(String deviceId, Long alarmTime, String alarmType, String description) {
+//        log.info("处理设备滞留告警消息: deviceId={}, alarmTime={}, alarmType={}", deviceId, alarmTime, alarmType);
+//
+//        // 记录设备滞留告警
+//        deviceEventService.recordDeviceRetentionAlarm(deviceId, alarmTime, alarmType, description);
+//    }
+//
+//    /**
+//     * 处理绑定设备请求
+//     */
+//    public void handleBindDeviceRequest(String deviceId, Long userId) {
+//        log.info("处理绑定设备请求: deviceId={}, userId={}", deviceId, userId);
+//
+//        // 调用应用层服务绑定设备
+//        boolean result = deviceCommandService.bindDevice(deviceId, userId);
+//
+//        // 发送绑定响应
+//        Map<String, Object> responseData = new HashMap<>();
+//        responseData.put("deviceId", deviceId);
+//        responseData.put("userId", userId);
+//        responseData.put("result", result);
+//        responseData.put("message", result ? "绑定成功" : "绑定失败");
+//        deviceCommandService.publishBindDeviceResponse(responseData);
+//    }
+//
+//    /**
+//     * 处理解绑设备请求
+//     */
+//    public void handleUnbindDeviceRequest(String deviceId, Long userId) {
+//        log.info("处理解绑设备请求: deviceId={}, userId={}", deviceId, userId);
+//
+//        // 调用应用层服务解绑设备
+//        boolean result = deviceCommandService.unbindDevice(deviceId, userId);
+//
+//        // 发送解绑响应
+//        Map<String, Object> responseData = new HashMap<>();
+//        responseData.put("deviceId", deviceId);
+//        responseData.put("userId", userId);
+//        responseData.put("result", result);
+//        responseData.put("message", result ? "解绑成功" : "解绑失败");
+//        deviceCommandService.publishUnbindDeviceResponse(responseData);
+//    }
+//
+//    /**
+//     * 处理更新设备网络配置请求
+//     */
+//    public void handleUpdateNetworkRequest(String deviceId, Device.NetworkInfo networkInfo) {
+//        log.info("处理更新设备网络配置请求: deviceId={}", deviceId);
+//
+//        // 更新到新接口
+//        deviceCommandService.handleUpdateDeviceNetwork(deviceId,
+//                networkInfo.getSsid(), networkInfo.getPassword());
+//    }
+//
+//    /**
+//     * 处理更新设备安装参数请求
+//     */
+//    public void handleUpdateInstallParamRequest(String deviceId, Device.InstallParam installParam) {
+//        log.info("处理更新设备安装参数请求: deviceId={}", deviceId);
+//
+//        // 更新到新接口
+//        String area = null;
+//        if (installParam.getTrackingRegion() != null) {
+//            area = String.format("%d,%d,%d,%d,%d,%d",
+//                installParam.getTrackingRegion().getStartX(),
+//                installParam.getTrackingRegion().getStartY(),
+//                installParam.getTrackingRegion().getStartZ(),
+//                installParam.getTrackingRegion().getStopX(),
+//                installParam.getTrackingRegion().getStopY(),
+//                installParam.getTrackingRegion().getStopZ());
+//        }
+//
+//        deviceCommandService.handleSetDeviceParam(deviceId,
+//                installParam.getMountPlain(), area, installParam.getHeight());
+//    }
+//
+//    /**
+//     * 处理更新设备告警计划请求
+//     */
+//    public void handleUpdateAlarmScheduleRequest(String deviceId, Map<String, Object> alarmSchedule) {
+//        log.info("处理更新设备告警计划请求: deviceId={}", deviceId);
+//
+//        // 使用新的告警参数设置接口
+//        deviceCommandService.handleSetAlarmParam(alarmSchedule);
+//    }
+//
+//    /**
+//     * 发送设备告警事件消息
+//     */
+//    public void sendAlarmEvent(Map<String, Object> alarmInfo) {
+//        String deviceId = alarmInfo.get("dev_id").toString();
+//        String description = alarmInfo.get("desc").toString();
+//        String table = alarmInfo.get("table").toString();
+//        int tableId = Integer.parseInt(alarmInfo.get("table_id").toString());
+//
+//        // 调用应用层服务发送告警事件
+//        deviceEventService.sendAlarmEventMessage(deviceId, description, table, tableId);
+//    }
+//
+//    /**
+//     * 发送设备状态更新消息
+//     */
+//    public void sendDeviceStatusUpdate(Device device) {
+//        String deviceId = device.getDevId();
+//        String topic = String.format(TopicConstants.TOPIC_DEV_UPDATE, deviceId);
+//
+//        JSONObject message = new JSONObject();
+//        message.put("message", "notify");
+//        message.put("timestamp", System.currentTimeMillis());
+//        message.put("dev_id", deviceId);
+//        message.put("online", device.getOnline() == 1);
+//        message.put("dev_type", device.getDevType());
+//        message.put("firmware", device.getSoftware());
+//        message.put("hardware", device.getHardware());
+//
+//        if (device.getNetwork() != null) {
+//            JSONObject network = new JSONObject();
+//            network.put("ssid", device.getNetwork().getSsid());
+//            network.put("password", device.getNetwork().getPassword());
+//            network.put("ip", device.getNetwork().getIp());
+//            message.put("network", network);
+//        }
+//
+//        if (device.getInstallParam() != null) {
+//            JSONObject radarParam = new JSONObject();
+//            radarParam.put("mount_plain", device.getInstallParam().getMountPlain());
+//            radarParam.put("height", device.getInstallParam().getHeight());
+//
+//            if (device.getInstallParam().getTrackingRegion() != null) {
+//                JSONObject trackingRegion = new JSONObject();
+//                trackingRegion.put("start_x", device.getInstallParam().getTrackingRegion().getStartX());
+//                trackingRegion.put("start_y", device.getInstallParam().getTrackingRegion().getStartY());
+//                trackingRegion.put("start_z", device.getInstallParam().getTrackingRegion().getStartZ());
+//                trackingRegion.put("stop_x", device.getInstallParam().getTrackingRegion().getStopX());
+//                trackingRegion.put("stop_y", device.getInstallParam().getTrackingRegion().getStopY());
+//                trackingRegion.put("stop_z", device.getInstallParam().getTrackingRegion().getStopZ());
+//                radarParam.put("tracking_region", trackingRegion);
+//            }
+//
+//            message.put("radar_param", radarParam);
+//        }
+//
+//        // 发送MQTT消息
+//        mqttTemplate.sendJson(topic, message, QOS, RETAIN);
+//    }
+//
+//    /**
+//     * 发送设备状态更新消息
+//     */
+//    public void sendDeviceStatusUpdate(String deviceId, Map<String, Object> statusInfo) {
+//        String topic = String.format(TopicConstants.TOPIC_DEV_UPDATE, deviceId);
+//
+//        JSONObject message = new JSONObject();
+//        message.put("message", "notify");
+//        message.put("timestamp", System.currentTimeMillis());
+//        message.put("dev_id", deviceId);
+//
+//        // 添加状态信息
+//        for (Map.Entry<String, Object> entry : statusInfo.entrySet()) {
+//            message.put(entry.getKey(), entry.getValue());
+//        }
+//
+//        // 发送MQTT消息
+//        mqttTemplate.sendJson(topic, message, QOS, RETAIN);
+//    }
+//
+//    /**
+//     * 发送设备绑定响应消息
+//     */
+//    public void sendBindDeviceResponse(String deviceId, Long userId, boolean result, String message) {
+//        log.info("发送设备绑定响应: deviceId={}, userId={}, result={}", deviceId, userId, result);
+//
+//        // 构建响应消息
+//        Map<String, Object> responseData = new HashMap<>();
+//        responseData.put("deviceId", deviceId);
+//        responseData.put("userId", userId);
+//        responseData.put("result", result);
+//        responseData.put("message", message);
+//
+//        // 使用新接口发送响应
+//        deviceCommandService.publishBindDeviceResponse(responseData);
+//    }
+//
+//    /**
+//     * 发送设备解绑响应消息
+//     */
+//    public void sendUnbindDeviceResponse(String deviceId, Long userId, boolean result, String message) {
+//        log.info("发送设备解绑响应: deviceId={}, userId={}, result={}", deviceId, userId, result);
+//
+//        // 构建响应消息
+//        Map<String, Object> responseData = new HashMap<>();
+//        responseData.put("deviceId", deviceId);
+//        responseData.put("userId", userId);
+//        responseData.put("result", result);
+//        responseData.put("message", message);
+//
+//        // 使用新接口发送响应
+//        deviceCommandService.publishUnbindDeviceResponse(responseData);
+//    }
+//}

+ 0 - 55
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/gateway/MqttGatewayImplTest.java

@@ -1,55 +0,0 @@
-package com.hfln.device.infrastructure.gateway;
-
-import com.hfln.device.domain.entity.Device;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import static org.mockito.Mockito.*;
-
-class MqttGatewayImplTest {
-    @InjectMocks
-    private MqttGatewayImpl mqttGatewayImpl;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testSendDeviceStatusMessage() {
-        Device device = mock(Device.class);
-        when(device.getDevId()).thenReturn("dev1");
-        when(device.getOnline()).thenReturn(1);
-        mqttGatewayImpl = spy(mqttGatewayImpl);
-        doNothing().when(mqttGatewayImpl).sendMessage(anyString(), any());
-        mqttGatewayImpl.sendDeviceStatusMessage(device);
-        verify(mqttGatewayImpl, times(1)).sendMessage(anyString(), any());
-    }
-
-    @Test
-    void testSendRealtimePoseMessage() {
-        mqttGatewayImpl = spy(mqttGatewayImpl);
-        doNothing().when(mqttGatewayImpl).sendMessage(anyString(), any());
-        mqttGatewayImpl.sendRealtimePoseMessage("dev2", 1, new float[]{1.0f, 2.0f, 3.0f});
-        verify(mqttGatewayImpl, times(1)).sendMessage(anyString(), any());
-    }
-
-    @Test
-    void testSendAlarmMessage() {
-        mqttGatewayImpl = spy(mqttGatewayImpl);
-        doNothing().when(mqttGatewayImpl).sendMessage(anyString(), any());
-        mqttGatewayImpl.sendAlarmMessage("dev3", "alarmType", new java.util.HashMap<>());
-        verify(mqttGatewayImpl, times(1)).sendMessage(anyString(), any());
-    }
-
-    @Test
-    void testSendEventMessage() {
-        mqttGatewayImpl = spy(mqttGatewayImpl);
-        doNothing().when(mqttGatewayImpl).sendMessage(anyString(), any());
-        mqttGatewayImpl.sendEventMessage("dev4", 2, new float[]{4.0f, 5.0f, 6.0f}, "event");
-        verify(mqttGatewayImpl, times(1)).sendMessage(anyString(), any());
-    }
-} 

+ 0 - 40
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/gateway/impl/MqttGatewayDefaultImplTest.java

@@ -1,40 +0,0 @@
-package com.hfln.device.infrastructure.gateway.impl;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
-
-import static org.mockito.Mockito.*;
-
-class MqttGatewayDefaultImplTest {
-    @Mock
-    private MqttPahoMessageHandler mqttOutbound;
-    @InjectMocks
-    private MqttGatewayDefaultImpl mqttGatewayDefaultImpl;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testSendMessage() {
-        mqttGatewayDefaultImpl.sendMessage("/test/topic", "payload");
-        verify(mqttOutbound, atLeastOnce()).handleMessage(any());
-    }
-
-    @Test
-    void testSendRealtimePoseMessage() {
-        mqttGatewayDefaultImpl.sendRealtimePoseMessage("dev1", 1, new float[]{1.0f, 2.0f, 3.0f});
-        verify(mqttOutbound, atLeastOnce()).handleMessage(any());
-    }
-
-    @Test
-    void testSendEventMessage() {
-        mqttGatewayDefaultImpl.sendEventMessage("dev2", 2, new float[]{4.0f, 5.0f, 6.0f}, "fall_confirmed");
-        verify(mqttOutbound, atLeastOnce()).handleMessage(any());
-    }
-} 

+ 0 - 58
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/MqttGatewayEmqxImplTest.java

@@ -1,58 +0,0 @@
-package com.hfln.device.infrastructure.mqtt;
-
-import com.hfln.device.domain.entity.Device;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.MockitoAnnotations;
-
-import static org.mockito.Mockito.*;
-
-class MqttGatewayEmqxImplTest {
-    @InjectMocks
-    private MqttGatewayEmqxImpl mqttGatewayEmqxImpl;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-        mqttGatewayEmqxImpl = spy(mqttGatewayEmqxImpl);
-    }
-
-    @Test
-    void testSendDeviceLoginResponse() {
-        doNothing().when(mqttGatewayEmqxImpl).publishJson(anyString(), any(), anyInt(), anyBoolean());
-        mqttGatewayEmqxImpl.sendDeviceLoginResponse("dev1", 0);
-        verify(mqttGatewayEmqxImpl, times(1)).publishJson(anyString(), any(), anyInt(), anyBoolean());
-    }
-
-    @Test
-    void testSendDeviceStatusMessage() {
-        doNothing().when(mqttGatewayEmqxImpl).publishJson(anyString(), any(), anyInt(), anyBoolean());
-        Device device = mock(Device.class);
-        when(device.getDevId()).thenReturn("dev2");
-        when(device.getOnline()).thenReturn(1);
-        mqttGatewayEmqxImpl.sendDeviceStatusMessage(device);
-        verify(mqttGatewayEmqxImpl, times(1)).publishJson(anyString(), any(), anyInt(), anyBoolean());
-    }
-
-    @Test
-    void testSendRealtimePoseMessage() {
-        doNothing().when(mqttGatewayEmqxImpl).publishJson(anyString(), any(), anyInt(), anyBoolean());
-        mqttGatewayEmqxImpl.sendRealtimePoseMessage("dev3", 1, new float[]{1.0f, 2.0f, 3.0f});
-        verify(mqttGatewayEmqxImpl, times(1)).publishJson(anyString(), any(), anyInt(), anyBoolean());
-    }
-
-    @Test
-    void testSendAlarmMessage() {
-        doNothing().when(mqttGatewayEmqxImpl).publishJson(anyString(), any(), anyInt(), anyBoolean());
-        mqttGatewayEmqxImpl.sendAlarmMessage("dev4", "alarmType", new java.util.HashMap<>());
-        verify(mqttGatewayEmqxImpl, times(1)).publishJson(anyString(), any(), anyInt(), anyBoolean());
-    }
-
-    @Test
-    void testSendEventMessage() {
-        doNothing().when(mqttGatewayEmqxImpl).publishJson(anyString(), any(), anyInt(), anyBoolean());
-        mqttGatewayEmqxImpl.sendEventMessage("dev5", 2, new float[]{4.0f, 5.0f, 6.0f}, "event");
-        verify(mqttGatewayEmqxImpl, times(1)).publishJson(anyString(), any(), anyInt(), anyBoolean());
-    }
-} 

+ 0 - 260
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/MqttSubscriberFunctionalTest.java

@@ -1,260 +0,0 @@
-package com.hfln.device.infrastructure.mqtt;
-
-import cn.hfln.framework.mqtt.annotation.MqttSubscriber;
-import org.junit.jupiter.api.Test;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.boot.test.context.TestConfiguration;
-import org.springframework.context.annotation.Bean;
-import org.springframework.messaging.Message;
-import org.springframework.messaging.support.GenericMessage;
-import org.springframework.test.context.ContextConfiguration;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import static org.junit.jupiter.api.Assertions.*;
-
-/**
- * @MqttSubscriber注解功能测试
- * 
- * 测试目标:
- * 1. 验证@MqttSubscriber注解是否能正常工作
- * 2. 测试消息路由和处理机制
- * 3. 确认没有重复消费问题
- */
-@SpringBootTest(classes = {MqttSubscriberFunctionalTest.TestConfig.class})
-@ContextConfiguration
-public class MqttSubscriberFunctionalTest {
-
-    @TestConfiguration
-    static class TestConfig {
-        
-        @Bean
-        public TestMqttSubscriber testMqttSubscriber() {
-            return new TestMqttSubscriber();
-        }
-    }
-    
-    /**
-     * 测试用的MQTT订阅者
-     */
-    public static class TestMqttSubscriber {
-        
-        private final CountDownLatch latch = new CountDownLatch(1);
-        private volatile String lastReceivedTopic;
-        private volatile String lastReceivedPayload;
-        private volatile boolean messageReceived = false;
-        
-        @MqttSubscriber(topic = "/test/device/+/login", qos = 1, desc = "测试设备登录")
-        public void handleTestDeviceLogin(String topic, Message<?> message) {
-            System.out.println("收到MQTT消息 - Topic: " + topic + ", Payload: " + message.getPayload());
-            
-            this.lastReceivedTopic = topic;
-            this.lastReceivedPayload = message.getPayload().toString();
-            this.messageReceived = true;
-            
-            latch.countDown();
-        }
-        
-        @MqttSubscriber(topic = "/test/device/+/keepalive", qos = 0, desc = "测试设备心跳") 
-        public void handleTestDeviceKeepAlive(String topic, Message<?> message) {
-            System.out.println("收到心跳消息 - Topic: " + topic);
-        }
-        
-        @MqttSubscriber(topic = "/test/app/+/command", qos = 1, desc = "测试应用命令")
-        public void handleTestAppCommand(String topic, Message<?> message) {
-            System.out.println("收到应用命令 - Topic: " + topic + ", Payload: " + message.getPayload());
-        }
-        
-        public boolean waitForMessage(long timeoutSeconds) throws InterruptedException {
-            return latch.await(timeoutSeconds, TimeUnit.SECONDS);
-        }
-        
-        public String getLastReceivedTopic() {
-            return lastReceivedTopic;
-        }
-        
-        public String getLastReceivedPayload() {
-            return lastReceivedPayload;
-        }
-        
-        public boolean isMessageReceived() {
-            return messageReceived;
-        }
-    }
-
-    @Test
-    public void testMqttSubscriberAnnotationBasicFunctionality() throws Exception {
-        System.out.println("=== 测试@MqttSubscriber注解基础功能 ===");
-        
-        // 这个测试验证@MqttSubscriber注解能否被正确识别和处理
-        TestMqttSubscriber subscriber = new TestMqttSubscriber();
-        
-        // 验证订阅者对象创建成功
-        assertNotNull(subscriber, "@MqttSubscriber对象应该能正常创建");
-        
-        // 模拟消息处理
-        Map<String, Object> headers = new HashMap<>();
-        headers.put("mqtt_receivedTopic", "/test/device/test001/login");
-        
-        String testPayload = "{\"device_info\":{\"deviceid\":\"test001\",\"firmware\":\"v1.0.0\"}}";
-        Message<String> testMessage = new GenericMessage<>(testPayload, headers);
-        
-        // 直接调用处理方法(模拟MQTT框架的调用)
-        subscriber.handleTestDeviceLogin("/test/device/test001/login", testMessage);
-        
-        // 验证消息处理结果
-        assertTrue(subscriber.isMessageReceived(), "消息应该被正确接收");
-        assertEquals("/test/device/test001/login", subscriber.getLastReceivedTopic(), "主题应该匹配");
-        assertEquals(testPayload, subscriber.getLastReceivedPayload(), "载荷应该匹配");
-        
-        System.out.println("✓ @MqttSubscriber注解基础功能测试通过");
-    }
-    
-    @Test
-    public void testMqttSubscriberMultipleTopicPatterns() throws Exception {
-        System.out.println("=== 测试@MqttSubscriber多主题模式 ===");
-        
-        TestMqttSubscriber subscriber = new TestMqttSubscriber();
-        
-        // 测试不同的主题模式
-        String[] testTopics = {
-            "/test/device/abc123/login",
-            "/test/device/xyz789/keepalive", 
-            "/test/app/admin/command"
-        };
-        
-        for (String topic : testTopics) {
-            Message<String> message = new GenericMessage<>("test payload");
-            
-            // 根据主题调用相应的处理方法
-            if (topic.contains("/login")) {
-                assertDoesNotThrow(() -> {
-                    subscriber.handleTestDeviceLogin(topic, message);
-                }, "登录消息处理不应该抛出异常");
-            } else if (topic.contains("/keepalive")) {
-                assertDoesNotThrow(() -> {
-                    subscriber.handleTestDeviceKeepAlive(topic, message);
-                }, "心跳消息处理不应该抛出异常");
-            } else if (topic.contains("/command")) {
-                assertDoesNotThrow(() -> {
-                    subscriber.handleTestAppCommand(topic, message);
-                }, "命令消息处理不应该抛出异常");
-            }
-        }
-        
-        System.out.println("✓ 多主题模式测试通过");
-    }
-    
-    @Test
-    public void testMqttSubscriberErrorHandling() throws Exception {
-        System.out.println("=== 测试@MqttSubscriber错误处理 ===");
-        
-        TestMqttSubscriber subscriber = new TestMqttSubscriber();
-        
-        // 测试null消息
-        assertDoesNotThrow(() -> {
-            subscriber.handleTestDeviceLogin("/test/device/test001/login", null);
-        }, "null消息不应该导致异常");
-        
-        // 测试空载荷
-        Message<String> emptyMessage = new GenericMessage<>("");
-        assertDoesNotThrow(() -> {
-            subscriber.handleTestDeviceLogin("/test/device/test001/login", emptyMessage);
-        }, "空载荷消息不应该导致异常");
-        
-        // 测试无效JSON载荷
-        Message<String> invalidJsonMessage = new GenericMessage<>("invalid json{[}");
-        assertDoesNotThrow(() -> {
-            subscriber.handleTestDeviceLogin("/test/device/test001/login", invalidJsonMessage);
-        }, "无效JSON载荷不应该导致异常");
-        
-        System.out.println("✓ 错误处理测试通过");
-    }
-    
-    @Test
-    public void testMqttSubscriberPerformance() throws Exception {
-        System.out.println("=== 测试@MqttSubscriber性能 ===");
-        
-        TestMqttSubscriber subscriber = new TestMqttSubscriber();
-        
-        // 性能测试:处理大量消息
-        int messageCount = 1000;
-        long startTime = System.currentTimeMillis();
-        
-        for (int i = 0; i < messageCount; i++) {
-            String topic = "/test/device/perf" + i + "/login";
-            String payload = "{\"device_info\":{\"deviceid\":\"perf" + i + "\"}}";
-            Message<String> message = new GenericMessage<>(payload);
-            
-            subscriber.handleTestDeviceLogin(topic, message);
-        }
-        
-        long endTime = System.currentTimeMillis();
-        long duration = endTime - startTime;
-        
-        System.out.println("处理 " + messageCount + " 条消息耗时: " + duration + "ms");
-        System.out.println("平均每条消息耗时: " + (duration * 1.0 / messageCount) + "ms");
-        
-        // 性能要求:平均每条消息处理时间应该小于10ms
-        assertTrue(duration < messageCount * 10, "性能测试:平均处理时间应该小于10ms/条");
-        
-        System.out.println("✓ 性能测试通过");
-    }
-    
-    @Test
-    public void testMqttSubscriberConfiguration() throws Exception {
-        System.out.println("=== 测试@MqttSubscriber配置 ===");
-        
-        // 这个测试验证注解的配置参数是否正确
-        TestMqttSubscriber subscriber = new TestMqttSubscriber();
-        
-        // 通过反射检查方法上的注解
-        Class<?> subscriberClass = subscriber.getClass();
-        
-        // 检查登录处理方法的注解
-        try {
-            java.lang.reflect.Method loginMethod = subscriberClass.getMethod("handleTestDeviceLogin", String.class, Message.class);
-            MqttSubscriber annotation = loginMethod.getAnnotation(MqttSubscriber.class);
-            
-            assertNotNull(annotation, "应该能找到@MqttSubscriber注解");
-            assertEquals("/test/device/+/login", annotation.topic(), "主题配置应该正确");
-            assertEquals(1, annotation.qos(), "QoS配置应该正确");
-            assertEquals("测试设备登录", annotation.desc(), "描述配置应该正确");
-            
-        } catch (NoSuchMethodException e) {
-            fail("应该能找到handleTestDeviceLogin方法");
-        }
-        
-        System.out.println("✓ 配置测试通过");
-    }
-    
-    @Test
-    public void testMqttSubscriberIsolation() throws Exception {
-        System.out.println("=== 测试@MqttSubscriber消息隔离 ===");
-        
-        TestMqttSubscriber subscriber = new TestMqttSubscriber();
-        
-        // 验证不同的订阅方法相互独立
-        String loginTopic = "/test/device/test001/login";
-        String keepaliveTopic = "/test/device/test001/keepalive";
-        String commandTopic = "/test/app/admin/command";
-        
-        Message<String> message = new GenericMessage<>("test");
-        
-        // 调用登录处理方法
-        subscriber.handleTestDeviceLogin(loginTopic, message);
-        assertTrue(subscriber.isMessageReceived(), "登录消息应该被处理");
-        
-        // 调用其他方法不应该影响登录消息的状态
-        subscriber.handleTestDeviceKeepAlive(keepaliveTopic, message);
-        subscriber.handleTestAppCommand(commandTopic, message);
-        
-        // 验证消息状态仍然正确
-        assertEquals(loginTopic, subscriber.getLastReceivedTopic(), "最后接收的主题应该仍是登录主题");
-        
-        System.out.println("✓ 消息隔离测试通过");
-    }
-} 

+ 0 - 82
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/MqttSubscriberProcessorTest.java

@@ -1,82 +0,0 @@
-package com.hfln.device.infrastructure.mqtt;
-
-import cn.hfln.framework.mqtt.annotation.MqttSubscriber;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.Mockito;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.boot.test.mock.mockito.SpyBean;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
-import org.springframework.messaging.Message;
-import org.springframework.messaging.support.MessageBuilder;
-import org.springframework.test.context.TestPropertySource;
-import cn.hfln.framework.mqtt.handler.MqttSubscriberProcessor;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.*;
-
-@SpringBootTest(classes = {MqttSubscriberProcessorTest.TestConfig.class, MqttSubscriberProcessor.class})
-@TestPropertySource(properties = {
-        "spring.main.allow-bean-definition-overriding=true"
-})
-public class MqttSubscriberProcessorTest {
-
-    @Autowired
-    private MqttSubscriberProcessor processor;
-
-    @Autowired
-    private TestSubscriberBean testSubscriberBean;
-
-    @SpyBean
-    private MqttPahoMessageDrivenChannelAdapter mqttInbound;
-
-    @BeforeEach
-    void setup() {
-        // 触发扫描注册
-        processor.afterSingletonsInstantiated();
-    }
-
-    @Test
-    void testMqttSubscriberAnnotationIsProcessed() {
-        String testTopic = "/test/topic";
-        Message<String> message = MessageBuilder.withPayload("test payload")
-                .setHeader("mqtt_receivedTopic", testTopic)
-                .build();
-
-        // 触发消息处理
-        // processor.getMessageHandler().handleMessage(message);
-        // 适配starter实现,直接调用processMessage
-        try {
-            java.lang.reflect.Method processMethod = processor.getClass().getDeclaredMethod("processMessage", org.springframework.messaging.Message.class);
-            processMethod.setAccessible(true);
-            processMethod.invoke(processor, message);
-        } catch (Exception e) {
-            throw new RuntimeException(e);
-        }
-
-        // 验证方法是否被调用
-        assertThat(testSubscriberBean.isCalled()).isTrue();
-    }
-
-    @Configuration
-    static class TestConfig {
-        @Bean
-        public TestSubscriberBean testSubscriberBean() {
-            return new TestSubscriberBean();
-        }
-
-        @Bean
-        public MqttPahoMessageDrivenChannelAdapter mqttInbound() {
-            // mock一个bean,避免真实MQTT连接
-            return Mockito.mock(MqttPahoMessageDrivenChannelAdapter.class);
-        }
-
-        @Bean
-        public org.eclipse.paho.client.mqttv3.MqttClient mqttClient() {
-            return Mockito.mock(org.eclipse.paho.client.mqttv3.MqttClient.class);
-        }
-    }
-} 

+ 0 - 228
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/SimpleMqttSubscriberTest.java

@@ -1,228 +0,0 @@
-package com.hfln.device.infrastructure.mqtt;
-
-import cn.hfln.framework.mqtt.annotation.MqttSubscriber;
-import org.junit.jupiter.api.Test;
-import org.springframework.messaging.Message;
-import org.springframework.messaging.support.GenericMessage;
-
-import java.lang.reflect.Method;
-
-import static org.junit.jupiter.api.Assertions.*;
-
-/**
- * 简单的@MqttSubscriber注解测试
- * 
- * 不依赖Spring Boot Context,仅测试注解本身的功能
- */
-public class SimpleMqttSubscriberTest {
-
-    /**
-     * 测试类,包含@MqttSubscriber注解的方法
-     */
-    public static class TestSubscriber {
-        
-        @MqttSubscriber(topic = "/test/device/+/login", qos = 1, desc = "测试设备登录")
-        public void handleDeviceLogin(String topic, Message<?> message) {
-            System.out.println("处理设备登录: " + topic + " -> " + message.getPayload());
-        }
-        
-        @MqttSubscriber(topic = "/test/device/+/keepalive", qos = 0, desc = "测试设备心跳")
-        public void handleDeviceKeepAlive(String topic, Message<?> message) {
-            System.out.println("处理设备心跳: " + topic);
-        }
-        
-        @MqttSubscriber(topic = "/test/app/+/command", qos = 1, desc = "测试应用命令")
-        public void handleAppCommand(String topic, Message<?> message) {
-            System.out.println("处理应用命令: " + topic + " -> " + message.getPayload());
-        }
-        
-        // 没有注解的方法
-        public void handleRegularMethod(String topic, Message<?> message) {
-            System.out.println("普通方法: " + topic);
-        }
-    }
-
-    @Test
-    public void testMqttSubscriberAnnotationPresence() {
-        System.out.println("=== 测试@MqttSubscriber注解是否存在 ===");
-        
-        TestSubscriber subscriber = new TestSubscriber();
-        Class<?> subscriberClass = subscriber.getClass();
-        
-        // 获取所有方法
-        Method[] methods = subscriberClass.getDeclaredMethods();
-        
-        int annotatedMethodCount = 0;
-        
-        for (Method method : methods) {
-            MqttSubscriber annotation = method.getAnnotation(MqttSubscriber.class);
-            
-            if (annotation != null) {
-                annotatedMethodCount++;
-                System.out.println("找到@MqttSubscriber注解方法: " + method.getName());
-                System.out.println("  - 主题: " + annotation.topic());
-                System.out.println("  - QoS: " + annotation.qos());
-                System.out.println("  - 描述: " + annotation.desc());
-                
-                // 验证注解属性
-                assertNotNull(annotation.topic(), "topic不应该为null");
-                assertTrue(annotation.topic().length() > 0, "topic不应该为空");
-                assertTrue(annotation.qos() >= 0 && annotation.qos() <= 2, "QoS应该在0-2之间");
-                assertNotNull(annotation.desc(), "desc不应该为null");
-            }
-        }
-        
-        // 应该有3个带@MqttSubscriber注解的方法
-        assertEquals(3, annotatedMethodCount, "应该有3个带@MqttSubscriber注解的方法");
-        
-        System.out.println("✓ 注解存在性测试通过");
-    }
-    
-    @Test
-    public void testMqttSubscriberAnnotationConfiguration() {
-        System.out.println("=== 测试@MqttSubscriber注解配置 ===");
-        
-        TestSubscriber subscriber = new TestSubscriber();
-        Class<?> subscriberClass = subscriber.getClass();
-        
-        try {
-            // 测试设备登录方法的注解
-            Method loginMethod = subscriberClass.getMethod("handleDeviceLogin", String.class, Message.class);
-            MqttSubscriber loginAnnotation = loginMethod.getAnnotation(MqttSubscriber.class);
-            
-            assertNotNull(loginAnnotation, "应该能找到登录方法的@MqttSubscriber注解");
-            assertEquals("/test/device/+/login", loginAnnotation.topic(), "登录方法的主题应该正确");
-            assertEquals(1, loginAnnotation.qos(), "登录方法的QoS应该是1");
-            assertEquals("测试设备登录", loginAnnotation.desc(), "登录方法的描述应该正确");
-            
-            // 测试设备心跳方法的注解
-            Method keepaliveMethod = subscriberClass.getMethod("handleDeviceKeepAlive", String.class, Message.class);
-            MqttSubscriber keepaliveAnnotation = keepaliveMethod.getAnnotation(MqttSubscriber.class);
-            
-            assertNotNull(keepaliveAnnotation, "应该能找到心跳方法的@MqttSubscriber注解");
-            assertEquals("/test/device/+/keepalive", keepaliveAnnotation.topic(), "心跳方法的主题应该正确");
-            assertEquals(0, keepaliveAnnotation.qos(), "心跳方法的QoS应该是0");
-            assertEquals("测试设备心跳", keepaliveAnnotation.desc(), "心跳方法的描述应该正确");
-            
-            // 测试应用命令方法的注解
-            Method commandMethod = subscriberClass.getMethod("handleAppCommand", String.class, Message.class);
-            MqttSubscriber commandAnnotation = commandMethod.getAnnotation(MqttSubscriber.class);
-            
-            assertNotNull(commandAnnotation, "应该能找到命令方法的@MqttSubscriber注解");
-            assertEquals("/test/app/+/command", commandAnnotation.topic(), "命令方法的主题应该正确");
-            assertEquals(1, commandAnnotation.qos(), "命令方法的QoS应该是1");
-            assertEquals("测试应用命令", commandAnnotation.desc(), "命令方法的描述应该正确");
-            
-            // 测试普通方法没有注解
-            Method regularMethod = subscriberClass.getMethod("handleRegularMethod", String.class, Message.class);
-            MqttSubscriber regularAnnotation = regularMethod.getAnnotation(MqttSubscriber.class);
-            
-            assertNull(regularAnnotation, "普通方法不应该有@MqttSubscriber注解");
-            
-        } catch (NoSuchMethodException e) {
-            fail("应该能找到测试方法: " + e.getMessage());
-        }
-        
-        System.out.println("✓ 注解配置测试通过");
-    }
-    
-    @Test
-    public void testMqttSubscriberMethodInvocation() {
-        System.out.println("=== 测试@MqttSubscriber方法调用 ===");
-        
-        TestSubscriber subscriber = new TestSubscriber();
-        
-        // 创建测试消息
-        Message<String> testMessage = new GenericMessage<>("test payload");
-        
-        // 测试各个方法是否能正常调用
-        assertDoesNotThrow(() -> {
-            subscriber.handleDeviceLogin("/test/device/test001/login", testMessage);
-        }, "设备登录方法调用不应该抛出异常");
-        
-        assertDoesNotThrow(() -> {
-            subscriber.handleDeviceKeepAlive("/test/device/test001/keepalive", testMessage);
-        }, "设备心跳方法调用不应该抛出异常");
-        
-        assertDoesNotThrow(() -> {
-            subscriber.handleAppCommand("/test/app/admin/command", testMessage);
-        }, "应用命令方法调用不应该抛出异常");
-        
-        assertDoesNotThrow(() -> {
-            subscriber.handleRegularMethod("/test/regular", testMessage);
-        }, "普通方法调用不应该抛出异常");
-        
-        System.out.println("✓ 方法调用测试通过");
-    }
-    
-    @Test
-    public void testMqttSubscriberTopicPatterns() {
-        System.out.println("=== 测试@MqttSubscriber主题模式 ===");
-        
-        TestSubscriber subscriber = new TestSubscriber();
-        Class<?> subscriberClass = subscriber.getClass();
-        
-        // 收集所有的主题模式
-        String[] expectedTopics = {
-            "/test/device/+/login",
-            "/test/device/+/keepalive", 
-            "/test/app/+/command"
-        };
-        
-        int foundTopics = 0;
-        Method[] methods = subscriberClass.getDeclaredMethods();
-        
-        for (Method method : methods) {
-            MqttSubscriber annotation = method.getAnnotation(MqttSubscriber.class);
-            if (annotation != null) {
-                String topic = annotation.topic();
-                
-                // 检查是否是预期的主题之一
-                boolean isExpectedTopic = false;
-                for (String expectedTopic : expectedTopics) {
-                    if (expectedTopic.equals(topic)) {
-                        isExpectedTopic = true;
-                        foundTopics++;
-                        break;
-                    }
-                }
-                
-                assertTrue(isExpectedTopic, "主题 " + topic + " 应该是预期的主题之一");
-                
-                // 验证主题格式
-                assertTrue(topic.startsWith("/"), "主题应该以/开头");
-                assertTrue(topic.contains("+"), "测试主题应该包含通配符+");
-            }
-        }
-        
-        assertEquals(expectedTopics.length, foundTopics, "应该找到所有预期的主题");
-        
-        System.out.println("✓ 主题模式测试通过");
-    }
-    
-    @Test
-    public void testMqttSubscriberErrorHandling() {
-        System.out.println("=== 测试@MqttSubscriber错误处理 ===");
-        
-        TestSubscriber subscriber = new TestSubscriber();
-        
-        // 测试null参数处理
-        assertDoesNotThrow(() -> {
-            subscriber.handleDeviceLogin(null, null);
-        }, "null参数不应该导致异常");
-        
-        // 测试空主题
-        Message<String> message = new GenericMessage<>("test");
-        assertDoesNotThrow(() -> {
-            subscriber.handleDeviceLogin("", message);
-        }, "空主题不应该导致异常");
-        
-        // 测试空载荷
-        Message<String> emptyMessage = new GenericMessage<>("");
-        assertDoesNotThrow(() -> {
-            subscriber.handleDeviceLogin("/test/device/test001/login", emptyMessage);
-        }, "空载荷不应该导致异常");
-        
-        System.out.println("✓ 错误处理测试通过");
-    }
-} 

+ 0 - 17
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/TestSubscriberBean.java

@@ -1,17 +0,0 @@
-package com.hfln.device.infrastructure.mqtt;
-
-import cn.hfln.framework.mqtt.annotation.MqttSubscriber;
-import org.springframework.messaging.Message;
-
-public class TestSubscriberBean {
-    private boolean called = false;
-
-    @MqttSubscriber(topic = "/test/topic")
-    public void handle(String topic, String payload) {
-        this.called = true;
-    }
-
-    public boolean isCalled() {
-        return called;
-    }
-} 

+ 0 - 89
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/subscriber/AppMessageSubscriberTest.java

@@ -1,89 +0,0 @@
-//package com.hfln.device.infrastructure.mqtt.subscriber;
-//
-//import com.hfln.device.application.service.DeviceCommandService;
-//import com.hfln.device.domain.port.DeviceEventPort;
-//import org.junit.jupiter.api.BeforeEach;
-//import org.junit.jupiter.api.Test;
-//import org.mockito.InjectMocks;
-//import org.mockito.Mock;
-//import org.mockito.MockitoAnnotations;
-//import org.mockito.ArgumentCaptor;
-//import org.springframework.messaging.Message;
-//import org.springframework.messaging.support.GenericMessage;
-//
-//import java.util.HashMap;
-//import java.util.Map;
-//
-//import static org.mockito.Mockito.*;
-//import static org.junit.jupiter.api.Assertions.*;
-//
-//class AppMessageSubscriberTest {
-//    @Mock
-//    private DeviceEventPort deviceEventPort;
-//    @Mock
-//    private DeviceCommandService deviceCommandService;
-//    @InjectMocks
-//    private AppMessageSubscriber appMessageSubscriber;
-//
-//    @BeforeEach
-//    void setUp() {
-//        MockitoAnnotations.initMocks(this);
-//    }
-//
-//    @Test
-//    void testHandleFallEventAck() {
-//        Message<String> message = new GenericMessage<>("{\"deviceId\":\"dev1\",\"eventId\":123}");
-//        appMessageSubscriber.handleFallEventAck("topic", message);
-//        ArgumentCaptor<String> deviceIdCaptor = ArgumentCaptor.forClass(String.class);
-//        ArgumentCaptor<Long> eventIdCaptor = ArgumentCaptor.forClass(Long.class);
-//        verify(deviceEventPort, times(1)).handleAlarmAck(deviceIdCaptor.capture(), eventIdCaptor.capture());
-//        assertEquals("dev1", deviceIdCaptor.getValue());
-//        assertEquals(123L, eventIdCaptor.getValue());
-//    }
-//
-//    @Test
-//    void testHandleBindDevice_success() {
-//        Message<String> message = new GenericMessage<>("{\"deviceId\":\"dev2\",\"userId\":456}");
-//        when(deviceCommandService.checkDeviceExists("dev2")).thenReturn(true);
-//        when(deviceCommandService.isDeviceBound("dev2")).thenReturn(false);
-//        when(deviceCommandService.bindDevice("dev2", 456L)).thenReturn(true);
-//        ArgumentCaptor<Map> captor = ArgumentCaptor.forClass(Map.class);
-//        doNothing().when(deviceCommandService).publishBindDeviceResponse(captor.capture());
-//        appMessageSubscriber.handleBindDevice("topic", message);
-//        Map<String, Object> response = captor.getValue();
-//        assertEquals("dev2", response.get("deviceId"));
-//        assertEquals(456L, response.get("userId"));
-//        assertEquals(true, response.get("result"));
-//        assertEquals("Bind success", response.get("message"));
-//    }
-//
-//    @Test
-//    void testHandleBindDevice_deviceNotFound() {
-//        Message<String> message = new GenericMessage<>("{\"deviceId\":\"devX\",\"userId\":456}");
-//        when(deviceCommandService.checkDeviceExists("devX")).thenReturn(false);
-//        ArgumentCaptor<Map> captor = ArgumentCaptor.forClass(Map.class);
-//        doNothing().when(deviceCommandService).publishBindDeviceResponse(captor.capture());
-//        appMessageSubscriber.handleBindDevice("topic", message);
-//        Map<String, Object> response = captor.getValue();
-//        assertEquals("devX", response.get("deviceId"));
-//        assertEquals(456L, response.get("userId"));
-//        assertEquals(false, response.get("result"));
-//        assertEquals("Device not found", response.get("message"));
-//    }
-//
-//    @Test
-//    void testHandleUnbindDevice_success() {
-//        Message<String> message = new GenericMessage<>("{\"deviceId\":\"dev3\",\"userId\":789}");
-//        when(deviceCommandService.checkDeviceExists("dev3")).thenReturn(true);
-//        when(deviceCommandService.isUserDevice("dev3", 789L)).thenReturn(true);
-//        when(deviceCommandService.unbindDevice("dev3", 789L)).thenReturn(true);
-//        ArgumentCaptor<Map> captor = ArgumentCaptor.forClass(Map.class);
-//        doNothing().when(deviceCommandService).publishUnbindDeviceResponse(captor.capture());
-//        appMessageSubscriber.handleUnbindDevice("topic", message);
-//        Map<String, Object> response = captor.getValue();
-//        assertEquals("dev3", response.get("deviceId"));
-//        assertEquals(789L, response.get("userId"));
-//        assertEquals(true, response.get("result"));
-//        assertEquals("Unbind success", response.get("message"));
-//    }
-//}

+ 0 - 92
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/subscriber/DasMessageSubscriberTest.java

@@ -1,92 +0,0 @@
-//package com.hfln.device.infrastructure.mqtt.subscriber;
-//
-//import com.hfln.device.application.service.DeviceCommandService;
-//import com.hfln.device.domain.port.DeviceEventPort;
-//import org.junit.jupiter.api.BeforeEach;
-//import org.junit.jupiter.api.Test;
-//import org.mockito.InjectMocks;
-//import org.mockito.Mock;
-//import org.mockito.MockitoAnnotations;
-//import org.springframework.messaging.Message;
-//import org.springframework.messaging.support.GenericMessage;
-//
-//import java.util.*;
-//
-//import static org.mockito.Mockito.*;
-//
-//class DasMessageSubscriberTest {
-//    @Mock
-//    private DeviceEventPort deviceEventPort;
-//    @Mock
-//    private DeviceCommandService deviceCommandService;
-//    @InjectMocks
-//    private DasMessageSubscriber dasMessageSubscriber;
-//
-//    @BeforeEach
-//    void setUp() {
-//        MockitoAnnotations.initMocks(this);
-//    }
-//
-//    @Test
-//    void testHandleDeviceStatus() {
-//        Message<String> message = new GenericMessage<>(("{\"dev_id\":\"dev1\",\"online\":true,\"dev_type\":\"type\",\"software\":\"v1\",\"hardware\":\"h1\",\"network\":{},\"radar_param\":{}}"));
-//        dasMessageSubscriber.handleDeviceStatus("topic", message);
-//        verify(deviceEventPort, times(1)).handleDeviceStatusUpdate(anyString(), anyBoolean(), anyString(), anyString(), anyString(), anyMap(), anyMap());
-//    }
-//
-//    @Test
-//    void testHandleCloudPoint() {
-//        Message<String> message = new GenericMessage<>(("{\"dev_id\":\"dev2\",\"point_cloud\":[[1,2],[3,4]],\"target_point\":[5,6]}"));
-//        dasMessageSubscriber.handleCloudPoint("topic", message);
-//        verify(deviceEventPort, times(1)).handleCloudPoint(anyString(), anyList(), anyList());
-//    }
-//
-//    @Test
-//    void testHandleRealtimePosition() {
-//        Message<String> message = new GenericMessage<>(("{\"dev_id\":\"dev3\",\"pose\":1,\"target_point\":[[1,2],[3,4]]}"));
-//        dasMessageSubscriber.handleRealtimePosition("topic", message);
-//        verify(deviceEventPort, times(1)).handleRealtimePosition(anyString(), anyInt(), anyList());
-//    }
-//
-//    @Test
-//    void testHandleEvent() {
-//        Message<String> message = new GenericMessage<>(("{\"dev_id\":\"dev4\",\"event\":\"fall\",\"pose\":2,\"target_point\":[7,8]}"));
-//        dasMessageSubscriber.handleEvent("topic", message);
-//        verify(deviceEventPort, times(1)).handleEvent(anyString(), anyString(), anyInt(), anyList());
-//    }
-//
-//    @Test
-//    void testHandleAlarmEvent() {
-//        Message<String> message = new GenericMessage<>("{\"dev_id\":\"dev5\",\"desc\":\"desc\",\"table\":\"table\",\"table_id\":1}");
-//        dasMessageSubscriber.handleAlarmEvent("topic", message);
-//        verify(deviceEventPort, times(1)).handleAlarmEvent(anyString(), anyString(), anyString(), anyInt());
-//    }
-//
-//    @Test
-//    void testHandleSetAlarmParamAck() {
-//        Message<String> message = new GenericMessage<>("{\"code\":0,\"global\":{\"k\":\"v\"}}");
-//        dasMessageSubscriber.handleSetAlarmParamAck("topic", message);
-//        verify(deviceEventPort, times(1)).handleSetAlarmParamAck(anyInt(), anyMap());
-//    }
-//
-//    @Test
-//    void testHandleDeviceActivity() {
-//        Message<String> message = new GenericMessage<>("{\"dev_id\":\"dev6\",\"activity_level\":1,\"duration\":100,\"timestamp\":123456789,\"location\":[1,2,3]}");
-//        dasMessageSubscriber.handleDeviceActivity("topic", message);
-//        verify(deviceEventPort, times(1)).handleActivityBehavior(anyString(), anyInt(), anyLong(), anyList(), anyLong());
-//    }
-//
-//    @Test
-//    void testHandleDeviceRest() {
-//        Message<String> message = new GenericMessage<>("{\"dev_id\":\"dev7\",\"duration\":200,\"timestamp\":123456789,\"location\":[1,2,3],\"area_name\":\"area\"}");
-//        dasMessageSubscriber.handleDeviceRest("topic", message);
-//        verify(deviceEventPort, times(1)).handleRestBehavior(anyString(), anyLong(), anyList(), anyString(), anyLong());
-//    }
-//
-//    @Test
-//    void testHandlePoseDistribution() {
-//        Message<String> message = new GenericMessage<>("{\"dev_id\":\"dev8\",\"distribution\":{\"pose\":1},\"timestamp\":123456789}");
-//        dasMessageSubscriber.handlePoseDistribution("topic", message);
-//        verify(deviceEventPort, times(1)).handlePoseDistribution(anyString(), anyMap(), anyLong());
-//    }
-//}

+ 0 - 108
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/subscriber/DeviceMessageSubscriberTest.java

@@ -1,108 +0,0 @@
-//package com.hfln.device.infrastructure.mqtt.subscriber;
-//
-//import com.hfln.device.domain.port.DeviceEventPort;
-//import org.junit.jupiter.api.BeforeEach;
-//import org.junit.jupiter.api.Test;
-//import org.mockito.InjectMocks;
-//import org.mockito.Mock;
-//import org.mockito.MockitoAnnotations;
-//import org.springframework.messaging.Message;
-//import org.springframework.messaging.support.GenericMessage;
-//import org.mockito.ArgumentCaptor;
-//import static org.junit.jupiter.api.Assertions.*;
-//
-//import java.util.Arrays;
-//import java.util.HashMap;
-//import java.util.List;
-//import java.util.Map;
-//
-//import static org.mockito.Mockito.*;
-//
-//class DeviceMessageSubscriberTest {
-//    @Mock
-//    private DeviceEventPort deviceEventPort;
-//    @InjectMocks
-//    private DeviceMessageSubscriber deviceMessageSubscriber;
-//
-//    @BeforeEach
-//    void setUp() {
-//        MockitoAnnotations.initMocks(this);
-//    }
-//
-//    @Test
-//    void testHandleDeviceLogin() {
-//        Map<String, Object> deviceInfo = new HashMap<>();
-//        deviceInfo.put("deviceid", "dev1");
-//        Map<String, Object> payloadMap = new HashMap<>();
-//        payloadMap.put("device_info", deviceInfo);
-//        Message<String> message = new GenericMessage<>(com.hfln.device.common.util.JsonUtil.toJsonString(payloadMap));
-//        deviceMessageSubscriber.handleDeviceLogin("/dev/dev1/report_device_info", message);
-//        ArgumentCaptor<String> deviceIdCaptor = ArgumentCaptor.forClass(String.class);
-//        ArgumentCaptor<Map> deviceInfoCaptor = ArgumentCaptor.forClass(Map.class);
-//        verify(deviceEventPort, times(1)).handleDeviceLogin(deviceIdCaptor.capture(), deviceInfoCaptor.capture());
-//        assertEquals("dev1", deviceIdCaptor.getValue());
-//        assertEquals("dev1", deviceInfoCaptor.getValue().get("deviceid"));
-//    }
-//
-//    @Test
-//    void testHandleDeviceReportFall() {
-//        Map<String, Object> payloadMap = new HashMap<>();
-//        payloadMap.put("event", "fall");
-//        payloadMap.put("pose", 2);
-//        payloadMap.put("target_point", Arrays.asList(1, 2));
-//        Message<String> message = new GenericMessage<>(com.hfln.device.common.util.JsonUtil.toJsonString(payloadMap));
-//        deviceMessageSubscriber.handleDeviceReportFall("/dev/dev2/report_fall", message);
-//        ArgumentCaptor<String> deviceIdCaptor = ArgumentCaptor.forClass(String.class);
-//        ArgumentCaptor<String> eventCaptor = ArgumentCaptor.forClass(String.class);
-//        ArgumentCaptor<Integer> poseCaptor = ArgumentCaptor.forClass(Integer.class);
-//        ArgumentCaptor<List> targetPointCaptor = ArgumentCaptor.forClass(List.class);
-//        verify(deviceEventPort, times(1)).handleFallEvent(deviceIdCaptor.capture(), eventCaptor.capture(), poseCaptor.capture(), targetPointCaptor.capture());
-//        assertEquals("dev2", deviceIdCaptor.getValue());
-//        assertEquals("fall", eventCaptor.getValue());
-//        assertEquals(2, poseCaptor.getValue());
-//        assertEquals(Arrays.asList(1.0f, 2.0f), targetPointCaptor.getValue());
-//    }
-//
-//    @Test
-//    void testHandleDeviceCloudPoint() {
-//        Map<String, Object> payloadMap = new HashMap<>();
-//        payloadMap.put("point_cloud", Arrays.asList(Arrays.asList(1,2), Arrays.asList(3,4)));
-//        payloadMap.put("target_point", Arrays.asList(5,6));
-//        Message<String> message = new GenericMessage<>(com.hfln.device.common.util.JsonUtil.toJsonString(payloadMap));
-//        deviceMessageSubscriber.handleDeviceCloudPoint("/dev/dev3/cloudpoint", message);
-//        ArgumentCaptor<String> deviceIdCaptor = ArgumentCaptor.forClass(String.class);
-//        ArgumentCaptor<List> pointCloudCaptor = ArgumentCaptor.forClass(List.class);
-//        ArgumentCaptor<List> targetPointCaptor = ArgumentCaptor.forClass(List.class);
-//        verify(deviceEventPort, times(1)).handleCloudPoint(deviceIdCaptor.capture(), pointCloudCaptor.capture(), targetPointCaptor.capture());
-//        assertEquals("dev3", deviceIdCaptor.getValue());
-//        assertEquals(2, ((List)pointCloudCaptor.getValue()).size());
-//        assertEquals(Arrays.asList(5.0f, 6.0f), targetPointCaptor.getValue());
-//    }
-//
-//    @Test
-//    void testHandleDeviceReportDeviceParam() {
-//        Map<String, Object> payloadMap = new HashMap<>();
-//        payloadMap.put("param1", "value1");
-//        Message<String> message = new GenericMessage<>(com.hfln.device.common.util.JsonUtil.toJsonString(payloadMap));
-//        deviceMessageSubscriber.handleDeviceReportDeviceParam("/dev/dev4/report_device_param", message);
-//        // 只需验证无异常即可
-//    }
-//
-//    @Test
-//    void testHandleDeviceLoginByLoginTopic() {
-//        // 构造payload
-//        Map<String, Object> deviceInfo = new HashMap<>();
-//        deviceInfo.put("deviceid", "dev_login_1");
-//        deviceInfo.put("firmware", "v1.0.0");
-//        deviceInfo.put("blu_ver", "b1.0.0");
-//        deviceInfo.put("device_type", "typeA");
-//        Map<String, Object> payloadMap = new HashMap<>();
-//        payloadMap.put("device_info", deviceInfo);
-//        String payload = com.hfln.device.common.util.JsonUtil.toJsonString(payloadMap);
-//        org.springframework.messaging.Message<String> message = new org.springframework.messaging.support.GenericMessage<>(payload);
-//        // 调用方法
-//        deviceMessageSubscriber.handleDeviceLoginByLoginTopic("/dev/dev_login_1/login", message);
-//        // 验证依赖被调用
-//        verify(deviceEventPort, times(1)).handleDeviceLogin(eq("dev_login_1"), eq(deviceInfo));
-//    }
-//}

+ 0 - 81
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/subscriber/MpsMessageSubscriberTest.java

@@ -1,81 +0,0 @@
-//package com.hfln.device.infrastructure.mqtt.subscriber;
-//
-//import com.hfln.device.application.service.DeviceCommandService;
-//import org.junit.jupiter.api.BeforeEach;
-//import org.junit.jupiter.api.Test;
-//import org.mockito.InjectMocks;
-//import org.mockito.Mock;
-//import org.mockito.MockitoAnnotations;
-//import org.mockito.ArgumentCaptor;
-//import org.springframework.messaging.Message;
-//import org.springframework.messaging.support.GenericMessage;
-//
-//import static org.mockito.Mockito.*;
-//import static org.junit.jupiter.api.Assertions.*;
-//
-//class MpsMessageSubscriberTest {
-//    @Mock
-//    private DeviceCommandService deviceCommandService;
-//    @InjectMocks
-//    private MpsMessageSubscriber mpsMessageSubscriber;
-//
-//    @BeforeEach
-//    void setUp() {
-//        MockitoAnnotations.initMocks(this);
-//    }
-//
-//    @Test
-//    void testHandleGetDeviceInfo() {
-//        Message<String> message = new GenericMessage<>(("{\"deviceId\":\"dev1\"}"));
-//        mpsMessageSubscriber.handleGetDeviceInfo("topic", message);
-//        ArgumentCaptor<String> deviceIdCaptor = ArgumentCaptor.forClass(String.class);
-//        verify(deviceCommandService, times(1)).handleGetDeviceInfo(deviceIdCaptor.capture());
-//        assertEquals("dev1", deviceIdCaptor.getValue());
-//    }
-//
-//    @Test
-//    void testHandleSetDeviceParam() {
-//        Message<String> message = new GenericMessage<>(("{\"deviceId\":\"dev2\",\"mount_plain\":\"plain\",\"area\":\"area1\",\"height\":1.5}"));
-//        mpsMessageSubscriber.handleSetDeviceParam("topic", message);
-//        ArgumentCaptor<String> deviceIdCaptor = ArgumentCaptor.forClass(String.class);
-//        ArgumentCaptor<String> mountPlainCaptor = ArgumentCaptor.forClass(String.class);
-//        ArgumentCaptor<String> areaCaptor = ArgumentCaptor.forClass(String.class);
-//        ArgumentCaptor<Float> heightCaptor = ArgumentCaptor.forClass(Float.class);
-//        verify(deviceCommandService, times(1)).handleSetDeviceParam(deviceIdCaptor.capture(), mountPlainCaptor.capture(), areaCaptor.capture(), heightCaptor.capture());
-//        assertEquals("dev2", deviceIdCaptor.getValue());
-//        assertEquals("plain", mountPlainCaptor.getValue());
-//        assertEquals("area1", areaCaptor.getValue());
-//        assertEquals(1.5f, heightCaptor.getValue());
-//    }
-//
-//    @Test
-//    void testHandleRestartDevice() {
-//        Message<String> message = new GenericMessage<>(("{\"deviceId\":\"dev3\"}"));
-//        mpsMessageSubscriber.handleRestartDevice("topic", message);
-//        ArgumentCaptor<String> deviceIdCaptor = ArgumentCaptor.forClass(String.class);
-//        verify(deviceCommandService, times(1)).handleRestartDevice(deviceIdCaptor.capture());
-//        assertEquals("dev3", deviceIdCaptor.getValue());
-//    }
-//
-//    @Test
-//    void testHandleResetDevice() {
-//        Message<String> message = new GenericMessage<>(("{\"deviceId\":\"dev4\"}"));
-//        mpsMessageSubscriber.handleDeviceReboot("topic", message);
-//        ArgumentCaptor<String> deviceIdCaptor = ArgumentCaptor.forClass(String.class);
-//        verify(deviceCommandService, times(1)).handleResetDevice(deviceIdCaptor.capture());
-//        assertEquals("dev4", deviceIdCaptor.getValue());
-//    }
-//
-//    @Test
-//    void testHandleUpdateDeviceNetwork() {
-//        Message<String> message = new GenericMessage<>(("{\"deviceId\":\"dev5\",\"ssid\":\"wifi\",\"password\":\"pwd\"}"));
-//        mpsMessageSubscriber.han("topic", message);
-//        ArgumentCaptor<String> deviceIdCaptor = ArgumentCaptor.forClass(String.class);
-//        ArgumentCaptor<String> ssidCaptor = ArgumentCaptor.forClass(String.class);
-//        ArgumentCaptor<String> pwdCaptor = ArgumentCaptor.forClass(String.class);
-//        verify(deviceCommandService, times(1)).handleUpdateDeviceNetwork(deviceIdCaptor.capture(), ssidCaptor.capture(), pwdCaptor.capture());
-//        assertEquals("dev5", deviceIdCaptor.getValue());
-//        assertEquals("wifi", ssidCaptor.getValue());
-//        assertEquals("pwd", pwdCaptor.getValue());
-//    }
-//}

+ 0 - 46
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/mqtt/subscriber/OpcMessageSubscriberTest.java

@@ -1,46 +0,0 @@
-//package com.hfln.device.infrastructure.mqtt.subscriber;
-//
-//import com.hfln.device.application.service.OpcService;
-//import org.junit.jupiter.api.BeforeEach;
-//import org.junit.jupiter.api.Test;
-//import org.mockito.InjectMocks;
-//import org.mockito.Mock;
-//import org.mockito.MockitoAnnotations;
-//import org.springframework.messaging.Message;
-//import org.springframework.messaging.support.GenericMessage;
-//import org.springframework.messaging.support.MessageBuilder;
-//
-//import static org.mockito.Mockito.*;
-//
-//class OpcMessageSubscriberTest {
-//    @Mock
-//    private OpcService opcService;
-//    @InjectMocks
-//    private OpcMessageSubscriber opcMessageSubscriber;
-//
-//    @BeforeEach
-//    void setUp() {
-//        MockitoAnnotations.initMocks(this);
-//    }
-//
-//    @Test
-//    void testHandleGetAlarmParam() {
-//        Message<byte[]> message = new GenericMessage<>(("{\"param\":1}".getBytes()));
-//        opcMessageSubscriber.handleGetAlarmParam(message);
-//        verify(opcService, times(1)).handleGetAlarmParam(anyString());
-//    }
-//
-//    @Test
-//    void testHandleSetAlarmParam() {
-//        Message<byte[]> message = new GenericMessage<>(("{\"param\":2}".getBytes()));
-//        opcMessageSubscriber.handleSetAlarmParam(message);
-//        verify(opcService, times(1)).handleSetAlarmParam(anyString());
-//    }
-//
-//    @Test
-//    void testHandleAllOpcMessages() {
-//        Message<String> message = MessageBuilder.withPayload("payload").setHeader("mqtt_receivedTopic", "opc/topic").build();
-//        opcMessageSubscriber.handleAllOpcMessages(message);
-//        // 只需验证日志,无业务调用
-//    }
-//}

+ 0 - 24
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/service/DevGroupServiceTest.java

@@ -1,24 +0,0 @@
-package com.hfln.device.infrastructure.service;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-class DevGroupServiceTest {
-    @Mock
-    // TODO: Mock 依赖
-    @InjectMocks
-    private DevGroupService devGroupService;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testMainFunctionality() {
-        // TODO: 补充主流程测试
-    }
-} 

+ 0 - 24
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/service/DevInfoServiceTest.java

@@ -1,24 +0,0 @@
-package com.hfln.device.infrastructure.service;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-class DevInfoServiceTest {
-    @Mock
-    // TODO: Mock 依赖
-    @InjectMocks
-    private DevInfoService devInfoService;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testMainFunctionality() {
-        // TODO: 补充主流程测试
-    }
-} 

+ 0 - 24
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/service/DevShareServiceTest.java

@@ -1,24 +0,0 @@
-package com.hfln.device.infrastructure.service;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-class DevShareServiceTest {
-    @Mock
-    // TODO: Mock 依赖
-    @InjectMocks
-    private DevShareService devShareService;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testMainFunctionality() {
-        // TODO: 补充主流程测试
-    }
-} 

+ 0 - 24
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/service/DeviceBehaviorServiceTest.java

@@ -1,24 +0,0 @@
-package com.hfln.device.infrastructure.service;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-class DeviceBehaviorServiceTest {
-    @Mock
-    // TODO: Mock 依赖
-    @InjectMocks
-    private DeviceBehaviorService deviceBehaviorService;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testMainFunctionality() {
-        // TODO: 补充主流程测试
-    }
-} 

+ 0 - 24
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/service/EventServiceTest.java

@@ -1,24 +0,0 @@
-package com.hfln.device.infrastructure.service;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-class EventServiceTest {
-    @Mock
-    // TODO: Mock 依赖
-    @InjectMocks
-    private EventService eventService;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testMainFunctionality() {
-        // TODO: 补充主流程测试
-    }
-} 

+ 0 - 24
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/service/GroupShareServiceTest.java

@@ -1,24 +0,0 @@
-package com.hfln.device.infrastructure.service;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-class GroupShareServiceTest {
-    @Mock
-    // TODO: Mock 依赖
-    @InjectMocks
-    private GroupShareService groupShareService;
-
-    @BeforeEach
-    void setUp() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    void testMainFunctionality() {
-        // TODO: 补充主流程测试
-    }
-} 

+ 0 - 1
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/service/StayTimeServiceTest.java

@@ -1 +0,0 @@
- 

+ 0 - 29
device-service-infrastructure/src/test/java/com/hfln/device/infrastructure/service/UserServiceTest.java

@@ -1,29 +0,0 @@
-package com.hfln.device.infrastructure.service;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import static org.junit.jupiter.api.Assertions.*;
-
-class UserServiceTest {
-    private UserService userService;
-
-    @BeforeEach
-    void setUp() {
-        // TODO: 初始化userService,必要时mock依赖
-    }
-
-    @Test
-    void testMainFunctionality() {
-        // TODO: 测试主业务流程
-    }
-
-    @Test
-    void testEdgeCases() {
-        // TODO: 测试边界条件
-    }
-
-    @Test
-    void testExceptionHandling() {
-        // TODO: 测试异常处理
-    }
-} 

+ 1 - 11
device-service-server/src/main/java/com/hfln/device/server/DeviceApplication.java

@@ -23,17 +23,7 @@ import org.springframework.scheduling.annotation.EnableScheduling;
     scanBasePackageClasses = {RedisConfig.class, JacksonConfiguration.class}
 )
 @ComponentScan(
-    basePackages = {"com.hfln.device.**"},
-    excludeFilters = {
-        @ComponentScan.Filter(
-            type = FilterType.REGEX,
-            pattern = "com.hfln.device.infrastructure.mqtt.MqttGatewayImpl"
-        ),
-        @ComponentScan.Filter(
-            type = FilterType.REGEX,
-            pattern = "com.hfln.device.infrastructure.gateway.impl.MqttGatewayImpl"
-        )
-    }
+    basePackages = {"com.hfln.device.**"}
 )
 @EnableScheduling
 public class DeviceApplication {

+ 1 - 4
device-service-server/src/main/resources/bootstrap-local.yml

@@ -58,16 +58,13 @@ lnxx:
 
 
 mqtt:
-  enabled: true
   broker: tcp://8.130.28.21:1883
   client:
     id: hfln-device-service-${random.uuid}
   username: admin
   password: public
-  topics: hfln/device/#
   qos: 1
-  completion:
-    timeout: 5000
+
 
 # 设备配置
 device:

+ 0 - 7
pom.xml

@@ -160,13 +160,6 @@
                 <version>8.0.31</version>
             </dependency>
 
-
-            <dependency>
-                <groupId>cn.hfln.framework</groupId>
-                <artifactId>mqtt-spring-boot-starter</artifactId>
-                <version>1.0.0-SNAPSHOT</version>
-            </dependency>
-
         </dependencies>
     </dependencyManagement>