From e90e11527dce1e5b6d6c5453cf7ba47dd650ecd4 Mon Sep 17 00:00:00 2001 From: Timer <@> Date: Thu, 29 Jan 2026 17:06:01 +0800 Subject: [PATCH] initial --- .idea/.gitignore | 10 + .idea/misc.xml | 14 + .idea/sipaiis_datacollector.iml | 9 + .idea/vcs.xml | 6 + .../在GIS_Job中加入和达流量计计算点位推送.md | 55 ++ README.md | 92 ++ pom.xml | 284 ++++++ src/main/java/com/sipai/DataApplication.java | 47 + src/main/java/com/sipai/config/AppConfig.java | 18 + .../com/sipai/config/MockOpcUaClient.java | 38 + .../java/com/sipai/config/OpcUaConfig.java | 76 ++ .../com/sipai/config/OpcUaProperties.java | 66 ++ .../java/com/sipai/config/RedissonConfig.java | 75 ++ .../java/com/sipai/config/StartupLogger.java | 20 + src/main/java/com/sipai/config/UDPClient.java | 80 ++ .../sipai/config/UDPFilePollingClient.java | 135 +++ src/main/java/com/sipai/config/UDPServer.java | 859 ++++++++++++++++++ .../check/CheckServerController.java | 75 ++ .../data/PipeTopicMPointController.java | 170 ++++ .../data/PipelineEquipmentController.java | 271 ++++++ .../PipelineEquipmentMpointController.java | 136 +++ .../data/PipelineMpointLibraryController.java | 106 +++ .../controller/kafka/KafkaController.java | 26 + .../controller/mqtt/MqttConfigController.java | 145 +++ .../mqtt/MqttConfigTopicController.java | 41 + .../sipai/controller/mqtt/MqttController.java | 408 +++++++++ .../controller/mqtt/WebHookController.java | 108 +++ .../sipai/controller/opc/OpcUaController.java | 96 ++ .../controller/rabbitmq/MQController.java | 29 + .../controller/scada/MPointController.java | 114 +++ .../controller/user/CompanyController.java | 40 + .../sipai/controller/user/UserController.java | 35 + .../sipai/dao/Listener/ListenerHisDao.java | 24 + .../dao/Listener/ListenerInterfaceDao.java | 15 + .../dao/Listener/ListenerMessageDao.java | 15 + .../sipai/dao/Listener/ListenerPointDao.java | 15 + src/main/java/com/sipai/dao/base/CommDao.java | 125 +++ .../java/com/sipai/dao/base/CommDaoImpl.java | 151 +++ .../sipai/dao/data/PipeTopicMpointDao.java | 43 + .../sipai/dao/data/PipelineEquipmentDao.java | 47 + .../dao/data/PipelineEquipmentMpointDao.java | 37 + .../dao/data/PipelineMpointLibraryDao.java | 45 + .../com/sipai/dao/mqtt/MqttConfigDao.java | 32 + .../sipai/dao/mqtt/MqttConfigTopicDao.java | 34 + .../com/sipai/dao/scada/MPointBzwDao.java | 25 + .../java/com/sipai/dao/scada/MPointDao.java | 19 + .../com/sipai/dao/scada/MPointHistoryDao.java | 64 ++ .../java/com/sipai/dao/scada/MPointRepo.java | 8 + .../com/sipai/dao/scada/MPointRepository.java | 13 + .../sipai/dao/scada/MPointRepositoryImpl.java | 105 +++ .../java/com/sipai/dao/user/CompanyDao.java | 25 + src/main/java/com/sipai/dao/user/UserDao.java | 13 + .../sipai/entity/Listener/ListenerHis.java | 56 ++ .../entity/Listener/ListenerInterface.java | 56 ++ .../entity/Listener/ListenerMessage.java | 86 ++ .../sipai/entity/Listener/ListenerPoint.java | 123 +++ .../java/com/sipai/entity/base/Result.java | 65 ++ .../com/sipai/entity/base/SQLAdapter.java | 22 + .../com/sipai/entity/common/PageData.java | 37 + .../com/sipai/entity/data/ChannelData.java | 82 ++ .../com/sipai/entity/data/DeviceData.java | 88 ++ .../sipai/entity/data/DeviceDataPacket.java | 131 +++ .../sipai/entity/data/PipeTopicMpoint.java | 28 + .../sipai/entity/data/PipelineEquipment.java | 32 + .../entity/data/PipelineEquipmentMpoint.java | 25 + .../entity/data/PipelineMpointLibrary.java | 27 + .../com/sipai/entity/data/SensorData.java | 120 +++ .../sipai/entity/enums/DeviceTypeEnum.java | 71 ++ src/main/java/com/sipai/entity/mqtt/Mqtt.java | 16 + .../com/sipai/entity/mqtt/MqttConfig.java | 102 +++ .../sipai/entity/mqtt/MqttConfigTopic.java | 72 ++ .../com/sipai/entity/mqtt/MqttProperties.java | 45 + .../java/com/sipai/entity/scada/MPoint.java | 608 +++++++++++++ .../com/sipai/entity/scada/MPointBzw.java | 57 ++ .../java/com/sipai/entity/scada/MPointES.java | 42 + .../com/sipai/entity/scada/MPointHistory.java | 154 ++++ .../java/com/sipai/entity/user/Company.java | 201 ++++ src/main/java/com/sipai/entity/user/User.java | 36 + .../java/com/sipai/schedule/DataSynJob.java | 73 ++ .../service/Listener/ListenerHisService.java | 23 + .../Listener/ListenerInterfaceService.java | 22 + .../Listener/ListenerMessageService.java | 24 + .../Listener/ListenerPointService.java | 22 + .../Listener/impl/ListenerHisServiceImpl.java | 62 ++ .../impl/ListenerInterfaceServiceImpl.java | 56 ++ .../impl/ListenerMessageServiceImpl.java | 96 ++ .../impl/ListenerPointServiceImpl.java | 57 ++ .../sipai/service/data/DeviceDataParser.java | 126 +++ .../service/data/PipeTopicMpointService.java | 41 + .../data/PipelineEquipmentMpointService.java | 35 + .../data/PipelineEquipmentService.java | 60 ++ .../data/PipelineMpointLibraryService.java | 42 + .../data/impl/PipeTopicMpointServiceImpl.java | 59 ++ .../PipelineEquipmentMpointServiceImpl.java | 48 + .../impl/PipelineEquipmentServiceImpl.java | 126 +++ .../PipelineMpointLibraryServiceImpl.java | 54 ++ .../service/kafka/KafkaConsumerService.java | 24 + .../service/kafka/KafkaProducerService.java | 38 + .../sipai/service/mqtt/MqttConfigService.java | 62 ++ .../service/mqtt/MqttConfigTopicService.java | 28 + .../com/sipai/service/mqtt/MqttService.java | 57 ++ .../com/sipai/service/mqtt/PushCallback.java | 229 +++++ .../mqtt/impl/MqttConfigServiceImpl.java | 348 +++++++ .../mqtt/impl/MqttConfigTopicServiceImpl.java | 61 ++ .../service/mqtt/impl/MqttServiceImpl.java | 553 +++++++++++ .../sipai/service/opc/InitOpcUaService.java | 134 +++ .../com/sipai/service/opc/OpcUaService.java | 277 ++++++ .../com/sipai/service/rabbitmq/MQService.java | 5 + .../service/rabbitmq/impl/MQServiceImpl.java | 23 + .../sipai/service/scada/MPointBzwService.java | 21 + .../service/scada/MPointHistoryService.java | 17 + .../sipai/service/scada/MPointService.java | 87 ++ .../scada/impl/MPointBzwServiceImpl.java | 63 ++ .../scada/impl/MPointHistoryServiceImpl.java | 79 ++ .../service/scada/impl/MPointServiceImpl.java | 498 ++++++++++ .../sipai/service/user/CompanyService.java | 27 + .../com/sipai/service/user/UserService.java | 9 + .../service/user/impl/CompanyServiceImpl.java | 57 ++ .../service/user/impl/UserServiceImpl.java | 21 + src/main/java/com/sipai/tools/AlarmType.java | 23 + src/main/java/com/sipai/tools/CommString.java | 244 +++++ src/main/java/com/sipai/tools/CommUtil.java | 245 +++++ .../java/com/sipai/tools/ConstantString.java | 18 + .../com/sipai/tools/DataSourceAspect.java | 89 ++ .../sipai/tools/DataSourceContextHolder.java | 33 + .../java/com/sipai/tools/DataSourceEnum.java | 10 + .../com/sipai/tools/DataSourceTypeAnno.java | 16 + .../com/sipai/tools/DynamicDataSource.java | 12 + .../java/com/sipai/tools/EncryptGISUtils.java | 99 ++ src/main/java/com/sipai/tools/HttpUtil.java | 311 +++++++ .../java/com/sipai/tools/MyBatisConfig.java | 110 +++ src/main/java/com/sipai/tools/Result.java | 68 ++ .../com/sipai/tools/SpringContextUtil.java | 49 + src/main/java/com/sipai/tools/Test.java | 40 + .../java/com/sipai/tools/ThreadConfig.java | 57 ++ src/main/resources/application-dev.yml | 160 ++++ src/main/resources/application-pro.yml | 160 ++++ src/main/resources/application.yml | 4 + src/main/resources/generatior-config.xml | 55 ++ src/main/resources/log4j2.xml | 116 +++ src/main/resources/mybatis-config.xml | 17 + .../mybatis/mapper/Listener/ListenerHis.xml | 114 +++ .../Listener/ListenerInterfaceMapper.xml | 108 +++ .../mapper/Listener/ListenerMessageMapper.xml | 108 +++ .../mapper/Listener/ListenerPointMapper.xml | 166 ++++ .../mapper/data/PipeTopicMpointMapper.xml | 147 +++ .../mapper/data/PipelineEquipmentMapper.xml | 152 ++++ .../data/PipelineEquipmentMpointMapper.xml | 102 +++ .../data/PipelineMpointLibraryMapper.xml | 102 +++ .../mybatis/mapper/mqtt/MqttConfigMapper.xml | 153 ++++ .../mapper/mqtt/MqttConfigTopicMapper.xml | 123 +++ .../mybatis/mapper/scada/MPointBzw.xml | 78 ++ .../mapper/scada/MPointHistoryMapper.xml | 79 ++ .../mybatis/mapper/scada/MPointMapper.xml | 718 +++++++++++++++ .../mybatis/mapper/user/CompanyDao.xml | 267 ++++++ .../resources/mybatis/mapper/user/UserDao.xml | 16 + src/main/resources/templates/index.html | 10 + .../com/sipai/SpringbootApplicationTests.java | 13 + 158 files changed, 15057 insertions(+) create mode 100644 .idea/.gitignore create mode 100644 .idea/misc.xml create mode 100644 .idea/sipaiis_datacollector.iml create mode 100644 .idea/vcs.xml create mode 100644 .trae/documents/在GIS_Job中加入和达流量计计算点位推送.md create mode 100644 README.md create mode 100644 pom.xml create mode 100644 src/main/java/com/sipai/DataApplication.java create mode 100644 src/main/java/com/sipai/config/AppConfig.java create mode 100644 src/main/java/com/sipai/config/MockOpcUaClient.java create mode 100644 src/main/java/com/sipai/config/OpcUaConfig.java create mode 100644 src/main/java/com/sipai/config/OpcUaProperties.java create mode 100644 src/main/java/com/sipai/config/RedissonConfig.java create mode 100644 src/main/java/com/sipai/config/StartupLogger.java create mode 100644 src/main/java/com/sipai/config/UDPClient.java create mode 100644 src/main/java/com/sipai/config/UDPFilePollingClient.java create mode 100644 src/main/java/com/sipai/config/UDPServer.java create mode 100644 src/main/java/com/sipai/controller/check/CheckServerController.java create mode 100644 src/main/java/com/sipai/controller/data/PipeTopicMPointController.java create mode 100644 src/main/java/com/sipai/controller/data/PipelineEquipmentController.java create mode 100644 src/main/java/com/sipai/controller/data/PipelineEquipmentMpointController.java create mode 100644 src/main/java/com/sipai/controller/data/PipelineMpointLibraryController.java create mode 100644 src/main/java/com/sipai/controller/kafka/KafkaController.java create mode 100644 src/main/java/com/sipai/controller/mqtt/MqttConfigController.java create mode 100644 src/main/java/com/sipai/controller/mqtt/MqttConfigTopicController.java create mode 100644 src/main/java/com/sipai/controller/mqtt/MqttController.java create mode 100644 src/main/java/com/sipai/controller/mqtt/WebHookController.java create mode 100644 src/main/java/com/sipai/controller/opc/OpcUaController.java create mode 100644 src/main/java/com/sipai/controller/rabbitmq/MQController.java create mode 100644 src/main/java/com/sipai/controller/scada/MPointController.java create mode 100644 src/main/java/com/sipai/controller/user/CompanyController.java create mode 100644 src/main/java/com/sipai/controller/user/UserController.java create mode 100644 src/main/java/com/sipai/dao/Listener/ListenerHisDao.java create mode 100644 src/main/java/com/sipai/dao/Listener/ListenerInterfaceDao.java create mode 100644 src/main/java/com/sipai/dao/Listener/ListenerMessageDao.java create mode 100644 src/main/java/com/sipai/dao/Listener/ListenerPointDao.java create mode 100644 src/main/java/com/sipai/dao/base/CommDao.java create mode 100644 src/main/java/com/sipai/dao/base/CommDaoImpl.java create mode 100644 src/main/java/com/sipai/dao/data/PipeTopicMpointDao.java create mode 100644 src/main/java/com/sipai/dao/data/PipelineEquipmentDao.java create mode 100644 src/main/java/com/sipai/dao/data/PipelineEquipmentMpointDao.java create mode 100644 src/main/java/com/sipai/dao/data/PipelineMpointLibraryDao.java create mode 100644 src/main/java/com/sipai/dao/mqtt/MqttConfigDao.java create mode 100644 src/main/java/com/sipai/dao/mqtt/MqttConfigTopicDao.java create mode 100644 src/main/java/com/sipai/dao/scada/MPointBzwDao.java create mode 100644 src/main/java/com/sipai/dao/scada/MPointDao.java create mode 100644 src/main/java/com/sipai/dao/scada/MPointHistoryDao.java create mode 100644 src/main/java/com/sipai/dao/scada/MPointRepo.java create mode 100644 src/main/java/com/sipai/dao/scada/MPointRepository.java create mode 100644 src/main/java/com/sipai/dao/scada/MPointRepositoryImpl.java create mode 100644 src/main/java/com/sipai/dao/user/CompanyDao.java create mode 100644 src/main/java/com/sipai/dao/user/UserDao.java create mode 100644 src/main/java/com/sipai/entity/Listener/ListenerHis.java create mode 100644 src/main/java/com/sipai/entity/Listener/ListenerInterface.java create mode 100644 src/main/java/com/sipai/entity/Listener/ListenerMessage.java create mode 100644 src/main/java/com/sipai/entity/Listener/ListenerPoint.java create mode 100644 src/main/java/com/sipai/entity/base/Result.java create mode 100644 src/main/java/com/sipai/entity/base/SQLAdapter.java create mode 100644 src/main/java/com/sipai/entity/common/PageData.java create mode 100644 src/main/java/com/sipai/entity/data/ChannelData.java create mode 100644 src/main/java/com/sipai/entity/data/DeviceData.java create mode 100644 src/main/java/com/sipai/entity/data/DeviceDataPacket.java create mode 100644 src/main/java/com/sipai/entity/data/PipeTopicMpoint.java create mode 100644 src/main/java/com/sipai/entity/data/PipelineEquipment.java create mode 100644 src/main/java/com/sipai/entity/data/PipelineEquipmentMpoint.java create mode 100644 src/main/java/com/sipai/entity/data/PipelineMpointLibrary.java create mode 100644 src/main/java/com/sipai/entity/data/SensorData.java create mode 100644 src/main/java/com/sipai/entity/enums/DeviceTypeEnum.java create mode 100644 src/main/java/com/sipai/entity/mqtt/Mqtt.java create mode 100644 src/main/java/com/sipai/entity/mqtt/MqttConfig.java create mode 100644 src/main/java/com/sipai/entity/mqtt/MqttConfigTopic.java create mode 100644 src/main/java/com/sipai/entity/mqtt/MqttProperties.java create mode 100644 src/main/java/com/sipai/entity/scada/MPoint.java create mode 100644 src/main/java/com/sipai/entity/scada/MPointBzw.java create mode 100644 src/main/java/com/sipai/entity/scada/MPointES.java create mode 100644 src/main/java/com/sipai/entity/scada/MPointHistory.java create mode 100644 src/main/java/com/sipai/entity/user/Company.java create mode 100644 src/main/java/com/sipai/entity/user/User.java create mode 100644 src/main/java/com/sipai/schedule/DataSynJob.java create mode 100644 src/main/java/com/sipai/service/Listener/ListenerHisService.java create mode 100644 src/main/java/com/sipai/service/Listener/ListenerInterfaceService.java create mode 100644 src/main/java/com/sipai/service/Listener/ListenerMessageService.java create mode 100644 src/main/java/com/sipai/service/Listener/ListenerPointService.java create mode 100644 src/main/java/com/sipai/service/Listener/impl/ListenerHisServiceImpl.java create mode 100644 src/main/java/com/sipai/service/Listener/impl/ListenerInterfaceServiceImpl.java create mode 100644 src/main/java/com/sipai/service/Listener/impl/ListenerMessageServiceImpl.java create mode 100644 src/main/java/com/sipai/service/Listener/impl/ListenerPointServiceImpl.java create mode 100644 src/main/java/com/sipai/service/data/DeviceDataParser.java create mode 100644 src/main/java/com/sipai/service/data/PipeTopicMpointService.java create mode 100644 src/main/java/com/sipai/service/data/PipelineEquipmentMpointService.java create mode 100644 src/main/java/com/sipai/service/data/PipelineEquipmentService.java create mode 100644 src/main/java/com/sipai/service/data/PipelineMpointLibraryService.java create mode 100644 src/main/java/com/sipai/service/data/impl/PipeTopicMpointServiceImpl.java create mode 100644 src/main/java/com/sipai/service/data/impl/PipelineEquipmentMpointServiceImpl.java create mode 100644 src/main/java/com/sipai/service/data/impl/PipelineEquipmentServiceImpl.java create mode 100644 src/main/java/com/sipai/service/data/impl/PipelineMpointLibraryServiceImpl.java create mode 100644 src/main/java/com/sipai/service/kafka/KafkaConsumerService.java create mode 100644 src/main/java/com/sipai/service/kafka/KafkaProducerService.java create mode 100644 src/main/java/com/sipai/service/mqtt/MqttConfigService.java create mode 100644 src/main/java/com/sipai/service/mqtt/MqttConfigTopicService.java create mode 100644 src/main/java/com/sipai/service/mqtt/MqttService.java create mode 100644 src/main/java/com/sipai/service/mqtt/PushCallback.java create mode 100644 src/main/java/com/sipai/service/mqtt/impl/MqttConfigServiceImpl.java create mode 100644 src/main/java/com/sipai/service/mqtt/impl/MqttConfigTopicServiceImpl.java create mode 100644 src/main/java/com/sipai/service/mqtt/impl/MqttServiceImpl.java create mode 100644 src/main/java/com/sipai/service/opc/InitOpcUaService.java create mode 100644 src/main/java/com/sipai/service/opc/OpcUaService.java create mode 100644 src/main/java/com/sipai/service/rabbitmq/MQService.java create mode 100644 src/main/java/com/sipai/service/rabbitmq/impl/MQServiceImpl.java create mode 100644 src/main/java/com/sipai/service/scada/MPointBzwService.java create mode 100644 src/main/java/com/sipai/service/scada/MPointHistoryService.java create mode 100644 src/main/java/com/sipai/service/scada/MPointService.java create mode 100644 src/main/java/com/sipai/service/scada/impl/MPointBzwServiceImpl.java create mode 100644 src/main/java/com/sipai/service/scada/impl/MPointHistoryServiceImpl.java create mode 100644 src/main/java/com/sipai/service/scada/impl/MPointServiceImpl.java create mode 100644 src/main/java/com/sipai/service/user/CompanyService.java create mode 100644 src/main/java/com/sipai/service/user/UserService.java create mode 100644 src/main/java/com/sipai/service/user/impl/CompanyServiceImpl.java create mode 100644 src/main/java/com/sipai/service/user/impl/UserServiceImpl.java create mode 100644 src/main/java/com/sipai/tools/AlarmType.java create mode 100644 src/main/java/com/sipai/tools/CommString.java create mode 100644 src/main/java/com/sipai/tools/CommUtil.java create mode 100644 src/main/java/com/sipai/tools/ConstantString.java create mode 100644 src/main/java/com/sipai/tools/DataSourceAspect.java create mode 100644 src/main/java/com/sipai/tools/DataSourceContextHolder.java create mode 100644 src/main/java/com/sipai/tools/DataSourceEnum.java create mode 100644 src/main/java/com/sipai/tools/DataSourceTypeAnno.java create mode 100644 src/main/java/com/sipai/tools/DynamicDataSource.java create mode 100644 src/main/java/com/sipai/tools/EncryptGISUtils.java create mode 100644 src/main/java/com/sipai/tools/HttpUtil.java create mode 100644 src/main/java/com/sipai/tools/MyBatisConfig.java create mode 100644 src/main/java/com/sipai/tools/Result.java create mode 100644 src/main/java/com/sipai/tools/SpringContextUtil.java create mode 100644 src/main/java/com/sipai/tools/Test.java create mode 100644 src/main/java/com/sipai/tools/ThreadConfig.java create mode 100644 src/main/resources/application-dev.yml create mode 100644 src/main/resources/application-pro.yml create mode 100644 src/main/resources/application.yml create mode 100644 src/main/resources/generatior-config.xml create mode 100644 src/main/resources/log4j2.xml create mode 100644 src/main/resources/mybatis-config.xml create mode 100644 src/main/resources/mybatis/mapper/Listener/ListenerHis.xml create mode 100644 src/main/resources/mybatis/mapper/Listener/ListenerInterfaceMapper.xml create mode 100644 src/main/resources/mybatis/mapper/Listener/ListenerMessageMapper.xml create mode 100644 src/main/resources/mybatis/mapper/Listener/ListenerPointMapper.xml create mode 100644 src/main/resources/mybatis/mapper/data/PipeTopicMpointMapper.xml create mode 100644 src/main/resources/mybatis/mapper/data/PipelineEquipmentMapper.xml create mode 100644 src/main/resources/mybatis/mapper/data/PipelineEquipmentMpointMapper.xml create mode 100644 src/main/resources/mybatis/mapper/data/PipelineMpointLibraryMapper.xml create mode 100644 src/main/resources/mybatis/mapper/mqtt/MqttConfigMapper.xml create mode 100644 src/main/resources/mybatis/mapper/mqtt/MqttConfigTopicMapper.xml create mode 100644 src/main/resources/mybatis/mapper/scada/MPointBzw.xml create mode 100644 src/main/resources/mybatis/mapper/scada/MPointHistoryMapper.xml create mode 100644 src/main/resources/mybatis/mapper/scada/MPointMapper.xml create mode 100644 src/main/resources/mybatis/mapper/user/CompanyDao.xml create mode 100644 src/main/resources/mybatis/mapper/user/UserDao.xml create mode 100644 src/main/resources/templates/index.html create mode 100644 src/test/java/com/sipai/SpringbootApplicationTests.java diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..ccf5566 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,10 @@ +# ĬϺԵļ +/shelf/ +/workspace.xml +# ڱ༭ HTTP ͻ +/httpRequests/ +# ڻ Maven Ŀ¼· +/mavenHomeManager.xml +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..d227fcd --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,14 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/sipaiis_datacollector.iml b/.idea/sipaiis_datacollector.iml new file mode 100644 index 0000000..d6ebd48 --- /dev/null +++ b/.idea/sipaiis_datacollector.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.trae/documents/在GIS_Job中加入和达流量计计算点位推送.md b/.trae/documents/在GIS_Job中加入和达流量计计算点位推送.md new file mode 100644 index 0000000..8a3a177 --- /dev/null +++ b/.trae/documents/在GIS_Job中加入和达流量计计算点位推送.md @@ -0,0 +1,55 @@ +## 变更目标 + +* 在 `com.sipai.schedule.GIS_Job.jobGIS` 的 SQL WHERE 过滤中,加入 6 个新计算点位的精确匹配,使其随既有点位一起下发到管网平台。 + +* 新增点位:`KCGW_53564_A8`、`KCGW_53564_A7`、`KCGW_53564_P1`、`KCGW_53581_A8`、`KCGW_53581_A7`、`KCGW_53581_P1`。 + +## 代码位置 + +* 文件:`src/main/java/com/sipai/schedule/GIS_Job.java` + +* 方法:`jobGIS` + +* 现有 SQL 拼接区间:`GIS_Job.java:427-436` + +## 具体改动 + +* 在现有两条和达设备前缀过滤之后、分号之前,按既有格式追加以下条件: + +``` +" OR id = 'KCGW_53564_A8'\n" + +" OR id = 'KCGW_53564_A7'\n" + +" OR id = 'KCGW_53564_P1'\n" + +" OR id = 'KCGW_53581_A8'\n" + +" OR id = 'KCGW_53581_A7'\n" + +" OR id = 'KCGW_53581_P1'\n" + +``` + +* 保持原有 `LIKE 'KCGW_22008_53564_%'` 与 `LIKE 'KCGW_22029_53581_%'` 不变,避免影响既有轮询点位推送。 + +## 实现步骤 + +* 编辑 `sql` 字符串,追加上述 6 行 `OR id = '...'` 条件,保留末尾分号。 + +* 不改动其他逻辑(查询、组装 JSON、MQTT 发送)。 + +## 校验与验证 + +* 在本地运行 `jobGIS` 定时任务或手动触发同路径查询,确认 `mPointService.selectListByWhere(sql)` 返回集合包含新增 6 点位(可在日志或调试中检视)。 + +* 观察 MQTT 推送内容(主题 `CommString.Mqtt_Topic_DATA`)是否包含对应 `mpcode` 与最新值/时间。 + +* 关注日志输出与异常堆栈,确保无 SQL 拼接格式错误。 + +## 兼容性与命名一致性 + +* 新增 ID 与 `HD_Job` 中计算点位编码一致:`KCGW__`。 + +* 不影响既有 `SignalTag`、`P1_DAY/HOUR`、`KCGW_15001_A1_*` 等过滤。 + +## 风险与回退 + +* 若后续计算点位命名规范调整,需同步更新此处精确匹配。 + +* 若管网平台不需要这 6 个点位,可直接移除新增的 `OR id = '...'` 条件回退。 + diff --git a/README.md b/README.md new file mode 100644 index 0000000..ff90759 --- /dev/null +++ b/README.md @@ -0,0 +1,92 @@ +# SIPAIIS_DataCollector + + + +## Getting started + +To make it easy for you to get started with GitLab, here's a list of recommended next steps. + +Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! + +## Add your files + +- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files +- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: + +``` +cd existing_repo +git remote add origin http://localhost/backend/sipaiis_datacollector.git +git branch -M main +git push -uf origin main +``` + +## Integrate with your tools + +- [ ] [Set up project integrations](http://localhost/backend/sipaiis_datacollector/-/settings/integrations) + +## Collaborate with your team + +- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) +- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) +- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) +- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) +- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) + +## Test and Deploy + +Use the built-in continuous integration in GitLab. + +- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) +- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) +- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) +- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) +- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) + +*** + +# Editing this README + +When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. + +## Suggestions for a good README +Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. + +## Name +Choose a self-explaining name for your project. + +## Description +Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. + +## Badges +On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. + +## Visuals +Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. + +## Installation +Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. + +## Usage +Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. + +## Support +Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. + +## Roadmap +If you have ideas for releases in the future, it is a good idea to list them in the README. + +## Contributing +State if you are open to contributions and what your requirements are for accepting them. + +For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. + +You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. + +## Authors and acknowledgment +Show your appreciation to those who have contributed to the project. + +## License +For open source projects, say how it is licensed. + +## Project status +If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..88d7d16 --- /dev/null +++ b/pom.xml @@ -0,0 +1,284 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.0.RELEASE + + + com.sipai + springboot + 0.0.1-SNAPSHOT + jar + springboot + Demo project for Spring Boot + + 1.8 + 4.1.86.Final + 2.3.7.RELEASE + + + + org.springframework.boot + spring-boot-starter-web + + + logback-core + ch.qos.logback + + + logback-classic + ch.qos.logback + + + spring-boot-starter-logging + org.springframework.boot + + + log4j-to-slf4j + org.apache.logging.log4j + + + + + + org.springframework.boot + spring-boot-starter-data-elasticsearch + + + + org.projectlombok + lombok + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + + org.mybatis.generator + mybatis-generator-core + 1.3.5 + + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 2.0.0 + + + com.alibaba + druid-spring-boot-starter + 1.1.10 + + + + com.microsoft.sqlserver + mssql-jdbc + runtime + + + + mysql + mysql-connector-java + 8.0.11 + + + org.eclipse.paho + org.eclipse.paho.client.mqttv3 + 1.1.0 + + + + com.fasterxml.uuid + java-uuid-generator + 4.0.1 + + + + com.alibaba + fastjson + 1.2.75 + + + org.aspectj + aspectjweaver + 1.9.4 + + + + org.springframework + spring-jdbc + + + + + com.google.code.gson + gson + 2.8.5 + + + + org.springframework + springloaded + 1.2.8.RELEASE + + + + org.springframework.boot + spring-boot-starter-amqp + + + + + io.springfox + springfox-swagger2 + 2.9.2 + + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + + org.apache.commons + commons-collections4 + 4.4 + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + + org.redisson + redisson + 3.13.3 + + + + io.netty + netty-all + ${netty.version} + + + + + org.eclipse.milo + sdk-client + 0.6.10 + + + com.google.guava + guava + + + + + + org.eclipse.milo + stack-core + 0.6.10 + + + + + com.google.guava + guava + 31.1-jre + + + + + org.springframework.kafka + spring-kafka + ${spring-kafka.version} + + + + + com.github.ben-manes.caffeine + caffeine + 2.9.3 + + + + com.github.pagehelper + pagehelper-spring-boot-starter + 1.4.6 + + + + + org.springframework.boot + spring-boot-starter-log4j2 + + + + + org.apache.httpcomponents + httpclient + 4.5.13 + + + org.apache.httpcomponents + httpmime + 4.5.13 + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.sipai.DataApplication + + + + + org.mybatis.generator + mybatis-generator-maven-plugin + 1.3.2 + + ${basedir}/src/main/resources/generatior-config.xml + true + true + + + + + + src/main/webapp + META-INF/resources + + **/** + + + + src/main/resources + + **/** + + + + + + \ No newline at end of file diff --git a/src/main/java/com/sipai/DataApplication.java b/src/main/java/com/sipai/DataApplication.java new file mode 100644 index 0000000..cf2cebd --- /dev/null +++ b/src/main/java/com/sipai/DataApplication.java @@ -0,0 +1,47 @@ +package com.sipai; + +import com.sipai.tools.DataSourceAspect; +import com.sipai.tools.DataSourceContextHolder; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration; +import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration; +import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.ImportResource; +import org.springframework.context.annotation.PropertySource; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +//@SpringBootApplication + +/** + * @SpringBootApplication 为 + * @Configuration、@EnableAutoConfiguration、@ComponentScan 三个注解的组合 + */ + +@SpringBootApplication(exclude = { + DataSourceAutoConfiguration.class +}) +@EnableTransactionManagement //开启事务功能 +@EnableAsync//开启异步 +@EnableScheduling +@MapperScan("src/main/resources/mybatis/mapper") +//@PropertySource("classpath:application-pro.yml")//yml里面指定pro失效,只能在这强制指定 +public class DataApplication { + + static{ + System.setProperty("es.set.netty.runtime.available.processors", "false"); + } + + public static void main(String[] args) { + SpringApplication app = new SpringApplication(DataApplication.class); + app.setAllowBeanDefinitionOverriding(false); // 检查是否有此设置 + app.run(args); + } + +} diff --git a/src/main/java/com/sipai/config/AppConfig.java b/src/main/java/com/sipai/config/AppConfig.java new file mode 100644 index 0000000..a29e6cd --- /dev/null +++ b/src/main/java/com/sipai/config/AppConfig.java @@ -0,0 +1,18 @@ +package com.sipai.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "app") +public class AppConfig { + private int maxPoints; + + public int getMaxPoints() { + return maxPoints; + } + + public void setMaxPoints(int maxPoints) { + this.maxPoints = maxPoints; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/config/MockOpcUaClient.java b/src/main/java/com/sipai/config/MockOpcUaClient.java new file mode 100644 index 0000000..ecffa7f --- /dev/null +++ b/src/main/java/com/sipai/config/MockOpcUaClient.java @@ -0,0 +1,38 @@ +package com.sipai.config; + +import org.eclipse.milo.opcua.sdk.client.OpcUaClient; +import org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig; +import org.eclipse.milo.opcua.stack.client.UaStackClient; +import org.eclipse.milo.opcua.stack.core.types.builtin.*; +import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; + +public class MockOpcUaClient extends OpcUaClient { + public MockOpcUaClient(OpcUaClientConfig config) throws Exception { + super(config, (UaStackClient) Executors.newSingleThreadExecutor()); // 提供所有必需的参数 + } + + private static OpcUaClientConfig createMockConfig() { + return OpcUaClientConfig.builder() + .setEndpoint(null) // 模拟端点 + .setApplicationName(LocalizedText.english("Mock OPC UA Client")) + .build(); + } + + public static MockOpcUaClient createMockClient() throws Exception { + return new MockOpcUaClient(createMockConfig()); + } + + @Override + public CompletableFuture readValue(double timeout, TimestampsToReturn timestamps, NodeId nodeId) { + DataValue dataValue = new DataValue( + new Variant(0), // 模拟值 + StatusCode.GOOD, + null, + null + ); + return CompletableFuture.completedFuture(dataValue); + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/config/OpcUaConfig.java b/src/main/java/com/sipai/config/OpcUaConfig.java new file mode 100644 index 0000000..fa24e73 --- /dev/null +++ b/src/main/java/com/sipai/config/OpcUaConfig.java @@ -0,0 +1,76 @@ +package com.sipai.config; + +import org.eclipse.milo.opcua.sdk.client.OpcUaClient; +import org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig; +import org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider; +import org.eclipse.milo.opcua.sdk.client.api.identity.IdentityProvider; +import org.eclipse.milo.opcua.sdk.client.api.identity.UsernameProvider; +import org.eclipse.milo.opcua.stack.client.DiscoveryClient; +import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy; +import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger; +import org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.List; + +@Configuration +public class OpcUaConfig { + @Autowired + private OpcUaProperties properties; + + @Bean + @ConditionalOnProperty(prefix = "opcua", name = "enabled", havingValue = "true") + public OpcUaClient opcUaClient() throws Exception { + return createClient(properties); + } + + /*@Bean + public OpcUaClient opcUaClient(OpcUaProperties properties) throws Exception { + if (!properties.isEnabled()) { + // 如果 OPC UA 功能未启用,返回 null 或抛出自定义异常 + return null; // 或者抛出一个自定义异常 + } + return createClient(properties); + }*/ + + private OpcUaClient createClient(OpcUaProperties properties) throws Exception { + // 1. 发现端点 + List endpoints = DiscoveryClient + .getEndpoints(properties.getServerUrl()) + .get(); + + // 2. 根据配置选择端点 + EndpointDescription endpoint = endpoints.stream() + .filter(e -> e.getSecurityPolicyUri().equals(SecurityPolicy.None.getUri())) + .findFirst() + .orElseThrow(() -> new Exception("未找到匿名访问端点")); + + // 3. 创建身份认证提供者 + IdentityProvider identityProvider; + if (properties.getUsername() != null && !properties.getUsername().isEmpty()) { + // 使用用户名/密码认证 + identityProvider = new UsernameProvider( + properties.getUsername(), + properties.getPassword() + ); + } else { + // 使用匿名认证 + identityProvider = new AnonymousProvider(); + } + + // 4. 创建客户端配置 + OpcUaClientConfig config = OpcUaClientConfig.builder() + .setEndpoint(endpoint) + .setRequestTimeout(UInteger.valueOf(5000)) + .setIdentityProvider(identityProvider) + .build(); + + // 5. 创建并连接客户端 + OpcUaClient client = OpcUaClient.create(config); + client.connect().get(); + return client; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/config/OpcUaProperties.java b/src/main/java/com/sipai/config/OpcUaProperties.java new file mode 100644 index 0000000..9762bbd --- /dev/null +++ b/src/main/java/com/sipai/config/OpcUaProperties.java @@ -0,0 +1,66 @@ +package com.sipai.config; + +import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy; +import org.eclipse.milo.opcua.stack.core.types.enumerated.MessageSecurityMode; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "opcua") +public class OpcUaProperties { + private String serverUrl; + private SecurityPolicy securityPolicy = SecurityPolicy.None; + private MessageSecurityMode securityMode = MessageSecurityMode.None; + private String username; + private String password; + private boolean enabled = false;//是否启用opc客户端 + + // Getters and Setters + public String getServerUrl() { + return serverUrl; + } + + public void setServerUrl(String serverUrl) { + this.serverUrl = serverUrl; + } + + public SecurityPolicy getSecurityPolicy() { + return securityPolicy; + } + + public void setSecurityPolicy(SecurityPolicy securityPolicy) { + this.securityPolicy = securityPolicy; + } + + public MessageSecurityMode getSecurityMode() { + return securityMode; + } + + public void setSecurityMode(MessageSecurityMode securityMode) { + this.securityMode = securityMode; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/config/RedissonConfig.java b/src/main/java/com/sipai/config/RedissonConfig.java new file mode 100644 index 0000000..e61c62b --- /dev/null +++ b/src/main/java/com/sipai/config/RedissonConfig.java @@ -0,0 +1,75 @@ +package com.sipai.config; + + +import org.redisson.Redisson; +import org.redisson.api.RedissonClient; +import org.redisson.client.codec.Codec; +import org.redisson.codec.JsonJacksonCodec; +import org.redisson.config.Config; +import org.redisson.config.SingleServerConfig; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @Author : YYJ + * @CreateTime : 2021/9/13 + * @Description : + **/ +@Configuration +public class RedissonConfig { + private static String MODE_SINGLE = "single"; + private static String MODE_CLUSTER = "cluster"; + @Value("${spring.redis.mode}") + public String mode; + + @Value("${spring.redis.cluster.nodes}") + public String cluster; + + @Value("${spring.redis.password}") + public String password; + + @Value("${spring.redis.host}") + public String host; + + @Value("${spring.redis.port}") + public String port; + + @Value("${spring.redis.timeout}") + public Integer timeout; + +// @Value("${redis.database}") +// public String database; + + @Bean + public RedissonClient redissonClient(){ + RedissonClient redisson = null; + Config conf = new Config(); + + if(MODE_SINGLE.equals(mode)) {//单机 + //单节点模式 + SingleServerConfig singleServerConfig = conf.useSingleServer(); + //设置连接地址:redis://127.0.0.1:6379 + singleServerConfig.setAddress("redis://" + host + ":" + port); + //设置连接密码 + singleServerConfig.setPassword(password); +// singleServerConfig.setDatabase(Integer.valueOf(database)); + }else if(MODE_CLUSTER.equals(mode)){//集群 + String[] nodes = cluster.split(","); + for (int i = 0; i < nodes.length; i++) { + nodes[i] = "redis://" + nodes[i]; + } + conf.useClusterServers() + .setScanInterval(2000) + .addNodeAddress(nodes) + .setTimeout(timeout) + .setPassword(password); + } + + //使用json序列化方式 + Codec codec = new JsonJacksonCodec(); + conf.setCodec(codec); + redisson = Redisson.create(conf); + return redisson; + } +} diff --git a/src/main/java/com/sipai/config/StartupLogger.java b/src/main/java/com/sipai/config/StartupLogger.java new file mode 100644 index 0000000..925a90e --- /dev/null +++ b/src/main/java/com/sipai/config/StartupLogger.java @@ -0,0 +1,20 @@ +package com.sipai.config; + +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +import java.net.InetAddress; +import java.net.UnknownHostException; + +@Component +public class StartupLogger { + + @EventListener(ApplicationReadyEvent.class) + public void onStartup() throws UnknownHostException { + String ip = InetAddress.getLocalHost().getHostAddress(); + String port = System.getProperty("server.port");//bat脚本传过来的端口 + String url = ip + ":" + port; + System.out.println("Spring Boot 服务已启动完成!" + (url != null ? "开发环境" : url)); + } +} diff --git a/src/main/java/com/sipai/config/UDPClient.java b/src/main/java/com/sipai/config/UDPClient.java new file mode 100644 index 0000000..ccd0989 --- /dev/null +++ b/src/main/java/com/sipai/config/UDPClient.java @@ -0,0 +1,80 @@ +package com.sipai.config; + +import org.springframework.beans.factory.annotation.Value; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; + +/** + * 用于测试 - 南昌项目 + * sj 2025-05-21 + */ +public class UDPClient { + +// @Value("${udp.server.port}") +// private static int serverPort; + + public static void main(String[] args) { + +// 管网监测设备采集 +// 192.168.10.18:5006 +// 223.84.61.83:5006 + +// String serverHost = "116.236.176.248"; +// String serverHost = "127.0.0.1"; + String serverHost = "223.84.61.83"; + int serverPort = 5006; + + //智能井盖 + String hexString = "AB CD 00 4D 2A FB 25 07 20 12 00 01 A0 01 68 00 02 08 48 4B 33 35 2D 49 49 3B 56 31 2E 31 3B 56 31 2E 30 2E 30 36 00 00 00 00 00 00 00 00 04 01 C2 D2 00 00 04 02 40 E0 00 00 04 03 3F EC 7D AF 04 04 47 C3 50 00 04 05 47 C3 50 00 05 01 00 00 D3 0D 0A"; + //流量计 +// String hexString = "AB CD 00 71 56 03 25 07 08 09 15 01 0F 02 D8 00 FD 12 48 38 36 45 3B 31 2E 33 3B 31 2E 30 2E 33 35 20 20 20 20 20 00 00 00 00 00 00 00 00 01 01 DC 02 00 00 25 A8 00 00 01 02 00 00 00 00 03 00 00 00 01 03 DC 02 00 00 22 A8 00 00 04 01 3C A3 D7 0A 04 02 3D A3 D7 0A 04 03 41 A0 00 00 04 04 41 C4 7A E1 04 07 41 2C CC CD 04 08 3E 45 A1 CB 05 01 00 00 A2 0D 0A"; + //液位计 +// String hexString = "AB CD 00 B7 59 F7 25 07 08 09 05 03 05 01 6D 00 C0 06 48 4B 31 39 52 3B 33 2E 31 3B 31 2E 30 2E 30 30 00 00 00 00 00 00 00 00 00 00 00 00 04 01 42 E0 00 00 42 E0 00 00 42 E0 00 00 04 02 40 00 00 00 40 00 00 00 40 00 00 00 04 03 43 E8 80 00 43 E8 80 00 43 E8 80 00 04 04 3F C0 6A 32 40 0A 7D B4 3F C0 6A 32 04 05 40 69 D8 88 40 69 D8 88 40 69 D8 88 04 06 00 00 00 00 00 00 00 00 00 00 00 00 04 07 00 00 00 00 00 00 00 00 00 00 00 00 04 08 40 65 E3 55 40 65 D2 F2 40 65 B2 2E 04 09 3D DD 2F 00 3D DF 3B 60 3D E3 53 E0 04 0A 3D DD 2F 00 3D DF 3B 60 3D E3 53 E0 34 0D 0A"; + //电导 +// String hexString = "AB CD 00 A3 36 B1 25 06 21 18 15 08 0F 02 DC 00 D2 0D 48 38 36 45 3B 31 2E 33 3B 31 2E 30 2E 33 35 20 20 20 20 20 00 00 00 00 00 00 00 00 04 03 41 40 00 00 41 40 00 00 41 40 00 00 41 40 00 00 41 40 00 00 41 40 00 00 41 40 00 00 41 40 00 00 04 07 00 00 00 00 3A 83 12 6F 3A 83 12 6F 3A 83 12 6F 3A 83 12 6F 3A 83 12 6F 3A 83 12 6F 3A 83 12 6F 04 08 41 C8 CC CD 41 CA 66 66 41 CB 33 33 41 CC CC CD 41 D0 CC CD 41 D3 33 33 41 D4 CC CD 41 D5 99 9A 05 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 A1 0D 0A"; + //雨量计 +// String hexString = "AB CD 00 8B 3A 99 25 06 21 13 33 02 01 04 64 00 A5 15 48 38 31 45 2D 3B 31 2E 34 3B 35 2E 30 2E 30 34 20 20 20 20 00 00 00 00 00 00 00 00 01 01 00 00 00 00 00 00 00 00 00 00 00 00 01 02 00 00 00 00 00 00 00 00 00 00 00 00 01 04 00 00 00 00 00 00 00 00 00 00 00 00 01 05 00 00 00 00 00 00 00 00 00 00 00 00 04 01 43 37 66 66 43 37 66 66 04 02 00 00 00 00 00 00 00 00 04 04 40 E8 80 00 40 F0 00 00 04 05 00 00 00 00 00 00 00 00 EE 0D 0A"; + //内涝‘ +// String hexString = "AB CD 00 6A 3E 81 25 06 21 13 33 01 01 05 6A 00 05 19 56 38 38 20 53 6D 61 72 74 20 20 20 20 20 20 20 20 20 20 20 00 00 00 00 00 00 00 00 01 01 00 00 00 00 00 00 00 00 01 02 00 00 00 00 00 00 00 00 02 03 01 02 04 01 02 09 00 02 0A 00 02 0B 00 04 01 00 00 00 00 04 02 00 00 00 00 04 0D 00 00 00 00 01 0E 00 00 00 00 00 00 00 00 70 0D 0A"; + + + hexString = hexString.replaceAll("\\s+", ""); // Remove all whitespace + byte[] data = hexStringToByteArray(hexString); + + try (DatagramSocket socket = new DatagramSocket()) { + InetAddress serverAddress = InetAddress.getByName(serverHost); + + // 发送数据包 + DatagramPacket packet = new DatagramPacket( + data, data.length, serverAddress, serverPort); + socket.send(packet); + System.out.println("已发送数据包到服务器"); + + // 接收响应 + byte[] buffer = new byte[1024]; + DatagramPacket response = new DatagramPacket(buffer, buffer.length); + socket.receive(response); + + String responseStr = new String( + response.getData(), 0, response.getLength()); + System.out.println("服务器响应: " + responseStr); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + // 十六进制字符串转字节数组的方法 + private static byte[] hexStringToByteArray(String s) { + int len = s.length(); + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + + Character.digit(s.charAt(i + 1), 16)); + } + return data; + } +} diff --git a/src/main/java/com/sipai/config/UDPFilePollingClient.java b/src/main/java/com/sipai/config/UDPFilePollingClient.java new file mode 100644 index 0000000..07be833 --- /dev/null +++ b/src/main/java/com/sipai/config/UDPFilePollingClient.java @@ -0,0 +1,135 @@ +package com.sipai.config; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.*; +import java.util.concurrent.TimeUnit; + +/** + * 用于测试 - 南昌项目 + * 修改为轮询txt文件并发送内容 + * sj 2025-05-21 + * 修改为仅轮询一次 + */ +public class UDPFilePollingClient { + + private static final String SERVER_HOST = "223.84.61.83"; // 默认本地 + private static final int SERVER_PORT = 5006; + private static final String WATCH_DIRECTORY = "D:\\data_logs\\yewei"; // 监控当前目录 + private static final Set processedFiles = Collections.synchronizedSet(new HashSet<>()); + + public static void main(String[] args) { + System.out.println("启动UDP文件轮询服务(单次运行),监控目录: " + WATCH_DIRECTORY); + pollAndProcessFiles(); + System.out.println("文件轮询处理完成"); + } + + private static void pollAndProcessFiles() { + try { + List txtFiles = new ArrayList<>(); + + // 收集所有txt文件 + Files.walkFileTree(Paths.get(WATCH_DIRECTORY), new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { + if (file.toString().toLowerCase().endsWith(".txt")) { + txtFiles.add(file); + } + return FileVisitResult.CONTINUE; + } + }); + + // 按修改时间排序(从旧到新) + txtFiles.sort(Comparator.comparing(path -> { + try { + return Files.getLastModifiedTime(path).toMillis(); + } catch (IOException e) { + return 0L; + } + })); + + // 处理未处理过的文件 + for (Path file : txtFiles) { + if (!processedFiles.contains(file)) { + processFile(file); + processedFiles.add(file); + } + } + } catch (IOException e) { + System.err.println("目录轮询错误: " + e.getMessage()); + } + } + + private static void processFile(Path file) { + try { + // 正确读取文件内容为字符串 + String fileContent = new String(Files.readAllBytes(file)).trim(); + + if (fileContent.isEmpty()) { + System.out.println("文件内容为空,跳过: " + file.getFileName()); + return; + } + + // 发送UDP请求 + sendUdpRequest(fileContent); + + // 可选: 发送成功后移动或删除文件 + Files.delete(file); + // 或移动到已处理目录 + // Files.move(file, Paths.get("processed", file.getFileName())); + + } catch (IOException e) { + System.err.println("处理文件错误 " + file.getFileName() + ": " + e.getMessage()); + } + } + + private static void sendUdpRequest(String hexString) { + hexString = hexString.replaceAll("\\s+", ""); // 移除所有空白字符 + + try (DatagramSocket socket = new DatagramSocket()) { + InetAddress serverAddress = InetAddress.getByName(SERVER_HOST); + byte[] data = hexStringToByteArray(hexString); + + // 发送数据包 + DatagramPacket packet = new DatagramPacket( + data, data.length, serverAddress, SERVER_PORT); + socket.send(packet); + System.out.println("已发送UDP数据包到 " + SERVER_HOST + ":" + SERVER_PORT); + + // 接收响应(可选) + byte[] buffer = new byte[1024]; + DatagramPacket response = new DatagramPacket(buffer, buffer.length); + socket.setSoTimeout(1000); // 3秒超时 + try { + socket.receive(response); + String responseStr = new String( + response.getData(), 0, response.getLength()); + System.out.println("服务器响应: " + responseStr); + } catch (IOException e) { + System.out.println("未收到服务器响应(超时)"); + } + + } catch (IOException e) { + System.err.println("UDP通信错误: " + e.getMessage()); + } + } + + // 十六进制字符串转字节数组的方法 + private static byte[] hexStringToByteArray(String s) { + int len = s.length(); + if (len % 2 != 0) { + throw new IllegalArgumentException("十六进制字符串长度必须为偶数"); + } + + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + + Character.digit(s.charAt(i + 1), 16)); + } + return data; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/config/UDPServer.java b/src/main/java/com/sipai/config/UDPServer.java new file mode 100644 index 0000000..44e9e71 --- /dev/null +++ b/src/main/java/com/sipai/config/UDPServer.java @@ -0,0 +1,859 @@ +package com.sipai.config; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.sipai.entity.data.DeviceData; +import com.sipai.entity.data.PipelineEquipment; +import com.sipai.entity.data.PipelineEquipmentMpoint; +import com.sipai.entity.data.SensorData; +import com.sipai.entity.mqtt.MqttConfig; +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointES; +import com.sipai.entity.scada.MPointHistory; +import com.sipai.service.data.PipelineEquipmentMpointService; +import com.sipai.service.data.PipelineEquipmentService; +import com.sipai.service.mqtt.MqttConfigService; +import com.sipai.service.scada.MPointHistoryService; +import com.sipai.service.scada.MPointService; +import com.sipai.tools.AlarmType; +import com.sipai.tools.CommString; +import com.sipai.tools.CommUtil; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import org.redisson.api.RBatch; +import org.redisson.api.RMapCache; +import org.redisson.api.RedissonClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.math.BigDecimal; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; + +/** + * 南昌项目upd接收数据处理 + * sj 2025-05-21 + */ +@Component +public class UDPServer implements CommandLineRunner { + + @Value("${udp.server.port}") //端口 + private int port; + @Value("${udp.server.enabled:true}") // 默认值为true + private boolean enabled; + private static final int BUFFER_SIZE = 1024; + + @Autowired + private PipelineEquipmentService pipelineEquipmentService; + @Autowired + private PipelineEquipmentMpointService pipelineEquipmentMpointService; + @Autowired + private MPointService mPointService; + @Autowired + private MPointHistoryService mPointHistoryService; + @Autowired + private MqttConfigService mqttConfigService; + + //缓存点位 + private static final Map dataCache = new ConcurrentHashMap<>(); + + @Override + public void run(String... args) throws Exception { + + if (!enabled) { + System.out.println("UDP服务未启用"); + return; + } + + try (DatagramSocket socket = new DatagramSocket(port)) { + System.out.println("UDP服务端启动,监听端口: " + port); + byte[] buffer = new byte[BUFFER_SIZE]; + DatagramPacket packet = new DatagramPacket(buffer, buffer.length); + while (true) { + socket.receive(packet); +// System.out.println(CommUtil.nowDate() + "======收到来自 " + packet.getAddress() + ":" + packet.getPort() + " 的数据"); + + // 发送应答 + String response = "@222\r\n"; + byte[] responseData = response.getBytes(StandardCharsets.UTF_8); + DatagramPacket responsePacket = new DatagramPacket( + responseData, responseData.length, + packet.getAddress(), packet.getPort()); + socket.send(responsePacket); + + // 解析数据包 + byte[] receivedData = new byte[packet.getLength()]; + System.arraycopy(packet.getData(), 0, receivedData, 0, packet.getLength()); + // 打印原始字节数组(十六进制格式) +// System.out.println("原始数据包(十六进制): " + bytesToHex(receivedData)); + + DeviceData data = parseDeviceData(Unpooled.wrappedBuffer(receivedData)); + if (data != null) { + String jsonData = CommUtil.toJson(data); + JSONObject jsonObject = JSON.parseObject(jsonData); + System.out.println("站号收到数据:" + jsonObject.get("stationId")+":"+jsonObject.get("startTime")); + JSONArray jsonArray = JSONArray.parseArray(jsonObject.get("sensorDataList").toString()); + if (jsonArray != null && !jsonArray.isEmpty()) { + processSensorData(jsonObject, jsonArray, bytesToHex(receivedData)); + } + } + } + } catch (IOException e) { + Logger logger = LoggerFactory.getLogger(UDPServer.class); + logger.error("UDP服务端启动异常", e); + e.printStackTrace(); + } + } + + //每次收到的报文存到D盘下 - 用于调试 + private void logs(String type, String bytes, String path) { + try { + // 获取当前时间 + LocalDateTime now = LocalDateTime.now(); + + // 定义文件名(保持原来的格式) + String fileName = DateTimeFormatter + .ofPattern("yyyyMMdd_HHmmss") + .format(now) + "_" + type + ".txt"; + + // 定义文件路径(D:/data_logs/年-月-日/自定义路径/) + String dateDir = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(now); + Path dirPath = Paths.get("D:/data_logs_new/" + dateDir + "/" + path + "/"); + + if (!Files.exists(dirPath)) { + Files.createDirectories(dirPath); // 如果目录不存在,则创建 + } + + Path filePath = dirPath.resolve(fileName); // 完整路径 + Files.write(filePath, bytes.getBytes()); // 写入内容到文件 + } catch (IOException e) { + e.printStackTrace(); + } + } + + //分发到各个业务处理 + private void processSensorData(JSONObject jsonObject, JSONArray jsonArray, String bytes) { + String stationId = jsonObject.get("stationId").toString(); + switch (stationId.charAt(1)) { + case '1'://井盖 + logs(stationId, bytes, "jinggai"); + processManholeCoverData(jsonObject, jsonArray); + break; + case '2'://流量计 + logs(stationId, bytes, "liuliang"); + processFlowMeterData(jsonObject, jsonArray); + break; + case '3'://液位计 + logs(stationId, bytes, "yewei"); + processLevelMeterData(jsonObject, jsonArray); + break; + case '4'://电导率 + logs(stationId, bytes, "diandao"); + processConductivityMeterData(jsonObject, jsonArray); + break; + case '5'://雨量计 + logs(stationId, bytes, "yuliang"); + processRainGaugeData(jsonObject, jsonArray); + break; + case '6'://内涝监测 + logs(stationId, bytes, "neilao"); + processWaterloggingMonitoringData(jsonObject, jsonArray); + break; + default: + System.out.println("未知设备类型"); + } + } + + // 井盖处理逻辑 + private void processManholeCoverData(JSONObject jsonObject, JSONArray jsonArray) { +// System.out.println("开始处理井盖数据=============================================="); + int dataCount = jsonObject.getIntValue("dataCount"); + String startTimeStr = jsonObject.getString("startTime"); + int intervalMinutes = jsonObject.getIntValue("intervalMinutes"); + String stationId = jsonObject.getString("stationId"); + double batteryVoltage = jsonObject.getDouble("batteryVoltage"); // 获取电池电压 + +// System.out.println("数据个数:" + dataCount); +// System.out.println("开始时间:" + startTimeStr); +// System.out.println("间隔分钟:" + intervalMinutes); + + //单独处理电压 + String channelName = stationId + "_V1"; + String mpcode = getMpcodeFromCacheOrDB(stationId, channelName, "V1"); + if (!mpcode.equals("未配置")) { + //推送kafka + mPointService.sendKafka4UDP("",mpcode, batteryVoltage, startTimeStr, 0, 1); + //推送mqtt + JSONArray jsonArray_mqtt = new JSONArray(); + JSONObject jsonObject_mqtt = new JSONObject(); + jsonObject_mqtt.put("mpcode", mpcode); + jsonObject_mqtt.put("value", batteryVoltage); + jsonObject_mqtt.put("time", startTimeStr); + jsonArray_mqtt.add(jsonObject_mqtt); + mqttConfigService.doSendView(jsonArray_mqtt,CommString.Mqtt_Topic_DATA); + } + + // 生成时间点序列 + List timePoints = generateTimePoints(startTimeStr, dataCount, intervalMinutes); + + // 处理模拟量数据 (type=4) +// System.out.println("\n模拟量数据:"); + Map analogMappings = new HashMap<>(); + analogMappings.put(1, "A1"); // 信号强度 + analogMappings.put(2, "A2"); // 基站序号 + analogMappings.put(3, "A3"); // 井盖角度 + analogMappings.put(4, "A4"); // 电阻值1 + analogMappings.put(5, "A5"); // 电阻值2 + processSensorData(stationId, jsonArray, 4, analogMappings, "analogValues", timePoints); + + // 创建新的JSONArray来存储处理后的报警数据 + JSONArray processedAlarmData = new JSONArray(); + + // 处理报警量数据 (type=5) +// System.out.println("\n报警量数据:"); + for (Object obj : jsonArray) { + JSONObject sensorData = (JSONObject) obj; + if (sensorData.getIntValue("type") == 5) { + int qValue = sensorData.getIntValue("qValue"); + + // 提取各报警位状态(0/1) + int voltageAlarm = (qValue & 0x0001) != 0 ? 1 : 0; // Q10 + int waterAlarm = (qValue & 0x0002) != 0 ? 1 : 0; // Q11 + int coverAlarm = (qValue & 0x0004) != 0 ? 1 : 0; // Q12 + + // 为每个报警位创建单独的数据对象 + JSONObject voltageAlarmData = new JSONObject(); + voltageAlarmData.put("type", 5); + voltageAlarmData.put("channel", 0); // Q10对应channel 0 + voltageAlarmData.put("qValues", Collections.nCopies(dataCount, voltageAlarm)); + + JSONObject waterAlarmData = new JSONObject(); + waterAlarmData.put("type", 5); + waterAlarmData.put("channel", 1); // Q11对应channel 1 + waterAlarmData.put("qValues", Collections.nCopies(dataCount, waterAlarm)); + + JSONObject coverAlarmData = new JSONObject(); + coverAlarmData.put("type", 5); + coverAlarmData.put("channel", 2); // Q12对应channel 2 + coverAlarmData.put("qValues", Collections.nCopies(dataCount, coverAlarm)); + + // 添加到处理后的报警数据数组 + processedAlarmData.add(voltageAlarmData); + processedAlarmData.add(waterAlarmData); + processedAlarmData.add(coverAlarmData); + } else { + // 非报警数据直接保留 + processedAlarmData.add(sensorData); + } + } + + // 处理报警数据存储 + Map alarmMappings = new HashMap<>(); + alarmMappings.put(0, "Q10"); // 电压报警 + alarmMappings.put(1, "Q11"); // 水浸报警 + alarmMappings.put(2, "Q12"); // 开盖报警 + processSensorData(stationId, processedAlarmData, 5, alarmMappings, "qValues", timePoints); + } + + // 流量计处理逻辑 + private void processFlowMeterData(JSONObject jsonObject, JSONArray jsonArray) { +// System.out.println("开始处理流量计数据=============================================="); + int dataCount = jsonObject.getIntValue("dataCount"); + String startTimeStr = jsonObject.getString("startTime"); + int intervalMinutes = jsonObject.getIntValue("intervalMinutes"); + String stationId = jsonObject.getString("stationId"); + +// System.out.println("数据个数:" + dataCount); +// System.out.println("开始时间:" + startTimeStr); +// System.out.println("间隔分钟:" + intervalMinutes); + + // 生成时间点序列 + List timePoints = generateTimePoints(startTimeStr, dataCount, intervalMinutes); + + // 处理脉冲量数据 (type=1) +// System.out.println("\n脉冲量数据:"); + Map pulseMappings = new HashMap<>(); + pulseMappings.put(1, "P1"); + pulseMappings.put(2, "P2"); + pulseMappings.put(3, "P3"); + processSensorData(stationId, jsonArray, 1, pulseMappings, "accumulatedFlows", timePoints); + + // 处理模拟量数据 (type=4) +// System.out.println("\n模拟量数据:"); + Map analogMappings = new HashMap<>(); + analogMappings.put(1, "A1"); + analogMappings.put(2, "A2"); + analogMappings.put(4, "A4"); + analogMappings.put(7, "A7"); + analogMappings.put(8, "A8"); + processSensorData(stationId, jsonArray, 4, analogMappings, "analogValues", timePoints); + } + + // 液位计处理逻辑 + private void processLevelMeterData(JSONObject jsonObject, JSONArray jsonArray) { +// System.out.println("开始处理液位计数据=============================================="); + int dataCount = jsonObject.getIntValue("dataCount"); + String startTimeStr = jsonObject.getString("startTime"); + int intervalMinutes = jsonObject.getIntValue("intervalMinutes"); + String stationId = jsonObject.getString("stationId"); + +// System.out.println("数据个数:" + dataCount); +// System.out.println("开始时间:" + startTimeStr); +// System.out.println("间隔分钟:" + intervalMinutes); + + // 生成时间点序列 + List timePoints = generateTimePoints(startTimeStr, dataCount, intervalMinutes); + + // 处理模拟量数据 (type=4) +// System.out.println("\n液位计模拟量数据:"); + Map analogMappings = new HashMap<>(); + analogMappings.put(1, "A1"); // 信号接收功率(dBm) + analogMappings.put(2, "A2"); // 信噪比 + analogMappings.put(3, "A3"); // 小区ID + analogMappings.put(4, "A4"); // 倾斜角度(°) + analogMappings.put(5, "A5"); // 电池电压(V) + analogMappings.put(6, "A6"); // 投入式液位(m) + analogMappings.put(8, "A8"); // 雷达水位(m) + analogMappings.put(10, "A10"); // 综合液位(m) + + processSensorData(stationId, jsonArray, 4, analogMappings, "analogValues", timePoints); + } + + // 电导率仪处理逻辑 + private void processConductivityMeterData(JSONObject jsonObject, JSONArray jsonArray) { +// System.out.println("开始处理电导率仪数据=============================================="); + int dataCount = jsonObject.getIntValue("dataCount"); + String startTimeStr = jsonObject.getString("startTime"); + int intervalMinutes = jsonObject.getIntValue("intervalMinutes"); + String stationId = jsonObject.getString("stationId"); + double batteryVoltage = jsonObject.getDouble("batteryVoltage"); +// System.out.println("数据个数:" + dataCount); +// System.out.println("开始时间:" + startTimeStr); +// System.out.println("间隔分钟:" + intervalMinutes); + + //单独处理电压 + String channelName = stationId + "_V"; + String mpcode = getMpcodeFromCacheOrDB(stationId, channelName, "V"); + if (!mpcode.equals("未配置")) { + mPointService.sendKafka4UDP("",mpcode, batteryVoltage, startTimeStr, 0, 1); + //推送mqtt + JSONArray jsonArray_mqtt = new JSONArray(); + JSONObject jsonObject_mqtt = new JSONObject(); + jsonObject_mqtt.put("mpcode", mpcode); + jsonObject_mqtt.put("value", batteryVoltage); + jsonObject_mqtt.put("time", startTimeStr); + jsonArray_mqtt.add(jsonObject_mqtt); + mqttConfigService.doSendView(jsonArray_mqtt,CommString.Mqtt_Topic_DATA); + } + + // 生成时间点序列 + List timePoints = generateTimePoints(startTimeStr, dataCount, intervalMinutes); + + // 处理模拟量数据 (type=4) +// System.out.println("\n电导率仪数据:"); + Map analogMappings = new HashMap<>(); + analogMappings.put(7, "A7"); // 电导率值 + analogMappings.put(8, "A8"); // 温度值 + processSensorData(stationId, jsonArray, 4, analogMappings, "analogValues", timePoints); + } + + // 雨量计处理逻辑 + private void processRainGaugeData(JSONObject jsonObject, JSONArray jsonArray) { +// System.out.println("开始处理雨量计数据=============================================="); + int dataCount = jsonObject.getIntValue("dataCount"); + String startTimeStr = jsonObject.getString("startTime"); + int intervalMinutes = jsonObject.getIntValue("intervalMinutes"); + String stationId = jsonObject.getString("stationId"); + +// System.out.println("数据个数:" + dataCount); +// System.out.println("开始时间:" + startTimeStr); +// System.out.println("间隔分钟:" + intervalMinutes); + + // 生成时间点序列 + List timePoints = generateTimePoints(startTimeStr, dataCount, intervalMinutes); + + // 处理模拟量数据 (type=4) +// System.out.println("\n雨量计数据:"); + Map analogMappings = new HashMap<>(); + analogMappings.put(1, "A1"); // 雨量值 + processSensorData(stationId, jsonArray, 4, analogMappings, "analogValues", timePoints); + } + + // 内涝监测处理逻辑 + private void processWaterloggingMonitoringData(JSONObject jsonObject, JSONArray jsonArray) { +// System.out.println("开始处理内涝监测数据=============================================="); + int dataCount = jsonObject.getIntValue("dataCount"); + String startTimeStr = jsonObject.getString("startTime"); + int intervalMinutes = jsonObject.getIntValue("intervalMinutes"); + String stationId = jsonObject.getString("stationId"); + +// System.out.println("数据个数:" + dataCount); +// System.out.println("开始时间:" + startTimeStr); +// System.out.println("间隔分钟:" + intervalMinutes); + + // 生成时间点序列 + List timePoints = generateTimePoints(startTimeStr, dataCount, intervalMinutes); + + // 处理模拟量数据 (type=4) +// System.out.println("\n水位数据:"); + Map analogMappings = new HashMap<>(); + analogMappings.put(13, "A13"); // 水位值(0x0D) +// analogMappings.put(14, "A14"); // 状态值(0x0D) + processSensorData(stationId, jsonArray, 4, analogMappings, "analogValues", timePoints); + + // 处理脉冲量数据 (type=1) +// System.out.println("\n状态数据:"); + Map pulseMappings = new HashMap<>(); + pulseMappings.put(14, "P14"); // 状态值(0x0E) + processSensorData(stationId, jsonArray, 1, pulseMappings, "accumulatedFlows", timePoints); + } + + private DeviceData parseDeviceData(ByteBuf buf) { + // 查找起始符位置 + int startIndex = -1; + for (int i = 0; i < buf.readableBytes() - 1; i++) { + if (buf.getByte(i) == (byte) 0xAB && buf.getByte(i + 1) == (byte) 0xCD) { + startIndex = i; + break; + } + } + if (startIndex == -1) { + // 没找到起始符,丢弃所有数据 + buf.skipBytes(buf.readableBytes()); + return null; + } + // 跳过起始符前的所有字节 + buf.skipBytes(startIndex); + // 标记当前位置 + buf.markReaderIndex(); + // 验证起始符 + byte b1 = buf.readByte(); + byte b2 = buf.readByte(); + if (b1 != (byte) 0xAB || b2 != (byte) 0xCD) { + buf.resetReaderIndex(); + buf.skipBytes(1); + return null; + } + // 确保有足够数据读取长度 + if (buf.readableBytes() < 2) { + buf.resetReaderIndex(); + return null; + } + // 读取长度 + int dataLength = buf.readUnsignedShort(); + // 计算完整包长度 + int totalLength = 2 + 2 + dataLength + 2; // AB CD + len + data + 结束符 + // 确保有完整数据包 + if (buf.readableBytes() < dataLength + 2) { + buf.resetReaderIndex(); + return null; + } + // 读取完整数据包 + ByteBuf frame = buf.readRetainedSlice(dataLength + 2); + DeviceData data = new DeviceData(); + // 1. 基础信息解析 + data.setStationId(frame.readUnsignedShort()); + byte[] timeBytes = new byte[5]; + frame.readBytes(timeBytes); + data.setStartTime(parseBcdTime(timeBytes)); + data.setDataCount(frame.readUnsignedByte()); + data.setIntervalMinutes(frame.readUnsignedByte()); + data.setBatteryVoltage(frame.readUnsignedShort() / 100.0f); + data.setUploadCount(frame.readUnsignedShort()); + //设备信息处理 + int infoLength = frame.readUnsignedByte(); + // 读取实际设备信息(固定20字节) + byte[] deviceInfo = new byte[20]; + frame.readBytes(deviceInfo); + data.setDeviceInfo(new String(deviceInfo, StandardCharsets.US_ASCII).trim()); + int bytesToSkip = 8; // 跳过预留的8字节 + frame.skipBytes(bytesToSkip); + //解析传感器数据 + List sensorDataList = new ArrayList<>(); + while (frame.readableBytes() >= 2) { + int type = frame.readUnsignedByte(); + int channel = frame.readUnsignedByte(); +// System.out.printf("Parsing sensor: type=%02X, channel=%02X at pos=%d%n", type, channel, frame.readerIndex() - 2); + SensorData sensor = new SensorData(); + sensor.setType(type); + sensor.setChannel(channel); + try { + switch (type) { + case 0x01: // 脉冲量 + long yesterdayFlow = frame.readUnsignedIntLE(); + sensor.setYesterdayFlow(yesterdayFlow); + List flows = new ArrayList<>(); + for (int j = 0; j < data.getDataCount(); j++) { + if (frame.readableBytes() < 4) { + break; + } + flows.add(frame.readUnsignedIntLE()); + } + sensor.setAccumulatedFlows(flows); + break; + + case 0x02: // 开关量/报警量 + // 每个通道只读取1字节状态值 + if (frame.readableBytes() >= 1) { + int status = frame.readUnsignedByte(); + List statusList = new ArrayList<>(); + statusList.add(status); + sensor.setDescription("开关量状态"); + } + break; + case 0x41: // 不知道啥类型 + // 不知道啥类型 + if (frame.readableBytes() >= 1) { + + } + break; + + case 0x42: // 不知道啥类型 + // 不知道啥类型 + if (frame.readableBytes() >= 1) { + + } + break; + + case 0x43: // 不知道啥类型 + // 不知道啥类型 + if (frame.readableBytes() >= 1) { + + } + break; + + case 0x04: // 模拟量 + List analogs = new ArrayList<>(); + for (int j = 0; j < data.getDataCount(); j++) { + if (frame.readableBytes() < 4) { + break; + } + float value = 0.0f; + try { + // 智能井盖 + if (String.valueOf(data.getStationId()).charAt(1) == '1') { + // 尝试不同的解析方式,根据通道类型选择合适的解析方法 + switch (channel) { + case 1: // A1 信号强度 (dBm) + byte signalByte = frame.readByte(); + frame.skipBytes(3); // 跳过剩余3字节 + value = (float) signalByte; + break; + case 2: // A2 基站序号 + value = (float) frame.readUnsignedIntLE(); + break; + case 3: // A3 井盖角度 + int angleInt = frame.readInt(); // 使用readInt()读取大端序 + value = Float.intBitsToFloat(angleInt); + // 验证是否为合理的角度值 + if (value < 0 || value > 360) { + frame.resetReaderIndex(); + frame.skipBytes(j * 4); + int angleFixed = frame.readUnsignedShort(); + frame.skipBytes(2); + value = (float) angleFixed / 100.0f; + } + break; + case 4: // A4 电阻值1 + case 5: // A5 电阻值2 + case 7: // + case 8: // + int resistanceInt1 = frame.readInt(); // 使用readInt()读取大端序 + value = Float.intBitsToFloat(resistanceInt1); + break; + default: // 其他模拟量,默认使用浮点数解析 + int intValue = frame.readIntLE(); + value = Float.intBitsToFloat(intValue); + break; + } + } + // 流量计 + if (String.valueOf(data.getStationId()).charAt(1) == '2') { + // 统一使用大端序读取IEEE754浮点数 + int intValue = frame.readInt(); // 改为readInt()而不是readIntLE() + value = Float.intBitsToFloat(intValue); + // 保留3位小数 + value = (float) (Math.round(value * 1000) / 1000.0); + // 格式化为3位小数,不足补零 + String formattedValue = String.format("%.3f", value); // 例如 7.4 → "7.400" + value = Float.parseFloat(formattedValue); // 转回float(可选) + } + // 液位计 + if (String.valueOf(data.getStationId()).charAt(1) == '3') { + // 统一使用大端序读取IEEE754浮点数 + int intValue = frame.readInt(); // 改为readInt()而不是readIntLE() + value = Float.intBitsToFloat(intValue); + // 保留3位小数 + value = (float) (Math.round(value * 1000) / 1000.0); + // 格式化为3位小数,不足补零 + String formattedValue = String.format("%.3f", value); // 例如 7.4 → "7.400" + value = Float.parseFloat(formattedValue); // 转回float(可选) + } + // 电导率 + /*if (String.valueOf(data.getStationId()).charAt(1) == '4') { + int intValue = frame.readIntLE(); + value = Float.intBitsToFloat(intValue); + // 保留2位小数 + value = (float) (Math.round(value * 100) / 100.0); + }*/ + // 电导率 + if (String.valueOf(data.getStationId()).charAt(1) == '4') { + // 改为使用大端序读取 + int intValue = frame.readInt(); // 改为readInt()而不是readIntLE() + value = Float.intBitsToFloat(intValue); + // 保留2位小数 + value = (float) (Math.round(value * 100) / 100.0); + } + // 雨量计 + if (String.valueOf(data.getStationId()).charAt(1) == '5') { + // 改为使用大端序读取 + int intValue = frame.readInt(); // 改为readInt()而不是readIntLE() + value = Float.intBitsToFloat(intValue); + // 保留2位小数 + value = (float) (Math.round(value * 100) / 100.0); + } + // 内涝监测设备 + if (String.valueOf(data.getStationId()).charAt(1) == '6') { + // 改为使用大端序读取 + int intValue = frame.readInt(); // 改为readInt()而不是readIntLE() + value = Float.intBitsToFloat(intValue); + // 保留2位小数 + value = (float) (Math.round(value * 100) / 100.0); + } + // 过滤异常值 + if (Float.isNaN(value) || Float.isInfinite(value) || value < -1000000.0f || value > 1000000.0f) { + value = 0.0f; + } + } catch (Exception e) { + frame.skipBytes(4); + value = 0.0f; + } + analogs.add(value); + } + sensor.setAnalogValues(analogs); + // 智能井盖特定通道处理 + if (String.valueOf(data.getStationId()).charAt(1) == '1') { + switch (channel) { + case 1: // A1信号强度 + sensor.setDescription("A1信号强度"); + break; + case 2: // A2基站序号 + sensor.setDescription("A2基站序号"); + break; + case 3: // A3井盖角度 + sensor.setDescription("A3井盖角度"); + break; + case 4: // A4电阻值1 + sensor.setDescription("A4电阻值1"); + break; + case 5: // A5电阻值2 + sensor.setDescription("A5电阻值2"); + break; + } + } + break; + case 0x05: // Q通道数据(数字量输出) + int qValue = frame.readUnsignedShort(); + // 校验 qValue 范围(0x0000 ~ 0xFFFF) + if (qValue < 0 || qValue > 0xFFFF) { + throw new IllegalArgumentException("Invalid Q channel value: " + qValue); + } + + // 解析各报警位状态 + Map alarmStatus = new EnumMap<>(AlarmType.class); + for (AlarmType alarm : AlarmType.values()) { + alarmStatus.put(alarm, alarm.isTriggered(qValue)); + } + + // 构建报警描述 + StringBuilder alarmDesc = new StringBuilder("Q通道状态: "); + for (AlarmType alarm : AlarmType.values()) { + alarmDesc.append(alarm.getDescription()) + .append(alarmStatus.get(alarm) ? "触发" : "正常") + .append(", "); + } + sensor.setDescription(alarmDesc.toString().replaceAll(", $", "")); + + // 存储原始报警值(可选) + sensor.setqValue(qValue); + sensor.setAlarmStatus(alarmStatus); + + // 记录报警日志 + if (alarmStatus.get(AlarmType.COVER_ALARM)) { + LoggerFactory.getLogger(UDPServer.class) + .warn("井盖开盖报警触发!站号: {}, Q值: {}", data.getStationId(), qValue); + } + break; + default: + int bytesToSkip2 = data.getDataCount() * 4; + if (frame.readableBytes() >= bytesToSkip2) { + frame.skipBytes(bytesToSkip2); + } else { +// System.err.printf("Not enough readable bytes to skip %d bytes. Current readable bytes: %d%n", +// bytesToSkip2, frame.readableBytes()); + // 可选择抛出异常、记录日志或者做其他处理 + } + continue; + } + sensorDataList.add(sensor); + } catch (Exception e) { + System.err.println("Error parsing sensor"); + e.printStackTrace(); + break; + } + // 检查是否到达结束符 + if (frame.readableBytes() >= 2 && frame.getByte(frame.readerIndex()) == 0x0D && frame.getByte(frame.readerIndex() + 1) == 0x0A) { + // 跳过结束符 + frame.skipBytes(2); + break; + } + } + data.setSensorDataList(sensorDataList); + return data; + } + + private String parseBcdTime(byte[] bytes) { + // bytes: 19 05 29 10 47 + int year = 2000 + ((bytes[0] >> 4) & 0xF) * 10 + (bytes[0] & 0xF); + int month = ((bytes[1] >> 4) & 0xF) * 10 + (bytes[1] & 0xF); + int day = ((bytes[2] >> 4) & 0xF) * 10 + (bytes[2] & 0xF); + int hour = ((bytes[3] >> 4) & 0xF) * 10 + (bytes[3] & 0xF); + int minute = ((bytes[4] >> 4) & 0xF) * 10 + (bytes[4] & 0xF); + + return String.format("%04d-%02d-%02d %02d:%02d", year, month, day, hour, minute); + } + + private static String bytesToHex(byte[] bytes) { + StringBuilder sb = new StringBuilder(); + for (byte b : bytes) { + sb.append(String.format("%02X ", b)); + } + return sb.toString(); + } + + + /** + * 通用传感器数据处理方法 + * + * @param stationId 站点id 用于redis组合key + * @param jsonArray 传感器数据数组 + * @param type 要处理的数据类型 + * @param channelMappings 通道映射 + * @param valueFieldName 值字段名 + * @param timePoints 时间点列表 + */ + private void processSensorData(String stationId, JSONArray jsonArray, int type, + Map channelMappings, + String valueFieldName, + List timePoints) { + try { + for (Object obj : jsonArray) { + JSONObject sensorData = (JSONObject) obj; + if (sensorData.getIntValue("type") == type) { + int channel = sensorData.getIntValue("channel"); + if (channelMappings.containsKey(channel)) { + String channelName = stationId + "_" + channelMappings.get(channel); + JSONArray values = sensorData.getJSONArray(valueFieldName); + + if (values != null && !values.isEmpty()) { + //获取mpcode (优先从缓存拿) + String mpcode = getMpcodeFromCacheOrDB(stationId, channelName, channelMappings.get(channel)); + if (!mpcode.equals("未配置")) { + JSONObject dataCache = new JSONObject(); + + JSONArray jsonArray_mqtt = new JSONArray(); + for (int i = 0; i < values.size(); i++) { + String timePoint = timePoints.get(i); + timePoint = timePoint.length() == 16 ? timePoint + ":00" : timePoint; + Object value = values.get(i); + dataCache.put(timePoint, value); + //推送至kafka + mPointService.sendKafka4UDP("",mpcode, value, timePoint, i, values.size()); + + //添加到mqtt数组 + JSONObject jsonObject_mqtt = new JSONObject(); + jsonObject_mqtt.put("mpcode", mpcode); + jsonObject_mqtt.put("value", value); + jsonObject_mqtt.put("time", timePoint); + jsonArray_mqtt.add(jsonObject_mqtt); + } + + //批量推送mqtt + mqttConfigService.doSendView(jsonArray_mqtt, CommString.Mqtt_Topic_DATA); + } else { + System.out.println("站点:" + stationId + " 标识:" + channelMappings.get(channel) + " 未配置"); + } + } + } + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + + // 从缓存或数据库获取mpcode + private String getMpcodeFromCacheOrDB(String stationId, String channelName, String tag) { + // 先查缓存 + String mpcode = dataCache.get(channelName); + if (mpcode != null) { + return mpcode; + } + + // 缓存没有则查询数据库 + List equipmentList = pipelineEquipmentService.selectListByWhere( + "where station_code = '" + stationId + "'"); + if (equipmentList != null && !equipmentList.isEmpty()) { + List mpointList = pipelineEquipmentMpointService.selectListByWhere( + "where pid = '" + equipmentList.get(0).getId() + "' and tag = '" + tag + "'"); + if (mpointList != null && !mpointList.isEmpty()) { + mpcode = mpointList.get(0).getMpcode(); + // 存入缓存 + dataCache.put(channelName, mpcode); + return mpcode; + } + } + return "未配置"; // 或根据业务需求返回默认值 + } + + //时间生成方法 + private List generateTimePoints(String startTimeStr, int count, int intervalMinutes) { + List timePoints = new ArrayList<>(); + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + Date date = sdf.parse(startTimeStr); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + for (int i = 0; i < count; i++) { + timePoints.add(sdf.format(calendar.getTime())); + calendar.add(Calendar.MINUTE, intervalMinutes); + } + } catch (ParseException e) { + e.printStackTrace(); + // 如果解析失败,使用简单的时间格式 + for (int i = 0; i < count; i++) { + timePoints.add(startTimeStr + " +" + (i * intervalMinutes) + "分钟"); + } + } + return timePoints; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/controller/check/CheckServerController.java b/src/main/java/com/sipai/controller/check/CheckServerController.java new file mode 100644 index 0000000..7fedd69 --- /dev/null +++ b/src/main/java/com/sipai/controller/check/CheckServerController.java @@ -0,0 +1,75 @@ +package com.sipai.controller.check; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; + +/** + * 普罗米修斯 监听接口 + */ +@RestController +@RequestMapping("/check") +public class CheckServerController { + + @RequestMapping("/server.do") + public String server() { + return "suc"; + } + + @RequestMapping("/testSendUdp.do") + public String testSendUdp() { + //修改成服务端的IP +// String serverHost = "132.120.132.77"; +// String serverHost = "116.236.176.248"; + String serverHost = "192.168.10.18"; + int serverPort = 5006; + + //智能井盖 +// String hexString = "ABCD004D00002505121109013C016800001F484B33352D49493B56312E313B56312E302E303600000000000000000401C25000000402000000000403429E293C040447C35000040547C3500005010004A70D0A"; + //流量仪 + String hexString = "AB CD 01 C7 00 7B 25 05 19 16 18 0A 01 02 E2 00 00 00 48 38 36 45 3B 31 2E 33 3B 31 2E 30 2E 33 35 20 20 20 20 20 00 00 00 00 00 00 00 00 01 01 00 00 00 00 00 00 00 00 01 00 00 00 03 00 00 00 05 00 00 00 07 00 00 00 09 00 00 00 0B 00 00 00 0D 00 00 00 0E 00 00 00 10 00 00 00 01 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 03 00 00 00 00 00 00 00 00 01 00 00 00 03 00 00 00 05 00 00 00 07 00 00 00 09 00 00 00 0B 00 00 00 0D 00 00 00 0E 00 00 00 10 00 00 00 04 01 40 EC 62 C6 40 EC 62 C6 40 EC 62 C6 40 EC 62 C6 40 EC 62 C6 40 EC D0 CD 40 48 F5 C3 40 48 F5 C3 40 48 F5 C3 40 48 F5 C3 04 02 40 EB 86 B8 40 EB 86 B8 40 EB 86 B8 40 EB 86 B8 40 EB 86 B8 40 EB F4 BF 3D FB E7 6D 3D FB E7 6D 3D FB E7 6D 3D FB E7 6D 04 03 41 F0 00 00 41 B0 00 00 41 F8 00 00 41 B8 00 00 41 B8 00 00 41 F8 00 00 41 F8 00 00 41 F8 00 00 41 F8 00 00 41 F8 00 00 04 04 41 BB 99 9A 41 BB 99 9A 41 BB 99 9A 41 BB 99 9A 41 BB 99 9A 41 BB 99 9A 41 BB 99 9A 41 BB 99 9A 41 BB 99 9A 41 BB 99 9A 04 07 42 ED 99 9A 42 ED 99 9A 42 ED 99 9A 42 ED 99 9A 42 ED 99 9A 42 ED 99 9A 42 B4 00 00 42 B4 00 00 42 B4 00 00 42 B4 00 00 04 08 3E 40 83 12 3E 40 83 12 3E 40 83 12 3E 40 83 12 3E 40 83 12 3E 40 83 12 3E 40 83 12 3E 40 83 12 3E 40 83 12 3E 40 83 12 05 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 6B 0D 0A"; + //厂家传的异常数据 +// String hexString = "AA AA B7 56 0E 25 06 03 10 15 08 31 02 E1 30 11 00 00 0B 47 00 00 0F 50 00 03 00 03 00 04 00 04 00 03 00 04 00 03 12 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 00 13 00 00 0B 47 00 00 0F 4C 00 03 00 03 00 04 00 04 00 03 00 04 00 03 31 00 02 00 02 00 02 00 02 00 02 00 02 00 02 00 02 32 00 08 00 08 00 08 00 08 00 08 00 08 00 08 00 08 33 04 B0 04 B0 04 B0 04 B0 04 B0 04 B0 04 B0 04 B0 34 07 9E 07 9E 07 9C 07 9D 07 99 07 99 07 9A 07 98 37 00 12 00 0A 00 0E 00 0E 00 0E 00 0E 00 0E 00 0E 38 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0D 0A"; + + hexString = hexString.replaceAll("\\s+", ""); // Remove all whitespace + byte[] data = hexStringToByteArray(hexString); + + try (DatagramSocket socket = new DatagramSocket()) { + InetAddress serverAddress = InetAddress.getByName(serverHost); + + // 发送数据包 + DatagramPacket packet = new DatagramPacket( + data, data.length, serverAddress, serverPort); + socket.send(packet); + System.out.println("已发送数据包到服务器"); + + // 接收响应 + byte[] buffer = new byte[1024]; + DatagramPacket response = new DatagramPacket(buffer, buffer.length); + socket.receive(response); + + String responseStr = new String( + response.getData(), 0, response.getLength()); + System.out.println("服务器响应: " + responseStr); + + } catch (IOException e) { + e.printStackTrace(); + } + return "suc"; + } + + // 十六进制字符串转字节数组的方法 + private static byte[] hexStringToByteArray(String s) { + int len = s.length(); + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + + Character.digit(s.charAt(i + 1), 16)); + } + return data; + } +} diff --git a/src/main/java/com/sipai/controller/data/PipeTopicMPointController.java b/src/main/java/com/sipai/controller/data/PipeTopicMPointController.java new file mode 100644 index 0000000..c22090b --- /dev/null +++ b/src/main/java/com/sipai/controller/data/PipeTopicMPointController.java @@ -0,0 +1,170 @@ +package com.sipai.controller.data; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.sipai.entity.base.Result; +import com.sipai.entity.common.PageData; +import com.sipai.entity.data.PipeTopicMpoint; +import com.sipai.entity.data.PipelineEquipmentMpoint; +import com.sipai.entity.scada.MPoint; +import com.sipai.service.data.PipeTopicMpointService; +import com.sipai.service.scada.MPointService; +import com.sipai.tools.CommUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 管网专题页点位控制器 + */ +@RestController +@RequestMapping("/pipeTopicMPoint") +public class PipeTopicMPointController { + + @Autowired + private PipeTopicMpointService pipeTopicMpointService; + @Autowired + private MPointService mPointService; + + /** + * 根据主键查询点位信息 + */ + @GetMapping("/selectById.do") + public Result selectByPrimaryKey(@RequestParam Integer id) { + PipeTopicMpoint mpoint = pipeTopicMpointService.selectByPrimaryKey(id); + if (mpoint != null) { + return Result.success(mpoint); + } else { + return Result.failed("点位不存在"); + } + } + + /** + * 新增点位信息 + */ + @PostMapping("/save.do") + public String save(@ModelAttribute PipeTopicMpoint mpoint) { + int res = pipeTopicMpointService.insert(mpoint); + if (res > 0) { + return CommUtil.toJson(Result.success(mpoint.getId())); + } else { + return CommUtil.toJson(Result.failed("新增失败")); + } + } + + /** + * 更新点位信息 + */ + @PostMapping("/update.do") + public String update(@ModelAttribute PipeTopicMpoint mpoint) { + boolean res = pipeTopicMpointService.update(mpoint); + return CommUtil.toJson(res ? Result.success(1) : Result.failed("更新失败")); + } + + /** + * 根据主键删除点位 + */ + @PostMapping("/deleteById.do") + public String deleteById(@RequestParam Integer id) { + boolean res = pipeTopicMpointService.delete(id); + return CommUtil.toJson(res ? Result.success(1) : Result.failed("删除失败")); + } + + /** + * 批量删除点位 + */ + @PostMapping("/deleteBatch.do") + public String deleteBatch(@RequestBody List idList) { + boolean res = pipeTopicMpointService.deleteBatch(idList); + return CommUtil.toJson(res ? Result.success(1) : Result.failed("批量删除失败")); + } + + /** + * 分页查询点位列表 + */ + @GetMapping("/list.do") + public PageData selectList( + @RequestParam(defaultValue = "1") Integer pageNum, + @RequestParam(defaultValue = "10") Integer pageSize, + @RequestParam(required = false) String type) { + + PageHelper.startPage(pageNum, pageSize); + String where = "where 1=1"; + if (type != null && !type.isEmpty()) { + where += " AND type = '" + type + "'"; + } + + List list = pipeTopicMpointService.selectListByWhere(where); + PageInfo pageInfo = new PageInfo<>(list); + return new PageData<>(pageInfo); + } + + /** + * 获取 “管网专题页” 数据 + * + * @param type + * @return + */ + @GetMapping("/getData.do") + public Result getData(@RequestParam(required = false) String type) { + String where = "where 1=1"; + if (type != null && !type.isEmpty()) { + where += " AND type = '" + type + "'"; + } + + // 定义 type 含义的映射关系 + Map typeMap = new HashMap<>(); + typeMap.put("0", "污水厂"); + typeMap.put("1", "新城南大道污水泵站"); + typeMap.put("2", "神农西大道雨水泵站"); + typeMap.put("3", "新祺周大道雨水泵站"); + + JSONArray jsonArray = new JSONArray(); + try { + List list = pipeTopicMpointService.selectListByWhere(where); + if (list != null && list.size() > 0) { + for (int i = 0; i < list.size(); i++) { + PipeTopicMpoint item = list.get(i); + JSONObject jsonObject = new JSONObject(); + + // 添加 type 信息(如果 type 存在) + if (type != null && !type.isEmpty()) { + jsonObject.put("type", type); + jsonObject.put("typeName", typeMap.getOrDefault(type, "未知类型")); + } + + if (item.getIsConstant() == 1) { // 常量 + if (item.getPointName().equals("调度模式")) { + jsonObject.put("parmvalue", "输送模式-常规输送"); + } else { + jsonObject.put("parmvalue", item.getConstantValue()); + } + jsonObject.put("mpcode", item.getPointCode()); + jsonObject.put("mpname", item.getPointName()); + jsonObject.put("measuredt", CommUtil.nowDate()); + jsonObject.put("unit", ""); + } else { // 读点位 + MPoint mPoint = mPointService.selectById("",item.getPointCode()); + if (mPoint != null) { + jsonObject.put("mpcode", mPoint.getMpointcode()); + jsonObject.put("mpname", mPoint.getParmname()); + jsonObject.put("parmvalue", mPoint.getParmvalue() != null ? mPoint.getParmvalue() : 0); + jsonObject.put("measuredt", mPoint.getMeasuredt()); + jsonObject.put("unit", mPoint.getUnit() != null ? mPoint.getUnit() : ""); + } + } + jsonArray.add(jsonObject); + } + } + return Result.success(jsonArray); + } catch (Exception e) { + return Result.failed("无数据"); + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/controller/data/PipelineEquipmentController.java b/src/main/java/com/sipai/controller/data/PipelineEquipmentController.java new file mode 100644 index 0000000..2f058c8 --- /dev/null +++ b/src/main/java/com/sipai/controller/data/PipelineEquipmentController.java @@ -0,0 +1,271 @@ +package com.sipai.controller.data; + +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.sipai.entity.base.Result; +import com.sipai.entity.common.PageData; +import com.sipai.entity.data.PipelineEquipment; +import com.sipai.entity.data.PipelineEquipmentMpoint; +import com.sipai.entity.enums.DeviceTypeEnum; +import com.sipai.service.data.PipelineEquipmentMpointService; +import com.sipai.service.data.PipelineEquipmentService; +import com.sipai.tools.CommUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 管网设备列表 + */ +@RestController +@RequestMapping("/pipeline-equipment") +public class PipelineEquipmentController { + + @Autowired + private PipelineEquipmentService pipelineEquipmentService; + @Autowired + private PipelineEquipmentMpointService pipelineEquipmentMpointService; + + // 根据主键查询管道设备信息 + @GetMapping("/selectById.do") + public Result selectByPrimaryKey(@RequestParam(value = "id") Integer id) { + PipelineEquipment pipelineEquipment = pipelineEquipmentService.selectByPrimaryKey(id); + if(pipelineEquipment!=null){ + return Result.success(pipelineEquipment); + }else{ + return Result.failed("设备不存在"); + } + } + + // 删除指定主键的管道设备信息 + @PostMapping("/deleteById.do") + public String deleteByPrimaryKey(@RequestParam(value = "id") Integer id) { + boolean res = pipelineEquipmentService.delete(id); + if(res){ + Result result = Result.success(1); + return CommUtil.toJson(result); + }else{ + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + // 删除指定主键的管道设备信息 + @PostMapping("/deleteByIds.do") + public String deleteByIds(@RequestParam(value = "id") Integer id) { + boolean res = pipelineEquipmentService.delete(id); + if(res){ + Result result = Result.success(1); + return CommUtil.toJson(result); + }else{ + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + //新增 + @PostMapping("/save.do") + public String save(@ModelAttribute PipelineEquipment pipelineEquipment) { + int res = pipelineEquipmentService.insert(pipelineEquipment); + if (res > 0) { + int generatedId = pipelineEquipment.getId(); + Result result = Result.success(generatedId); + return CommUtil.toJson(result); + }else{ + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + //修改 + @PostMapping("/update.do") + public String update(@ModelAttribute PipelineEquipment pipelineEquipment) { + boolean res = pipelineEquipmentService.update(pipelineEquipment); + if(res){ + Result result = Result.success(1); + return CommUtil.toJson(result); + }else{ + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + /** + * 分页查询管道设备列表 + * @param pageNum + * @param pageSize + * @param equipmentTypeId 类型id + * @param stationCode 站号 + * @param status 1在线 0离线 null为未检测 + * @return + */ + @GetMapping("/list.do") + public PageData selectListByWhere( + @RequestParam(defaultValue = "1") Integer pageNum, + @RequestParam(defaultValue = "10") Integer pageSize, + @RequestParam(required = false) String equipmentTypeId, + @RequestParam(required = false) String stationCode, + @RequestParam(required = false) String status) { + + // 设置分页参数 + PageHelper.startPage(pageNum, pageSize); + + // 构建查询条件 + String where = "where 1=1"; + //类型筛选 + if (equipmentTypeId != null && !equipmentTypeId.isEmpty()) { + where += " AND equipment_type = '" + equipmentTypeId + "'"; + } + //站号筛选 + if (stationCode != null && !stationCode.isEmpty()) { + where += " AND station_code = '" + stationCode + "'"; + } + //状态筛选 + if (status != null && !status.isEmpty()) { + where += " AND status = '" + status + "'"; + } + + // 执行查询 + List list = pipelineEquipmentService.selectListByWhere(where); + + // 封装分页信息 + PageInfo pageInfo = new PageInfo<>(list); + + // 返回分页数据 + return new PageData<>(pageInfo); + } + + /** + * 获取管网设备类型 + * @return + */ + @GetMapping("/device-types") + public List> getDeviceTypes() { + List> deviceTypes = new ArrayList<>(); + for (DeviceTypeEnum deviceType : DeviceTypeEnum.values()) { + Map deviceTypeMap = new HashMap<>(); + deviceTypeMap.put("typeName", deviceType.getTypeName()); + deviceTypeMap.put("typeCode", deviceType.getTypeCode()); + deviceTypes.add(deviceTypeMap); + } + return deviceTypes; + } + + /** + * 手动初始化关联 设备-点位 关系 + * + * @return + */ + @GetMapping("/hand-save.do") + public String handSave() { + + //井盖 + List list = pipelineEquipmentService.selectListByWhere("where equipment_type = '1'"); + for (int i = 0; i < list.size(); i++) { + //格式:KCGW_21001_A1 + String[] codes = new String[]{"A1", "A2", "A3", "A4", "A5", "Q10", "Q11", "Q12", "V1"}; + String[] names = new String[]{"信号强度", "基站序号", "井盖角度", "电阻值1", "电阻值2", "电压报警", "水浸报警", "开盖报警", "电池电压"}; + for (int j = 0; j < codes.length; j++) { + String mpcode = "KCGW_" + list.get(i).getStationCode() + "_" + codes[j]; + PipelineEquipmentMpoint pipelineEquipmentMpoint = new PipelineEquipmentMpoint(); + pipelineEquipmentMpoint.setPid(list.get(i).getId()); + pipelineEquipmentMpoint.setMpcode(mpcode); + pipelineEquipmentMpoint.setMpname(names[j]); + pipelineEquipmentMpoint.setTag(codes[j]); + pipelineEquipmentMpointService.insert(pipelineEquipmentMpoint); + } + } + + //流量计 + List list2 = pipelineEquipmentService.selectListByWhere("where equipment_type = '2'"); + for (int i = 0; i < list2.size(); i++) { + //格式:KCGW_21001_A1 + String[] codes = new String[]{"A1", "A2", "A4", "A7", "A8", "P1", "P2", "P3"}; + String[] names = new String[]{"过水面积","液位","温度","瞬时流量","流速","正向累计","反向累计","实际累计"}; + for (int j = 0; j < codes.length; j++) { + String mpcode = "KCGW_" + list2.get(i).getStationCode() + "_" + codes[j]; + PipelineEquipmentMpoint pipelineEquipmentMpoint = new PipelineEquipmentMpoint(); + pipelineEquipmentMpoint.setPid(list2.get(i).getId()); + pipelineEquipmentMpoint.setMpcode(mpcode); + pipelineEquipmentMpoint.setMpname(names[j]); + pipelineEquipmentMpoint.setTag(codes[j]); + pipelineEquipmentMpointService.insert(pipelineEquipmentMpoint); + } + } + + //液位计 + List list3 = pipelineEquipmentService.selectListByWhere("where equipment_type = '3'"); + for (int i = 0; i < list3.size(); i++) { + //格式:KCGW_21001_A1 + String[] codes = new String[]{"A1", "A2", "A3", "A4", "A5", "A6", "A8", "A10"}; + String[] names = new String[]{"信号接收功率","信噪比","小区ID","倾斜角度","电池电压","投入式液位","雷达水位","综合液位"}; + for (int j = 0; j < codes.length; j++) { + String mpcode = "KCGW_" + list3.get(i).getStationCode() + "_" + codes[j]; + PipelineEquipmentMpoint pipelineEquipmentMpoint = new PipelineEquipmentMpoint(); + pipelineEquipmentMpoint.setPid(list3.get(i).getId()); + pipelineEquipmentMpoint.setMpcode(mpcode); + pipelineEquipmentMpoint.setMpname(names[j]); + pipelineEquipmentMpoint.setTag(codes[j]); + pipelineEquipmentMpointService.insert(pipelineEquipmentMpoint); + } + } + + //电导率 + List list4 = pipelineEquipmentService.selectListByWhere("where equipment_type = '4'"); + for (int i = 0; i < list4.size(); i++) { + //格式:KCGW_21001_A1 + String[] codes = new String[]{"A7", "A8", "V"}; + String[] names = new String[]{"电导率","温度","电池电压"}; + for (int j = 0; j < codes.length; j++) { + String mpcode = "KCGW_" + list4.get(i).getStationCode() + "_" + codes[j]; + PipelineEquipmentMpoint pipelineEquipmentMpoint = new PipelineEquipmentMpoint(); + pipelineEquipmentMpoint.setPid(list4.get(i).getId()); + pipelineEquipmentMpoint.setMpcode(mpcode); + pipelineEquipmentMpoint.setMpname(names[j]); + pipelineEquipmentMpoint.setTag(codes[j]); + pipelineEquipmentMpointService.insert(pipelineEquipmentMpoint); + } + } + + //雨量计 + List list5 = pipelineEquipmentService.selectListByWhere("where equipment_type = '5'"); + for (int i = 0; i < list5.size(); i++) { + //格式:KCGW_21001_A1 + String[] codes = new String[]{"A1"}; + String[] names = new String[]{"雨量值"}; + for (int j = 0; j < codes.length; j++) { + String mpcode = "KCGW_" + list5.get(i).getStationCode() + "_" + codes[j]; + PipelineEquipmentMpoint pipelineEquipmentMpoint = new PipelineEquipmentMpoint(); + pipelineEquipmentMpoint.setPid(list5.get(i).getId()); + pipelineEquipmentMpoint.setMpcode(mpcode); + pipelineEquipmentMpoint.setMpname(names[j]); + pipelineEquipmentMpoint.setTag(codes[j]); + pipelineEquipmentMpointService.insert(pipelineEquipmentMpoint); + } + } + + //内涝监测 + List list6 = pipelineEquipmentService.selectListByWhere("where equipment_type = '6'"); + for (int i = 0; i < list6.size(); i++) { + //格式:KCGW_21001_A1 + String[] codes = new String[]{"A13", "P14"}; + String[] names = new String[]{"水位", "状态(有水/无水)"}; + for (int j = 0; j < codes.length; j++) { + String mpcode = "KCGW_" + list6.get(i).getStationCode() + "_" + codes[j]; + PipelineEquipmentMpoint pipelineEquipmentMpoint = new PipelineEquipmentMpoint(); + pipelineEquipmentMpoint.setPid(list6.get(i).getId()); + pipelineEquipmentMpoint.setMpcode(mpcode); + pipelineEquipmentMpoint.setMpname(names[j]); + pipelineEquipmentMpoint.setTag(codes[j]); + pipelineEquipmentMpointService.insert(pipelineEquipmentMpoint); + } + } + + return "suc"; + } + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/controller/data/PipelineEquipmentMpointController.java b/src/main/java/com/sipai/controller/data/PipelineEquipmentMpointController.java new file mode 100644 index 0000000..7cf0fb9 --- /dev/null +++ b/src/main/java/com/sipai/controller/data/PipelineEquipmentMpointController.java @@ -0,0 +1,136 @@ +package com.sipai.controller.data; + +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.sipai.entity.base.Result; +import com.sipai.entity.common.PageData; +import com.sipai.entity.data.PipelineEquipmentMpoint; +import com.sipai.entity.data.PipelineMpointLibrary; +import com.sipai.service.data.PipelineEquipmentMpointService; +import com.sipai.service.data.PipelineMpointLibraryService; +import com.sipai.tools.CommUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 管网设备附属点位列表 + */ +@RestController +@RequestMapping("/pipeline-equipment-mpoint") +public class PipelineEquipmentMpointController { + + @Autowired + private PipelineEquipmentMpointService pipelineEquipmentMpointService; + @Autowired + private PipelineMpointLibraryService pipelineMpointLibraryService; + + // 根据主键查询管道设备与测点关联信息 + @GetMapping("/selectById.do") + public Result selectByPrimaryKey(@RequestParam(value = "id") Integer id) { + PipelineEquipmentMpoint mpoint = pipelineEquipmentMpointService.selectByPrimaryKey(id); + if (mpoint != null) { + return Result.success(mpoint); + } else { + return Result.failed("关联信息不存在"); + } + } + + // 删除指定主键的管道设备与测点关联信息 + @PostMapping("/deleteById.do") + public String deleteByPrimaryKey(@RequestParam(value = "id") Integer id) { + boolean res = pipelineEquipmentMpointService.delete(id); + if (res) { + Result result = Result.success(1); + return CommUtil.toJson(result); + } else { + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + // 新增管道设备与测点关联信息 + @PostMapping("/save.do") + public String save(@ModelAttribute PipelineEquipmentMpoint mpoint) { + boolean res = pipelineEquipmentMpointService.insert(mpoint); + if (res) { + Result result = Result.success(1); + return CommUtil.toJson(result); + } else { + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + // 修改管道设备与测点关联信息 + @PostMapping("/update.do") + public String update(@ModelAttribute PipelineEquipmentMpoint mpoint) { + boolean res = pipelineEquipmentMpointService.update(mpoint); + if (res) { + Result result = Result.success(1); + return CommUtil.toJson(result); + } else { + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + // 分页查询管道设备与测点关联信息列表 + @GetMapping("/list.do") + public PageData selectListByWhere( + @RequestParam(defaultValue = "1") Integer pageNum, + @RequestParam(defaultValue = "10") Integer pageSize, + @RequestParam(required = false) String pid) { + + // 设置分页参数 + PageHelper.startPage(pageNum, pageSize); + + // 构建查询条件 + String where = "where 1=1"; + if (pid != null && !pid.isEmpty()) { + where += " AND pid = '" + pid + "'"; + } + + // 执行查询 + List list = pipelineEquipmentMpointService.selectListByWhere(where); + + // 封装分页信息 + PageInfo pageInfo = new PageInfo<>(list); + + // 返回分页数据 + return new PageData<>(pageInfo); + } + + /** + * 根据类型一键导入 + * + * @param equipmentTypeId + * @return + */ + @PostMapping("/import4Type.do") + public String import4Type(@RequestParam(required = true) Integer pid, + @RequestParam(required = true) String equipmentTypeId) { + try{ + // 构建查询条件 + String where = "where 1=1 AND equipment_type = '" + equipmentTypeId + "'"; + // 执行查询 + List list = pipelineMpointLibraryService.selectListByWhere(where); + if (list != null && list.size() > 0) { + for (int i = 0; i < list.size(); i++) { + PipelineEquipmentMpoint pipelineEquipmentMpoint = new PipelineEquipmentMpoint(); + pipelineEquipmentMpoint.setPid(pid); + pipelineEquipmentMpoint.setTag(list.get(i).getCode()); + pipelineEquipmentMpoint.setMpname(list.get(i).getName()); + pipelineEquipmentMpointService.insert(pipelineEquipmentMpoint); + } + } + Result result = Result.success(1); + return CommUtil.toJson(result); + }catch (Exception e){ + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/controller/data/PipelineMpointLibraryController.java b/src/main/java/com/sipai/controller/data/PipelineMpointLibraryController.java new file mode 100644 index 0000000..e81b060 --- /dev/null +++ b/src/main/java/com/sipai/controller/data/PipelineMpointLibraryController.java @@ -0,0 +1,106 @@ +package com.sipai.controller.data; + +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.sipai.entity.base.Result; +import com.sipai.entity.common.PageData; +import com.sipai.entity.data.PipelineMpointLibrary; +import com.sipai.service.data.PipelineMpointLibraryService; +import com.sipai.tools.CommUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/pipeline-mpoint-library") +public class PipelineMpointLibraryController { + + @Autowired + private PipelineMpointLibraryService pipelineMpointLibraryService; + + // 根据主键查询记录 + @GetMapping("/selectById.do") + public PipelineMpointLibrary selectByPrimaryKey(@RequestParam(value = "id") String id) { + return pipelineMpointLibraryService.selectByPrimaryKey(id); + } + + // 删除指定主键的记录 + @PostMapping("/deleteById.do") + public String deleteByPrimaryKey(@RequestParam(value = "id") String id) { + boolean res = pipelineMpointLibraryService.delete(id); + if (res) { + Result result = Result.success(1); + return CommUtil.toJson(result); + } else { + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + // 多删指定主键的记录 + @PostMapping("/deleteByIds.do") + public String deleteByIds(@RequestParam(value = "ids") List idList) { + int count = pipelineMpointLibraryService.deleteBatch(idList); + if (count > 0) { + Result result = Result.success(count); + return CommUtil.toJson(result); + } else { + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + // 插入记录 + @PostMapping("/save.do") + public String save(@ModelAttribute PipelineMpointLibrary pipelineMpointLibrary) { + pipelineMpointLibrary.setId(CommUtil.getUUID()); + boolean res = pipelineMpointLibraryService.insert(pipelineMpointLibrary); + if (res) { + Result result = Result.success(1); + return CommUtil.toJson(result); + } else { + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + // 根据主键选择性更新记录 + @PostMapping("/update.do") + public String update(@ModelAttribute PipelineMpointLibrary pipelineMpointLibrary) { + boolean res = pipelineMpointLibraryService.update(pipelineMpointLibrary); + if (res) { + Result result = Result.success(1); + return CommUtil.toJson(result); + } else { + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + // 分页查询列表 + @GetMapping("/list.do") + public PageData selectListByWhere( + @RequestParam(defaultValue = "1") Integer pageNum, + @RequestParam(defaultValue = "10") Integer pageSize, + @RequestParam(required = false) String equipmentTypeId) { + + // 设置分页参数 + PageHelper.startPage(pageNum, pageSize); + + // 构建查询条件 + String where = "where 1=1"; + if (equipmentTypeId != null && !equipmentTypeId.isEmpty()) { + where += " AND equipment_type = '" + equipmentTypeId + "'"; + } + + // 执行查询 + List list = pipelineMpointLibraryService.selectListByWhere(where); + + // 封装分页信息 + PageInfo pageInfo = new PageInfo<>(list); + + // 返回分页数据 + return new PageData<>(pageInfo); + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/controller/kafka/KafkaController.java b/src/main/java/com/sipai/controller/kafka/KafkaController.java new file mode 100644 index 0000000..ecc39b9 --- /dev/null +++ b/src/main/java/com/sipai/controller/kafka/KafkaController.java @@ -0,0 +1,26 @@ +package com.sipai.controller.kafka; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/kafka") +public class KafkaController { + + @Autowired + private KafkaTemplate kafkaTemplate; + + @GetMapping("/testSendMessage") + public String readValue() { + String topic = "my-topic"; // 替换为你的主题名 + String message = "Hello, Kafka!"; + // 发送消息 + kafkaTemplate.send(topic, message); + System.out.println("消息已发送: " + message); + return "suc"; + } +} diff --git a/src/main/java/com/sipai/controller/mqtt/MqttConfigController.java b/src/main/java/com/sipai/controller/mqtt/MqttConfigController.java new file mode 100644 index 0000000..8ea4a2a --- /dev/null +++ b/src/main/java/com/sipai/controller/mqtt/MqttConfigController.java @@ -0,0 +1,145 @@ +package com.sipai.controller.mqtt; + +import com.sipai.entity.mqtt.MqttConfig; +import com.sipai.service.mqtt.MqttConfigService; +import com.sipai.tools.Result; +import org.apache.commons.codec.binary.Base64; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttPersistenceException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.stereotype.Repository; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/04/22/14:30 + * @Description: mqtt配置主表 + */ +@Controller +@RequestMapping("/mqttConfig") +public class MqttConfigController { + @Autowired + private MqttConfigService mqttConfigService; + + @GetMapping("/getById") + public String getById() { + MqttConfig mqttConfig = mqttConfigService.selectByPrimaryKey("2"); + if (mqttConfig != null) { + System.out.println(mqttConfig.getClientName()); + } else { + System.out.println("无数据"); + } + return "index"; + } + + //连接代理 + @RequestMapping("/connectStart.do") + @ResponseBody + public Result connectStart(HttpServletRequest request, Model model) { + String id = request.getParameter("id"); + mqttConfigService.connect(id); + Result res = Result.success(1); + return res; + } + + /** + * 连接 mqtt + * + * @param request + * @param model + */ + /*@GetMapping("/connect.do") + public void connect(HttpServletRequest request, Model model) { + String ids = request.getParameter("ids"); + if (ids != null && !ids.equals("")) { + String[] idstr = ids.split(","); + for (int i = 0; i < idstr.length; i++) { + MqttConfig mqttConfig = mqttConfigService.selectByPrimaryKey(idstr[i]); + if (mqttConfig != null) { + String str = "http://" + request.getServerName() + ":" + mqttConfig.getTomcatPort() + "/mqttConfig/connectStart.do?id=" + idstr[i]; + this.doPost(str); + } + } + } + }*/ + @GetMapping("/connect.do") + @ResponseBody + public Result connect(HttpServletRequest request, Model model) { + String ids = request.getParameter("ids"); + if (ids != null && !ids.equals("")) { + String[] idstr = ids.split(","); + for (int i = 0; i < idstr.length; i++) { + MqttConfig mqttConfig = mqttConfigService.selectByPrimaryKey(idstr[i]); + if (mqttConfig != null) { + //String str = "http://" + request.getServerName() + ":" + mqttConfig.getTomcatPort() + "/mqttConfig/connectStart.do?id=" + idstr[i]; + String str = "http://" + mqttConfig.getTomcatPort() + "/mqttConfig/connectStart.do?id=" + idstr[i]; + this.doPost(str); + } + } + } + Result res = Result.success(1); + return res; + } + + public String doPost(String URL) { + OutputStreamWriter out = null; + BufferedReader in = null; + StringBuilder result = new StringBuilder(); + HttpURLConnection conn = null; + try { + java.net.URL url = new URL(URL); + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("POST"); + //发送POST请求必须设置为true + conn.setDoOutput(true); + conn.setDoInput(true); + //设置连接超时时间和读取超时时间 + conn.setConnectTimeout(30000); + conn.setReadTimeout(10000); + conn.setRequestProperty("Content-Type", "application/json"); + conn.setRequestProperty("Accept", "application/json"); + //获取输出流 + out = new OutputStreamWriter(conn.getOutputStream()); + String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}"; + out.write(jsonStr); + out.flush(); + out.close(); + //取得输入流,并使用Reader读取 + if (200 == conn.getResponseCode()) { + in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); + String line; + while ((line = in.readLine()) != null) { + result.append(line); + System.out.println(line); + } + } else { + System.out.println("ResponseCode is an error code:" + conn.getResponseCode()); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (out != null) { + out.close(); + } + if (in != null) { + in.close(); + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } + return result.toString(); + } +} diff --git a/src/main/java/com/sipai/controller/mqtt/MqttConfigTopicController.java b/src/main/java/com/sipai/controller/mqtt/MqttConfigTopicController.java new file mode 100644 index 0000000..720c34d --- /dev/null +++ b/src/main/java/com/sipai/controller/mqtt/MqttConfigTopicController.java @@ -0,0 +1,41 @@ +package com.sipai.controller.mqtt; + +import com.sipai.entity.mqtt.MqttConfigTopic; +import com.sipai.service.mqtt.MqttConfigTopicService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/04/22/14:42 + * @Description: mqtt配置主表 + */ +@Controller +@RequestMapping("/mqttConfigTopic") +public class MqttConfigTopicController { + @Autowired + private MqttConfigTopicService mqttConfigTopicService; + + @RequestMapping("/save.do") + @ResponseBody + public Integer save(HttpServletRequest request, Model model, + @ModelAttribute("mqttConfigTopic") MqttConfigTopic mqttConfigTopic) { + return mqttConfigTopicService.insert(mqttConfigTopic); + } + + @RequestMapping("/delete.do") + @ResponseBody + public int delete(HttpServletRequest request, Model model, + @ModelAttribute("id") String id) { + return mqttConfigTopicService.deleteByPrimaryKey(id); + } + +} diff --git a/src/main/java/com/sipai/controller/mqtt/MqttController.java b/src/main/java/com/sipai/controller/mqtt/MqttController.java new file mode 100644 index 0000000..3c62ffc --- /dev/null +++ b/src/main/java/com/sipai/controller/mqtt/MqttController.java @@ -0,0 +1,408 @@ +package com.sipai.controller.mqtt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.sipai.entity.mqtt.MqttConfig; +import com.sipai.entity.mqtt.MqttConfigTopic; +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointES; +import com.sipai.entity.user.Company; +import com.sipai.service.mqtt.MqttConfigService; +import com.sipai.service.mqtt.MqttConfigTopicService; +import com.sipai.service.mqtt.MqttService; +import com.sipai.service.scada.MPointService; +import com.sipai.service.user.CompanyService; +import com.sipai.tools.CommUtil; +import com.sipai.tools.Result; +import org.apache.commons.codec.binary.Base64; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttPersistenceException; +import org.elasticsearch.index.query.BoolQueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; +import org.elasticsearch.search.sort.SortBuilders; +import org.elasticsearch.search.sort.SortOrder; +import org.redisson.api.RMap; +import org.redisson.api.RedissonClient; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; +import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; +import springfox.documentation.spring.web.json.Json; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.math.BigDecimal; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.List; +import java.util.Random; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@Controller +@RequestMapping("/mqtt") +public class MqttController { + @Autowired + private MqttService mqttService; + @Autowired + private CompanyService companyService; + @Autowired + private MPointService mPointService; + @Autowired + private MqttConfigService mqttConfigService; + @Autowired + private MqttConfigTopicService mqttConfigTopicService; + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; + @Autowired + private RedissonClient redissonClient; + + /** + * 用于提供云平台 查询指定网关是否在线 (单个网关) + * sj 2021-05-25 + */ + @RequestMapping("/getClientStatus.do") + @ResponseBody + public String getClientStatus(HttpServletRequest request, Model model) { + String unitId = request.getParameter("unitId");//厂id + String line = null; + try { + URL url = new URL("http://172.16.242.16:28083/api/v4/clients/" + unitId + "_01"); + Base64 b = new Base64(); + String encoding = b.encodeAsString(new String("admin:public").getBytes()); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("Authorization", "Basic " + encoding); + InputStream content = (InputStream) connection.getInputStream(); + BufferedReader in = new BufferedReader(new InputStreamReader(content)); + while ((line = in.readLine()) != null) { + return line; + } + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } + + /** + * 用于提供云平台 返回所有在线的网关 (所有网关) + * sj 2021-05-25 + */ + @RequestMapping("/getClientListStatus.do") + @ResponseBody + public String getClientListStatus() { + String line = null; + try { + URL url = new URL("http://172.16.242.16:28083/api/v4/clients/"); + Base64 b = new Base64(); + String encoding = b.encodeAsString(new String("admin:public").getBytes()); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("Authorization", "Basic " + encoding); + InputStream content = (InputStream) connection.getInputStream(); + BufferedReader in = new BufferedReader(new InputStreamReader(content)); + while ((line = in.readLine()) != null) { + return line; + } + } catch (Exception e) { + e.printStackTrace(); + } + System.out.println(line); + return ""; + } + + /** + * 根据厂id,返回该厂所有的网关在线状态 (必须配置了_COM点) + * sj 2021-08-12 + */ + @RequestMapping("/getClientListStatus4UnitId.do") + @ResponseBody + public String getClientListStatus4UnitId(HttpServletRequest request, Model model, + @ModelAttribute("unitId") String unitId) { + + NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder(); + BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); + BoolQueryBuilder childBoolQueryBuilder = QueryBuilders.boolQuery(); + childBoolQueryBuilder.must(QueryBuilders.matchQuery("bizid", unitId)); + childBoolQueryBuilder.must(QueryBuilders.matchQuery("signaltag", "COMMU")); + boolQueryBuilder.should(childBoolQueryBuilder); + nativeSearchQueryBuilder.withQuery(boolQueryBuilder); + nativeSearchQueryBuilder.withPageable(PageRequest.of(0, 300)); + //先根据es找到改厂所有的通讯点,然后获取mpointId去网关中查询在线状态 + List runMPoint = this.mPointService.selectListByWhere4Es(nativeSearchQueryBuilder); + String str = ""; + String line = null; + JSONArray jsonArray = new JSONArray(); + if (runMPoint.size() > 0) { + //循环所有网关 + for (int i = 0; i < runMPoint.size(); i++) { + String mpointid = runMPoint.get(i).getMpointid(); + String parmname = runMPoint.get(i).getParmname(); + //网关id + mpointid = mpointid.replace("_COM", ""); + + try { + URL url = new URL("http://172.16.242.16:28083/api/v4/clients/" + mpointid); + Base64 b = new Base64(); + String encoding = b.encodeAsString(new String("admin:public").getBytes()); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("Authorization", "Basic " + encoding); + InputStream content = (InputStream) connection.getInputStream(); + BufferedReader in = new BufferedReader(new InputStreamReader(content)); + + JSONObject jsonObject = JSONObject.parseObject(in.readLine()); + String data = jsonObject.get("data").toString(); + JSONArray jsonArrayStr = JSONArray.parseArray(data); + if (jsonArrayStr.size() > 0) { + //获取第一个网关对象 + JSONObject jsonObjectStr = (JSONObject) jsonArrayStr.get(0); + + JSONObject jsonData = new JSONObject(); + jsonData.put("clientid", jsonObjectStr.get("clientid")); + jsonData.put("parmname", parmname); + jsonData.put("connected", true);//在线 + jsonArray.add(jsonData); + } else { + JSONObject jsonData = new JSONObject(); + jsonData.put("clientid", mpointid); + jsonData.put("parmname", parmname); + jsonData.put("connected", false);//不在线 + jsonArray.add(jsonData); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + } + return jsonArray.toString(); + } + + /** + * 用于提供云平台 给plc发布指令接口 + * sj 2021-05-25 + */ + @RequestMapping("/doPublish4Vue.do") + @ResponseBody + public String doPublish4Vue(HttpServletRequest request, Model model) { + String mpid = request.getParameter("mpid");//测量点Id + String bizType = request.getParameter("bizType");//网关编号 + String value = request.getParameter("value");//指令下发的值 + String userId = request.getParameter("userId");//操作人员id + String rate = request.getParameter("rate");//倍率 + String directtype = request.getParameter("directtype");//取反类型 1为取反 其余为正常 + + String topic = bizType + "_DOWN"; + JSONObject jsonObject = new JSONObject(); + + String bizId = bizType.substring(0, 7); + Company company = companyService.selectByPrimaryKey(bizId); + if (company != null) { + bizId = company.getPid(); + } + + /* + 取反操作 + */ + if (directtype != null && directtype.equals("1")) { + //取反 + if (value.equals("0")) { + value = "1"; + } else if (value.equals("1")) { + value = "0"; + } else { + //正常 + } + } else { + //正常 + } + + BigDecimal val = null; + if (rate != null && !rate.equals("0")) { + BigDecimal num1 = new BigDecimal(value); + BigDecimal num2 = new BigDecimal(rate); + +// MPoint mPoint = mPointService.selectById(bizId, mpid); + MPoint mPoint = mPointService.selectById(bizId,mpid); + //AO根据写入的小数位赋值 + if (mPoint != null && mPoint.getSignaltype().equals("AO")) { + BigDecimal bd = new BigDecimal(String.valueOf(value)); + // bd.scale() 为小数位 + val = num1.divide(num2, bd.scale(), BigDecimal.ROUND_HALF_UP); + } + //DO截取0位 + if (mPoint != null && mPoint.getSignaltype().equals("DO")) { + val = num1.divide(num2, 0, BigDecimal.ROUND_HALF_UP); + } + jsonObject.put("TagValue", val); + } else { + String str = String.valueOf(value);//浮点变量a转换为字符串str + int idx = str.lastIndexOf(".");//查找小数点的位置 + if (idx == -1) { + jsonObject.put("TagValue", value); + } else { + String strNum = str.substring(0, idx);//截取从字符串开始到小数点位置的字符串,就是整数部分 + int num = Integer.valueOf(strNum);//把整数部分通过Integer.valueof方法转换为数字 + jsonObject.put("TagValue", num); + } + } + + jsonObject.put("method", "setValue"); + jsonObject.put("TagName", mpid); + + int res = this.mqttService.doPublish(jsonObject, topic, userId, bizId); + String json = null; + if (res == 0) { + Result result = Result.success(res); + json = CommUtil.toJson(result); + } else { + Result result = Result.failed("指令下发失败"); + json = CommUtil.toJson(result); + } + return json; + } + + /** + * 网关数据全部召回(Recall) 传bizid召回该厂该网关的所有数据 + * sj 2021-06-25 + * + * @param request + * @param model + * @return + */ + @RequestMapping("/doRecall.do") + @ResponseBody + public String doRecall(HttpServletRequest request, Model model) { + String unitId = request.getParameter("unitId");//厂id + JSONObject jsonObject = new JSONObject(); + jsonObject.put("command", "Upload immediately"); + mqttService.doRecall(unitId, jsonObject); + Result result = Result.success(""); + String json = null; + json = CommUtil.toJson(result); + return json; + } + + /** + * 前端传主题,根据配置,查询属于哪个代理 + * sj 2021-09-15 + * + * @param request + * @param model + * @return + */ + @RequestMapping("/getEmqx4Topic.do") + @ResponseBody + public String getEmqx4Topic(HttpServletRequest request, Model model) { + String topic = request.getParameter("topic");//厂id + + if (topic != null && topic.contains("_VUE")) { + topic = topic.replace("_VUE", ""); + } + + JSONObject jsonObject = mqttConfigService.getEmqxHost4WS(topic); + + Result result = null; + if (jsonObject != null && jsonObject.size() > 0) { + result = Result.success(jsonObject); + } else { + result = Result.failed("无法查询该代理地址"); + } + String json = null; + json = CommUtil.toJson(result); + return json; + } + + /** + * 演示推送开始 + * + * @param request + * @param model + * @return + */ + @RequestMapping("/startSend.do") + @ResponseBody + public String startSend(HttpServletRequest request, Model model) { + String mp1 = "SPF_XFJZ1_FV2"; //15-50 1秒加1 + String mp2 = "SPF_XFJZ1_FV2_test1"; //15-50 1秒加1 + String mp3 = "SPF_XFJZ1_FV2_test2"; //15-50 1秒加1 + String mp4 = "SPF_XFJZ1_FL2"; //3000-8000 随机 + String mp5 = "SPF_XFJZ1_FL2_test1"; //3000-8000 随机 + String mp6 = "SPF_XFJZ1_FL2_test2"; //3000-8000 随机 + String mp7 = "SPF_XFJZ1_RUN1_test"; + + RMap map_list = redissonClient.getMap("test_mpoint"); + map_list.fastPutAsync(mp1, 15); + map_list.fastPutAsync(mp2, 15); + map_list.fastPutAsync(mp3, 15); + map_list.fastPutAsync(mp4, 3000); + map_list.fastPutAsync(mp5, 3000); + map_list.fastPutAsync(mp6, 3000); + map_list.fastPutAsync(mp7, 1); + + //将推送状态设置为no + RMap map_status = redissonClient.getMap("test_mpoint_status"); + map_status.fastPutAsync("status", "yes"); + + return "开始推送" + CommUtil.nowDate(); + } + + /** + * 演示推送开始 + * + * @param request + * @param model + * @return + */ + @RequestMapping("/stopSend.do") + @ResponseBody + public String stopSend(HttpServletRequest request, Model model) { + + String mp1 = "SPF_XFJZ1_FV2"; //15-50 1秒加1 + String mp2 = "SPF_XFJZ1_FV2_test1"; //15-50 1秒加1 + String mp3 = "SPF_XFJZ1_FV2_test2"; //15-50 1秒加1 + String mp4 = "SPF_XFJZ1_FL2"; //3000-8000 随机 + String mp5 = "SPF_XFJZ1_FL2_test1"; //3000-8000 随机 + String mp6 = "SPF_XFJZ1_FL2_test2"; //3000-8000 随机 + String mp7 = "SPF_XFJZ1_RUN1_test"; + + //数据置0 + RMap map_list = redissonClient.getMap("test_mpoint"); + map_list.fastPutAsync(mp1, 0); + map_list.fastPutAsync(mp2, 0); + map_list.fastPutAsync(mp3, 0); + map_list.fastPutAsync(mp4, 0); + map_list.fastPutAsync(mp5, 0); + map_list.fastPutAsync(mp6, 0); + map_list.fastPutAsync(mp7, 0); + + //推送数据 +// mPointService.sendDataTest(map_list); + + //将推送状态设置为no + RMap map_status = redissonClient.getMap("test_mpoint_status"); + map_status.fastPutAsync("status", "no"); + + return "关闭推送" + CommUtil.nowDate(); + } + +} diff --git a/src/main/java/com/sipai/controller/mqtt/WebHookController.java b/src/main/java/com/sipai/controller/mqtt/WebHookController.java new file mode 100644 index 0000000..4dafbfa --- /dev/null +++ b/src/main/java/com/sipai/controller/mqtt/WebHookController.java @@ -0,0 +1,108 @@ +package com.sipai.controller.mqtt; + +import com.alibaba.druid.util.StringUtils; +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointHistory; +import com.sipai.entity.user.Company; +import com.sipai.service.mqtt.MqttService; +import com.sipai.service.scada.MPointHistoryService; +import com.sipai.service.scada.MPointService; +import com.sipai.service.user.CompanyService; +import com.sipai.tools.CommUtil; +import com.sipai.tools.ConstantString; +import com.sipai.tools.SpringContextUtil; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.math.BigDecimal; +import java.util.Map; + +/** + * 通过emqx webHook 获取所有设备的上下线消息 并存生产库 _COM点 如水口:MZ_SK11_C_01_COM + * sj 2021-05-24 + */ +@Slf4j +@AllArgsConstructor +@RestController +@RequestMapping("/webHook") +public class WebHookController { + @Autowired + private MqttService mqttService; + + @PostMapping("/onJkWebHook") + public void onWebHook(@RequestBody Map param) { + MPointService mPointService = (MPointService) SpringContextUtil.getBean("mPointService"); + MPointHistoryService mPointHistoryService = (MPointHistoryService) SpringContextUtil.getBean("mPointHistoryService"); + CompanyService companyService = (CompanyService) SpringContextUtil.getBean("companyService"); + + String action = MapUtils.getString(param, "action", ""); + try { + String dt = "";//时间戳(秒) + String cid = "";//cid截取9位 为厂id + String dtime = "";//时间 (yyyy-MM-dd HH:mm:ss) + int st = 0; + //连接 + if ("client_connected".equals(action)) { + cid = MapUtils.getString(param, "client_id", ""); + if (StringUtils.isEmpty(cid)) { + cid = MapUtils.getString(param, "clientid", ""); + } + dt = MapUtils.getString(param, "connected_at", ""); + st = 1; + dtime = CommUtil.stampToDate(dt); + + System.out.println("连接:cid=" + cid); + } + //断开连接 + if ("client_disconnected".equals(action)) { + cid = MapUtils.getString(param, "client_id", ""); + if (StringUtils.isEmpty(cid)) { + cid = MapUtils.getString(param, "clientid", ""); + } + dt = MapUtils.getString(param, "disconnected_at", ""); + st = 0; + dtime = CommUtil.stampToDate(dt); + + System.out.println("断开:cid=" + cid); + } + String mpId = cid + "_COM";//测量点id + String bizId = cid.substring(0, 9);//厂id + Company company = companyService.selectByPrimaryKey(bizId); + if (company != null) { + bizId = company.getPid(); +// MPoint mPoint = mPointService.selectById(bizId, mpId); + MPoint mPoint = mPointService.selectById(bizId,mpId); + if (mPoint != null) { + MPointHistory mPointHistory = new MPointHistory(); + //修改主表 + mPoint.setId(mPoint.getId()); + mPoint.setMeasuredt(dtime); + mPoint.setParmvalue(new BigDecimal(st)); + mPointService.update(mPoint); + //插入子表 + mPointHistory.setMeasuredt(dtime); + mPointHistory.setParmvalue(new BigDecimal(st)); + mPointHistory.setTbName("[tb_mp_" + mpId + "]"); + mPointHistoryService.save(bizId, mPointHistory); + //System.out.println(mpId + "执行时间戳:" + CommUtil.stampToDate(dt)); + + //网关掉线发送至报警服务 + System.out.println("设备掉线已推给报警服务(" + mpId + ")" + "----" + st); + mqttService.sentRabbitmq(ConstantString.MQ_ALARM_MQTT, mpId, st + "", dtime); + } else { + System.out.println("点不存在"); + } + } else { + System.out.println("厂不存在"); + } + } catch (Exception e) { + System.out.println("通讯接口执行失败:" + e); + } + } +} diff --git a/src/main/java/com/sipai/controller/opc/OpcUaController.java b/src/main/java/com/sipai/controller/opc/OpcUaController.java new file mode 100644 index 0000000..0df21a6 --- /dev/null +++ b/src/main/java/com/sipai/controller/opc/OpcUaController.java @@ -0,0 +1,96 @@ +package com.sipai.controller.opc; + +import com.sipai.service.opc.InitOpcUaService; +import com.sipai.service.opc.OpcUaService; +import org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/api/opcua") +public class OpcUaController { + + private final OpcUaService opcUaService; + + @Autowired + private InitOpcUaService initOpcUaService; + + public OpcUaController(@Autowired(required = false) OpcUaService opcUaService) { + this.opcUaService = opcUaService; + } + + /** + * 读取单个OPC UA节点的值 + * + * @param nodeId 节点ID,格式为:ns=2;s=通道 1.设备 1.标记3 + * @return 节点值或错误信息 + */ + @GetMapping("/read") + public Object readValue(@RequestParam String nodeId) { + if (opcUaService == null) { + return "OPC UA 未启动,请检查yml配置文件钟:opc: enabled: true"; + } + try { + return opcUaService.readNodeValue(nodeId); + } catch (Exception e) { + return "读取值错误: " + e.getMessage(); + } + } + + /** + * 写入单个OPC UA节点的值 + * + * @param nodeId 节点ID,格式为:ns=2;s=通道 1.设备 1.标记3 + * @param value 要写入的值 + * @return 写入是否成功或错误信息 + */ + @PostMapping("/write") + public String writeValue(@RequestParam String nodeId, @RequestParam Object value) { + if (opcUaService == null) { + return "OPC UA 未启动,请检查yml配置文件钟:opc: enabled: true"; + } + try { + boolean success = opcUaService.writeNodeValue(nodeId, value); + return success ? "写入成功" : "写入失败"; + } catch (Exception e) { + return "写入错误: " + e.getMessage(); + } + } + + /** + * 取消订阅 + * + * @param nodeId + * @return + */ + @PostMapping("/unsubscribeFromNode") + public String unsubscribeFromNode(@RequestParam String nodeId) { + if (opcUaService == null) { + return "OPC UA 未启动,请检查yml配置文件钟:opc: enabled: true"; + } + try { + boolean success = opcUaService.unsubscribeFromNode(nodeId); + return success ? "取消成功" : "取消失败"; + } catch (Exception e) { + return "取消错误: " + e.getMessage(); + } + } + + /** + * 同步opcua订阅点位(查询es中opcua的采集点位,将不需要的点位取消订阅)-一般默认1小时会进行一次同步,有些点位修改总表或es后可手动调用一次立即同步 + * + * @return + */ + @PostMapping("/sysSub") + public String sysSub() { + if (opcUaService == null) { + return "OPC UA 未启动,请检查yml配置文件钟:opc: enabled: true"; + } + initOpcUaService.manualSyncSubscriptions(); + return "suc"; + } + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/controller/rabbitmq/MQController.java b/src/main/java/com/sipai/controller/rabbitmq/MQController.java new file mode 100644 index 0000000..986997b --- /dev/null +++ b/src/main/java/com/sipai/controller/rabbitmq/MQController.java @@ -0,0 +1,29 @@ +package com.sipai.controller.rabbitmq; + +import com.sipai.service.rabbitmq.MQService; +import com.sipai.tools.ConstantString; +import io.swagger.annotations.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/mq") +@Api(value = "/mq", tags = "发送RabbitMQ消息") +public class MQController { + @Autowired + private MQService mQService; + + @RequestMapping("sendMQ") + @ApiOperation(value = "发送消息", notes = "发送消息", httpMethod = "POST") + @ApiResponses({@ApiResponse(code = 400, message = "请求参数没填好")}) + @ApiImplicitParams({ + @ApiImplicitParam(name = "msg", value = "msg", dataType = "String", paramType = "query", example = "YES! PPG", required = true), + }) + public String sendMQ(@RequestParam(value = "msg", required = false, defaultValue = "YES! PPG") String msg) { + this.mQService.sendMQ(ConstantString.MQ_ALARM_MQTT, msg); + return "success"; + } + +} diff --git a/src/main/java/com/sipai/controller/scada/MPointController.java b/src/main/java/com/sipai/controller/scada/MPointController.java new file mode 100644 index 0000000..69cfb70 --- /dev/null +++ b/src/main/java/com/sipai/controller/scada/MPointController.java @@ -0,0 +1,114 @@ +package com.sipai.controller.scada; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.sipai.config.AppConfig; +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.user.Company; +import com.sipai.entity.user.User; +import com.sipai.service.scada.MPointService; +import com.sipai.tools.CommString; +import com.sipai.tools.Result; +import org.redisson.api.RMapCache; +import org.redisson.api.RedissonClient; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: 你的名字 + * @Date: 2021/04/25/21:42 + * @Description: + */ +@Controller +@RequestMapping("/mPoint") +public class MPointController { + @Autowired + private MPointService mPointService; + @Autowired + private RedissonClient redissonClient; + @Autowired + private AppConfig appConfig; + + @RequestMapping("/update.do") + @ResponseBody + public Integer update(HttpServletRequest request, Model model, + @ModelAttribute("mPoint") MPoint mPoint, + @ModelAttribute("bizid") String bizid) { + return mPointService.update(mPoint); + } + + @RequestMapping("/selectById.do") + @ResponseBody + public MPoint selectById(HttpServletRequest request, Model model, + @ModelAttribute(value = "id") String id) { + MPoint mPoint = mPointService.selectById4Es(id); + return mPoint; + } + + /** + * 管网平台获取实时数据接口 + * @param request + * @param model + * @param mpcode + * @return + */ + @RequestMapping("/getDataByMpCode.do") + @ResponseBody + public Result getDataByMpCode(HttpServletRequest request, Model model, + @ModelAttribute(value = "mpcode") String mpcode) { + JSONArray jsonArray = new JSONArray(); + + String[] mpcodes = mpcode.split(","); + if (mpcodes != null && mpcodes.length > 0) { + if (mpcodes.length > appConfig.getMaxPoints()) { + Result res = Result.failed("一次最多处理" + appConfig.getMaxPoints() + "个点位"); + return res; + } else { + System.out.println("收到点位(" + mpcodes.length + "个):"); + } + + String ids = ""; + for (int i = 0; i < mpcodes.length; i++) { + ids += "'" + mpcodes[i] + "',"; + } + ids = ids.substring(0, ids.length() - 1); + + Map map = new HashMap<>(); + List list = mPointService.selectListByWhere("where 1=1 and id in (" + ids + ")"); + for (MPoint mPoint : list) { + if (mPoint.getParmvalue() != null && mPoint.getMeasuredt() != null) { + map.put(mPoint.getId(), mPoint.getParmvalue() + ";" + mPoint.getMeasuredt()); + } + } + + for (int i = 0; i < mpcodes.length; i++) { + if (map.get(mpcodes[i]) != null) { + String[] val = map.get(mpcodes[i]).split(";"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("mpcode", mpcodes[i]); + jsonObject.put("parmvalue", val[0]); + jsonObject.put("measuredt", val[1].length() > 19 ? val[1].substring(0, 19) : val[1]); + jsonArray.add(jsonObject); + } else { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("mpcode", mpcodes[i]); + jsonObject.put("parmvalue", ""); + jsonObject.put("measuredt", ""); + jsonArray.add(jsonObject); + } + } + + } + Result res = Result.success(jsonArray); + return res; + } +} diff --git a/src/main/java/com/sipai/controller/user/CompanyController.java b/src/main/java/com/sipai/controller/user/CompanyController.java new file mode 100644 index 0000000..e2b9739 --- /dev/null +++ b/src/main/java/com/sipai/controller/user/CompanyController.java @@ -0,0 +1,40 @@ +package com.sipai.controller.user; + +import com.sipai.entity.user.Company; +import com.sipai.service.user.CompanyService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: 你的名字 + * @Date: 2021/04/25/21:15 + * @Description: + */ +@Controller +@RequestMapping("/company") +public class CompanyController { + @Autowired + private CompanyService companyService; + + @RequestMapping("/save.do") + @ResponseBody + public Integer save(HttpServletRequest request, Model model, + @ModelAttribute("company") Company company) { + return companyService.insert(company); + } + + @RequestMapping("/delete.do") + @ResponseBody + public int delete(HttpServletRequest request, Model model, + @ModelAttribute("id") String id) { + return companyService.deleteByPrimaryKey(id); + } +} diff --git a/src/main/java/com/sipai/controller/user/UserController.java b/src/main/java/com/sipai/controller/user/UserController.java new file mode 100644 index 0000000..d6b8ef8 --- /dev/null +++ b/src/main/java/com/sipai/controller/user/UserController.java @@ -0,0 +1,35 @@ +package com.sipai.controller.user; + +import com.sipai.entity.user.User; +import com.sipai.service.user.UserService; +import com.sipai.tools.Result; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +@Controller +@RequestMapping("/user") +public class UserController { + @Autowired + private UserService userService; + + @RequestMapping(value = "/test1") + @ResponseBody + public Result index(HttpServletRequest request) { + Result result = Result.success(1); + return result; + } + + @RequestMapping(value = "/test2") + @ResponseBody + public Result index2(HttpServletRequest request) { + Result result = Result.failed(""); + return result; + } + +} diff --git a/src/main/java/com/sipai/dao/Listener/ListenerHisDao.java b/src/main/java/com/sipai/dao/Listener/ListenerHisDao.java new file mode 100644 index 0000000..6adf421 --- /dev/null +++ b/src/main/java/com/sipai/dao/Listener/ListenerHisDao.java @@ -0,0 +1,24 @@ +package com.sipai.dao.Listener; + +import com.sipai.dao.base.CommDaoImpl; +import com.sipai.entity.Listener.ListenerHis; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public class ListenerHisDao extends CommDaoImpl { + + public ListenerHisDao() { + super(); + this.setMappernamespace("Listener.ListenerHisMapper"); + } + + public List selectTopByWhere(String where) { + ListenerHis listenerHis = new ListenerHis(); + listenerHis.setWhere(where); + List list = this.getSqlSession().selectList("Listener.ListenerHisMapper.selectTopByWhere", listenerHis); + return list; + } + +} diff --git a/src/main/java/com/sipai/dao/Listener/ListenerInterfaceDao.java b/src/main/java/com/sipai/dao/Listener/ListenerInterfaceDao.java new file mode 100644 index 0000000..c0e866e --- /dev/null +++ b/src/main/java/com/sipai/dao/Listener/ListenerInterfaceDao.java @@ -0,0 +1,15 @@ +package com.sipai.dao.Listener; + +import com.sipai.dao.base.CommDaoImpl; +import com.sipai.entity.Listener.ListenerInterface; +import org.springframework.stereotype.Repository; + +@Repository +public class ListenerInterfaceDao extends CommDaoImpl { + + public ListenerInterfaceDao() { + super(); + this.setMappernamespace("Listener.ListenerInterfaceMapper"); + } + +} diff --git a/src/main/java/com/sipai/dao/Listener/ListenerMessageDao.java b/src/main/java/com/sipai/dao/Listener/ListenerMessageDao.java new file mode 100644 index 0000000..b57e891 --- /dev/null +++ b/src/main/java/com/sipai/dao/Listener/ListenerMessageDao.java @@ -0,0 +1,15 @@ +package com.sipai.dao.Listener; + +import com.sipai.dao.base.CommDaoImpl; +import com.sipai.entity.Listener.ListenerMessage; +import org.springframework.stereotype.Repository; + +@Repository +public class ListenerMessageDao extends CommDaoImpl { + + public ListenerMessageDao() { + super(); + this.setMappernamespace("Listener.ListenerMessageMapper"); + } + +} diff --git a/src/main/java/com/sipai/dao/Listener/ListenerPointDao.java b/src/main/java/com/sipai/dao/Listener/ListenerPointDao.java new file mode 100644 index 0000000..4ad8d53 --- /dev/null +++ b/src/main/java/com/sipai/dao/Listener/ListenerPointDao.java @@ -0,0 +1,15 @@ +package com.sipai.dao.Listener; + +import com.sipai.dao.base.CommDaoImpl; +import com.sipai.entity.Listener.ListenerPoint; +import org.springframework.stereotype.Repository; + +@Repository +public class ListenerPointDao extends CommDaoImpl { + + public ListenerPointDao() { + super(); + this.setMappernamespace("Listener.ListenerPointMapper"); + } + +} diff --git a/src/main/java/com/sipai/dao/base/CommDao.java b/src/main/java/com/sipai/dao/base/CommDao.java new file mode 100644 index 0000000..27f71d1 --- /dev/null +++ b/src/main/java/com/sipai/dao/base/CommDao.java @@ -0,0 +1,125 @@ +package com.sipai.dao.base; + +import java.util.List; + + +public interface CommDao{ + /**====基础的CURD操作====**/ + /** + * 根据id查找唯一对象 + * @param + * @param t + * @return + */ + public T selectByPrimaryKey(String t); + /** + * 根据id删除唯一对象 + * @param + * @param t + * @return + */ + public int deleteByPrimaryKey(String t); + /** + * 根据对象信息插入数据 + * @param + * @param t + * @return + */ + public int insert(T t); + /** + * 根据对象信息插入数据,只插入不为null的字段,不会影响有默认值的字段 + * @param + * @param t + * @return + */ +// public int insertSelective(T t); + /** + * 根据对象信息更新数据,只跟新不为null的字段 + * @param + * @param t + * @return + */ + public int updateByPrimaryKeySelective(T t); + /** + * 根据对象id信息更新数据,只跟新不为null的字段 + * @param + * @param t + * @return + */ +// public int updateByPrimaryKey(T t); + + /**=====扩展的查询=====**/ + /** + * 根据where条件查找唯一对象 + * @param + * @param t + * @return + */ + public T selectByWhere(T t); + + /** + * 根据where条件查找对象列表 + * @param + * @param t + * @return + */ + public List selectList(T t); + /** + * 查找和t某些值相等的对象列表 + * @param + * @param t + * @return + */ + + /** + * 根据where条件查找对象列表 + * @param + * @param t + * @return + */ + public List selectListByWhere(T t); + /** + * 查找和t某些值相等的对象列表 + * @param + * @param t + * @return + */ + public List selectListByObj(T t); + /** + * 根据sql语句查找对象列表 + * @param + * @param t + * @return + */ + public List selectListBySql(T t); + /** + * 根据sql语句查询唯一字段值 + * @param + * @param t + * @return + */ + public Object selectValueBySql(T t); + /** + * 根据where条件删除 + * @param + * @param t + */ + public int deleteByWhere(T t); + /** + * 根据where条件更新 + * @param + * @param t + */ + public int updateByWhere(T t); + /** + * 执行sql语句 :增,删,改 + * @param + * @param t + */ + public int executeSql(T t); + public void commit(); + public void close(); + + +} + diff --git a/src/main/java/com/sipai/dao/base/CommDaoImpl.java b/src/main/java/com/sipai/dao/base/CommDaoImpl.java new file mode 100644 index 0000000..4b5bb11 --- /dev/null +++ b/src/main/java/com/sipai/dao/base/CommDaoImpl.java @@ -0,0 +1,151 @@ +package com.sipai.dao.base; + +import java.math.BigDecimal; +import java.util.List; + +import javax.annotation.Resource; + +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.springframework.stereotype.Repository; + +@Repository +public class CommDaoImpl implements CommDao { + @Resource + private SqlSessionFactory sqlSessionFactory; + @Resource + private SqlSession sqlSession; + private String mappernamespace; // 需要操作的mappernamespace名(也是数据库表名) + private boolean isAuto = true;// 默认自动提交 + + public CommDaoImpl() { + super(); + } + + public SqlSessionFactory getSqlSessionFactory() { + return sqlSessionFactory; + } + + public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { + this.sqlSessionFactory = sqlSessionFactory; + } + + public boolean isAuto() { + return isAuto; + } + + public void setAuto(boolean isAuto) { + this.isAuto = isAuto; + } + + public String getMappernamespace() { + return mappernamespace; + } + + public void setMappernamespace(String mappernamespace) { + this.mappernamespace = mappernamespace; + } + + public T selectByPrimaryKey(String t){ + T o = getSqlSession().selectOne(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + return o; + } + /** + * wxp为activiti测试修改 + * @param t + * @return + */ + public T selectByID(BigDecimal t){ + T o = getSqlSession().selectOne(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + return o; + } + public int deleteByPrimaryKey(String t) { + return getSqlSession().delete(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + + public int insert(T t){ + return getSqlSession().insert(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + + public int insertSelective(T t){ + return getSqlSession().insert(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + + public int updateByPrimaryKeySelective(T t){ + return getSqlSession().update(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + +// public int updateByPrimaryKey(T t){ +// return getSqlSession().update(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); +// } + + public T selectByWhere( T t) { + List list = getSqlSession().selectList(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + if (list != null && list.size() > 0) { + return list.get(0); + } else { + return null; + } + } + + public List selectList(T t) { + List list = getSqlSession().selectList(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + return list; + } + + public List selectListByWhere( T t) { + List list = getSqlSession().selectList(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + return list; + } + + public List selectListByObj(T t) { + List list = getSqlSession().selectList(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + return list; + } + public List selectListByt( T t) { + List list = getSqlSession().selectList(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + return list; + } + + public List selectListBySql( T t) { + List list = getSqlSession().selectList(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + return list; + } + + public T selectValueBySql( T t) { + List list = getSqlSession().selectList(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + if (list != null && list.size() > 0) { + return list.get(0); + } else { + return null; + } + } + + public int deleteByWhere( T t) { + return this.getSqlSession().delete(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + + public int updateByWhere( T t) { + return this.getSqlSession().update(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + + public int executeSql( T t) { + return this.getSqlSession().update(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + + public void commit() { + if (sqlSession != null) + sqlSession.commit(); + } + + public SqlSession getSqlSession() { + sqlSession = sqlSession == null ? sqlSessionFactory.openSession(isAuto) : sqlSession; + return sqlSession; + } + + public void close() { + if (sqlSession != null) + sqlSession.close(); + } + +} diff --git a/src/main/java/com/sipai/dao/data/PipeTopicMpointDao.java b/src/main/java/com/sipai/dao/data/PipeTopicMpointDao.java new file mode 100644 index 0000000..9fb8d0a --- /dev/null +++ b/src/main/java/com/sipai/dao/data/PipeTopicMpointDao.java @@ -0,0 +1,43 @@ +package com.sipai.dao.data; + +import com.sipai.entity.data.PipeTopicMpoint; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +@Repository +public interface PipeTopicMpointDao { + + /** + * 添加管网专题页点位信息 + */ + int insert(PipeTopicMpoint pipeTopicMpoint); + + /** + * 根据主键删除点位信息 + */ + boolean deleteByPrimaryKey(Integer id); + + /** + * 批量删除点位信息 + */ + int deleteBatchByIds(@Param("list") List idList); + + /** + * 更新点位信息 + */ + boolean updateByPrimaryKeySelective(PipeTopicMpoint pipeTopicMpoint); + + /** + * 根据主键获取点位详情 + */ + PipeTopicMpoint selectByPrimaryKey(Integer id); + + /** + * 根据条件查询点位列表 + */ + List selectListByWhere(PipeTopicMpoint pipeTopicMpoint); +} \ No newline at end of file diff --git a/src/main/java/com/sipai/dao/data/PipelineEquipmentDao.java b/src/main/java/com/sipai/dao/data/PipelineEquipmentDao.java new file mode 100644 index 0000000..5b69da8 --- /dev/null +++ b/src/main/java/com/sipai/dao/data/PipelineEquipmentDao.java @@ -0,0 +1,47 @@ +package com.sipai.dao.data; + +import com.sipai.dao.base.CommDaoImpl; +import com.sipai.entity.data.PipelineEquipment; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +@Repository +public interface PipelineEquipmentDao{ + + /** + * 添加设备 + */ + int insert(PipelineEquipment pipelineEquipment); + + /** + * 删除设备 + */ + boolean deleteByPrimaryKey(Integer id); + + /** + * 多删设备 + * @param idList + * @return + */ + int deleteBatchByIds(@Param("list") List idList); + + /** + * 更新设备信息 + */ + boolean updateByPrimaryKeySelective(PipelineEquipment equipment); + + /** + * 获取设备详情 + */ + PipelineEquipment selectByPrimaryKey(Integer id); + + /** + * 获取所有设备列表 + */ + List selectListByWhere(PipelineEquipment equipment); + +} diff --git a/src/main/java/com/sipai/dao/data/PipelineEquipmentMpointDao.java b/src/main/java/com/sipai/dao/data/PipelineEquipmentMpointDao.java new file mode 100644 index 0000000..596ff3c --- /dev/null +++ b/src/main/java/com/sipai/dao/data/PipelineEquipmentMpointDao.java @@ -0,0 +1,37 @@ +package com.sipai.dao.data; + +import com.sipai.entity.data.PipelineEquipmentMpoint; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +@Repository +public interface PipelineEquipmentMpointDao { + + /** + * 添加关联信息 + */ + boolean insert(PipelineEquipmentMpoint mpoint); + + /** + * 删除关联信息 + */ + boolean deleteByPrimaryKey(Integer id); + + /** + * 更新关联信息 + */ + boolean updateByPrimaryKeySelective(PipelineEquipmentMpoint mpoint); + + /** + * 获取关联信息详情 + */ + PipelineEquipmentMpoint selectByPrimaryKey(Integer id); + + /** + * 获取所有关联信息列表 + */ + List selectListByWhere(PipelineEquipmentMpoint mpoint); +} \ No newline at end of file diff --git a/src/main/java/com/sipai/dao/data/PipelineMpointLibraryDao.java b/src/main/java/com/sipai/dao/data/PipelineMpointLibraryDao.java new file mode 100644 index 0000000..020f526 --- /dev/null +++ b/src/main/java/com/sipai/dao/data/PipelineMpointLibraryDao.java @@ -0,0 +1,45 @@ +package com.sipai.dao.data; + +import com.sipai.entity.data.PipelineMpointLibrary; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +@Repository +public interface PipelineMpointLibraryDao { + + /** + * 添加测点库信息 + */ + boolean insert(PipelineMpointLibrary mpointLibrary); + + /** + * 删除测点库信息 + */ + boolean deleteByPrimaryKey(String id); + + /** + * 多删测点库信息 + * @param idList + * @return + */ + int deleteBatchByIds(@Param("list") List idList); + + /** + * 更新测点库信息 + */ + boolean updateByPrimaryKeySelective(PipelineMpointLibrary mpointLibrary); + + /** + * 获取测点库详情 + */ + PipelineMpointLibrary selectByPrimaryKey(String id); + + /** + * 获取所有测点库列表 + */ + List selectListByWhere(PipelineMpointLibrary mpointLibrary); +} \ No newline at end of file diff --git a/src/main/java/com/sipai/dao/mqtt/MqttConfigDao.java b/src/main/java/com/sipai/dao/mqtt/MqttConfigDao.java new file mode 100644 index 0000000..2b22928 --- /dev/null +++ b/src/main/java/com/sipai/dao/mqtt/MqttConfigDao.java @@ -0,0 +1,32 @@ +package com.sipai.dao.mqtt; + +import com.sipai.entity.mqtt.MqttConfig; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: 你的名字 + * @Date: 2021/03/24/17:14 + * @Description: + */ +@Mapper +@Repository +public interface MqttConfigDao { + + public abstract MqttConfig selectByPrimaryKey(String id); + + public abstract Integer deleteByPrimaryKey(String id); + + public abstract Integer insert(MqttConfig entity); + + public abstract Integer updateByPrimaryKeySelective(MqttConfig entity); + + public abstract List selectListByWhere(MqttConfig entity); + + public abstract Integer deleteByWhere(String where); + +} diff --git a/src/main/java/com/sipai/dao/mqtt/MqttConfigTopicDao.java b/src/main/java/com/sipai/dao/mqtt/MqttConfigTopicDao.java new file mode 100644 index 0000000..a628ac1 --- /dev/null +++ b/src/main/java/com/sipai/dao/mqtt/MqttConfigTopicDao.java @@ -0,0 +1,34 @@ +package com.sipai.dao.mqtt; + +import com.sipai.entity.mqtt.MqttConfigTopic; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: 你的名字 + * @Date: 2021/03/24/17:55 + * @Description: + */ +@Mapper +@Repository +public interface MqttConfigTopicDao { + + public abstract MqttConfigTopic selectByPrimaryKey(String id); + + public abstract Integer deleteByPrimaryKey(String id); + + public abstract Integer insert(MqttConfigTopic entity); + + public abstract Integer updateByPrimaryKeySelective(MqttConfigTopic entity); + + public abstract List selectListByWhere(MqttConfigTopic entity); + + public abstract Integer deleteByWhere(String wherestr); + + public abstract List selectListByPid(String pid); + +} diff --git a/src/main/java/com/sipai/dao/scada/MPointBzwDao.java b/src/main/java/com/sipai/dao/scada/MPointBzwDao.java new file mode 100644 index 0000000..ba52a48 --- /dev/null +++ b/src/main/java/com/sipai/dao/scada/MPointBzwDao.java @@ -0,0 +1,25 @@ +package com.sipai.dao.scada; + +import com.sipai.entity.scada.MPointBzw; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +@Repository +public interface MPointBzwDao { + + public abstract MPointBzw selectByPrimaryKey(String id); + + public abstract int deleteByPrimaryKey(String id); + + public abstract int insert(MPointBzw entity); + + public abstract int updateByPrimaryKeySelective(MPointBzw entity); + + public abstract List selectListByWhere(MPointBzw entity); + + public abstract int deleteByWhere(String where); + +} diff --git a/src/main/java/com/sipai/dao/scada/MPointDao.java b/src/main/java/com/sipai/dao/scada/MPointDao.java new file mode 100644 index 0000000..480dd69 --- /dev/null +++ b/src/main/java/com/sipai/dao/scada/MPointDao.java @@ -0,0 +1,19 @@ +package com.sipai.dao.scada; + + +import com.sipai.dao.base.CommDaoImpl; +import com.sipai.entity.scada.MPoint; +import org.springframework.stereotype.Repository; + + +@Repository +public class MPointDao extends CommDaoImpl { + public MPointDao() { + super(); + this.setMappernamespace("scada.MPointMapper"); + } + + public int updateValueByKey(MPoint t) { + return getSqlSession().update("scada.MPointMapper."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/dao/scada/MPointHistoryDao.java b/src/main/java/com/sipai/dao/scada/MPointHistoryDao.java new file mode 100644 index 0000000..ee11507 --- /dev/null +++ b/src/main/java/com/sipai/dao/scada/MPointHistoryDao.java @@ -0,0 +1,64 @@ +package com.sipai.dao.scada; + +import com.sipai.dao.base.CommDaoImpl; +import com.sipai.entity.scada.MPointHistory; +import org.springframework.stereotype.Repository; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Repository +public class MPointHistoryDao extends CommDaoImpl { + public MPointHistoryDao() { + super(); + this.setMappernamespace("scada.MPointHistoryMapper"); + } + + public List selectListByTableAWhere(String tablename, String wherestr) { + Map paramMap=new HashMap<>(); + paramMap.put("table",tablename); + paramMap.put("where",wherestr); + List list = getSqlSession().selectList("scada.MPointHistoryMapper."+Thread.currentThread().getStackTrace()[1].getMethodName(), paramMap); + return list; + } + + public int deleteByTableAWhere(String tablename, String wherestr) { + Map paramMap=new HashMap<>(); + paramMap.put("table",tablename); + paramMap.put("where",wherestr); + return this.getSqlSession().delete("scada.MPointHistoryMapper."+Thread.currentThread().getStackTrace()[1].getMethodName(), paramMap); + } + + public int createTable(String tablename){ + Map paramMap=new HashMap<>(1); + paramMap.put("table",tablename); + return getSqlSession().update("scada.MPointHistoryMapper."+Thread.currentThread().getStackTrace()[1].getMethodName(), paramMap); + } + + public Integer checkTableExist(String tablename){ + Map paramMap = new HashMap<>(1); + paramMap.put("table",tablename); + return getSqlSession().selectOne("scada.MPointHistoryMapper.checkTableExist", paramMap); + } + + public Integer selectCount(MPointHistory t){ + return getSqlSession().selectOne("scada.MPointHistoryMapper."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + + public int updateByMeasureDt(MPointHistory t) { + return getSqlSession().update("scada.MPointHistoryMapper."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + + public List selectIndustrialLibrary(String IP,String MPointID, String intv, String sdt,String edt) { + Map paramMap=new HashMap<>(); + paramMap.put("IP",IP); + paramMap.put("MPointID",MPointID); + paramMap.put("intv",intv); + paramMap.put("sdt",sdt); + paramMap.put("edt",edt); + List list = getSqlSession().selectList("scada.MPointHistoryMapper."+Thread.currentThread().getStackTrace()[1].getMethodName(), paramMap); + return list; + } + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/dao/scada/MPointRepo.java b/src/main/java/com/sipai/dao/scada/MPointRepo.java new file mode 100644 index 0000000..a09486b --- /dev/null +++ b/src/main/java/com/sipai/dao/scada/MPointRepo.java @@ -0,0 +1,8 @@ +package com.sipai.dao.scada; + +import com.sipai.entity.scada.MPoint; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +public interface MPointRepo extends ElasticsearchRepository, MPointRepository { + +} diff --git a/src/main/java/com/sipai/dao/scada/MPointRepository.java b/src/main/java/com/sipai/dao/scada/MPointRepository.java new file mode 100644 index 0000000..ba5a784 --- /dev/null +++ b/src/main/java/com/sipai/dao/scada/MPointRepository.java @@ -0,0 +1,13 @@ +package com.sipai.dao.scada; + +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointES; + +import java.util.List; + +public interface MPointRepository { +// int updateSelective(MPoint mpoint); +// int updateValue(MPoint mpoint); + void batchInsert(List mPointES); + void batchUpdate(List mPointES); +} diff --git a/src/main/java/com/sipai/dao/scada/MPointRepositoryImpl.java b/src/main/java/com/sipai/dao/scada/MPointRepositoryImpl.java new file mode 100644 index 0000000..6b950f4 --- /dev/null +++ b/src/main/java/com/sipai/dao/scada/MPointRepositoryImpl.java @@ -0,0 +1,105 @@ +package com.sipai.dao.scada; + +import com.google.gson.Gson; +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointES; +import com.sipai.tools.CommUtil; +import org.elasticsearch.action.index.IndexRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.core.query.IndexQuery; +import org.springframework.data.elasticsearch.core.query.UpdateQuery; +import org.springframework.data.elasticsearch.core.query.UpdateQueryBuilder; + +import java.beans.PropertyDescriptor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +public class MPointRepositoryImpl implements MPointRepository { + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; + + public void batchInsert(List mPointES){ + + int counter = 0; + + //判断index 是否存在 + if (!elasticsearchTemplate.indexExists("es_measurepoint")) { + elasticsearchTemplate.createIndex("es_measurepoint"); + } + + Gson gson = new Gson(); + List queries = new ArrayList(); + if(mPointES != null && mPointES.size()>0){ + for (MPointES item : mPointES) { + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(item.getId().toString()); + indexQuery.setSource(gson.toJson(item)); + indexQuery.setIndexName("es_measurepoint"); + indexQuery.setType("esmeasurepoint"); + queries.add(indexQuery); + //分批提交索引 + if (counter % 500 == 0) { + elasticsearchTemplate.bulkIndex(queries); + queries.clear(); + //System.out.println("bulkIndex counter : " + counter); + } + counter++; + } + + } + //不足批的索引最后不要忘记提交 + if (queries.size() > 0) { + elasticsearchTemplate.bulkIndex(queries); + } +// elasticsearchTemplate.refresh("es_measurepoint"); + } + + @Override + public void batchUpdate(List mPointES) { + + int counter = 0; + + //判断index 是否存在 + if (!elasticsearchTemplate.indexExists("es_measurepoint")) { + elasticsearchTemplate.createIndex("es_measurepoint"); + } + + Gson gson = new Gson(); + + List queries = new ArrayList<>(); + if (mPointES != null && mPointES.size() > 0) { + for (MPointES item : mPointES) { + if (item.getMeasuredt() != null) { + IndexRequest indexRequest = new IndexRequest(); + indexRequest.source("measuredt", item.getMeasuredt()); + UpdateQuery updateQuery = new UpdateQueryBuilder().withId(item.getId()).withClass(MPoint.class).withIndexRequest(indexRequest).build(); + queries.add(updateQuery); + } + if (item.getParmvalue() != null) { + IndexRequest indexRequest = new IndexRequest(); + indexRequest.source("parmvalue", item.getParmvalue()); + UpdateQuery updateQuery = new UpdateQueryBuilder().withId(item.getId()).withClass(MPoint.class).withIndexRequest(indexRequest).build(); + queries.add(updateQuery); + } + //分批提交索引 + if (counter % 500 == 0) { + elasticsearchTemplate.bulkUpdate(queries); + queries.clear(); + } + counter++; + } + } + + //不足批的索引最后不要忘记提交 + if (queries.size() > 0) { + elasticsearchTemplate.bulkUpdate(queries); + } +// elasticsearchTemplate.refresh("es_measurepoint"); + } +} diff --git a/src/main/java/com/sipai/dao/user/CompanyDao.java b/src/main/java/com/sipai/dao/user/CompanyDao.java new file mode 100644 index 0000000..9437b85 --- /dev/null +++ b/src/main/java/com/sipai/dao/user/CompanyDao.java @@ -0,0 +1,25 @@ +package com.sipai.dao.user; + +import com.sipai.entity.user.Company; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +@Repository +public interface CompanyDao { + + public abstract Company selectByPrimaryKey(String id); + + public abstract Integer deleteByPrimaryKey(String id); + + public abstract Integer insert(Company entity); + + public abstract Integer updateByPrimaryKeySelective(Company entity); + + public abstract List selectListByWhere(Company entity); + + public abstract Integer deleteByWhere(String where); + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/dao/user/UserDao.java b/src/main/java/com/sipai/dao/user/UserDao.java new file mode 100644 index 0000000..a5e3f60 --- /dev/null +++ b/src/main/java/com/sipai/dao/user/UserDao.java @@ -0,0 +1,13 @@ +package com.sipai.dao.user; + +import com.sipai.entity.user.User; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +@Repository +public interface UserDao { + public abstract List listuser2(); +} diff --git a/src/main/java/com/sipai/entity/Listener/ListenerHis.java b/src/main/java/com/sipai/entity/Listener/ListenerHis.java new file mode 100644 index 0000000..e51877b --- /dev/null +++ b/src/main/java/com/sipai/entity/Listener/ListenerHis.java @@ -0,0 +1,56 @@ +package com.sipai.entity.Listener; + +import com.sipai.entity.base.SQLAdapter; + +public class ListenerHis extends SQLAdapter { + + private String id; + + private String pointid; + + private String value; + + private String type; + + private String insdt; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getPointid() { + return pointid; + } + + public void setPointid(String pointid) { + this.pointid = pointid; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getInsdt() { + return insdt; + } + + public void setInsdt(String insdt) { + this.insdt = insdt; + } +} diff --git a/src/main/java/com/sipai/entity/Listener/ListenerInterface.java b/src/main/java/com/sipai/entity/Listener/ListenerInterface.java new file mode 100644 index 0000000..7d8d80c --- /dev/null +++ b/src/main/java/com/sipai/entity/Listener/ListenerInterface.java @@ -0,0 +1,56 @@ +package com.sipai.entity.Listener; + +import com.sipai.entity.base.SQLAdapter; + +public class ListenerInterface extends SQLAdapter { + + private String id; + + private String name; + + private String type; + + private String url; + + private String port; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getPort() { + return port; + } + + public void setPort(String port) { + this.port = port; + } +} diff --git a/src/main/java/com/sipai/entity/Listener/ListenerMessage.java b/src/main/java/com/sipai/entity/Listener/ListenerMessage.java new file mode 100644 index 0000000..04ebbe9 --- /dev/null +++ b/src/main/java/com/sipai/entity/Listener/ListenerMessage.java @@ -0,0 +1,86 @@ +package com.sipai.entity.Listener; + +import com.sipai.entity.base.SQLAdapter; +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.user.Company; + +public class ListenerMessage extends SQLAdapter { + + private String id; + + private String Cmdtype; + + private String Objid; + + private String Action; + + private String insdt; + + private MPoint mPoint; +// private ProcessSection processSection; + private Company company; + + public MPoint getmPoint() { + return mPoint; + } + + public void setmPoint(MPoint mPoint) { + this.mPoint = mPoint; + } + +// public ProcessSection getProcessSection() { +// return processSection; +// } +// +// public void setProcessSection(ProcessSection processSection) { +// this.processSection = processSection; +// } + + public Company getCompany() { + return company; + } + + public void setCompany(Company company) { + this.company = company; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getCmdtype() { + return Cmdtype; + } + + public void setCmdtype(String cmdtype) { + Cmdtype = cmdtype; + } + + public String getObjid() { + return Objid; + } + + public void setObjid(String objid) { + Objid = objid; + } + + public String getAction() { + return Action; + } + + public void setAction(String action) { + Action = action; + } + + public String getInsdt() { + return insdt; + } + + public void setInsdt(String insdt) { + this.insdt = insdt; + } +} diff --git a/src/main/java/com/sipai/entity/Listener/ListenerPoint.java b/src/main/java/com/sipai/entity/Listener/ListenerPoint.java new file mode 100644 index 0000000..ef83dec --- /dev/null +++ b/src/main/java/com/sipai/entity/Listener/ListenerPoint.java @@ -0,0 +1,123 @@ +package com.sipai.entity.Listener; + +import com.sipai.entity.base.SQLAdapter; + +public class ListenerPoint extends SQLAdapter { + + private String id; + + private String intid; + + private String name; + + private String address; + + private String type; + + private String mpcode; + + private String datatype; + + private String unitid; + + //逻辑条件 + //= 等于 + //> 大于 + //< 小于 + //change 变化 + private String logi; + + //逻辑条件对应的值 + private String logiVal; + + //动作 如等于reset 为置0 + private String action; + + public String getLogiVal() { + return logiVal; + } + + public void setLogiVal(String logiVal) { + this.logiVal = logiVal; + } + + public String getLogi() { + return logi; + } + + public void setLogi(String logi) { + this.logi = logi; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getIntid() { + return intid; + } + + public void setIntid(String intid) { + this.intid = intid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMpcode() { + return mpcode; + } + + public void setMpcode(String mpcode) { + this.mpcode = mpcode; + } + + public String getDatatype() { + return datatype; + } + + public void setDatatype(String datatype) { + this.datatype = datatype; + } + + public String getUnitid() { + return unitid; + } + + public void setUnitid(String unitid) { + this.unitid = unitid; + } +} diff --git a/src/main/java/com/sipai/entity/base/Result.java b/src/main/java/com/sipai/entity/base/Result.java new file mode 100644 index 0000000..cb4cbd7 --- /dev/null +++ b/src/main/java/com/sipai/entity/base/Result.java @@ -0,0 +1,65 @@ +package com.sipai.entity.base; + +import com.alibaba.fastjson.JSON; + +/** + * + * @author WXP + * + */ +public class Result { + public static final int SUCCESS = 1; + public static final int FAILED = 0; + public static final int REPEATED = 2;//重复添加 + + public Result(){ + + } + public Result(int code, String message, Object result) { + this.code = code; + this.msg = message; + if (result instanceof String) { + this.result = JSON.parse(result.toString()); + }else{ + this.result =result; + } + + } + public static Result success(Object result,String msg) { + return new Result(SUCCESS, msg, result); + } + public static Result success(Object result) { + return new Result(SUCCESS, "", result); + } + public static Result success() { + return new Result(SUCCESS, "", null); + } + public static Result failed(String msg) { + return new Result(FAILED, msg, null); + } + public int code; + public String msg; + public Object result; + + public int getCode() { + return code; + } + public void setCode(int code) { + this.code = code; + } + public String getMsg() { + return msg; + } + public void setMsg(String msg) { + this.msg = msg; + } + public Object getResult() { + return result; + } + public void setResult(Object result) { + this.result = result; + } + + + +} diff --git a/src/main/java/com/sipai/entity/base/SQLAdapter.java b/src/main/java/com/sipai/entity/base/SQLAdapter.java new file mode 100644 index 0000000..a3cee4a --- /dev/null +++ b/src/main/java/com/sipai/entity/base/SQLAdapter.java @@ -0,0 +1,22 @@ +package com.sipai.entity.base; + +public class SQLAdapter { + private String sql; + private String where; + + public String getSql() { + return sql; + } + public void setSql(String sql) { + this.sql = sql; + } + + public String getWhere() { + return where; + } + + public void setWhere(String where) { + this.where = where; + } + +} diff --git a/src/main/java/com/sipai/entity/common/PageData.java b/src/main/java/com/sipai/entity/common/PageData.java new file mode 100644 index 0000000..4f3c0d1 --- /dev/null +++ b/src/main/java/com/sipai/entity/common/PageData.java @@ -0,0 +1,37 @@ +package com.sipai.entity.common; + +import com.github.pagehelper.PageInfo; +import java.util.List; + +/** + * 分页数据封装类 + */ +public class PageData { + private long total; // 总记录数 + private int pageSize; // 每页大小 + private int pageNum; // 当前页码 + private int pages; // 总页数 + private List list; // 数据列表 + + public PageData() {} + + public PageData(PageInfo pageInfo) { + this.total = pageInfo.getTotal(); + this.pageSize = pageInfo.getPageSize(); + this.pageNum = pageInfo.getPageNum(); + this.pages = pageInfo.getPages(); + this.list = pageInfo.getList(); + } + + // getters and setters + public long getTotal() { return total; } + public void setTotal(long total) { this.total = total; } + public int getPageSize() { return pageSize; } + public void setPageSize(int pageSize) { this.pageSize = pageSize; } + public int getPageNum() { return pageNum; } + public void setPageNum(int pageNum) { this.pageNum = pageNum; } + public int getPages() { return pages; } + public void setPages(int pages) { this.pages = pages; } + public List getList() { return list; } + public void setList(List list) { this.list = list; } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/data/ChannelData.java b/src/main/java/com/sipai/entity/data/ChannelData.java new file mode 100644 index 0000000..62b71c4 --- /dev/null +++ b/src/main/java/com/sipai/entity/data/ChannelData.java @@ -0,0 +1,82 @@ +package com.sipai.entity.data; + +import java.util.List; + +/** + * 报文实体类 + * 频道数据 + */ +public class ChannelData { + private int type; // 类型 1-6 + private int channelNumber; // 通道号 + private String channelName; // 通道名称 P1, P2等 + private int yesterdayFlow; // 昨日流量 + private List cumulativeFlows; // 累计流量列表 + private List analogValues; // 模拟量数据(类型4) + private Integer qChannelData; // Q通道数据(类型5) + private Integer mChannelData; // M通道数据(类型6) + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + public int getChannelNumber() { + return channelNumber; + } + + public void setChannelNumber(int channelNumber) { + this.channelNumber = channelNumber; + } + + public String getChannelName() { + return channelName; + } + + public void setChannelName(String channelName) { + this.channelName = channelName; + } + + public int getYesterdayFlow() { + return yesterdayFlow; + } + + public void setYesterdayFlow(int yesterdayFlow) { + this.yesterdayFlow = yesterdayFlow; + } + + public List getCumulativeFlows() { + return cumulativeFlows; + } + + public void setCumulativeFlows(List cumulativeFlows) { + this.cumulativeFlows = cumulativeFlows; + } + + public List getAnalogValues() { + return analogValues; + } + + public void setAnalogValues(List analogValues) { + this.analogValues = analogValues; + } + + public Integer getqChannelData() { + return qChannelData; + } + + public void setqChannelData(Integer qChannelData) { + this.qChannelData = qChannelData; + } + + public Integer getmChannelData() { + return mChannelData; + } + + public void setmChannelData(Integer mChannelData) { + this.mChannelData = mChannelData; + } +} diff --git a/src/main/java/com/sipai/entity/data/DeviceData.java b/src/main/java/com/sipai/entity/data/DeviceData.java new file mode 100644 index 0000000..e0de66f --- /dev/null +++ b/src/main/java/com/sipai/entity/data/DeviceData.java @@ -0,0 +1,88 @@ +package com.sipai.entity.data; + +import java.util.List; + +public class DeviceData { + private int stationId; + private String startTime; + private int dataCount; + private int length; + private int intervalMinutes; + private float batteryVoltage; + private String deviceInfo; + + private int uploadCount; + private List sensorDataList; + + public int getUploadCount() { + return uploadCount; + } + + public void setUploadCount(int uploadCount) { + this.uploadCount = uploadCount; + } + + public int getLength() { + return length; + } + + public void setLength(int length) { + this.length = length; + } + + public int getStationId() { + return stationId; + } + + public void setStationId(int stationId) { + this.stationId = stationId; + } + + public String getStartTime() { + return startTime; + } + + public void setStartTime(String startTime) { + this.startTime = startTime; + } + + public int getDataCount() { + return dataCount; + } + + public void setDataCount(int dataCount) { + this.dataCount = dataCount; + } + + public int getIntervalMinutes() { + return intervalMinutes; + } + + public void setIntervalMinutes(int intervalMinutes) { + this.intervalMinutes = intervalMinutes; + } + + public float getBatteryVoltage() { + return batteryVoltage; + } + + public void setBatteryVoltage(float batteryVoltage) { + this.batteryVoltage = batteryVoltage; + } + + public String getDeviceInfo() { + return deviceInfo; + } + + public void setDeviceInfo(String deviceInfo) { + this.deviceInfo = deviceInfo; + } + + public List getSensorDataList() { + return sensorDataList; + } + + public void setSensorDataList(List sensorDataList) { + this.sensorDataList = sensorDataList; + } +} diff --git a/src/main/java/com/sipai/entity/data/DeviceDataPacket.java b/src/main/java/com/sipai/entity/data/DeviceDataPacket.java new file mode 100644 index 0000000..f04a42d --- /dev/null +++ b/src/main/java/com/sipai/entity/data/DeviceDataPacket.java @@ -0,0 +1,131 @@ +package com.sipai.entity.data; + +import java.time.LocalDateTime; +import java.util.Date; +import java.util.List; + +/** + * 报文实体类 + * 设备数据分组 + */ +public class DeviceDataPacket { + private String startCode; // 起始符 AB CD + private int length; // 长度 0x007D + private int stationId; // 站号 0x0066 + private LocalDateTime timestamp; // 年月日时分 11 05 24 16 15 + private int dataCount; // 数据个数 0x03 + private int interval; // 数据间隔(分钟) 0x15 + private float batteryVoltage; // 电池电压 7.18V + private int uploadCount; // 上发次数 5 + private int signalStrength; // 信号强度 0x1E + private String deviceInfo; // 设备信息 "D115 1.4 1.0.11" + private List channelDataList; // 通道数据列表 + private int checksum; // 校验和 + private String endCode; // 结束符 0D 0A + + public String getStartCode() { + return startCode; + } + + public void setStartCode(String startCode) { + this.startCode = startCode; + } + + public int getLength() { + return length; + } + + public void setLength(int length) { + this.length = length; + } + + public int getStationId() { + return stationId; + } + + public void setStationId(int stationId) { + this.stationId = stationId; + } + + public LocalDateTime getTimestamp() { + return timestamp; + } + + public void setTimestamp(LocalDateTime timestamp) { + this.timestamp = timestamp; + } + + public int getDataCount() { + return dataCount; + } + + public void setDataCount(int dataCount) { + this.dataCount = dataCount; + } + + public int getInterval() { + return interval; + } + + public void setInterval(int interval) { + this.interval = interval; + } + + public float getBatteryVoltage() { + return batteryVoltage; + } + + public void setBatteryVoltage(float batteryVoltage) { + this.batteryVoltage = batteryVoltage; + } + + public int getUploadCount() { + return uploadCount; + } + + public void setUploadCount(int uploadCount) { + this.uploadCount = uploadCount; + } + + public int getSignalStrength() { + return signalStrength; + } + + public void setSignalStrength(int signalStrength) { + this.signalStrength = signalStrength; + } + + public String getDeviceInfo() { + return deviceInfo; + } + + public void setDeviceInfo(String deviceInfo) { + this.deviceInfo = deviceInfo; + } + + public List getChannelDataList() { + return channelDataList; + } + + public void setChannelDataList(List channelDataList) { + this.channelDataList = channelDataList; + } + + public int getChecksum() { + return checksum; + } + + public void setChecksum(int checksum) { + this.checksum = checksum; + } + + public String getEndCode() { + return endCode; + } + + public void setEndCode(String endCode) { + this.endCode = endCode; + } +} + + diff --git a/src/main/java/com/sipai/entity/data/PipeTopicMpoint.java b/src/main/java/com/sipai/entity/data/PipeTopicMpoint.java new file mode 100644 index 0000000..d85b168 --- /dev/null +++ b/src/main/java/com/sipai/entity/data/PipeTopicMpoint.java @@ -0,0 +1,28 @@ +package com.sipai.entity.data; + +import com.sipai.entity.base.SQLAdapter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** + * 管网专题页点位信息实体类 + */ +@Data +public class PipeTopicMpoint extends SQLAdapter implements Serializable { + private Integer id; // 自增主键 + private String pointName; // 点位名称 + private String pointCode; // 点位编号 + private String type; // 所属类型 + private Integer isConstant; // 是否常量(0-否,1-是) + private String constantValue; // 常量值 + private Integer sortOrder; // 排序序号 + + @JsonIgnore + private String sql; + + @JsonIgnore + private String where; +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/data/PipelineEquipment.java b/src/main/java/com/sipai/entity/data/PipelineEquipment.java new file mode 100644 index 0000000..27a0401 --- /dev/null +++ b/src/main/java/com/sipai/entity/data/PipelineEquipment.java @@ -0,0 +1,32 @@ +package com.sipai.entity.data; + +import com.sipai.entity.base.SQLAdapter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * 管道设备实体类 + */ +@Data +public class PipelineEquipment extends SQLAdapter implements Serializable { + private Integer id; + private String stationCode;//站点编号 + private String equipmentType;//设备类型:井盖、流量计、液位计、电导率、雨量计、内涝监测 + private String productModel;//产品型号 + private Integer uploadCycle;//上传周期 + private String uploadCycleUnit;//上传周期 单位 + private String lastUploadTime;//最近一次上传数据时间 + private String status; //1在线 0离线 null为未检测 + + //用于查询对应的name + private String equipmentTypeName;//设备类型:井盖、流量计、液位计、电导率、雨量计、内涝监测 + + @JsonIgnore + private String sql; + + @JsonIgnore + private String where; +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/data/PipelineEquipmentMpoint.java b/src/main/java/com/sipai/entity/data/PipelineEquipmentMpoint.java new file mode 100644 index 0000000..f6ec426 --- /dev/null +++ b/src/main/java/com/sipai/entity/data/PipelineEquipmentMpoint.java @@ -0,0 +1,25 @@ +package com.sipai.entity.data; + +import com.sipai.entity.base.SQLAdapter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; + +import java.io.Serializable; + +/** + * 管道设备与测点关联实体类 + */ +@Data +public class PipelineEquipmentMpoint extends SQLAdapter implements Serializable { + private Integer id; + private Integer pid; // 关联 PipelineEquipment 的 id + private String mpcode; // 测点 + private String mpname; // 名称 + private String tag; // 编码 + + @JsonIgnore + private String sql; + + @JsonIgnore + private String where; +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/data/PipelineMpointLibrary.java b/src/main/java/com/sipai/entity/data/PipelineMpointLibrary.java new file mode 100644 index 0000000..cf997e4 --- /dev/null +++ b/src/main/java/com/sipai/entity/data/PipelineMpointLibrary.java @@ -0,0 +1,27 @@ +package com.sipai.entity.data; + +import com.sipai.entity.base.SQLAdapter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; + +import java.io.Serializable; + +/** + * 管道测点 库(这边维护好,设备那边可以直接导入) + * sj 2025-06-18 + */ +@Data +public class PipelineMpointLibrary extends SQLAdapter implements Serializable { + private String id; + private String equipmentType; + private String code; + private String name; + private Integer morder; + + // 用于查询对应的name + @JsonIgnore + private String sql; + + @JsonIgnore + private String where; +} diff --git a/src/main/java/com/sipai/entity/data/SensorData.java b/src/main/java/com/sipai/entity/data/SensorData.java new file mode 100644 index 0000000..13a80ca --- /dev/null +++ b/src/main/java/com/sipai/entity/data/SensorData.java @@ -0,0 +1,120 @@ +package com.sipai.entity.data; + +import com.sipai.tools.AlarmType; + +import java.util.List; +import java.util.Map; + +public class SensorData { + private int type; // 1-脉冲量, 2-开关量, 3-报警量, 4-模拟量, 5-Q通道, 6-M通道 + private int channel; + + // 脉冲量特有 + private long yesterdayFlow; + private List accumulatedFlows; + + private int qValue; // 原始Q通道值 + private Map alarmStatus; // 报警状态映射 + + // 开关量/报警量 + private List statusList; + + // 模拟量 + private List analogValues; + + // Q通道 + private List qValues; + + // M通道 + private List mValues; + + private String description; + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + public int getChannel() { + return channel; + } + + public void setChannel(int channel) { + this.channel = channel; + } + + public long getYesterdayFlow() { + return yesterdayFlow; + } + + public void setYesterdayFlow(long yesterdayFlow) { + this.yesterdayFlow = yesterdayFlow; + } + + public List getAccumulatedFlows() { + return accumulatedFlows; + } + + public void setAccumulatedFlows(List accumulatedFlows) { + this.accumulatedFlows = accumulatedFlows; + } + + public List getStatusList() { + return statusList; + } + + public void setStatusList(List statusList) { + this.statusList = statusList; + } + + public List getAnalogValues() { + return analogValues; + } + + public void setAnalogValues(List analogValues) { + this.analogValues = analogValues; + } + + public List getqValues() { + return qValues; + } + + public void setqValues(List qValues) { + this.qValues = qValues; + } + + public List getmValues() { + return mValues; + } + + public void setmValues(List mValues) { + this.mValues = mValues; + } + + public int getqValue() { + return qValue; + } + + public void setqValue(int qValue) { + this.qValue = qValue; + } + + public Map getAlarmStatus() { + return alarmStatus; + } + + public void setAlarmStatus(Map alarmStatus) { + this.alarmStatus = alarmStatus; + } +} diff --git a/src/main/java/com/sipai/entity/enums/DeviceTypeEnum.java b/src/main/java/com/sipai/entity/enums/DeviceTypeEnum.java new file mode 100644 index 0000000..dc058ed --- /dev/null +++ b/src/main/java/com/sipai/entity/enums/DeviceTypeEnum.java @@ -0,0 +1,71 @@ +package com.sipai.entity.enums; + +public enum DeviceTypeEnum { + // 枚举常量,对应下拉框中的类型 + MANHOLE_COVER("井盖", "1"), + FLOW_METER("流量计", "2"), + LIQUID_LEVEL_METER("液位计", "3"), + CONDUCTIVITY("电导率", "4"), + RAIN_GAUGE("雨量计", "5"), + WATERLOGGING_DETECTION("内涝检测", "6"); + + // 类型名称 + private final String typeName; + // 类型编码 + private final String typeCode; + + /** + * 构造方法 + * @param typeName 类型名称 + * @param typeCode 类型编码 + */ + DeviceTypeEnum(String typeName, String typeCode) { + this.typeName = typeName; + this.typeCode = typeCode; + } + + /** + * 获取类型名称 + * @return 类型名称 + */ + public String getTypeName() { + return typeName; + } + + /** + * 获取类型编码 + * @return 类型编码 + */ + public String getTypeCode() { + return typeCode; + } + + // 也可根据需求添加根据名称或编码获取枚举常量的方法,示例如下: + /** + * 根据类型名称获取枚举常量 + * @param typeName 类型名称 + * @return 对应的枚举常量,若未找到返回 null + */ + public static DeviceTypeEnum getByTypeName(String typeName) { + for (DeviceTypeEnum enumConstant : DeviceTypeEnum.values()) { + if (enumConstant.getTypeName().equals(typeName)) { + return enumConstant; + } + } + return null; + } + + /** + * 根据类型编码获取枚举常量 + * @param typeCode 类型编码 + * @return 对应的枚举常量,若未找到返回 null + */ + public static DeviceTypeEnum getByTypeCode(String typeCode) { + for (DeviceTypeEnum enumConstant : DeviceTypeEnum.values()) { + if (enumConstant.getTypeCode().equals(typeCode)) { + return enumConstant; + } + } + return null; + } +} diff --git a/src/main/java/com/sipai/entity/mqtt/Mqtt.java b/src/main/java/com/sipai/entity/mqtt/Mqtt.java new file mode 100644 index 0000000..4548a1a --- /dev/null +++ b/src/main/java/com/sipai/entity/mqtt/Mqtt.java @@ -0,0 +1,16 @@ +package com.sipai.entity.mqtt; + +import org.springframework.beans.factory.annotation.Autowired; + +/** + * 用于配置emqx的常量 和 提供云平台的一些接口 如指令下发,获取网关在线状态等 + * sj 2021-05-27 + */ +public class Mqtt { + + /*public static String BrokerAddress = "tcp://192.168.10.17:1883"; + public static String Dashboard_01 = "http://192.168.10.17:18083"; + + public static String Username = "admin"; + public static String Password = "sipai@64368180";*/ +} diff --git a/src/main/java/com/sipai/entity/mqtt/MqttConfig.java b/src/main/java/com/sipai/entity/mqtt/MqttConfig.java new file mode 100644 index 0000000..9996283 --- /dev/null +++ b/src/main/java/com/sipai/entity/mqtt/MqttConfig.java @@ -0,0 +1,102 @@ +package com.sipai.entity.mqtt; + +import com.sipai.entity.base.SQLAdapter; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/03/24/16:26 + * @Description: mqtt配置主表 + */ +public class MqttConfig extends SQLAdapter { + private String id; + + private String insdt; + + private String clientId; + + private String clientName; + + private String brokerIp; + + private String tomcatPort; + + private String username; + + private String password; + + private Integer morder; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getInsdt() { + return insdt; + } + + public void setInsdt(String insdt) { + this.insdt = insdt; + } + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getClientName() { + return clientName; + } + + public void setClientName(String clientName) { + this.clientName = clientName; + } + + public String getBrokerIp() { + return brokerIp; + } + + public void setBrokerIp(String brokerIp) { + this.brokerIp = brokerIp; + } + + public String getTomcatPort() { + return tomcatPort; + } + + public void setTomcatPort(String tomcatPort) { + this.tomcatPort = tomcatPort; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Integer getMorder() { + return morder; + } + + public void setMorder(Integer morder) { + this.morder = morder; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/mqtt/MqttConfigTopic.java b/src/main/java/com/sipai/entity/mqtt/MqttConfigTopic.java new file mode 100644 index 0000000..881515a --- /dev/null +++ b/src/main/java/com/sipai/entity/mqtt/MqttConfigTopic.java @@ -0,0 +1,72 @@ +package com.sipai.entity.mqtt; + +import com.sipai.entity.base.SQLAdapter; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/03/24/16:26 + * @Description: mqtt配置副表 + */ +public class MqttConfigTopic extends SQLAdapter { + private String id; + + private String name; + + private String topic; + + private String status; + + private String pid; + + private Integer morder; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id == null ? null : id.trim(); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name == null ? null : name.trim(); + } + + public String getTopic() { + return topic; + } + + public void setTopic(String topic) { + this.topic = topic == null ? null : topic.trim(); + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status == null ? null : status.trim(); + } + + public String getPid() { + return pid; + } + + public void setPid(String pid) { + this.pid = pid == null ? null : pid.trim(); + } + + public Integer getMorder() { + return morder; + } + + public void setMorder(Integer morder) { + this.morder = morder; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/mqtt/MqttProperties.java b/src/main/java/com/sipai/entity/mqtt/MqttProperties.java new file mode 100644 index 0000000..022ad46 --- /dev/null +++ b/src/main/java/com/sipai/entity/mqtt/MqttProperties.java @@ -0,0 +1,45 @@ +package com.sipai.entity.mqtt; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix = "mqtt") +public class MqttProperties { + private String brokerAddress; // 对应原 BrokerAddress + private String dashboard01; // 对应原 Dashboard_01 + private String username; // 对应原 Username + private String password; // 对应原 Password + + public String getBrokerAddress() { + return brokerAddress; + } + + public void setBrokerAddress(String brokerAddress) { + this.brokerAddress = brokerAddress; + } + + public String getDashboard01() { + return dashboard01; + } + + public void setDashboard01(String dashboard01) { + this.dashboard01 = dashboard01; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/src/main/java/com/sipai/entity/scada/MPoint.java b/src/main/java/com/sipai/entity/scada/MPoint.java new file mode 100644 index 0000000..609bdce --- /dev/null +++ b/src/main/java/com/sipai/entity/scada/MPoint.java @@ -0,0 +1,608 @@ +package com.sipai.entity.scada; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.sipai.entity.base.SQLAdapter; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Mapping; +import org.springframework.data.elasticsearch.annotations.Setting; +import org.springframework.stereotype.Component; + +import java.io.Serializable; +import java.math.BigDecimal; + + +@Mapping(mappingPath = "mpoint_search_mapping.json") +@Setting(settingPath = "mpoint_search_setting.json") +@Document(indexName = "es_measurepoint", type = "esmeasurepoint") +@Component +public class MPoint extends SQLAdapter implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -7579438089469008076L; + public static String Flag_Enable = "1"; + public static String Flag_Disable = "0"; + + public static String Flag_Sql = "sql"; + public static String Flag_Modbus = "modbus"; + public static String Flag_LinkData = "link"; + + public static String Flag_Type_CAL = "CAL";//单元格计算测量点 + public static String Flag_Type_KPI = "KPI";//KPI测量�? + public static String Flag_Type_Data = "data"; + public static String Flag_Type_Hand = "hand";//手动测量�? + public static String Flag_Type_Auto = "auto";//自动转发测量�? + + public static String Flag_BizType_Hand = "Manual"; + public static String Flag_BizType_Auto = "auto";//自动转发 + + private String chineseValue;//测量点�? valuemeaning对应的中文�? + + @Id + private String id; + private String mpointid; + private String mpointcode; + private String parmname; + private String unit; + private BigDecimal alarmmax; + private BigDecimal alarmmin; + private BigDecimal parmvalue; + //@Field(type = FieldType.Date) + private String measuredt; + private BigDecimal rate; + private Integer freq; + private String frequnit; + private String signaltype; + @JsonProperty("signaltag") + private String signaltag; + private String ledtype; + private String ledcolor; + private String directtype; + private String bizid; + private String biztype; + private String numtail; + private String prochour; + private String procday; + private String procmonth; + private String showname; + private String exp; + private BigDecimal forcemin; + private BigDecimal forcemax; + private BigDecimal avgmax; + private BigDecimal avgmin; + private String remoteup; + private Integer morder; + private String triggeralarm; + private String confirmalarm; + private BigDecimal flowset; + private String triggercycle; + private BigDecimal cyclemax; + private BigDecimal cyclemin; + private String triggermutation; + private BigDecimal mutationset; + private BigDecimal causeset; + private BigDecimal operateset; + private BigDecimal resultset; + private String triggerequoff; + private String mathop; + private String valuetype; + private String valuemeaning; + private String active; + private String soundalarm; + private String scdtype; + private BigDecimal spanrange; + private String modbusfigid; + private String register; + private String processsectioncode; + private String equipmentid; + @JsonProperty("source_type") + private String sourceType; + @JsonProperty("patrol_type") + private String patrolType; + private String remark; + private Integer alarmLevel; + + private String bizname; + private String disname; + + private int subscriptionStatus; + + public String getChineseValue() { + return chineseValue; + } + + public void setChineseValue(String chineseValue) { + this.chineseValue = chineseValue; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getMpointid() { + return mpointid; + } + + public void setMpointid(String mpointid) { + this.mpointid = mpointid; + } + + public String getMpointcode() { + return mpointcode; + } + + public void setMpointcode(String mpointcode) { + this.mpointcode = mpointcode; + } + + public String getParmname() { + return parmname; + } + + public void setParmname(String parmname) { + this.parmname = parmname; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + + public BigDecimal getAlarmmax() { + return alarmmax; + } + + public void setAlarmmax(BigDecimal alarmmax) { + this.alarmmax = alarmmax; + } + + public BigDecimal getAlarmmin() { + return alarmmin; + } + + public void setAlarmmin(BigDecimal alarmmin) { + this.alarmmin = alarmmin; + } + + public BigDecimal getParmvalue() { + return parmvalue; + } + + public void setParmvalue(BigDecimal parmvalue) { + this.parmvalue = parmvalue; + } + + public String getMeasuredt() { + return measuredt; + } + + public void setMeasuredt(String measuredt) { + this.measuredt = measuredt; + } + + public BigDecimal getRate() { + return rate; + } + + public void setRate(BigDecimal rate) { + this.rate = rate; + } + + public Integer getFreq() { + return freq; + } + + public void setFreq(Integer freq) { + this.freq = freq; + } + + public String getFrequnit() { + return frequnit; + } + + public void setFrequnit(String frequnit) { + this.frequnit = frequnit; + } + + public String getSignaltype() { + return signaltype; + } + + public void setSignaltype(String signaltype) { + this.signaltype = signaltype; + } + + public String getSignaltag() { + return signaltag; + } + + public void setSignaltag(String signaltag) { + this.signaltag = signaltag; + } + + public String getLedtype() { + return ledtype; + } + + public void setLedtype(String ledtype) { + this.ledtype = ledtype; + } + + public String getLedcolor() { + return ledcolor; + } + + public void setLedcolor(String ledcolor) { + this.ledcolor = ledcolor; + } + + public String getDirecttype() { + return directtype; + } + + public void setDirecttype(String directtype) { + this.directtype = directtype; + } + + public String getBizid() { + return bizid; + } + + public void setBizid(String bizid) { + this.bizid = bizid; + } + + public String getBiztype() { + return biztype; + } + + public void setBiztype(String biztype) { + this.biztype = biztype; + } + + public String getNumtail() { + return numtail; + } + + public void setNumtail(String numtail) { + this.numtail = numtail; + } + + public String getProchour() { + return prochour; + } + + public void setProchour(String prochour) { + this.prochour = prochour; + } + + public String getProcday() { + return procday; + } + + public void setProcday(String procday) { + this.procday = procday; + } + + public String getProcmonth() { + return procmonth; + } + + public void setProcmonth(String procmonth) { + this.procmonth = procmonth; + } + + public String getShowname() { + return showname; + } + + public void setShowname(String showname) { + this.showname = showname; + } + + public String getExp() { + return exp; + } + + public void setExp(String exp) { + this.exp = exp; + } + + public BigDecimal getForcemin() { + return forcemin; + } + + public void setForcemin(BigDecimal forcemin) { + this.forcemin = forcemin; + } + + public BigDecimal getForcemax() { + return forcemax; + } + + public void setForcemax(BigDecimal forcemax) { + this.forcemax = forcemax; + } + + public BigDecimal getAvgmax() { + return avgmax; + } + + public void setAvgmax(BigDecimal avgmax) { + this.avgmax = avgmax; + } + + public BigDecimal getAvgmin() { + return avgmin; + } + + public void setAvgmin(BigDecimal avgmin) { + this.avgmin = avgmin; + } + + public String getRemoteup() { + return remoteup; + } + + public void setRemoteup(String remoteup) { + this.remoteup = remoteup; + } + + public Integer getMorder() { + return morder; + } + + public void setMorder(Integer morder) { + this.morder = morder; + } + + public String getTriggeralarm() { + return triggeralarm; + } + + public void setTriggeralarm(String triggeralarm) { + this.triggeralarm = triggeralarm; + } + + public String getConfirmalarm() { + return confirmalarm; + } + + public void setConfirmalarm(String confirmalarm) { + this.confirmalarm = confirmalarm; + } + + public BigDecimal getFlowset() { + return flowset; + } + + public void setFlowset(BigDecimal flowset) { + this.flowset = flowset; + } + + public String getTriggercycle() { + return triggercycle; + } + + public void setTriggercycle(String triggercycle) { + this.triggercycle = triggercycle; + } + + public BigDecimal getCyclemax() { + return cyclemax; + } + + public void setCyclemax(BigDecimal cyclemax) { + this.cyclemax = cyclemax; + } + + public BigDecimal getCyclemin() { + return cyclemin; + } + + public void setCyclemin(BigDecimal cyclemin) { + this.cyclemin = cyclemin; + } + + public String getTriggermutation() { + return triggermutation; + } + + public void setTriggermutation(String triggermutation) { + this.triggermutation = triggermutation; + } + + public BigDecimal getMutationset() { + return mutationset; + } + + public void setMutationset(BigDecimal mutationset) { + this.mutationset = mutationset; + } + + public BigDecimal getCauseset() { + return causeset; + } + + public void setCauseset(BigDecimal causeset) { + this.causeset = causeset; + } + + public BigDecimal getOperateset() { + return operateset; + } + + public void setOperateset(BigDecimal operateset) { + this.operateset = operateset; + } + + public BigDecimal getResultset() { + return resultset; + } + + public void setResultset(BigDecimal resultset) { + this.resultset = resultset; + } + + public String getTriggerequoff() { + return triggerequoff; + } + + public void setTriggerequoff(String triggerequoff) { + this.triggerequoff = triggerequoff; + } + + public String getMathop() { + return mathop; + } + + public void setMathop(String mathop) { + this.mathop = mathop; + } + + public String getValuetype() { + return valuetype; + } + + public void setValuetype(String valuetype) { + this.valuetype = valuetype; + } + + public String getValuemeaning() { + return valuemeaning; + } + + public void setValuemeaning(String valuemeaning) { + this.valuemeaning = valuemeaning; + } + + public String getActive() { + return active; + } + + public void setActive(String active) { + this.active = active; + } + + public String getSoundalarm() { + return soundalarm; + } + + public void setSoundalarm(String soundalarm) { + this.soundalarm = soundalarm; + } + + public String getScdtype() { + return scdtype; + } + + public void setScdtype(String scdtype) { + this.scdtype = scdtype; + } + + public BigDecimal getSpanrange() { + return spanrange; + } + + public void setSpanrange(BigDecimal spanrange) { + this.spanrange = spanrange; + } + + public String getModbusfigid() { + return modbusfigid; + } + + public void setModbusfigid(String modbusfigid) { + this.modbusfigid = modbusfigid; + } + + public String getRegister() { + return register; + } + + public void setRegister(String register) { + this.register = register; + } + + public String getProcesssectioncode() { + return processsectioncode; + } + + public void setProcesssectioncode(String processsectioncode) { + this.processsectioncode = processsectioncode; + } + + public String getEquipmentid() { + return equipmentid; + } + + public void setEquipmentid(String equipmentid) { + this.equipmentid = equipmentid; + } + + public String getSourceType() { + return sourceType; + } + + public void setSourceType(String sourceType) { + this.sourceType = sourceType; + } + + public String getPatrolType() { + return patrolType; + } + + public void setPatrolType(String patrolType) { + this.patrolType = patrolType; + } + + public String getRemark() { + return remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } + + public Integer getAlarmLevel() { + return alarmLevel; + } + + public void setAlarmLevel(Integer alarmLevel) { + this.alarmLevel = alarmLevel; + } + + public String getBizname() { + return bizname; + } + + public void setBizname(String bizname) { + this.bizname = bizname; + } + + public String getDisname() { + return disname; + } + + public void setDisname(String disname) { + this.disname = disname; + } + + public int getSubscriptionStatus() { + return subscriptionStatus; + } + + public void setSubscriptionStatus(int subscriptionStatus) { + this.subscriptionStatus = subscriptionStatus; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/scada/MPointBzw.java b/src/main/java/com/sipai/entity/scada/MPointBzw.java new file mode 100644 index 0000000..b21cacf --- /dev/null +++ b/src/main/java/com/sipai/entity/scada/MPointBzw.java @@ -0,0 +1,57 @@ +package com.sipai.entity.scada; + +import com.sipai.entity.base.SQLAdapter; + +import java.io.Serializable; + +/** + * 测点标识对照表实体类 + */ +public class MPointBzw extends SQLAdapter implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 测点ID + */ + private String mpointId; + + /** + * 测点标识ID + */ + private String mpointbzwId; + + // 无参构造器 + public MPointBzw() { + } + + // 全参构造器 + public MPointBzw(String mpointId, String mpointbzwId) { + this.mpointId = mpointId; + this.mpointbzwId = mpointbzwId; + } + + // Getters and Setters + public String getMpointId() { + return mpointId; + } + + public void setMpointId(String mpointId) { + this.mpointId = mpointId; + } + + public String getMpointbzwId() { + return mpointbzwId; + } + + public void setMpointbzwId(String mpointbzwId) { + this.mpointbzwId = mpointbzwId; + } + + @Override + public String toString() { + return "MPointBzw{" + + "mpointId='" + mpointId + '\'' + + ", mpointbzwId='" + mpointbzwId + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/scada/MPointES.java b/src/main/java/com/sipai/entity/scada/MPointES.java new file mode 100644 index 0000000..97497b7 --- /dev/null +++ b/src/main/java/com/sipai/entity/scada/MPointES.java @@ -0,0 +1,42 @@ +package com.sipai.entity.scada; + + +import com.alibaba.fastjson.JSON; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + + +public class MPointES extends MPoint { + + private static final long serialVersionUID = -4222932639259909065L; + private String source_type; + + public String getSource_type() { + return source_type; + } + + public void setSource_type(String source_type) { + this.source_type = source_type; + } + + + public static MPointES format(MPoint mPoint) { + String str = JSON.toJSONString(mPoint); + MPointES mPointES = JSON.parseObject(str, MPointES.class); + mPointES.setSource_type(mPoint.getSourceType()); + //时间格式处理 + DateTimeFormatter dfES = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"); + DateTimeFormatter dfSQL = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + if (mPoint.getMeasuredt() != null) { + try { + LocalDateTime confirmTime = LocalDateTime.parse(mPoint.getMeasuredt().substring(0, 19), dfSQL); + String confirmTimeStr = dfES.format(confirmTime); + mPointES.setMeasuredt(confirmTimeStr); + } catch (Exception e) { + + } + } + return mPointES; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/scada/MPointHistory.java b/src/main/java/com/sipai/entity/scada/MPointHistory.java new file mode 100644 index 0000000..567c043 --- /dev/null +++ b/src/main/java/com/sipai/entity/scada/MPointHistory.java @@ -0,0 +1,154 @@ +package com.sipai.entity.scada; + +import com.sipai.entity.base.SQLAdapter; +import java.io.Serializable; +import java.math.BigDecimal; + +public class MPointHistory extends SQLAdapter implements Serializable{ + /** + * + */ + private static final long serialVersionUID = 4552977217414444717L; + + private Long itemid; + + private BigDecimal parmvalue; + + private String measuredt; + + private String memotype; + + private String memo; + + private String userid; + + private String insdt; + + private String tbName; + + private short tag;//标志位值 + + //为报表展示使用 CPELM + private String year; + private String month; + private String day; + private String hour; + private String min; + + public short getTag() { + return tag; + } + + public void setTag(short tag) { + this.tag = tag; + } + + public Long getItemid() { + return itemid; + } + + public void setItemid(Long itemid) { + this.itemid = itemid; + } + + public BigDecimal getParmvalue() { + return parmvalue; + } + + public void setParmvalue(BigDecimal parmvalue) { + this.parmvalue = parmvalue; + } + + public String getMeasuredt() { + return measuredt; + } + + public void setMeasuredt(String measuredt) { + this.measuredt = measuredt; + } + + public String getMemotype() { + return memotype; + } + + public void setMemotype(String memotype) { + this.memotype = memotype; + } + + public String getMemo() { + return memo; + } + + public void setMemo(String memo) { + this.memo = memo; + } + + public String getUserid() { + return userid; + } + + public void setUserid(String userid) { + this.userid = userid; + } + + public String getInsdt() { + return insdt; + } + + public void setInsdt(String insdt) { + this.insdt = insdt; + } + + public String getTbName() { + return tbName; + } + + public void setTbName(String tbName) { + this.tbName = tbName; + } + + public String getYear() { + return year; + } + + public void setYear(String year) { + this.year = year; + } + + public String getMonth() { + return month; + } + + public void setMonth(String month) { + this.month = month; + } + + public String getDay() { + return day; + } + + public void setDay(String day) { + this.day = day; + } + + public String getHour() { + return hour; + } + + public void setHour(String hour) { + this.hour = hour; + } + + public String getMin() { + return min; + } + + public void setMin(String min) { + this.min = min; + } + + public static long getSerialversionuid() { + return serialVersionUID; + } + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/user/Company.java b/src/main/java/com/sipai/entity/user/Company.java new file mode 100644 index 0000000..47caaac --- /dev/null +++ b/src/main/java/com/sipai/entity/user/Company.java @@ -0,0 +1,201 @@ +package com.sipai.entity.user; + +import com.sipai.entity.base.SQLAdapter; + +import java.math.BigDecimal; + +/** + * 公司表 + */ +public class Company extends SQLAdapter { + + private String id; + + private String name; + + private String pid; + + private String address; + + private String tel; + + private String website; + + private String taskid; + + private String post; + + private String insdt; + + private String insuser; + + private Integer version; + + private Integer morder; + + private String sname; + + private String active; + + private String type; + + private String ename; + + private BigDecimal longitude; + + private BigDecimal latitude; + + private String isCount; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getPid() { + return pid; + } + + public void setPid(String pid) { + this.pid = pid; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getTel() { + return tel; + } + + public void setTel(String tel) { + this.tel = tel; + } + + public String getWebsite() { + return website; + } + + public void setWebsite(String website) { + this.website = website; + } + + public String getTaskid() { + return taskid; + } + + public void setTaskid(String taskid) { + this.taskid = taskid; + } + + public String getPost() { + return post; + } + + public void setPost(String post) { + this.post = post; + } + + public String getInsdt() { + return insdt; + } + + public void setInsdt(String insdt) { + this.insdt = insdt; + } + + public String getInsuser() { + return insuser; + } + + public void setInsuser(String insuser) { + this.insuser = insuser; + } + + public Integer getVersion() { + return version; + } + + public void setVersion(Integer version) { + this.version = version; + } + + public Integer getMorder() { + return morder; + } + + public void setMorder(Integer morder) { + this.morder = morder; + } + + public String getSname() { + return sname; + } + + public void setSname(String sname) { + this.sname = sname; + } + + public String getActive() { + return active; + } + + public void setActive(String active) { + this.active = active; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getEname() { + return ename; + } + + public void setEname(String ename) { + this.ename = ename; + } + + public BigDecimal getLongitude() { + return longitude; + } + + public void setLongitude(BigDecimal longitude) { + this.longitude = longitude; + } + + public BigDecimal getLatitude() { + return latitude; + } + + public void setLatitude(BigDecimal latitude) { + this.latitude = latitude; + } + + public String getIsCount() { + return isCount; + } + + public void setIsCount(String isCount) { + this.isCount = isCount; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/user/User.java b/src/main/java/com/sipai/entity/user/User.java new file mode 100644 index 0000000..1195bde --- /dev/null +++ b/src/main/java/com/sipai/entity/user/User.java @@ -0,0 +1,36 @@ +package com.sipai.entity.user; + +import com.sipai.entity.base.SQLAdapter; + +/** + * 人员表 + */ +public class User extends SQLAdapter { + private String id; + private String userName; + private String passWord; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getPassWord() { + return passWord; + } + + public void setPassWord(String passWord) { + this.passWord = passWord; + } +} diff --git a/src/main/java/com/sipai/schedule/DataSynJob.java b/src/main/java/com/sipai/schedule/DataSynJob.java new file mode 100644 index 0000000..881b788 --- /dev/null +++ b/src/main/java/com/sipai/schedule/DataSynJob.java @@ -0,0 +1,73 @@ +package com.sipai.schedule; + +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointHistory; +import com.sipai.service.mqtt.MqttConfigService; +import com.sipai.service.opc.InitOpcUaService; +import com.sipai.service.scada.MPointHistoryService; +import com.sipai.service.scada.MPointService; +import com.sipai.tools.CommUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import java.util.*; + +/** + * 定时将总表数据插入到子表 + */ +@Service +public class DataSynJob { + @Autowired + private MPointService mPointService; + @Autowired + private MPointHistoryService mPointHistoryService; + @Autowired + private MqttConfigService mqttConfigService; + @Autowired + private InitOpcUaService initOpcUaService; + + //定时器yml配置是否启动 + @Value("${scheduled.enabled:true}") + private boolean scheduledEnabled; + + // @Scheduled(fixedRate = 3600000) // 同步一次opcua的订阅 + public void syncSubscriptions() { + initOpcUaService.manualSyncSubscriptions(); + } + + @Async + @Scheduled(initialDelay = 10000, fixedRate = 600000)//自动订阅mqtt + public void job1() { + if (!scheduledEnabled) return; // 手动拦截 + System.out.println("自动订阅========" + CommUtil.nowDate()); + mqttConfigService.connect("1"); + } + + @Async +// @Scheduled(cron = "0 0/3 * * * ?")//数据转发 + public void job2() { + if (!scheduledEnabled) return; // 手动拦截 + String addstr = "zhuanfa"; + System.out.println("开始定时器-----------------" + CommUtil.nowDate() + "-----------------" + addstr); + List list2 = this.mPointService.selectListByWhere("where bizid = '0791CNWS' and SignalType='AI' and MeasureDT>DATE_SUB(NOW(), INTERVAL 5 MINUTE) and source_type='auto' "); + if (list2 != null && list2.size() > 0) { + for (int j = 0; j < list2.size(); ++j) { + MPointHistory mPointHistory = new MPointHistory(); + mPointHistory.setParmvalue(list2.get(j).getParmvalue()); + mPointHistory.setMeasuredt(list2.get(j).getMeasuredt()); + mPointHistory.setTbName(list2.get(j).getMpointcode()); + mPointHistory.setUserid("data_job"); + mPointHistory.setInsdt(CommUtil.nowDate()); + mPointHistoryService.saveByCreate(list2.get(j).getBizid(), mPointHistory); + } + System.out.println("完成一次(有数据)转发,执行了" + list2.size() + "次点"); + } else { + System.out.println("完成一次(无数据)转发,执行了" + 0 + "次点"); + } + System.out.println("结束定时器-----------------" + CommUtil.nowDate()); + } + +} diff --git a/src/main/java/com/sipai/service/Listener/ListenerHisService.java b/src/main/java/com/sipai/service/Listener/ListenerHisService.java new file mode 100644 index 0000000..c863d5e --- /dev/null +++ b/src/main/java/com/sipai/service/Listener/ListenerHisService.java @@ -0,0 +1,23 @@ +package com.sipai.service.Listener; + +import com.sipai.entity.Listener.ListenerHis; + +import java.util.List; + +public interface ListenerHisService { + + public abstract ListenerHis selectById(String id); + + public abstract int deleteById(String id); + + public abstract int save(ListenerHis entity); + + public abstract int update(ListenerHis entity); + + public abstract List selectListByWhere(String wherestr); + + public abstract int deleteByWhere(String wherestr); + + public abstract List selectTopByWhere(String wherestr); + +} diff --git a/src/main/java/com/sipai/service/Listener/ListenerInterfaceService.java b/src/main/java/com/sipai/service/Listener/ListenerInterfaceService.java new file mode 100644 index 0000000..cdc2c9a --- /dev/null +++ b/src/main/java/com/sipai/service/Listener/ListenerInterfaceService.java @@ -0,0 +1,22 @@ +package com.sipai.service.Listener; + + +import com.sipai.entity.Listener.ListenerInterface; + +import java.util.List; + +public interface ListenerInterfaceService { + + public abstract ListenerInterface selectById(String id); + + public abstract int deleteById(String id); + + public abstract int save(ListenerInterface entity); + + public abstract int update(ListenerInterface entity); + + public abstract List selectListByWhere(String wherestr); + + public abstract int deleteByWhere(String wherestr); + +} diff --git a/src/main/java/com/sipai/service/Listener/ListenerMessageService.java b/src/main/java/com/sipai/service/Listener/ListenerMessageService.java new file mode 100644 index 0000000..2e731fb --- /dev/null +++ b/src/main/java/com/sipai/service/Listener/ListenerMessageService.java @@ -0,0 +1,24 @@ +package com.sipai.service.Listener; + +import com.sipai.entity.Listener.ListenerMessage; + +import java.util.List; + +public interface ListenerMessageService { + + public abstract ListenerMessage selectById(String id); + + public abstract int deleteById(String id); + + public abstract int save(ListenerMessage entity); + + public abstract int update(ListenerMessage entity); + + public abstract List selectListByWhere(String wherestr); + + //带入设备编号查询 + public abstract List selectListByWhere4Equ(String wherestr, String equipmentId); + + public abstract int deleteByWhere(String wherestr); + +} diff --git a/src/main/java/com/sipai/service/Listener/ListenerPointService.java b/src/main/java/com/sipai/service/Listener/ListenerPointService.java new file mode 100644 index 0000000..209c446 --- /dev/null +++ b/src/main/java/com/sipai/service/Listener/ListenerPointService.java @@ -0,0 +1,22 @@ +package com.sipai.service.Listener; + + +import com.sipai.entity.Listener.ListenerPoint; + +import java.util.List; + +public interface ListenerPointService { + + public abstract ListenerPoint selectById(String id); + + public abstract int deleteById(String id); + + public abstract int save(ListenerPoint entity); + + public abstract int update(ListenerPoint entity); + + public abstract List selectListByWhere(String wherestr); + + public abstract int deleteByWhere(String wherestr); + +} diff --git a/src/main/java/com/sipai/service/Listener/impl/ListenerHisServiceImpl.java b/src/main/java/com/sipai/service/Listener/impl/ListenerHisServiceImpl.java new file mode 100644 index 0000000..ba34280 --- /dev/null +++ b/src/main/java/com/sipai/service/Listener/impl/ListenerHisServiceImpl.java @@ -0,0 +1,62 @@ +package com.sipai.service.Listener.impl; + +import com.sipai.dao.Listener.ListenerHisDao; +import com.sipai.entity.Listener.ListenerHis; +import com.sipai.service.Listener.ListenerHisService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +@Service("listenerHisService") +public class ListenerHisServiceImpl implements ListenerHisService { + + @Resource + public ListenerHisDao listenerHisDao; + + @Override + public ListenerHis selectById(String id) { + ListenerHis listenerHis = listenerHisDao.selectByPrimaryKey(id); + return listenerHis; + } + + @Override + public int deleteById(String id) { + int i = listenerHisDao.deleteByPrimaryKey(id); + return i; + } + + @Override + public int save(ListenerHis entity) { + int insert = listenerHisDao.insert(entity); + return insert; + } + + @Override + public int update(ListenerHis entity) { + int i = listenerHisDao.updateByPrimaryKeySelective(entity); + return i; + } + + @Override + public List selectListByWhere(String wherestr) { + ListenerHis listenerHis = new ListenerHis(); + listenerHis.setWhere(wherestr); + List listenerHiss = listenerHisDao.selectListByWhere(listenerHis); + return listenerHiss; + } + + @Override + public int deleteByWhere(String wherestr) { + ListenerHis listenerHis = new ListenerHis(); + listenerHis.setWhere(wherestr); + int i = listenerHisDao.deleteByWhere(listenerHis); + return i; + } + + @Override + public List selectTopByWhere(String wherestr) { + List listenerHis = listenerHisDao.selectTopByWhere(wherestr); + return listenerHis; + } +} diff --git a/src/main/java/com/sipai/service/Listener/impl/ListenerInterfaceServiceImpl.java b/src/main/java/com/sipai/service/Listener/impl/ListenerInterfaceServiceImpl.java new file mode 100644 index 0000000..92b823a --- /dev/null +++ b/src/main/java/com/sipai/service/Listener/impl/ListenerInterfaceServiceImpl.java @@ -0,0 +1,56 @@ +package com.sipai.service.Listener.impl; + +import com.sipai.dao.Listener.ListenerInterfaceDao; +import com.sipai.entity.Listener.ListenerInterface; +import com.sipai.service.Listener.ListenerInterfaceService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +@Service("listenerInterfaceService") +public class ListenerInterfaceServiceImpl implements ListenerInterfaceService { + + @Resource + public ListenerInterfaceDao listenerInterfaceDao; + + @Override + public ListenerInterface selectById(String id) { + ListenerInterface listenerInterface = listenerInterfaceDao.selectByPrimaryKey(id); + return listenerInterface; + } + + @Override + public int deleteById(String id) { + int i = listenerInterfaceDao.deleteByPrimaryKey(id); + return i; + } + + @Override + public int save(ListenerInterface entity) { + int insert = listenerInterfaceDao.insert(entity); + return insert; + } + + @Override + public int update(ListenerInterface entity) { + int i = listenerInterfaceDao.updateByPrimaryKeySelective(entity); + return i; + } + + @Override + public List selectListByWhere(String wherestr) { + ListenerInterface listenerInterface = new ListenerInterface(); + listenerInterface.setWhere(wherestr); + List listenerInterfaces = listenerInterfaceDao.selectListByWhere(listenerInterface); + return listenerInterfaces; + } + + @Override + public int deleteByWhere(String wherestr) { + ListenerInterface listenerInterface = new ListenerInterface(); + listenerInterface.setWhere(wherestr); + int i = listenerInterfaceDao.deleteByWhere(listenerInterface); + return i; + } +} diff --git a/src/main/java/com/sipai/service/Listener/impl/ListenerMessageServiceImpl.java b/src/main/java/com/sipai/service/Listener/impl/ListenerMessageServiceImpl.java new file mode 100644 index 0000000..7fdc257 --- /dev/null +++ b/src/main/java/com/sipai/service/Listener/impl/ListenerMessageServiceImpl.java @@ -0,0 +1,96 @@ +package com.sipai.service.Listener.impl; + +import com.sipai.dao.Listener.ListenerMessageDao; +import com.sipai.entity.Listener.ListenerMessage; +import com.sipai.service.Listener.ListenerMessageService; +import com.sipai.service.scada.MPointService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.List; + +@Service("listenerMessageService") +public class ListenerMessageServiceImpl implements ListenerMessageService { + + @Resource + ListenerMessageDao listenerMessageDao; +// @Resource +// private CompanyService companyService; +// @Resource +// private ProcessSectionService processSectionService; + @Resource + private MPointService mPointService; + + @Override + public ListenerMessage selectById(String id) { + ListenerMessage listenerMessage = listenerMessageDao.selectByPrimaryKey(id); + return listenerMessage; + } + + @Override + public int deleteById(String id) { + int i = listenerMessageDao.deleteByPrimaryKey(id); + return i; + } + + @Override + public int save(ListenerMessage entity) { + int insert = listenerMessageDao.insert(entity); + return insert; + } + + @Override + public int update(ListenerMessage entity) { + int i = listenerMessageDao.updateByPrimaryKeySelective(entity); + return i; + } + + @Override + public List selectListByWhere(String wherestr) { + ListenerMessage listenerMessage = new ListenerMessage(); + listenerMessage.setWhere(wherestr); + List listenerMessages = listenerMessageDao.selectListByWhere(listenerMessage); + for (ListenerMessage entity : listenerMessages) { + +// MPoint mPoint = mPointService.selectById(entity.getObjid()); +// if (mPoint != null) { +// entity.setmPoint(mPoint); +// Company company = companyService.selectByPrimaryKey(mPoint.getBizid()); +// entity.setCompany(company); +// } + } + return listenerMessages; + } + + @Override + public List selectListByWhere4Equ(String wherestr, String equipmentId) { + ListenerMessage listenerMessage = new ListenerMessage(); + listenerMessage.setWhere(wherestr); + List listenerMessages = listenerMessageDao.selectListByWhere(listenerMessage); + List listenerMessages2 = new ArrayList<>(); + for (int i = 0; i < listenerMessages.size(); i++) { +// MPoint mPoint = mPointService.selectById(listenerMessages.get(i).getObjid()); +// if (mPoint != null && mPoint.getEquipmentid().equals(equipmentId)) { +// listenerMessages2.add(listenerMessages.get(i)); +// } + } + for (ListenerMessage entity : listenerMessages2) { +// MPoint mPoint = mPointService.selectById(entity.getObjid()); +// if (mPoint != null) { +// entity.setmPoint(mPoint); +// Company company = companyService.selectByPrimaryKey(mPoint.getBizid()); +// entity.setCompany(company); +// } + } + return listenerMessages2; + } + + @Override + public int deleteByWhere(String wherestr) { + ListenerMessage listenerMessage = new ListenerMessage(); + listenerMessage.setWhere(wherestr); + int i = listenerMessageDao.deleteByWhere(listenerMessage); + return i; + } +} diff --git a/src/main/java/com/sipai/service/Listener/impl/ListenerPointServiceImpl.java b/src/main/java/com/sipai/service/Listener/impl/ListenerPointServiceImpl.java new file mode 100644 index 0000000..ca1d275 --- /dev/null +++ b/src/main/java/com/sipai/service/Listener/impl/ListenerPointServiceImpl.java @@ -0,0 +1,57 @@ +package com.sipai.service.Listener.impl; + +import com.sipai.dao.Listener.ListenerPointDao; +import com.sipai.entity.Listener.ListenerPoint; +import com.sipai.service.Listener.ListenerPointService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +@Service("listenerPointService") +public class ListenerPointServiceImpl implements ListenerPointService { + + @Resource + ListenerPointDao listenerPointDao; + + @Override + public ListenerPoint selectById(String id) { + ListenerPoint listenerPoint = listenerPointDao.selectByPrimaryKey(id); + return listenerPoint; + } + + @Override + public int deleteById(String id) { + int i = listenerPointDao.deleteByPrimaryKey(id); + return i; + } + + @Override + public int save(ListenerPoint entity) { + int insert = listenerPointDao.insert(entity); + return insert; + } + + @Override + public int update(ListenerPoint entity) { + int i = listenerPointDao.updateByPrimaryKeySelective(entity); + return i; + } + + @Override + public List selectListByWhere(String wherestr) { + ListenerPoint listenerPoint = new ListenerPoint(); + listenerPoint.setWhere(wherestr); + List listenerPoints = listenerPointDao.selectListByWhere(listenerPoint); + return listenerPoints; + } + + @Override + public int deleteByWhere(String wherestr) { + ListenerPoint listenerPoint = new ListenerPoint(); + listenerPoint.setWhere(wherestr); + int i = listenerPointDao.deleteByWhere(listenerPoint); + return i; + } + +} diff --git a/src/main/java/com/sipai/service/data/DeviceDataParser.java b/src/main/java/com/sipai/service/data/DeviceDataParser.java new file mode 100644 index 0000000..3dfaf72 --- /dev/null +++ b/src/main/java/com/sipai/service/data/DeviceDataParser.java @@ -0,0 +1,126 @@ +package com.sipai.service.data; + +import com.sipai.entity.data.ChannelData; +import com.sipai.entity.data.DeviceDataPacket; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +public class DeviceDataParser { + + public static DeviceDataPacket parse(byte[] data) { + ByteBuffer buffer = ByteBuffer.wrap(data); + buffer.order(ByteOrder.LITTLE_ENDIAN); // 设置为低位在前 + + // 1. 验证起始符 + if (buffer.get() != (byte) 0xAB || buffer.get() != (byte) 0xCD) { + throw new IllegalArgumentException("Invalid start code (expected AB CD)"); + } + + DeviceDataPacket packet = new DeviceDataPacket(); + packet.setStartCode("ABCD"); + + // 2. 解析固定字段 + packet.setLength(buffer.getShort() & 0xFFFF); // 长度 + packet.setStationId(buffer.getShort() & 0xFFFF); // 站号 + + // 3. 解析时间戳(BCD码:年(1)月(1)日(1)时(1)分(1)) + byte[] timeBytes = new byte[5]; + buffer.get(timeBytes); + packet.setTimestamp(LocalDateTime.of( + 2000 + bcdToInt(timeBytes[0]), // 年 + bcdToInt(timeBytes[1]), // 月 + bcdToInt(timeBytes[2]), // 日 + bcdToInt(timeBytes[3]), // 时 + bcdToInt(timeBytes[4]) // 分 + )); + + // 4. 解析其他字段 + packet.setDataCount(buffer.get() & 0xFF); // 数据个数 + packet.setInterval(buffer.get() & 0xFF); // 间隔(分钟) + packet.setBatteryVoltage((buffer.getShort() & 0xFFFF) / 100.0f); // 电池电压 + packet.setUploadCount(buffer.getShort() & 0xFFFF); // 上发次数 + packet.setSignalStrength(buffer.get() & 0xFF); // 信号强度 + + // 5. 解析设备信息(20字节ASCII) + byte[] deviceInfoBytes = new byte[20]; + buffer.get(deviceInfoBytes); + packet.setDeviceInfo(new String(deviceInfoBytes).trim()); + + // 跳过保留字段(8字节) + buffer.position(buffer.position() + 8); + + // 6. 解析通道数据 + List channelDataList = new ArrayList<>(); + while (buffer.remaining() > 3) { // 至少需要3字节(校验和+结束符) + ChannelData channelData = parseChannelData(buffer, packet.getDataCount()); + channelDataList.add(channelData); + } + + packet.setChannelDataList(channelDataList); + + // 7. 校验和与结束符 + if (buffer.remaining() >= 1) { + packet.setChecksum(buffer.get() & 0xFF); + } + if (buffer.remaining() >= 2) { + packet.setEndCode(String.format("%02X%02X", buffer.get(), buffer.get())); + } + + return packet; + } + + private static ChannelData parseChannelData(ByteBuffer buffer, int dataCount) { + ChannelData channelData = new ChannelData(); + channelData.setType(buffer.get() & 0xFF); // 类型 + channelData.setChannelNumber(buffer.get() & 0xFF); // 通道号 + + // 修复channelName乱码:直接转为HEX字符串 + byte[] nameBytes = new byte[]{buffer.get(), buffer.get()}; + channelData.setChannelName(String.format("%02X%02X", nameBytes[0], nameBytes[1])); + + // 根据类型解析数据 + switch (channelData.getType()) { + case 1: // 脉冲量 + case 2: // 开关量 + case 3: // 报警量 + channelData.setYesterdayFlow(buffer.getInt()); + channelData.setCumulativeFlows(parseIntList(buffer, dataCount)); + break; + case 4: // 模拟量 + channelData.setYesterdayFlow(buffer.getInt()); + channelData.setAnalogValues(parseFloatList(buffer, dataCount)); + break; + case 5: // 虚拟Q通道 + channelData.setqChannelData(buffer.getShort() & 0xFFFF); + break; + case 6: // 虚拟M通道 + channelData.setmChannelData(buffer.getInt()); + break; + } + return channelData; + } + + private static List parseIntList(ByteBuffer buffer, int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count && buffer.remaining() >= 4; i++) { + list.add(buffer.getInt()); + } + return list; + } + + private static List parseFloatList(ByteBuffer buffer, int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count && buffer.remaining() >= 4; i++) { + list.add(buffer.getFloat()); + } + return list; + } + + private static int bcdToInt(byte b) { + return ((b >> 4) & 0xF) * 10 + (b & 0xF); + } +} diff --git a/src/main/java/com/sipai/service/data/PipeTopicMpointService.java b/src/main/java/com/sipai/service/data/PipeTopicMpointService.java new file mode 100644 index 0000000..86fc878 --- /dev/null +++ b/src/main/java/com/sipai/service/data/PipeTopicMpointService.java @@ -0,0 +1,41 @@ +package com.sipai.service.data; + +import com.sipai.entity.data.PipeTopicMpoint; + +import java.util.List; + +/** + * 管网专题页点位服务接口 + */ +public interface PipeTopicMpointService { + + /** + * 添加点位信息 + */ + int insert(PipeTopicMpoint pipeTopicMpoint); + + /** + * 根据主键删除点位 + */ + boolean delete(Integer id); + + /** + * 批量删除点位 + */ + boolean deleteBatch(List idList); + + /** + * 更新点位信息 + */ + boolean update(PipeTopicMpoint pipeTopicMpoint); + + /** + * 根据主键获取点位详情 + */ + PipeTopicMpoint selectByPrimaryKey(Integer id); + + /** + * 根据条件查询点位列表 + */ + List selectListByWhere(String where); +} \ No newline at end of file diff --git a/src/main/java/com/sipai/service/data/PipelineEquipmentMpointService.java b/src/main/java/com/sipai/service/data/PipelineEquipmentMpointService.java new file mode 100644 index 0000000..acb0fa0 --- /dev/null +++ b/src/main/java/com/sipai/service/data/PipelineEquipmentMpointService.java @@ -0,0 +1,35 @@ +package com.sipai.service.data; + +import com.sipai.entity.data.PipelineEquipmentMpoint; + +import java.util.List; + +/** + * 管道设备与测点关联服务接口 + */ +public interface PipelineEquipmentMpointService { + /** + * 添加关联信息 + */ + boolean insert(PipelineEquipmentMpoint mpoint); + + /** + * 删除关联信息 + */ + boolean delete(Integer id); + + /** + * 更新关联信息 + */ + boolean update(PipelineEquipmentMpoint mpoint); + + /** + * 获取关联信息详情 + */ + PipelineEquipmentMpoint selectByPrimaryKey(Integer id); + + /** + * 获取所有关联信息列表 + */ + List selectListByWhere(String where); +} \ No newline at end of file diff --git a/src/main/java/com/sipai/service/data/PipelineEquipmentService.java b/src/main/java/com/sipai/service/data/PipelineEquipmentService.java new file mode 100644 index 0000000..05c7596 --- /dev/null +++ b/src/main/java/com/sipai/service/data/PipelineEquipmentService.java @@ -0,0 +1,60 @@ +package com.sipai.service.data; + +import com.sipai.entity.data.PipelineEquipment; + +import java.util.List; + +/** + * 管道设备服务接口 + */ +public interface PipelineEquipmentService { + /** + * 添加设备 + */ + int insert(PipelineEquipment pipelineEquipment); + + /** + * 删除设备 + */ + boolean delete(Integer id); + + /** + * 更新设备信息 + */ + boolean update(PipelineEquipment equipment); + + /** + * 获取设备详情 + */ + PipelineEquipment selectByPrimaryKey(Integer id); + + /** + * 获取所有设备列表 + */ + List selectListByWhere(String where); + + /** + * 根据站点编号查询设备 + */ + /*List getEquipmentByStation(String stationCode); + + *//** + * 根据设备类型查询设备 + *//* + List getEquipmentByType(String equipmentType); + + *//** + * 根据状态查询设备 + *//* + List getEquipmentByStatus(String status);*/ + + /** + * 更新设备状态 + */ +// boolean updateEquipmentStatus(String id, String status); + + /** + * 更新设备最后上传时间 + */ +// boolean updateLastUploadTime(String id); +} diff --git a/src/main/java/com/sipai/service/data/PipelineMpointLibraryService.java b/src/main/java/com/sipai/service/data/PipelineMpointLibraryService.java new file mode 100644 index 0000000..a60a408 --- /dev/null +++ b/src/main/java/com/sipai/service/data/PipelineMpointLibraryService.java @@ -0,0 +1,42 @@ +package com.sipai.service.data; + +import com.sipai.entity.data.PipelineMpointLibrary; + +import java.util.List; + +/** + * 管道测点库服务接口 + */ +public interface PipelineMpointLibraryService { + /** + * 添加测点库信息 + */ + boolean insert(PipelineMpointLibrary mpointLibrary); + + /** + * 删除测点库信息 + */ + boolean delete(String id); + + /** + * 多删测点库信息 + * @param idList + * @return + */ + int deleteBatch(List idList); + + /** + * 更新测点库信息 + */ + boolean update(PipelineMpointLibrary mpointLibrary); + + /** + * 获取测点库详情 + */ + PipelineMpointLibrary selectByPrimaryKey(String id); + + /** + * 获取所有测点库列表 + */ + List selectListByWhere(String where); +} \ No newline at end of file diff --git a/src/main/java/com/sipai/service/data/impl/PipeTopicMpointServiceImpl.java b/src/main/java/com/sipai/service/data/impl/PipeTopicMpointServiceImpl.java new file mode 100644 index 0000000..41af8d1 --- /dev/null +++ b/src/main/java/com/sipai/service/data/impl/PipeTopicMpointServiceImpl.java @@ -0,0 +1,59 @@ +package com.sipai.service.data.impl; + +import com.sipai.dao.data.PipeTopicMpointDao; +import com.sipai.entity.data.PipeTopicMpoint; +import com.sipai.service.data.PipeTopicMpointService; +import org.apache.commons.collections4.CollectionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class PipeTopicMpointServiceImpl implements PipeTopicMpointService { + + @Autowired + private PipeTopicMpointDao pipeTopicMpointDao; + + public PipeTopicMpointServiceImpl(PipeTopicMpointDao pipeTopicMpointDao) { + this.pipeTopicMpointDao = pipeTopicMpointDao; + } + + @Override + public int insert(PipeTopicMpoint pipeTopicMpoint) { + return pipeTopicMpointDao.insert(pipeTopicMpoint); + } + + @Override + public boolean delete(Integer id) { + return pipeTopicMpointDao.deleteByPrimaryKey(id); + } + + @Override + public boolean deleteBatch(List idList) { + if (CollectionUtils.isEmpty(idList)) { + return false; + } + int count = pipeTopicMpointDao.deleteBatchByIds(idList); + return count > 0; + } + + @Override + public boolean update(PipeTopicMpoint pipeTopicMpoint) { + return pipeTopicMpointDao.updateByPrimaryKeySelective(pipeTopicMpoint); + } + + @Override + public PipeTopicMpoint selectByPrimaryKey(Integer id) { + return pipeTopicMpointDao.selectByPrimaryKey(id); + } + + @Override + public List selectListByWhere(String where) { + PipeTopicMpoint pipeTopicMpoint = new PipeTopicMpoint(); + pipeTopicMpoint.setWhere(where); + return pipeTopicMpointDao.selectListByWhere(pipeTopicMpoint); + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/service/data/impl/PipelineEquipmentMpointServiceImpl.java b/src/main/java/com/sipai/service/data/impl/PipelineEquipmentMpointServiceImpl.java new file mode 100644 index 0000000..626f544 --- /dev/null +++ b/src/main/java/com/sipai/service/data/impl/PipelineEquipmentMpointServiceImpl.java @@ -0,0 +1,48 @@ +package com.sipai.service.data.impl; + +import com.sipai.dao.data.PipelineEquipmentMpointDao; +import com.sipai.entity.data.PipelineEquipmentMpoint; +import com.sipai.service.data.PipelineEquipmentMpointService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class PipelineEquipmentMpointServiceImpl implements PipelineEquipmentMpointService { + @Autowired + private PipelineEquipmentMpointDao pipelineEquipmentMpointDao; + + public PipelineEquipmentMpointServiceImpl(PipelineEquipmentMpointDao mpointDao) { + this.pipelineEquipmentMpointDao = mpointDao; + } + + @Override + public boolean insert(PipelineEquipmentMpoint mpoint) { + return pipelineEquipmentMpointDao.insert(mpoint); + } + + @Override + public boolean delete(Integer id) { + return pipelineEquipmentMpointDao.deleteByPrimaryKey(id); + } + + @Override + public boolean update(PipelineEquipmentMpoint mpoint) { + return pipelineEquipmentMpointDao.updateByPrimaryKeySelective(mpoint); + } + + @Override + public PipelineEquipmentMpoint selectByPrimaryKey(Integer id) { + return pipelineEquipmentMpointDao.selectByPrimaryKey(id); + } + + @Override + public List selectListByWhere(String where) { + PipelineEquipmentMpoint mpoint = new PipelineEquipmentMpoint(); + mpoint.setWhere(where); + return pipelineEquipmentMpointDao.selectListByWhere(mpoint); + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/service/data/impl/PipelineEquipmentServiceImpl.java b/src/main/java/com/sipai/service/data/impl/PipelineEquipmentServiceImpl.java new file mode 100644 index 0000000..f35b671 --- /dev/null +++ b/src/main/java/com/sipai/service/data/impl/PipelineEquipmentServiceImpl.java @@ -0,0 +1,126 @@ +package com.sipai.service.data.impl; + +import com.sipai.dao.data.PipelineEquipmentDao; +import com.sipai.dao.scada.MPointDao; +import com.sipai.entity.data.PipelineEquipment; +import com.sipai.entity.enums.DeviceTypeEnum; +import com.sipai.service.data.PipelineEquipmentService; +import org.apache.commons.collections4.CollectionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class PipelineEquipmentServiceImpl implements PipelineEquipmentService { + @Autowired + private PipelineEquipmentDao pipelineEquipmentDao; + + public PipelineEquipmentServiceImpl(PipelineEquipmentDao equipmentDao) { + this.pipelineEquipmentDao = equipmentDao; + } + + @Override + public int insert(PipelineEquipment equipment) { + int result = pipelineEquipmentDao.insert(equipment); + if (result > 0) { + // 插入成功,获取自增的ID + int generatedId = equipment.getId(); + } + return result; + } + + @Override + public boolean delete(Integer id) { + return pipelineEquipmentDao.deleteByPrimaryKey(id); + } + + /*@Override + public boolean deleteBatch(List idList) { + // 参数校验 + if (CollectionUtils.isEmpty(idList)) { + return false; + } + + // 执行批量删除 + int count = pipelineEquipmentDao.deleteBatchByIds(idList); + + return count > 0; + }*/ + + @Override + public boolean update(PipelineEquipment equipment) { + return pipelineEquipmentDao.updateByPrimaryKeySelective(equipment); + } + + @Override + public PipelineEquipment selectByPrimaryKey(Integer id) { + PipelineEquipment pipelineEquipment = pipelineEquipmentDao.selectByPrimaryKey(id); + if (pipelineEquipment != null) { + + //查询对应的设备名称 + String typeCode = pipelineEquipment.getEquipmentType(); + DeviceTypeEnum deviceType = DeviceTypeEnum.getByTypeCode(typeCode); + if (deviceType != null) { + pipelineEquipment.setEquipmentTypeName(deviceType.getTypeName()); + } + + return pipelineEquipment; + } else { + return null; + } + } + + @Override + public List selectListByWhere(String where) { + PipelineEquipment pipelineEquipment = new PipelineEquipment(); + pipelineEquipment.setWhere(where); + + List list = pipelineEquipmentDao.selectListByWhere(pipelineEquipment); + for (PipelineEquipment equipment : list) { + String typeCode = equipment.getEquipmentType(); + DeviceTypeEnum deviceType = DeviceTypeEnum.getByTypeCode(typeCode); + if (deviceType != null) { + equipment.setEquipmentTypeName(deviceType.getTypeName()); + } + } + return list; + } + + /*@Override + public List getEquipmentByStation(String stationCode) { + return equipmentDao.selectByStationCode(stationCode); + } + + @Override + public List getEquipmentByType(String equipmentType) { + return equipmentDao.selectByEquipmentType(equipmentType); + } + + @Override + public List getEquipmentByStatus(String status) { + return equipmentDao.selectByStatus(status); + }*/ + + /*@Override + public boolean updateEquipmentStatus(String id, String status) { + PipelineEquipment equipment = pipelineEquipmentDao.selectByPrimaryKey(id); + if (equipment == null) { + return false; + } + equipment.setStatus(status); + return pipelineEquipmentDao.updateByPrimaryKeySelective(equipment) > 0; + } + + @Override + public boolean updateLastUploadTime(String id) { + PipelineEquipment equipment = pipelineEquipmentDao.selectByPrimaryKey(id); + if (equipment == null) { + return false; + } + equipment.setLastUploadTime(new Date()); + return pipelineEquipmentDao.updateByPrimaryKeySelective(equipment) > 0; + }*/ +} diff --git a/src/main/java/com/sipai/service/data/impl/PipelineMpointLibraryServiceImpl.java b/src/main/java/com/sipai/service/data/impl/PipelineMpointLibraryServiceImpl.java new file mode 100644 index 0000000..bf3c950 --- /dev/null +++ b/src/main/java/com/sipai/service/data/impl/PipelineMpointLibraryServiceImpl.java @@ -0,0 +1,54 @@ +package com.sipai.service.data.impl; + +import com.sipai.dao.data.PipelineMpointLibraryDao; +import com.sipai.entity.data.PipelineMpointLibrary; +import com.sipai.service.data.PipelineMpointLibraryService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class PipelineMpointLibraryServiceImpl implements PipelineMpointLibraryService { + @Autowired + private PipelineMpointLibraryDao pipelineMpointLibraryDao; + + public PipelineMpointLibraryServiceImpl(PipelineMpointLibraryDao mpointLibraryDao) { + this.pipelineMpointLibraryDao = mpointLibraryDao; + } + + @Override + public boolean insert(PipelineMpointLibrary mpointLibrary) { + return pipelineMpointLibraryDao.insert(mpointLibrary); + } + + @Override + public boolean delete(String id) { + return pipelineMpointLibraryDao.deleteByPrimaryKey(id); + } + + @Override + public int deleteBatch(List idList) { + return pipelineMpointLibraryDao.deleteBatchByIds(idList); + } + + @Override + public boolean update(PipelineMpointLibrary mpointLibrary) { + return pipelineMpointLibraryDao.updateByPrimaryKeySelective(mpointLibrary); + } + + @Override + public PipelineMpointLibrary selectByPrimaryKey(String id) { + return pipelineMpointLibraryDao.selectByPrimaryKey(id); + } + + @Override + public List selectListByWhere(String where) { + PipelineMpointLibrary pipelineMpointLibrary = new PipelineMpointLibrary(); + pipelineMpointLibrary.setWhere(where); + + return pipelineMpointLibraryDao.selectListByWhere(pipelineMpointLibrary); + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/service/kafka/KafkaConsumerService.java b/src/main/java/com/sipai/service/kafka/KafkaConsumerService.java new file mode 100644 index 0000000..ae2c4b7 --- /dev/null +++ b/src/main/java/com/sipai/service/kafka/KafkaConsumerService.java @@ -0,0 +1,24 @@ +package com.sipai.service.kafka; + +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.kafka.support.Acknowledgment; +import org.springframework.stereotype.Service; + +/** + * 消费者服务 + */ +/*@Service +public class KafkaConsumerService { + + @KafkaListener(topics = "topic_data", groupId = "my-group-2.2.0") + public void listen(String message, Acknowledgment ack) { + try { +// System.out.println("topic_data收到数据: " + message); + // 手动提交offset + ack.acknowledge(); + } catch (Exception e) { + // 处理异常 + System.err.println("Error processing message: " + e.getMessage()); + } + } +}*/ diff --git a/src/main/java/com/sipai/service/kafka/KafkaProducerService.java b/src/main/java/com/sipai/service/kafka/KafkaProducerService.java new file mode 100644 index 0000000..414ef41 --- /dev/null +++ b/src/main/java/com/sipai/service/kafka/KafkaProducerService.java @@ -0,0 +1,38 @@ +package com.sipai.service.kafka; + +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.support.SendResult; +import org.springframework.util.concurrent.ListenableFuture; +import org.springframework.util.concurrent.ListenableFutureCallback; +import org.springframework.stereotype.Service; + +/** + * 生产者服务 + */ +/*@Service +public class KafkaProducerService { + + private final KafkaTemplate kafkaTemplate; + + public KafkaProducerService(KafkaTemplate kafkaTemplate) { + this.kafkaTemplate = kafkaTemplate; + } + + public void sendMessage(String topic, String message) { + ListenableFuture> future = kafkaTemplate.send(topic, message); + + future.addCallback(new ListenableFutureCallback>() { + @Override + public void onSuccess(SendResult result) { + System.out.println("Sent message=[" + message + + "] with offset=[" + result.getRecordMetadata().offset() + "]"); + } + + @Override + public void onFailure(Throwable ex) { + System.err.println("Unable to send message=[" + + message + "] due to : " + ex.getMessage()); + } + }); + } +}*/ diff --git a/src/main/java/com/sipai/service/mqtt/MqttConfigService.java b/src/main/java/com/sipai/service/mqtt/MqttConfigService.java new file mode 100644 index 0000000..acf5824 --- /dev/null +++ b/src/main/java/com/sipai/service/mqtt/MqttConfigService.java @@ -0,0 +1,62 @@ +package com.sipai.service.mqtt; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.sipai.entity.mqtt.MqttConfig; +import com.sipai.entity.scada.MPoint; + +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/03/24/16:44 + * @Description: + */ +public interface MqttConfigService { + + public abstract MqttConfig selectByPrimaryKey(String id); + + public abstract Integer deleteByPrimaryKey(String id); + + public abstract Integer insert(MqttConfig entity); + + public abstract Integer updateByPrimaryKeySelective(MqttConfig entity); + + public abstract List selectListByWhere(String wherestr); + + public abstract Integer deleteByWhere(String wherestr); + + public String connect(String id); + + /** + * 根据主题返回emqx代理地址 websocket方式 + * sj 2021-09-15 + * @param topic + * @return + */ + public JSONObject getEmqxHost4WS(String topic); + + /** + * 根据主题返回emqx代理地址 tcp方式 + * sj 2021-09-15 + * @param topic + * @return + */ + public String getEmqxHost4TCP(String topic); + + public void doSendMqttVue(List list, String topic); + + /** + * @param jsonArray 需要推送的数据 + * @param topic 推送的主题 + */ + public void doSendView(JSONArray jsonArray, String topic); + + /** + * @param jsonObject 需要推送的数据 + * @param topic 推送的主题 + */ + public void doSendJson(JSONObject jsonObject, String topic); +} diff --git a/src/main/java/com/sipai/service/mqtt/MqttConfigTopicService.java b/src/main/java/com/sipai/service/mqtt/MqttConfigTopicService.java new file mode 100644 index 0000000..ba8d314 --- /dev/null +++ b/src/main/java/com/sipai/service/mqtt/MqttConfigTopicService.java @@ -0,0 +1,28 @@ +package com.sipai.service.mqtt; + +import com.sipai.entity.mqtt.MqttConfigTopic; + +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/03/24/17:56 + * @Description: + */ +public interface MqttConfigTopicService { + public abstract MqttConfigTopic selectByPrimaryKey(String id); + + public abstract Integer deleteByPrimaryKey(String id); + + public abstract Integer insert(MqttConfigTopic entity); + + public abstract Integer updateByPrimaryKeySelective(MqttConfigTopic entity); + + public abstract List selectListByWhere(String wherestr); + + public abstract Integer deleteByWhere(String wherestr); + + public abstract List selectListByPid(String pid); +} diff --git a/src/main/java/com/sipai/service/mqtt/MqttService.java b/src/main/java/com/sipai/service/mqtt/MqttService.java new file mode 100644 index 0000000..fc9c722 --- /dev/null +++ b/src/main/java/com/sipai/service/mqtt/MqttService.java @@ -0,0 +1,57 @@ +package com.sipai.service.mqtt; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import org.springframework.scheduling.annotation.Scheduled; + +public interface MqttService { + /** + * 用于提供云平台 给plc发布指令接口 + * @param json + * @param topic + * @param userId + * @param bizId + * @return + */ + public abstract int doPublish(JSONObject json, String topic, String userId, String bizId); + + /** + * 处理mqtt订阅到的数据 + * @param bizId + * @param topic + * @param ip4 + * @param port + * @param jsonArray + */ + public abstract void doHandle(String bizId, String topic, String ip4, String port, JSONArray jsonArray); + + /** + * 处理mqtt订阅到的数据 -- (补发的数据 1.不报警 2.不更新主表 3.AI点3分钟存一次 DI点每次都存) + * @param bizId + * @param topic + * @param ip4 + * @param port + * @param jsonArray + */ + public abstract void doHandleHis(String bizId, String topic, String ip4, String port, JSONArray jsonArray); + + /** + * 网关数据全部召回 + * @param bizId + * @return + */ + public abstract void doRecall(String bizId,JSONObject jsonObject); + + /** + * 发送 rabbitmq + * + * @return + */ + public abstract void sentRabbitmq(String exchange, String key, String value_BigDecimal, String date); + + /** + * 清理测量点对象缓存 + */ + @Scheduled(fixedRate = 3600000) // 每小时清理一次 + void cleanCache(); +} diff --git a/src/main/java/com/sipai/service/mqtt/PushCallback.java b/src/main/java/com/sipai/service/mqtt/PushCallback.java new file mode 100644 index 0000000..d5c07ab --- /dev/null +++ b/src/main/java/com/sipai/service/mqtt/PushCallback.java @@ -0,0 +1,229 @@ +package com.sipai.service.mqtt; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.sipai.entity.user.Company; +import com.sipai.service.rabbitmq.MQService; +import com.sipai.service.user.CompanyService; +import com.sipai.tools.CommUtil; +import com.sipai.tools.SpringContextUtil; +import org.eclipse.paho.client.mqttv3.*; + +import javax.management.MBeanServer; +import javax.management.MalformedObjectNameException; +import javax.management.ObjectName; +import javax.management.Query; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.lang.management.ManagementFactory; +import java.math.BigDecimal; +import java.net.*; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Set; + +/** + * 发布消息的回调类 + *

+ * 必须实现MqttCallback的接口并实现对应的相关接口方法CallBack 类将实现 MqttCallBack。 + * 每个客户机标识都需要一个回调实例。在此示例中,构造函数传递客户机标识以另存为实例数据。 + * 在回调中,将它用来标识已经启动了该回调的哪个实例。 + * 必须在回调类中实现三个方法: + *

+ * public void messageArrived(MqttTopic topic, MqttMessage message)接收已经预订的发布。 + *

+ * public void connectionLost(Throwable cause)在断开连接时调用。 + *

+ * public void deliveryComplete(MqttDeliveryToken token)) + * 接收到已经发布的 QoS 1 或 QoS 2 消息的传递令牌时调用。 + * 由 MqttClient.connect 激活此回调。 + */ + +public class PushCallback implements MqttCallbackExtended { + + InetAddress ip4;//ip + + { + try { + ip4 = Inet4Address.getLocalHost(); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + } + + MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer(); + Set objectNames; + String port = "";//端口 + + { + try { + objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"), + Query.match(Query.attr("protocol"), Query.value("HTTP/1.1"))); +// port = objectNames.iterator().next().getKeyProperty("port"); + port = "8080"; + } catch (MalformedObjectNameException e) { + e.printStackTrace(); + } + } + + private MqttClient client; + private MqttConnectOptions options; + private String[] topic; + private int[] qos; + + public PushCallback(MqttClient client, MqttConnectOptions options, String[] topic, int[] qos) { + this.client = client; + this.options = options; + this.topic = topic; + this.qos = qos; + } + + /** + * 连接断开回调方法 + */ + public void connectionLost(Throwable cause) { + System.out.println("===连接断开回调方法"); + try { + if (null != client && !client.isConnected()) { + System.out.println("尝试重新连接"); + client.connect(options); + } else { + System.out.println("尝试建立新连接"); + client.connect(options); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 连接成功回调方法 + */ + @Override + public void connectComplete(boolean reconnect, String serverURI) { + System.out.println("===连接成功回调方法"); + try { + if (null != topic && null != qos) { + if (client.isConnected()) { + client.subscribe(topic, qos); + System.out.println("mqtt连接成功"); + } else { + System.out.println("mqtt连接失败"); + } + } + } catch (Exception e) { + System.out.println("mqtt订阅主题异常:" + e); + } + } + + public void deliveryComplete(IMqttDeliveryToken token) { +// System.out.println("deliveryComplete---------" + token.isComplete()); + } + + public void messageArrived(String topic, MqttMessage message) { + try { + JSONArray jsonArray = JSONArray.parseArray(message.toString()); +// System.out.println(topic + "===开始===" + CommUtil.nowDate() + "===" + jsonArray.size()); + String unitId = topic.substring(0, 4);//截取topic的前面部分作为厂id + MqttService mqttService = (MqttService) SpringContextUtil.getBean("mqttService"); + //正常的主题 -- 数据处理 + mqttService.doHandle(unitId, topic, ip4.toString(), port, jsonArray); + } catch (Exception e) { + System.out.println(topic + "执行失败" + e); + } + } + + + /** + * 日期格式字符串转换成时间戳 + * + * @param date_str 字符串日期 + * @param format 如:yyyy-MM-dd HH:mm:ss + * @return + */ + public static String date2TimeStamp(String date_str, String format) { + try { + SimpleDateFormat sdf = new SimpleDateFormat(format); + return String.valueOf(sdf.parse(date_str).getTime() / 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } + + /** + * 发送 rabbitmq + * + * @param key + * @param value_BigDecimal + * @param date + */ + public static void sentRabbitmq(String exchange, String key, String value_BigDecimal, String date) { + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("id", key); + jsonObject1.put("value", value_BigDecimal); + jsonObject1.put("time", date); + MQService mqService = (MQService) SpringContextUtil.getBean("mQService"); + mqService.sendMQ(exchange, jsonObject1.toString()); + } + + public static void sentRabbitMqMpoint(String exchange, String json) { + MQService mqService = (MQService) SpringContextUtil.getBean("mQService"); + mqService.sendMQ(exchange, json); + } + + public String doPost(String URL) { + OutputStreamWriter out = null; + BufferedReader in = null; + StringBuilder result = new StringBuilder(); + HttpURLConnection conn = null; + try { + java.net.URL url = new URL(URL); + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("POST"); + //发送POST请求必须设置为true + conn.setDoOutput(true); + conn.setDoInput(true); + //设置连接超时时间和读取超时时间 + conn.setConnectTimeout(30000); + conn.setReadTimeout(10000); + conn.setRequestProperty("Content-Type", "application/json"); + conn.setRequestProperty("Accept", "application/json"); + //获取输出流 + out = new OutputStreamWriter(conn.getOutputStream()); + String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}"; + out.write(jsonStr); + out.flush(); + out.close(); + //取得输入流,并使用Reader读取 + if (200 == conn.getResponseCode()) { + in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); + String line; + while ((line = in.readLine()) != null) { + result.append(line); + } + } else { + System.out.println("ResponseCode is an error code:" + conn.getResponseCode()); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (out != null) { + out.close(); + } + if (in != null) { + in.close(); + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } + return result.toString(); + } + +} diff --git a/src/main/java/com/sipai/service/mqtt/impl/MqttConfigServiceImpl.java b/src/main/java/com/sipai/service/mqtt/impl/MqttConfigServiceImpl.java new file mode 100644 index 0000000..57016ea --- /dev/null +++ b/src/main/java/com/sipai/service/mqtt/impl/MqttConfigServiceImpl.java @@ -0,0 +1,348 @@ +package com.sipai.service.mqtt.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.sipai.entity.mqtt.Mqtt; +import com.sipai.entity.mqtt.MqttProperties; +import com.sipai.entity.scada.MPoint; +import com.sipai.service.mqtt.PushCallback; +import com.sipai.dao.mqtt.MqttConfigDao; +import com.sipai.entity.mqtt.MqttConfig; +import com.sipai.entity.mqtt.MqttConfigTopic; +import com.sipai.service.mqtt.MqttConfigService; +import com.sipai.service.mqtt.MqttConfigTopicService; +import com.sipai.tools.CommUtil; +import org.apache.commons.codec.binary.Base64; +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/03/24/16:45 + * @Description: + */ +@Service +public class MqttConfigServiceImpl implements MqttConfigService { + private final MqttProperties mqttProperties; + @Autowired + private MqttConfigDao mqttConfigDao; + @Autowired + private MqttConfigTopicService mqttConfigTopicService; + + private static MqttClient mqttClient1; + + // 构造器注入 + @Autowired + public MqttConfigServiceImpl(MqttProperties mqttProperties) { + this.mqttProperties = mqttProperties; + } + + private static MqttClient connect(String brokeraddress, String clientId, String userName, String password) throws MqttException { + MemoryPersistence persistence = new MemoryPersistence(); + MqttConnectOptions connOpts = new MqttConnectOptions(); + connOpts.setCleanSession(true); + connOpts.setUserName(userName); + connOpts.setPassword(password.toCharArray()); + connOpts.setConnectionTimeout(1000); + connOpts.setKeepAliveInterval(1000); + mqttClient1 = new MqttClient(brokeraddress, clientId, persistence); + mqttClient1.connect(connOpts); + return mqttClient1; + } + + @Override + public MqttConfig selectByPrimaryKey(String id) { + return mqttConfigDao.selectByPrimaryKey(id); + } + + @Override + public Integer deleteByPrimaryKey(String id) { + return mqttConfigDao.deleteByPrimaryKey(id); + } + + @Override + public Integer insert(MqttConfig entity) { + return mqttConfigDao.insert(entity); + } + + @Override + public Integer updateByPrimaryKeySelective(MqttConfig entity) { + return mqttConfigDao.insert(entity); + } + + @Override + public List selectListByWhere(String whereStr) { + MqttConfig entity = new MqttConfig(); + entity.setWhere(whereStr); + return mqttConfigDao.selectListByWhere(entity); + } + + @Override + public Integer deleteByWhere(String whereStr) { + return mqttConfigDao.deleteByWhere(whereStr); + } + + @Override + public String connect(String id) { + String clientId = ""; + MqttConfig mqttConfig = mqttConfigDao.selectByPrimaryKey(id); + if (mqttConfig != null) { + clientId = mqttConfig.getTomcatPort() + "-" + CommUtil.getUUID(); + System.out.println(clientId); + String sql = "where id = '" + mqttConfig.getId() + "'"; + mqttConfig.setWhere(sql); + List list_config = mqttConfigDao.selectListByWhere(mqttConfig); + List topic_str = new ArrayList<>(); + + //每个客户端根据配置的tomcat端口号进行分区连接 + if (list_config != null && list_config.size() > 0) { + //循环配置主表 + for (int i = 0; i < list_config.size(); i++) { + String sql_detail = "where pid = '" + list_config.get(i).getId() + "'"; + List list_topic = mqttConfigTopicService.selectListByWhere(sql_detail); + if (list_topic != null && list_topic.size() > 0) { + //循环配置附表(获取所有topic) + for (int j = 0; j < list_topic.size(); j++) { + //配置的_UP主题 +// topic_str.add("$queue/" + list_topic.get(j).getTopic()); + topic_str.add(list_topic.get(j).getTopic()); + } + } + } + } + + //配置的条数即为数组的长度 + String[] topic = new String[topic_str.size()]; + System.out.println("订阅主题:" + topic_str); + int[] qos = new int[topic_str.size()]; + for (int j = 0; j < topic_str.size(); j++) { + topic[j] = topic_str.get(j); + qos[j] = 0; + } + try { + MqttConnectOptions connOpts = new MqttConnectOptions(); + connOpts.setCleanSession(true); + connOpts.setConnectionTimeout(1000); + //每隔1.5*10秒的时间向客户端发送个消息判断客户端是否在线 + connOpts.setKeepAliveInterval(1000); + //自动重连 + connOpts.setAutomaticReconnect(true); + connOpts.setUserName(mqttProperties.getUsername()); + connOpts.setPassword(mqttProperties.getPassword().toCharArray()); + + if (mqttClient1 != null) { + System.out.println("已连接"); + //回调 + mqttClient1.setCallback(new PushCallback(mqttClient1, connOpts, topic, qos)); + //订阅 + mqttClient1.subscribe(topic, qos); + } else { + System.out.println("重新连接"); + //连接 + mqttClient1 = connect(mqttConfig.getBrokerIp(), clientId, mqttProperties.getUsername(), mqttProperties.getPassword()); + //回调 + mqttClient1.setCallback(new PushCallback(mqttClient1, connOpts, topic, qos)); + //订阅 + mqttClient1.subscribe(topic, qos); + } + + } catch (MqttException me) { + me.printStackTrace(); + } + } + return clientId; + } + + public Boolean clientStatus(String clientId) { + boolean status = true; + try { + System.out.println(mqttProperties.getDashboard01() + "/api/v4/clients/" + clientId); + URL url = new URL(mqttProperties.getDashboard01() + "/api/v4/clients/" + clientId); + Base64 b = new Base64(); + String encoding = b.encodeAsString(new String("admin:sipai@64368180").getBytes()); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("Authorization", "Basic " + encoding); + InputStream content = connection.getInputStream(); + BufferedReader in = new BufferedReader(new InputStreamReader(content)); + + JSONObject jsonObject = JSONObject.parseObject(in.readLine()); + String data = jsonObject.get("data").toString(); + JSONArray jsonArrayStr = JSONArray.parseArray(data); + if (jsonArrayStr.size() > 0) { + JSONObject jsonObject1 = jsonArrayStr.getJSONObject(0); + if (jsonObject1.get("connected").equals(true)) { + status = true; + } else { + status = false; + } + } else { + status = false; + } + } catch (Exception e) { + e.printStackTrace(); + } + return status; + } + + @Override + public JSONObject getEmqxHost4WS(String topic) { + JSONObject jsonObject = new JSONObject(); + List list = mqttConfigTopicService.selectListByWhere("where topic = '" + topic + "'"); + if (list != null && list.size() > 0) { + MqttConfig mqttConfig = new MqttConfig(); + //增加个循环查出所有的 有些旧数据 跳过 只查有主表数据的 + for (int i = 0; i < list.size(); i++) { + mqttConfig.setWhere("where id = '" + list.get(i).getPid() + "'"); + List list2 = mqttConfigDao.selectListByWhere(mqttConfig); + if (list2 != null && list2.size() > 0) { + if (list2.get(0).getBrokerIp() != null && !list2.get(0).getBrokerIp().trim().equals("")) { + String ip = list2.get(0).getBrokerIp(); + ip = ip.replace("tcp://", ""); + String host = ip.substring(0, ip.indexOf(":")); + //一期 + if (host != null && host.equals("172.16.242.16")) { + jsonObject.put("host", "58.254.140.62"); + jsonObject.put("port", "8088"); + } + //二期 + if (host != null && host.equals("172.16.242.24")) { + jsonObject.put("host", "58.254.140.121"); + jsonObject.put("port", "8083"); + } + } + break; + } + } + } + return jsonObject; + } + + @Override + public String getEmqxHost4TCP(String topic) { + String host = mqttProperties.getBrokerAddress();//默认一期 + List list = mqttConfigTopicService.selectListByWhere("where topic = '" + topic + "'"); + if (list != null && list.size() > 0) { + MqttConfig mqttConfig = new MqttConfig(); + //增加个循环查出所有的 有些旧数据 跳过 只查有主表数据的 + for (int i = 0; i < list.size(); i++) { + + mqttConfig.setWhere("where id = '" + list.get(i).getPid() + "'"); + List list2 = mqttConfigDao.selectListByWhere(mqttConfig); + if (list2 != null && list2.size() > 0) { + if (list2.get(0).getBrokerIp() != null && !list2.get(0).getBrokerIp().trim().equals("")) { + host = list2.get(0).getBrokerIp(); + } + break; + } + } + } + return host; + } + + @Async + public void doSendMqttVue(List list, String topic) { + JSONArray jsonVue = (JSONArray) JSONArray.toJSON(list); + MqttMessage message = new MqttMessage(jsonVue.toString().getBytes()); + message.setQos(0); + message.setRetained(false); + try { + String host = this.getEmqxHost4TCP(topic); + if (host != null && !host.equals("")) { + String[] str = host.split(";"); + String ip = str[0];//连接的ip + String topic_vue = topic; + if (topic != null && topic.contains("_IM")) { + topic_vue = topic.replace("_IM", ""); + } +// topic_vue = topic_vue + "_VIEW"; + topic_vue = topic_vue.substring(0, 4) + "_01_UP_VIEW"; + int size = list != null ? list.size() : 0; + StringBuilder ids = new StringBuilder(); + if (list != null) { + int max = Math.min(5, list.size()); + for (int i = 0; i < max; i++) { + ids.append(list.get(i).getId()); + if (i < max - 1) ids.append(","); + } + } + System.out.println("推送VIEW: topic=" + topic_vue + " size=" + size); + if (mqttClient1 != null && mqttClient1.isConnected()) { + //发布 +// System.out.println("推送前端:" + topic_vue); + mqttClient1.publish(topic_vue, message); + } else { + System.out.println("===重新连接===" + "推VUE===主题:" + topic_vue + "===" + ip + "===" + CommUtil.nowDate() + "==="); + //连接 + String clientId = "send_vue_" + str[2]; + mqttClient1 = connect(ip, clientId, mqttProperties.getUsername(), mqttProperties.getPassword()); + //发布 + mqttClient1.publish(topic_vue, message); + } + } + } catch (MqttException e) { + e.printStackTrace(); + } + } + + @Async + public void doSendView(JSONArray jsonArray, String topic) { + MqttMessage message = new MqttMessage(jsonArray.toString().getBytes()); + message.setQos(0); + message.setRetained(false); + try { + if (mqttClient1 != null && mqttClient1.isConnected()) { + //发布 + mqttClient1.publish(topic, message); + } else { + mqttClient1 = connect(mqttProperties.getBrokerAddress(), "send_vue_" + CommUtil.getUUID(), mqttProperties.getUsername(), mqttProperties.getPassword()); + //发布 + mqttClient1.publish(topic, message); + } + } catch (MqttException e) { + e.printStackTrace(); + } + } + + /** + * @param jsonObject 需要推送的数据 + * @param topic 推送的主题 + */ + @Async + public void doSendJson(JSONObject jsonObject, String topic) { + MqttMessage message = new MqttMessage(jsonObject.toString().getBytes()); + message.setQos(0); + message.setRetained(false); + try { + if (mqttClient1 != null && mqttClient1.isConnected()) { + //发布 + mqttClient1.publish(topic, message); + } else { + mqttClient1 = connect(mqttProperties.getBrokerAddress(), "send_vue_" + CommUtil.getUUID(), mqttProperties.getUsername(), mqttProperties.getPassword()); + //发布 + mqttClient1.publish(topic, message); + } + } catch (MqttException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/main/java/com/sipai/service/mqtt/impl/MqttConfigTopicServiceImpl.java b/src/main/java/com/sipai/service/mqtt/impl/MqttConfigTopicServiceImpl.java new file mode 100644 index 0000000..4c3120e --- /dev/null +++ b/src/main/java/com/sipai/service/mqtt/impl/MqttConfigTopicServiceImpl.java @@ -0,0 +1,61 @@ +package com.sipai.service.mqtt.impl; + +import com.sipai.dao.mqtt.MqttConfigTopicDao; +import com.sipai.entity.mqtt.MqttConfigTopic; +import com.sipai.service.mqtt.MqttConfigTopicService; +import com.sipai.tools.DataSourceEnum; +import com.sipai.tools.DataSourceTypeAnno; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/03/24/17:56 + * @Description: + */ +@Service +public class MqttConfigTopicServiceImpl implements MqttConfigTopicService { + @Autowired + private MqttConfigTopicDao mqttConfigTopicDao; + + @Override + public MqttConfigTopic selectByPrimaryKey(String id) { + return mqttConfigTopicDao.selectByPrimaryKey(id); + } + + @Override + public Integer deleteByPrimaryKey(String id) { + return mqttConfigTopicDao.deleteByPrimaryKey(id); + } + + @Override + public Integer insert(MqttConfigTopic entity) { + return mqttConfigTopicDao.insert(entity); + } + + @Override + public Integer updateByPrimaryKeySelective(MqttConfigTopic entity) { + return mqttConfigTopicDao.updateByPrimaryKeySelective(entity); + } + + @Override + public List selectListByWhere(String wherestr) { + MqttConfigTopic entity = new MqttConfigTopic(); + entity.setWhere(wherestr); + return mqttConfigTopicDao.selectListByWhere(entity); + } + + @Override + public Integer deleteByWhere(String wherestr) { + return mqttConfigTopicDao.deleteByWhere(wherestr); + } + + @Override + public List selectListByPid(String pid) { + return mqttConfigTopicDao.selectListByPid(pid); + } +} diff --git a/src/main/java/com/sipai/service/mqtt/impl/MqttServiceImpl.java b/src/main/java/com/sipai/service/mqtt/impl/MqttServiceImpl.java new file mode 100644 index 0000000..a1e4480 --- /dev/null +++ b/src/main/java/com/sipai/service/mqtt/impl/MqttServiceImpl.java @@ -0,0 +1,553 @@ +package com.sipai.service.mqtt.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.sipai.entity.mqtt.Mqtt; +import com.sipai.entity.mqtt.MqttProperties; +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointES; +import com.sipai.entity.scada.MPointHistory; +import com.sipai.service.Listener.ListenerPointService; +import com.sipai.service.mqtt.MqttConfigService; +import com.sipai.service.mqtt.MqttConfigTopicService; +import com.sipai.service.mqtt.MqttService; +import com.sipai.service.rabbitmq.MQService; +import com.sipai.service.scada.MPointHistoryService; +import com.sipai.service.scada.MPointService; +import com.sipai.tools.*; +import jodd.util.ClassUtil; +import org.eclipse.paho.client.mqttv3.*; +import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; +import org.redisson.api.RBatch; +import org.redisson.api.RedissonClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; + +@Service("mqttService") +public class MqttServiceImpl implements MqttService { + private final MqttProperties mqttProperties; + @Autowired + private MPointService mPointService; + @Autowired + private MqttConfigService mqttConfigService; + @Autowired + private MqttConfigTopicService mqttConfigTopicService; + @Autowired + private ListenerPointService listenerPointService; + @Autowired + private RedissonClient redissonClient; + + private static MqttClient mqttClient; + private static String ipStr = ""; + private static final Logger loggger = LoggerFactory.getLogger(ClassUtil.class); + + //测量点对象缓存 + private final Map mPointCache = new ConcurrentHashMap<>(); + private final Set notFoundKeys = ConcurrentHashMap.newKeySet(); + + @Override + @Scheduled(fixedRate = 3600000)//每小时清理一次 + public void cleanCache() { + loggger.info("清理缓存(" + mPointCache.size() + " 条):" + CommUtil.nowDate()); + mPointCache.clear(); + notFoundKeys.clear(); + } + + public MqttServiceImpl(MqttProperties mqttProperties) { + this.mqttProperties = mqttProperties; + } + + private static MqttClient connect(String brokeraddress, String clientId, String userName, String password) throws MqttException { + + ipStr = brokeraddress; + + MemoryPersistence persistence = new MemoryPersistence(); + MqttConnectOptions connOpts = new MqttConnectOptions(); + connOpts.setCleanSession(true); + connOpts.setUserName(userName); + connOpts.setPassword(password.toCharArray()); + connOpts.setConnectionTimeout(10); + connOpts.setKeepAliveInterval(20); +// String[] uris = {"tcp://10.100.124.206:1883","tcp://10.100.124.207:1883"}; +// connOpts.setServerURIs(uris); //起到负载均衡和高可用的作用 +// MqttClient mqttClient = new MqttClient(brokeraddress, clientId, persistence); + mqttClient = new MqttClient(brokeraddress, clientId, persistence); + //mqttClient.setCallback(new PushCallback("test")); + mqttClient.connect(connOpts); + return mqttClient; + } + + @Async("getAsyncMqttHandle") + @Override + public void doHandle(String bizId, String topic, String ip4, String port, JSONArray jsonArray) { +// System.out.println("MQTT接收: biz=" + bizId + " topic=" + topic + " msgCount=" + jsonArray.size()); + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + // 解析时间戳 + String timestamp = jsonObject.getString("timestamp"); + String[] times = timestamp.split("\\."); + String date = CommUtil.timeStamp2Date(times[0], "yyyy-MM-dd HH:mm:ss"); + + // 解析数据对象 + JSONObject data = jsonObject.getJSONObject("Data"); + if (data == null || data.isEmpty()) { + loggger.warn("Data为空,跳过: @{}", date); + continue; + } + + List redisList = new ArrayList<>(); + List vueList = new ArrayList<>(); + + // 遍历数据条目 + for (String key : data.keySet()) { + String valueStr = data.getString(key); + // 过滤无效值 + if (!isValidValue(valueStr)) { + loggger.warn("值无效,跳过: key={} raw={} @{}", key, valueStr, date); + continue; + } + // 获取点位信息 + MPoint mPoint = getMPointCacheOrES(bizId, key); + if (mPoint == null) { + boolean inNotFound = notFoundKeys.contains(key); + loggger.warn("点位不存在,跳过: key={} notFoundCache={} @{}", key, inNotFound, date); + continue; + } + // 处理数值转换、倍率计算、取反操作、推报警信息、发送Kafka消息 + BigDecimal value = handleValueConversion(bizId, valueStr, key, date, vueList); + if (value == null) { + loggger.warn("数值转换失败,跳过: key={} raw={} @{}", key, valueStr, date); + continue; + } + // 处理ES数据 + MPointES esPoint = buildEsPoint(mPoint, value, date); + redisList.add(esPoint); + } + // 推送前端数据 +// loggger.info("准备推送前端: topic={} size={} @{}", topic, vueList.size(), date); + mqttConfigService.doSendMqttVue(vueList, topic); + + // 批量写入Redis + saveToRedisBatch(redisList); +// loggger.info("批量写入Redis完成: size={} @{}", redisList.size(), date); + } + } + + /** + * 校验值是否有效(非空且长度合法) + */ + private boolean isValidValue(String value) { + if (value == null || value.isEmpty()) { + loggger.warn("无效值: 空字符串"); + return false; + } + BigDecimal bd = new BigDecimal(value); + String plainValue = bd.toPlainString(); + String[] parts = plainValue.split("\\."); + boolean ok = parts[0].length() <= 15; + if (!ok) { + loggger.warn("无效值: 整数位过长 len={} raw={}", parts[0].length(), value); + } + return ok; + } + + /** + * 处理数值转换、倍率计算、取反操作、推报警信息、发送Kafka消息 + */ + private BigDecimal handleValueConversion(String unitId, String valueStr, String key, String date, List vueList) { + try { + double valDou = Double.parseDouble(valueStr); + MPoint mPoint = getMPointCacheOrES(unitId, key); + if (mPoint == null) { + return null; + } + + // 倍率计算 + BigDecimal rate = mPoint.getRate() != null ? mPoint.getRate() : BigDecimal.ONE; + BigDecimal value = (valDou == 0 || rate.compareTo(BigDecimal.ZERO) == 0) + ? BigDecimal.ZERO + : rate.multiply(new BigDecimal(valueStr)).divide(BigDecimal.ONE, 10, RoundingMode.HALF_UP); + + // 取反操作 + if ("1".equals(mPoint.getDirecttype())) { + value = "0".equals(valueStr) ? BigDecimal.ONE : ("1".equals(valueStr) ? BigDecimal.ZERO : value); + } + + // 推送报警信息 + if (mPoint.getTriggeralarm() != null && !"0".equals(mPoint.getTriggeralarm().trim())) { +// loggger.info("推送报警: {}={} @{}", key, value, date); +// mPointService.sendKafka4MQTT_Alarm(key, value, date, 0, 1); + } + + // 发送Kafka消息 +// mPointService.sendKafka4MQTT(unitId,key, value, date, 0, 1, mPoint.getSignaltype()); + + // 构建前端数据 + buildVuePoint(mPoint, value, date, vueList); + + return value; + } catch (NumberFormatException e) { + loggger.error("数值转换失败: {}", valueStr, e); + return null; + } + } + + /** + * 构建前端展示用点位对象 + */ + private void buildVuePoint(MPoint mPoint, BigDecimal value, String date, List vueList) { + MPoint vuePoint = new MPoint(); + vuePoint.setId(mPoint.getId()); + vuePoint.setMeasuredt(date); + int numtail = doNumtail(mPoint.getNumtail()); + vuePoint.setParmvalue(value.setScale(numtail, RoundingMode.HALF_UP)); + vueList.add(vuePoint); + } + + /** + * 构建ES存储用点位对象 + */ + private MPointES buildEsPoint(MPoint mPoint, BigDecimal value, String date) { + MPoint esPoint = new MPoint(); + esPoint.setId(mPoint.getId()); + esPoint.setMeasuredt(date); + esPoint.setParmvalue(value); + esPoint.setNumtail(mPoint.getNumtail()); + return MPointES.format(esPoint); + } + + /** + * 批量保存数据到Redis + */ + private void saveToRedisBatch(List esList) { + if (esList.isEmpty()) { + return; + } + + int batchSize = 200; + int total = esList.size(); + int batches = (total + batchSize - 1) / batchSize; + + try { + for (int i = 0; i < batches; i++) { + int start = i * batchSize; + int end = Math.min((i + 1) * batchSize, total); + RBatch batch = redissonClient.createBatch(); + + for (MPoint mPoint : esList.subList(start, end)) { + int num = mPoint.getId().hashCode() % 25; + String dt = mPoint.getMeasuredt().replace("T", " ").replace("Z", ""); + int numtail = doNumtail(mPoint.getNumtail()); + String val = mPoint.getParmvalue().setScale(numtail, RoundingMode.HALF_UP) + + ";" + mPoint.getParmvalue() + ";" + dt; + + batch.getMapCache(CommString.RedisMpointFlag + num) + .fastPutAsync(mPoint.getId(), val, 1, TimeUnit.DAYS); + } + batch.execute(); + } + } catch (Exception e) { + loggger.error("Redis批量保存失败", e); + } + } + + @Async("getAsyncMqttHandle") + @Override + public void doHandleHis(String bizId, String topic, String ip4, String port, JSONArray jsonArray) { + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + String timestamp = jsonObject.get("timestamp").toString();//时间戳 + String[] times = timestamp.split("\\."); + String date = CommUtil.timeStamp2Date(times[0], "yyyy-MM-dd HH:mm:ss"); + //数据 + JSONObject data = jsonObject.getJSONObject("Data"); + + MPointService mPointService = (MPointService) SpringContextUtil.getBean("mPointService"); + MPointHistoryService mPointHistoryService = (MPointHistoryService) SpringContextUtil.getBean("mPointHistoryService"); + MPointHistory mPointHistory = new MPointHistory(); + + for (String str : data.keySet()) { + String key = str;//测量点id + String value = data.get(str) + ""; + + //过滤掉长度超过15位的数值 money无法存 + if (value != null && !value.equals("")) { + BigDecimal bd = new BigDecimal(value); + value = bd.toPlainString(); + if (value.contains(".")) { + String[] vals = value.split("\\."); + if (vals[0].length() > 15) { + //超出 + continue; + } else { + //未超出 + } + } else { + if (value.length() > 15) { + //超出 + continue; + } else { + //未超出 + } + } + } else { + //为空 过滤掉 不存日志 + continue; + } + + BigDecimal value_BigDecimal = null; + double valDou = 0;//判断是否为0 或者0.00 或 0.000等 + + //将json中为""的过滤掉 + if (value != null && !value.equals("")) { + valDou = Double.parseDouble(value);//判断是否为0 或者0.00 或 0.000等 +// MPoint mPoint = mPointService.selectById(bizId, key); + MPoint mPoint = mPointService.selectById(bizId, key.toString()); + if (mPoint != null) { + BigDecimal numDecimal = mPoint.getRate(); + if (valDou == 0 || mPoint.getRate().equals(0)) { + value_BigDecimal = new BigDecimal(0); + } else { + value_BigDecimal = numDecimal.multiply(new BigDecimal(value)); + //截取长度防止 过长 除1再截取10位 + value_BigDecimal = value_BigDecimal.divide(new BigDecimal(1), 10, BigDecimal.ROUND_HALF_UP); + } + + //取反操作 + if (mPoint.getDirecttype() != null && mPoint.getDirecttype().equals("1")) { + //取反 + if (value.equals("0")) { + value_BigDecimal = new BigDecimal(1); + } else if (value.equals("1")) { + value_BigDecimal = new BigDecimal(0); + } else { + //正常 + } + } else { + //正常 + } + + try { + //DI点直接存 + if (mPoint.getSignaltype() != null && mPoint.getSignaltype().equals("DI")) { + mPointHistory.setMeasuredt(date); + mPointHistory.setParmvalue(value_BigDecimal); + mPointHistory.setTbName("[tb_mp_" + key + "]"); + mPointHistory.setUserid(ip4 + ":" + port); + mPointHistoryService.save(bizId, mPointHistory); + } + //AI点3分钟存一次 + if (mPoint.getSignaltype() != null && mPoint.getSignaltype().equals("DI")) { + String sqlStr = "where MeasureDT>dateadd(mi,-3,'" + date + "') order by MeasureDT desc"; + /*List mPointHistoryList = mPointHistoryService.selectTopNumListByTableAWhere(mPoint.getBizid(),"[tb_mp_" + key + "]", sqlStr, "1"); + if (mPointHistoryList != null && mPointHistoryList.size() > 0) { + //3分钟内存在 则不存 + } else { + mPointHistory.setMeasuredt(date); + mPointHistory.setParmvalue(value_BigDecimal); + mPointHistory.setTbName("[tb_mp_" + key + "]"); + mPointHistory.setUserid(ip4 + ":" + port); + mPointHistoryService.save(bizId, mPointHistory); + }*/ + } + } catch (Exception e) { + System.out.println("新增子表--执行结果:" + e); + } + } + } + } + } + } + + /** + * 发送 rabbitmq + * + * @param key + * @param value_BigDecimal + * @param date + */ + @Override + public void sentRabbitmq(String exchange, String key, String value_BigDecimal, String date) { + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("id", key); + jsonObject1.put("value", value_BigDecimal); + jsonObject1.put("time", date); + MQService mqService = (MQService) SpringContextUtil.getBean("mQService"); + mqService.sendMQ(exchange, jsonObject1.toString()); + } + + /** + * 指令下发 + * + * @param json + * @param topic + * @param userId + * @param bizId + * @return + */ + @Override + public int doPublish(JSONObject json, String topic, String userId, String bizId) { + try { + MqttMessage message = new MqttMessage(json.toString().getBytes()); + message.setQos(2); + message.setRetained(false); + + //查询主题属于哪个代理 + String topic_up = ""; + if (topic != null && !topic.equals("")) { + topic_up = topic.replace("_DOWN", "_UP"); + } + String host = mqttConfigService.getEmqxHost4TCP(topic_up); + + System.out.println("指令下发:" + host); + + //连接 + mqttClient = connect(host, "gy_publish_8080", mqttProperties.getUsername(), mqttProperties.getPassword()); + //发布 + mqttClient.publish(topic, message); + //断开连接 + mqttClient.disconnect(); + } catch (MqttPersistenceException e) { + e.printStackTrace(); + } catch (MqttException e) { + e.printStackTrace(); + } + return 0; + } + + /** + * 召回网关全部数据 + * + * @param bizId + * @param jsonObject + */ + @Override + public void doRecall(String bizId, JSONObject jsonObject) { + try { + MqttMessage message = new MqttMessage(jsonObject.toString().getBytes()); + message.setQos(2); + message.setRetained(false); + + //查询主题属于哪个代理 + String topic_up = bizId + "_01_UP"; + + String host = mqttConfigService.getEmqxHost4TCP(topic_up); + + System.out.println(CommUtil.nowDate() + "数据召回-执行Recall:" + bizId + "_01_RECALL" + "------" + host); + + //连接 + mqttClient = connect(host, "gy_recall_8080", mqttProperties.getUsername(), mqttProperties.getPassword()); + //发布主题 + mqttClient.publish(bizId + "_01_RECALL", message); + //断开连接 + mqttClient.disconnect(); + } catch (MqttException e) { + e.printStackTrace(); + } + } + + /** + * 将处理后的mqtt消息传到vue前端 + */ + @Async + public void doSendMqttVue(List list, String topic) { + JSONArray jsonVue = (JSONArray) JSONArray.toJSON(list); + MqttMessage message = new MqttMessage(jsonVue.toString().getBytes()); + message.setQos(0); + message.setRetained(false); + try { + if (mqttClient == null) { + System.out.println("掉线_sendMqttVue"); + mqttClient = connect(mqttProperties.getBrokerAddress(), "gy_sendMqttVue" + CommUtil.getUUID(), mqttProperties.getUsername(), mqttProperties.getPassword()); + } else { +// System.out.println("正常_sendMqttVue"); + } + String topic_vue = topic; + if (topic != null && topic.contains("_IM")) { + topic_vue = topic.replace("_IM", ""); + } + topic_vue = topic_vue + "_VUE"; + mqttClient.publish(topic_vue, message); + } catch (MqttException e) { + e.printStackTrace(); + } + } + + /** + * 返回精度 + * + * @param num + * @return + */ + public int doNumtail(String num) { + int numtail = 0; + if (num != null && !num.trim().equals("")) { + //0.00这种后面不用 暂时写死 以后标准全部用数字 + if (num.contains(".")) { + if (num.equals("0.0")) { + numtail = 1; + } + if (num.equals("0.00")) { + numtail = 2; + } + if (num.equals("0.000")) { + numtail = 3; + } + if (num.equals("0.0000")) { + numtail = 4; + } + } else { + numtail = Integer.parseInt(num); + } + } else { + numtail = 0; + } + return numtail; + } + + /** + * 优先从缓存查询MPoint对象,不存在则去es中查询 + * + * @param key + * @return + */ + private MPoint getMPointCacheOrES(String unitId, String key) { + // 查询缓存是否存在 + if (mPointCache.containsKey(key)) { + MPoint mp = mPointCache.get(key); +// loggger.debug("缓存命中: key={} id={}", key, mp.getId()); + return mp; + } + // 点位不存在 (新加的点位需要定时清理缓存的时候才会进入缓存,不然频繁去查询es) + if (notFoundKeys.contains(key)) { +// loggger.debug("已标记未找到,跳过ES查询: key={}", key); + return null; + } + // 从ES查询 + MPoint mPoint = mPointService.selectById(unitId, key); + if (mPoint != null) { + //添加缓存 + mPointCache.put(key, mPoint); +// loggger.debug("ES查询成功并缓存: key={} id={}", key, mPoint.getId()); + } else { + //没有该点位 + notFoundKeys.add(key); +// loggger.warn("ES未找到点位,加入未找到集合: key={}", key); + } + return mPoint; + } + +} diff --git a/src/main/java/com/sipai/service/opc/InitOpcUaService.java b/src/main/java/com/sipai/service/opc/InitOpcUaService.java new file mode 100644 index 0000000..9d24bf7 --- /dev/null +++ b/src/main/java/com/sipai/service/opc/InitOpcUaService.java @@ -0,0 +1,134 @@ +package com.sipai.service.opc; + +import com.sipai.entity.scada.MPoint; +import com.sipai.service.opc.OpcUaService; +import com.sipai.service.scada.MPointService; +import com.sipai.tools.CommString; +import com.sipai.tools.CommUtil; +import org.elasticsearch.index.query.BoolQueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.search.sort.SortBuilders; +import org.redisson.api.RBatch; +import org.redisson.api.RedissonClient; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; + +/** + * 初始化订阅数据 + */ +@Service +public class InitOpcUaService { + @Autowired(required = false) + private OpcUaService opcUaService; + @Autowired + private MPointService mPointService; + + // 本地缓存 + private final Cache mPointCache = Caffeine.newBuilder() + .maximumSize(10000) // 仅设置最大缓存数量 +// .expireAfterWrite(1, TimeUnit.HOURS) // 1小时后过期 + .build(); + + // 已订阅的点位集合 + private Set subscribedNodeIds = new HashSet<>(); + + @PostConstruct + public void init() { + if (opcUaService == null) { + System.out.println("OPC UA 未启动,请检查yml配置文件钟:opc: enabled: true"); + return; + } + try { + //查询所有的opcua采集点位 + List nodeIdList = fetchNodeIdsFromEs(); + for (String nodeId : nodeIdList) { + MPoint mPoint = mPointCache.get(nodeId, key -> mPointService.selectById("",nodeId)); + System.out.println(mPoint); + Consumer callback = value -> { + if (mPoint != null) { + mPointService.sendKafka4OpcUa(mPoint.getId(), value, CommUtil.nowDate()); + } + }; + opcUaService.subscribeToNode(nodeId, callback); + subscribedNodeIds.add(nodeId); // 记录已订阅的点位 + } + System.out.println("Subscribed to " + nodeIdList.size() + " nodes"); + } catch (Exception e) { + System.err.println("Failed to subscribe: " + e.getMessage()); + } + } + + /** + * 同步一次opcua订阅点位 + */ + public void manualSyncSubscriptions() { + try { + List currentNodeIds = fetchNodeIdsFromEs(); // 获取当前 Elasticsearch 中的点位信息 + Set newSubscribedNodeIds = new HashSet<>(); + + // 处理新增点位 + for (String nodeId : currentNodeIds) { + if (!subscribedNodeIds.contains(nodeId)) { // 新增点位 + MPoint mPoint = mPointCache.get(nodeId, key -> mPointService.selectById("",nodeId)); + System.out.println(mPoint); + Consumer callback = value -> { + if (mPoint != null) { + mPointService.sendKafka4OpcUa(mPoint.getId(), value, CommUtil.nowDate()); + } + }; + opcUaService.subscribeToNode(nodeId, callback); + newSubscribedNodeIds.add(nodeId); + } else { + newSubscribedNodeIds.add(nodeId); // 保留已订阅的点位 + } + } + + // 处理删除点位 + for (String nodeId : subscribedNodeIds) { + if (!currentNodeIds.contains(nodeId)) { // 删除点位 + opcUaService.unsubscribeFromNode(nodeId); + } + } + + // 更新已订阅点位集合 + subscribedNodeIds = newSubscribedNodeIds; + + System.out.println("进行一次opcua订阅同步"); + } catch (Exception e) { + System.err.println("opcua订阅同步失败: " + e.getMessage()); + } + } + + /** + * 查询所有的opcua采集点位 + * + * @return + */ + private List fetchNodeIdsFromEs() { + NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder(); + BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); + BoolQueryBuilder childBoolQueryBuilder = QueryBuilders.boolQuery(); + childBoolQueryBuilder.must(QueryBuilders.matchPhraseQuery("biztype", "opcua")); + boolQueryBuilder.should(childBoolQueryBuilder); + nativeSearchQueryBuilder.withQuery(boolQueryBuilder); + nativeSearchQueryBuilder.withPageable(PageRequest.of(0, 10000)); + List list_mps = this.mPointService.selectListByWhere4Es(nativeSearchQueryBuilder); + List nodeIdList = new ArrayList<>(); + for (MPoint mPoint : list_mps) { + nodeIdList.add(mPoint.getMpointid()); + } + return nodeIdList; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/service/opc/OpcUaService.java b/src/main/java/com/sipai/service/opc/OpcUaService.java new file mode 100644 index 0000000..457b2f6 --- /dev/null +++ b/src/main/java/com/sipai/service/opc/OpcUaService.java @@ -0,0 +1,277 @@ +package com.sipai.service.opc; + +import com.sipai.config.OpcUaProperties; +import org.eclipse.milo.opcua.sdk.client.OpcUaClient; +import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription; +import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem; +import org.eclipse.milo.opcua.sdk.client.nodes.UaVariableNode; +import org.eclipse.milo.opcua.stack.core.AttributeId; +import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned; +import org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode; +import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn; +import org.eclipse.milo.opcua.stack.core.types.structured.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue; +import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId; +import org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode; +import org.eclipse.milo.opcua.stack.core.types.builtin.Variant; + +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + + +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +@Service +public class OpcUaService { + + @Autowired(required = false) + private final OpcUaClient opcUaClient; + private final OpcUaProperties opcUaProperties; + + @Autowired + public OpcUaService(@Autowired(required = false) OpcUaClient opcUaClient, OpcUaProperties opcUaProperties) { + this.opcUaClient = opcUaClient; + this.opcUaProperties = opcUaProperties; + } + + /*public void printConfig() { + System.out.println("OPC UA Server URL: " + opcUaProperties.getServerUrl()); + System.out.println("Security Policy: " + opcUaProperties.getSecurityPolicy()); + System.out.println("Security Mode: " + opcUaProperties.getSecurityMode()); + }*/ + + /** + * 读取单个点位的值 + * + * @param nodeId + * @return + * @throws ExecutionException + * @throws InterruptedException + */ + public Object readNodeValue(String nodeId) throws ExecutionException, InterruptedException { + if (opcUaClient == null) { + throw new IllegalStateException("OPC UA 未启动,请检查yml配置文件钟:opc: enabled: true"); + } + NodeId node = NodeId.parse(nodeId); + DataValue dataValue = opcUaClient.readValue(0, TimestampsToReturn.Both, node).get(); + Variant variant = dataValue.getValue(); + return variant.getValue(); + } + + /** + * 写入单个点位的值 + * + * @param nodeId 节点ID + * @param value 要写入的值 + * @return 写入是否成功 + * @throws ExecutionException + * @throws InterruptedException + */ + public boolean writeNodeValue(String nodeId, Object value) { + try { + NodeId node = NodeId.parse(nodeId); + + // 读取节点的数据类型(使用 UaVariableNode 替代 VariableNode) + UaVariableNode variableNode = (UaVariableNode) opcUaClient.getAddressSpace().getVariableNode(node); + if (variableNode == null) { + throw new RuntimeException("无法找到节点: " + nodeId); + } + + NodeId dataTypeId = variableNode.getDataType(); + System.out.println(dataTypeId); + + if (dataTypeId == null) { + throw new RuntimeException("无法获取节点的数据类型"); + } + + // 根据数据类型创建对应的 Variant + Variant variant = createVariantForDataType(value, dataTypeId); + + DataValue dataValue = DataValue.valueOnly(variant); + StatusCode statusCode = opcUaClient.writeValue(node, dataValue).get(); + System.out.println(statusCode); + return statusCode.isGood(); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * typeId跟标准规范不一致,目前用 KEPServerEX6自带的OPCUA服务 测试的结果 + * + * @param value + * @param dataTypeId + * @return + */ + private Variant createVariantForDataType(Object value, NodeId dataTypeId) { + int typeId = ((Number) dataTypeId.getIdentifier()).intValue(); + // 标准类型处理 + switch (typeId) { + case 1: + return new Variant(convertToBoolean(value)); + case 4: // Int16 (有符号short) + short shortValue = (value instanceof Number) ? + ((Number) value).shortValue() : + Short.parseShort(value.toString()); + return new Variant(shortValue); + case 5: // UInt16/Word (无符号short) + int intValue = (value instanceof Number) ? + ((Number) value).intValue() : + Integer.parseInt(value.toString()); + if (intValue < 0 || intValue > 65535) { + throw new IllegalArgumentException("UInt16 值必须在 0~65535 之间"); + } + return new Variant(Unsigned.ushort(intValue)); + case 6: // Int32 + return new Variant(convertToInt(value)); + case 10: //Float + return new Variant(convertToFloat(value)); + case 11: // Double + return new Variant(convertToDouble(value)); + default: + return new Variant(value.toString()); + } + } + + // 类型转换辅助方法(保持不变) + private boolean convertToBoolean(Object value) { + if (value instanceof Boolean) return (Boolean) value; + String strVal = value.toString().trim().toLowerCase(); + return strVal.equals("true") || strVal.equals("1"); + } + + private float convertToFloat(Object value) { + if (value instanceof Number) return ((Number) value).floatValue(); + return Float.parseFloat(value.toString()); + } + + private double convertToDouble(Object value) { + if (value instanceof Number) return ((Number) value).doubleValue(); + return Double.parseDouble(value.toString()); + } + + private int convertToInt(Object value) { + if (value instanceof Number) return ((Number) value).intValue(); + return Integer.parseInt(value.toString()); + } + + private long convertToUInt(Object value) { + if (value instanceof Number) return ((Number) value).longValue(); + return Long.parseLong(value.toString()); + } + + // 订阅点位 + public void subscribeToNode(String nodeId, Consumer callback) throws Exception { + if (opcUaClient == null) { + throw new IllegalStateException("OPC UA 未启动,请检查yml配置文件钟:opc: enabled: true"); + } + try { + NodeId node = NodeId.parse(nodeId); + + UaSubscription subscription = opcUaClient + .getSubscriptionManager() + .createSubscription(1000.0) + .get(); + + MonitoringParameters parameters = new MonitoringParameters( + Unsigned.uint(1), + 1000.0, + null, + Unsigned.uint(10), + true + ); + + MonitoredItemCreateRequest request = new MonitoredItemCreateRequest( + new ReadValueId( + node, + AttributeId.Value.uid(), + null, + null + ), + MonitoringMode.Reporting, + parameters + ); + + subscription.createMonitoredItems( + TimestampsToReturn.Both, + Collections.singletonList(request), + new UaSubscription.ItemCreationCallback() { + @Override + public void onItemCreated(UaMonitoredItem item, int i) { + // 设置值的回调处理器 + item.setValueConsumer(value -> { + Variant variant = value.getValue(); + Object rawValue = variant.getValue(); + + if (rawValue instanceof Number) { + callback.accept(((Number) rawValue).doubleValue()); // 转为 Double + } else if (rawValue instanceof Boolean) { + callback.accept(((Boolean) rawValue) ? 1.0 : 0.0); // 布尔转0 1 + } else { + throw new ClassCastException("Expected Number or Boolean but received: " + + rawValue.getClass().getSimpleName()); + } + }); + } + } + ).get(); + + } catch (Exception e) { + throw new Exception("订阅失败: " + e.getMessage(), e); + } + } + + // 取消订阅点位 + public boolean unsubscribeFromNode(String nodeId) { + if (opcUaClient == null) { + throw new IllegalStateException("OPC UA 未启动,请检查yml配置文件钟:opc: enabled: true"); + } + try { + NodeId node = NodeId.parse(nodeId); + + // 获取所有订阅 + List subscriptions = opcUaClient.getSubscriptionManager().getSubscriptions(); + + for (UaSubscription subscription : subscriptions) { + // 获取所有监控项 + List monitoredItems = subscription.getMonitoredItems(); + + for (UaMonitoredItem monitoredItem : monitoredItems) { + if (monitoredItem.getReadValueId().getNodeId().equals(node)) { + // 删除监控项 + CompletableFuture> deleteFuture = subscription.deleteMonitoredItems( + Collections.singletonList(monitoredItem) + ); + + // 等待删除操作完成 + List statusCodes = deleteFuture.get(5, TimeUnit.SECONDS); + + // 检查删除结果 + for (StatusCode statusCode : statusCodes) { + if (!statusCode.isGood()) { + System.err.println("删除监控项失败: " + statusCode); + return false; + } + } + + System.out.println("成功取消订阅节点: " + nodeId); + return true; + } + } + } + + System.out.println("未找到节点: " + nodeId); + return false; + } catch (Exception e) { + System.err.println("取消订阅失败: " + e.getMessage()); + return false; + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/service/rabbitmq/MQService.java b/src/main/java/com/sipai/service/rabbitmq/MQService.java new file mode 100644 index 0000000..650f742 --- /dev/null +++ b/src/main/java/com/sipai/service/rabbitmq/MQService.java @@ -0,0 +1,5 @@ +package com.sipai.service.rabbitmq; + +public interface MQService { + void sendMQ(String exchange, String msg); +} diff --git a/src/main/java/com/sipai/service/rabbitmq/impl/MQServiceImpl.java b/src/main/java/com/sipai/service/rabbitmq/impl/MQServiceImpl.java new file mode 100644 index 0000000..22327f4 --- /dev/null +++ b/src/main/java/com/sipai/service/rabbitmq/impl/MQServiceImpl.java @@ -0,0 +1,23 @@ +package com.sipai.service.rabbitmq.impl; + +import com.sipai.service.rabbitmq.MQService; +import com.sipai.tools.ConstantString; +import org.springframework.amqp.core.AmqpTemplate; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; + +@Service("mQService") +public class MQServiceImpl implements MQService { + @Resource + @Lazy + private AmqpTemplate amqpTemplate; + + @Override + public void sendMQ(String exchange,String msg) { +// String exchange = ConstantString.MQ_ALARM_MQTT; + String key = ConstantString.KEY_ALARM_MSG; + this.amqpTemplate.convertAndSend(exchange,key,msg); + } +} diff --git a/src/main/java/com/sipai/service/scada/MPointBzwService.java b/src/main/java/com/sipai/service/scada/MPointBzwService.java new file mode 100644 index 0000000..ad26385 --- /dev/null +++ b/src/main/java/com/sipai/service/scada/MPointBzwService.java @@ -0,0 +1,21 @@ +package com.sipai.service.scada; + +import com.sipai.entity.scada.MPointBzw; + +import java.util.List; + +public interface MPointBzwService { + + public abstract MPointBzw selectByPrimaryKey(String id); + + public abstract Integer deleteByPrimaryKey(String id); + + public abstract Integer insert(MPointBzw entity); + + public abstract Integer updateByPrimaryKeySelective(MPointBzw entity); + + public abstract List selectListByWhere(String wherestr); + + public abstract Integer deleteByWhere(String wherestr); + +} diff --git a/src/main/java/com/sipai/service/scada/MPointHistoryService.java b/src/main/java/com/sipai/service/scada/MPointHistoryService.java new file mode 100644 index 0000000..8cf94c1 --- /dev/null +++ b/src/main/java/com/sipai/service/scada/MPointHistoryService.java @@ -0,0 +1,17 @@ +package com.sipai.service.scada; + +import com.sipai.entity.scada.MPointHistory; + +import java.util.List; + +public interface MPointHistoryService { + int save(String bizId, MPointHistory mPointHistory); + + List selectListByTableAWhere(String bizId, String table, String wherestr); + + int deleteByTableAWhere(String bizId,String table ,String wherestr); + + int saveByCreate(String bizId, MPointHistory mPointHistory); + + List selectIndustrialLibrary(String bizId, String IP,String MPointID, String intv, String sdt, String edt); +} diff --git a/src/main/java/com/sipai/service/scada/MPointService.java b/src/main/java/com/sipai/service/scada/MPointService.java new file mode 100644 index 0000000..14c2341 --- /dev/null +++ b/src/main/java/com/sipai/service/scada/MPointService.java @@ -0,0 +1,87 @@ +package com.sipai.service.scada; + +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointES; +import com.sipai.entity.scada.MPointHistory; +import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; + +import java.util.List; +import java.util.Map; + +/** + *

+ * 服务类 + *

+ * + * @author YYJ + * @since 2021-06-25 + */ +public interface MPointService { + MPoint selectById(String unitId,String id); + + MPoint selectById4Es(String id); + + List selectListByWhere(String wherestr); + + List selectListByES(Map map, Integer page, Integer rows); + + public abstract List selectListByWhere4Es(NativeSearchQueryBuilder nativeSearchQueryBuilder); + +// void publish(String msg); +// +// void receive(); + +// String testSchedulePublish(String bizId, String equipmentId); + + // int update(String bizId, MPoint entity); + int update(MPoint entity); + + int updateValueByKey(String bizId, MPoint entity); + + /** + * 根据name获取主题下对应的key value + * sj 2021-08-08 + * + * @param topicName + * @return + */ +// String getData4Topic(String topicName); + +// String getData4Bim(String topicName); + + /** + * 推送数据至kafka + * sj 2021-08-08 + * + * @param id + * @param uuid + * @return + */ +// String sentData4Kafka(String id, String uuid); + +// void publish4TopicName(String msg, String topicName); + + /** + * 机器人调用工业库数据 + * 机器人传他们自己的id在excel中找到对应的mpid + * + * @param + * @return + */ +// String getIndustrialLibrary4Id(String id); + +// public abstract int saveInfluxdb(String bizId, MPointHistory entity); + public abstract void saveAsync(List mPointES); + + //推送数据到kafka +// public void sendKafka4OpcUa(String nodeId, Double value); + public void sendKafka4OpcUa(String nodeId, Double value, String time); + + public void sendKafka4UDP(String unitId,String mpcode, Object value, String timePoint, int i, int length); + + public void sendKafka4MQTT(String unitId,String mpcode, Object value, String timePoint, int i, int length,String signaltype); + + public void sendKafka4MQTT_Alarm(String mpcode, Object value, String timePoint, int i, int length); + + public void saveRedis(String mpcode, Object value, String time); +} diff --git a/src/main/java/com/sipai/service/scada/impl/MPointBzwServiceImpl.java b/src/main/java/com/sipai/service/scada/impl/MPointBzwServiceImpl.java new file mode 100644 index 0000000..a3727a7 --- /dev/null +++ b/src/main/java/com/sipai/service/scada/impl/MPointBzwServiceImpl.java @@ -0,0 +1,63 @@ +package com.sipai.service.scada.impl; + +import com.sipai.dao.scada.MPointBzwDao; +import com.sipai.entity.scada.MPointBzw; +import com.sipai.service.scada.MPointBzwService; +import com.sipai.tools.DataSourceTypeAnno; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: 你的名字 + * @Date: 2021/04/25/21:37 + * @Description: + */ +@Service("mPointBzwService") +public class MPointBzwServiceImpl implements MPointBzwService { + @Autowired + private MPointBzwDao mPointBzwDao; + + @Override + @DataSourceTypeAnno() + public MPointBzw selectByPrimaryKey(String id) { + return mPointBzwDao.selectByPrimaryKey(id); + } + + @Override + @DataSourceTypeAnno() + public Integer deleteByPrimaryKey(String id) { + return mPointBzwDao.deleteByPrimaryKey(id); + } + + @Override + @DataSourceTypeAnno() + public Integer insert(MPointBzw entity) { + return mPointBzwDao.insert(entity); + } + + @Async + @Override + @DataSourceTypeAnno() + public Integer updateByPrimaryKeySelective(MPointBzw entity) { + return mPointBzwDao.updateByPrimaryKeySelective(entity); + } + + @Override + @DataSourceTypeAnno() + public List selectListByWhere(String wherestr) { + MPointBzw mPoint = new MPointBzw(); + mPoint.setWhere(wherestr); + return mPointBzwDao.selectListByWhere(mPoint); + } + + @Override + @DataSourceTypeAnno() + public Integer deleteByWhere(String wherestr) { + return mPointBzwDao.deleteByWhere(wherestr); + } + +} diff --git a/src/main/java/com/sipai/service/scada/impl/MPointHistoryServiceImpl.java b/src/main/java/com/sipai/service/scada/impl/MPointHistoryServiceImpl.java new file mode 100644 index 0000000..5776c1e --- /dev/null +++ b/src/main/java/com/sipai/service/scada/impl/MPointHistoryServiceImpl.java @@ -0,0 +1,79 @@ +package com.sipai.service.scada.impl; + +import com.sipai.dao.scada.MPointHistoryDao; +import com.sipai.entity.scada.MPointHistory; +import com.sipai.service.scada.MPointHistoryService; +import com.sipai.tools.CommUtil; +import com.sipai.tools.DataSourceContextHolder; +import com.sipai.tools.DataSourceTypeAnno; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Slf4j(topic = "MPointHistoryServiceImpl") +@Service +public class MPointHistoryServiceImpl implements MPointHistoryService { + + @Autowired + MPointHistoryDao mPointHistoryDao; + + @DataSourceTypeAnno() + @Override + public int save(String bizId, MPointHistory mPointHistory) { + try { + int res = mPointHistoryDao.insert(mPointHistory); + return res; + } catch (Exception e) { + System.out.println(e); + throw new RuntimeException(); + } + } + + @DataSourceTypeAnno() + @Override + public List selectListByTableAWhere(String bizId, String table, String wherestr) { + return mPointHistoryDao.selectListByTableAWhere(table ,wherestr); + } + + @DataSourceTypeAnno() + @Override + public int deleteByTableAWhere(String bizId,String table ,String wherestr) { + return mPointHistoryDao.deleteByTableAWhere(table ,wherestr); + } + + @DataSourceTypeAnno() + @Override + public int saveByCreate(String bizId, MPointHistory mPointHistory) { + mPointHistory.setTbName(CommUtil.getMPointTableName(mPointHistory.getTbName())); + if(CommUtil.isBlank(bizId)){ + return 0; + } + try { + int i = this.mPointHistoryDao.checkTableExist(mPointHistory.getTbName()); + if(i == 0) { + log.info(String.format("[重要]创建了表:%s %s",mPointHistory.getTbName(), DataSourceContextHolder.getDataSourceType())); + mPointHistoryDao.createTable(mPointHistory.getTbName()); + } + + // 添加时间判断 todo 将来优化 + mPointHistory.setWhere(" where MeasureDT = '" + mPointHistory.getMeasuredt() + "'"); + Integer count = this.mPointHistoryDao.selectCount(mPointHistory); + + int result = count == 0 ? mPointHistoryDao.insert(mPointHistory) : mPointHistoryDao.updateByMeasureDt(mPointHistory); + return result; + } catch (Exception e) { + System.out.println(DataSourceContextHolder.getDataSourceType() + " | " + e); + // 返回默认值 + return 0; + } + } + + @DataSourceTypeAnno() + @Override + public List selectIndustrialLibrary(String bizId, String IP, String MPointID, String intv, String sdt, String edt) { + return mPointHistoryDao.selectIndustrialLibrary(IP, MPointID, intv, sdt, edt); + } + +} diff --git a/src/main/java/com/sipai/service/scada/impl/MPointServiceImpl.java b/src/main/java/com/sipai/service/scada/impl/MPointServiceImpl.java new file mode 100644 index 0000000..05da6e9 --- /dev/null +++ b/src/main/java/com/sipai/service/scada/impl/MPointServiceImpl.java @@ -0,0 +1,498 @@ +package com.sipai.service.scada.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.sipai.dao.scada.MPointDao; +import com.sipai.dao.scada.MPointRepo; +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointES; +import com.sipai.entity.scada.MPointHistory; +import com.sipai.service.mqtt.MqttConfigService; +import com.sipai.service.scada.MPointHistoryService; +import com.sipai.service.scada.MPointService; +import com.sipai.tools.CommString; +import com.sipai.tools.CommUtil; +import com.sipai.tools.DataSourceTypeAnno; +import lombok.extern.slf4j.Slf4j; +import org.elasticsearch.index.query.BoolQueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.redisson.api.RBatch; +import org.redisson.api.RMap; +import org.redisson.api.RTopic; +import org.redisson.api.RedissonClient; +import org.redisson.api.listener.MessageListener; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; +import org.springframework.data.elasticsearch.core.query.SearchQuery; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.support.SendResult; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import org.springframework.util.concurrent.ListenableFuture; +import org.springframework.util.concurrent.ListenableFutureCallback; + +import javax.annotation.Resource; +import java.io.File; +import java.io.IOException; +import java.math.BigDecimal; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.TimeUnit; + +/** + *

+ * 服务实现类 + *

+ * + * @author YYJ + * @since 2021-06-25 + */ +//@Slf4j(topic = "MPointServiceImpl") +@Service("mPointService") +@Slf4j +public class MPointServiceImpl implements MPointService { + @Resource + private MPointDao mPointDao; + @Autowired + private RedissonClient redissonClient; + @Autowired + private KafkaTemplate kafkaTemplate; + // @Autowired +// private InfluxDBConfig influxDBConfig; + @Autowired + private MPointRepo mPointRepo; + @Autowired + private MPointHistoryService mPointHistoryService; + @Autowired + private MPointService mPointService; + @Autowired + private MqttConfigService mqttConfigService; + +// @Value("${file.path}") +// private String path; + + /*@DataSourceTypeAnno() + public MPoint selectById(String unitId, String id) { + return mPointDao.selectByPrimaryKey(id); + }*/ + + @DataSourceTypeAnno() + public MPoint selectById(String unitId, String id) { + return mPointDao.selectByPrimaryKey(id); + } + + /** + * es查询 + * + * @param id + * @return + */ + @Override + public MPoint selectById4Es(String id) { + if (id == null || id.isEmpty()) { + return null; + } + /*try { + Optional m = mPointRepo.findById(id); + if (!m.isPresent()) { + log.error(id + "未找到点位"); + return null; + } + MPoint mPoint = m.get(); + return mPoint; + } catch (Exception e) { + log.error(id + "未找到点位"); + e.printStackTrace(); + return null; + }*/ + + NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder(); + SearchQuery searchQuery = nativeSearchQueryBuilder.withQuery(QueryBuilders.idsQuery().addIds(id)).build(); + List mPoints = mPointRepo.search(searchQuery).getContent(); + if (mPoints != null && mPoints.size() > 0) { + return mPoints.get(0); + } else { + return null; + } + + } + + // @DataSourceTypeAnno() + @Override + public List selectListByWhere(String wherestr) { + MPoint mpoint = new MPoint(); + mpoint.setWhere(wherestr); + List mPoints = mPointDao.selectListByWhere(mpoint); + for (MPoint mPoint : mPoints) { + if (mPoint.getNumtail() != null) { + BigDecimal value = CommUtil.formatMPointValue(mPoint.getParmvalue(), mPoint.getNumtail(), mPoint.getRate()); + if (value != null) { + try { + mPoint.setParmvalue(value); + } catch (Exception e) { +// log.info(e.toString()); + System.out.println(e.toString()); + } + } + } + } + return mPoints; + } + + @Override + public List selectListByES(Map map, Integer page, Integer rows) { + List mpoints = new ArrayList<>(); + try { + NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder(); + BoolQueryBuilder childBoolQueryBuilder = QueryBuilders.boolQuery(); + //TODO 或与非 + for (Map.Entry entry : map.entrySet()) { + if (entry.getKey() != null && !entry.getKey().isEmpty() && entry.getValue() != null) { + childBoolQueryBuilder.must(QueryBuilders.matchQuery(entry.getKey(), entry.getValue())); + } + } +// boolQueryBuilder.should(childBoolQueryBuilder); + nativeSearchQueryBuilder.withQuery(childBoolQueryBuilder); + if (page != null && rows != null && page > 0 && rows > 0) { + nativeSearchQueryBuilder.withPageable(PageRequest.of(page - 1, rows)); + } + SearchQuery searchQuery = nativeSearchQueryBuilder.build(); + Page mPage = mPointRepo.search(searchQuery); + for (MPoint mPoint : mPage) { + if (mPoint.getNumtail() != null) { + BigDecimal value = CommUtil.formatMPointValue(mPoint.getParmvalue(), mPoint.getNumtail(), mPoint.getRate()); + if (value != null) { + try { + mPoint.setParmvalue(value); + } catch (Exception e) { + log.error(e.toString()); + } + } + } + } + mpoints = mPage.getContent(); + nativeSearchQueryBuilder = null; +// boolQueryBuilder = null; + childBoolQueryBuilder = null; + searchQuery = null; + mPage = null; + } catch (Exception e) { + e.printStackTrace(); + } + return mpoints; + } + + // @DataSourceTypeAnno() + @Override + public int update(MPoint entity) { + try { + int res = mPointDao.updateByPrimaryKeySelective(entity); + return res; + } catch (Exception e) { + System.out.println(e); + throw new RuntimeException(); + } + } + + @DataSourceTypeAnno() + @Override + public int updateValueByKey(String bizId, MPoint entity) { + try { + int res = mPointDao.updateValueByKey(entity); + return res; + } catch (Exception e) { + System.out.println(e); + throw new RuntimeException(); + } + } + + /*@Override + public void publish(MPoint mPoint) { + RTopic topic = redissonClient.getTopic(CommString.MPOINT_TOPIC); + topic.publish(mPoint); + }*/ + + /*@Override + public String getData4Topic(String topicName) { + + RMap map2 = redissonClient.getMap(topicName); + JSONArray jsonArray = new JSONArray(); + for (String key : map2.keySet()) { + String value = map2.get(key).toString();// + JSONObject jsonObject = new JSONObject(); + jsonObject.put("id", key); + jsonObject.put("value", value); + jsonArray.add(jsonObject); + } + + return jsonArray.toString(); + }*/ + + /*public String str = ""; + + @Override + public void publish4TopicName(String msg, String topicName) { + RTopic topic = redissonClient.getTopic(topicName); + topic.publish(msg); + }*/ + + /** + * 保存到 Influxdb + * + * @param bizId + * @param entity + * @return + */ + public int saveInfluxdb(String bizId, MPointHistory entity) { + Map fields = new HashMap<>(); + Map tags = new HashMap<>(); + if (entity.getMemo() != null) { + tags.put("memo", entity.getMemo()); + } + if (entity.getMemotype() != null) { + tags.put("memotype", entity.getMemotype()); + } + SimpleDateFormat longDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + long time = Calendar.getInstance().getTimeInMillis(); + try { + fields.put("parmvalue", Float.parseFloat(entity.getParmvalue().toString())); + time = longDateFormat.parse(entity.getMeasuredt()).getTime(); +// influxDBConfig.insert("tb_mp_" + entity.getTbName(), time, tags, fields); +// System.out.println("===插入数据成功===" + entity.getTbName() + "===" + Float.parseFloat(entity.getParmvalue().toString())); + } catch (ParseException e) { + e.printStackTrace(); + } + return 1; + } + + /** + * 批量更新es + * + * @param mPointES + */ +// @Async + @Override + public void saveAsync(List mPointES) { + this.mPointRepo.batchUpdate(mPointES); + } + + /** + * es查询 + * + * @return + */ + public List selectListByWhere4Es(NativeSearchQueryBuilder nativeSearchQueryBuilder) { + SearchQuery searchQuery = nativeSearchQueryBuilder.build(); + Page mPage = mPointRepo.search(searchQuery); + List mPoints = mPage.getContent(); + for (MPoint mPoint : mPoints) { + if (mPoint.getNumtail() != null) { + BigDecimal value = CommUtil.formatMPointValue(mPoint.getParmvalue(), mPoint.getNumtail(), mPoint.getRate()); + if (value != null) { + try { + mPoint.setParmvalue(value); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + return mPoints; + } + + /** + * +8小时 + * + * @param time + * @return + * @throws Exception + */ + public static String formatTimeEight(String time) throws Exception { + Date d = null; + SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + d = sd.parse(time); + long rightTime = (long) (d.getTime() + 8 * 60 * 60 * 1000); //把当前得到的时间用date.getTime()的方法写成时间戳的形式,再加上8小时对应的毫秒数 + String newtime = sd.format(rightTime); //把得到的新的时间戳再次格式化成时间的格式 + return newtime; + } + + public void sendKafka4OpcUa(String id, Double value, String time) { + JSONObject message = new JSONObject(); + message.put("id", id); + message.put("value", value); + message.put("value", value + ""); + message.put("time", time); + message.put("sourceType", "opcua"); + String messageStr = JSON.toJSONString(message); + //回调 + ListenableFutureCallback> callback = + new ListenableFutureCallback>() { + @Override + public void onSuccess(SendResult result) { + //成功 + } + + @Override + public void onFailure(Throwable ex) { + //失败 + } + }; + //异步发送到三个主题 + sendAsync(CommString.Kafka_Topic_Data, messageStr, callback);//实时数据 + sendAsync(CommString.Kafka_Topic_Alarm, messageStr, callback);//报警数据 (仅推送需要报警的点位) + sendAsync(CommString.Kafka_Topic_Frontend, messageStr, callback);//前端数据 + } + + /** + * 异步发送方法 + * + * @param topic 主题名称 + * @param message 消息内容 + * @param callback 回调处理器 + */ + private void sendAsync(String topic, String message, + ListenableFutureCallback> callback) { + try { + ListenableFuture> future = kafkaTemplate.send(topic, message); + future.addCallback(callback); + } catch (Exception e) { +// log.error("Exception occurred while sending message to topic {}", topic, e); + } + } + + @Override + public void saveRedis(String mpcode, Object value, String time) { + RBatch batch = redissonClient.createBatch(); + int hashCode = mpcode.hashCode(); + int num = hashCode % 25; + String dt = time; + String val = value + ";" + value + ";" + dt; + batch.getMapCache(CommString.RedisMpointFlag + num).fastPutAsync(mpcode, val, 2, TimeUnit.DAYS); + batch.execute(); + } + + public void sendKafka4UDP(String unitId,String mpcode, Object value, String timePoint, int i, int length) { + + JSONObject message = new JSONObject(); + message.put("id", mpcode); + message.put("value", value); + message.put("time", timePoint); + message.put("sourceType", "udp"); + String messageStr = JSON.toJSONString(message); + //回调 + ListenableFutureCallback> callback = + new ListenableFutureCallback>() { + @Override + public void onSuccess(SendResult result) { + //成功 + } + + @Override + public void onFailure(Throwable ex) { + //失败 + } + }; + //异步发送到三个主题 + sendAsync(CommString.Kafka_Topic_Data, messageStr, callback);//实时数据 +// sendAsync(CommString.Kafka_Topic_Alarm, messageStr, callback);//报警数据 (仅推送需要报警的点位) +// sendAsync(CommString.Kafka_Topic_Frontend, messageStr, callback);//前端数据 + + //推送Mqtt数据(给管网平台厂家) +// mqttConfigService.doSendJson(message, CommString.Mqtt_Topic_DATA); + + try { + MPointHistory mPointHistory = new MPointHistory(); + mPointHistory.setParmvalue(CommUtil.toBigDecimal(value)); + mPointHistory.setMeasuredt(timePoint); + mPointHistory.setTbName(mpcode); + mPointHistory.setUserid("datacollector"); + mPointHistory.setInsdt(CommUtil.nowDate()); + //写子表 + mPointHistoryService.saveByCreate(CommString.BIZID_KCGW, mPointHistory); + } catch (Exception e) { + e.printStackTrace(); + } + + //更新最后一条数据到总表 + if (i == length - 1) { + try { + MPoint mPoint = mPointService.selectById(unitId,mpcode); + if (mPoint != null) { + mPoint.setParmvalue(CommUtil.toBigDecimal(value)); + mPoint.setMeasuredt(timePoint); + mPointService.update(mPoint); + } + //更新redis + mPointService.saveRedis(mpcode, value, timePoint); + } catch (Exception e) { + e.printStackTrace(); + } + } + + } + + // @Async + @Override + public void sendKafka4MQTT(String unitId,String mpcode, Object value, String timePoint, int i, int length, String signaltype) { + //写子表 + if (signaltype != null && signaltype.equals("DI")) { + try { + MPointHistory mPointHistory = new MPointHistory(); + mPointHistory.setParmvalue(CommUtil.toBigDecimal(value)); + mPointHistory.setMeasuredt(timePoint); + mPointHistory.setTbName(mpcode); + mPointHistory.setUserid("datacollector"); + mPointHistory.setInsdt(CommUtil.nowDate()); + mPointHistoryService.saveByCreate(CommString.BIZID_KCGW, mPointHistory); + } catch (Exception e) { + e.printStackTrace(); + } + } + + //更新最后一条数据到总表 + if (i == length - 1) { + try { + MPoint mPoint = mPointService.selectById(unitId,mpcode); + if (mPoint != null) { + mPoint.setParmvalue(CommUtil.toBigDecimal(value)); + mPoint.setMeasuredt(timePoint); + mPointService.update(mPoint); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + // @Async + @Override + public void sendKafka4MQTT_Alarm(String mpcode, Object value, String timePoint, int i, int length) { + JSONObject message = new JSONObject(); + message.put("id", mpcode); + message.put("value", value); + message.put("time", timePoint); + message.put("sourceType", "mqtt"); + String messageStr = JSON.toJSONString(message); + //回调 + ListenableFutureCallback> callback = + new ListenableFutureCallback>() { + @Override + public void onSuccess(SendResult result) { + //成功 + } + + @Override + public void onFailure(Throwable ex) { + //失败 + } + }; + //异步发送到三个主题 + sendAsync(CommString.Kafka_Topic_Alarm, messageStr, callback);//报警数据 (仅推送需要报警的点位) + } + +} diff --git a/src/main/java/com/sipai/service/user/CompanyService.java b/src/main/java/com/sipai/service/user/CompanyService.java new file mode 100644 index 0000000..8d3fb73 --- /dev/null +++ b/src/main/java/com/sipai/service/user/CompanyService.java @@ -0,0 +1,27 @@ +package com.sipai.service.user; + +import com.sipai.entity.user.Company; + +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/04/25/21:09 + * @Description: + */ +public interface CompanyService { + public abstract Company selectByPrimaryKey(String id); + + public abstract Integer deleteByPrimaryKey(String id); + + public abstract Integer insert(Company entity); + + public abstract Integer updateByPrimaryKeySelective(Company entity); + + public abstract List selectListByWhere(String wherestr); + + public abstract Integer deleteByWhere(String wherestr); + +} diff --git a/src/main/java/com/sipai/service/user/UserService.java b/src/main/java/com/sipai/service/user/UserService.java new file mode 100644 index 0000000..217452e --- /dev/null +++ b/src/main/java/com/sipai/service/user/UserService.java @@ -0,0 +1,9 @@ +package com.sipai.service.user; + +import com.sipai.entity.user.User; + +import java.util.List; + +public interface UserService { + public abstract List listuser2(); +} diff --git a/src/main/java/com/sipai/service/user/impl/CompanyServiceImpl.java b/src/main/java/com/sipai/service/user/impl/CompanyServiceImpl.java new file mode 100644 index 0000000..ce134e1 --- /dev/null +++ b/src/main/java/com/sipai/service/user/impl/CompanyServiceImpl.java @@ -0,0 +1,57 @@ +package com.sipai.service.user.impl; + +import com.sipai.dao.user.CompanyDao; +import com.sipai.entity.user.Company; +import com.sipai.service.user.CompanyService; +import com.sipai.tools.DataSourceEnum; +import com.sipai.tools.DataSourceTypeAnno; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/04/25/21:10 + * @Description: + */ +@Service("companyService") +public class CompanyServiceImpl implements CompanyService { + @Autowired + private CompanyDao companyDao; + + @Override + public Company selectByPrimaryKey(String id) { + return companyDao.selectByPrimaryKey(id); + } + + @Override + public Integer deleteByPrimaryKey(String id) { + return companyDao.deleteByPrimaryKey(id); + } + + @Override + public Integer insert(Company entity) { + return companyDao.insert(entity); + } + + @Override + public Integer updateByPrimaryKeySelective(Company entity) { + return companyDao.updateByPrimaryKeySelective(entity); + } + + @Override + public List selectListByWhere(String wherestr) { + Company company = new Company(); + company.setWhere(wherestr); + return companyDao.selectListByWhere(company); + } + + @Override + public Integer deleteByWhere(String wherestr) { + return companyDao.deleteByWhere(wherestr); + } + +} diff --git a/src/main/java/com/sipai/service/user/impl/UserServiceImpl.java b/src/main/java/com/sipai/service/user/impl/UserServiceImpl.java new file mode 100644 index 0000000..3c21608 --- /dev/null +++ b/src/main/java/com/sipai/service/user/impl/UserServiceImpl.java @@ -0,0 +1,21 @@ +package com.sipai.service.user.impl; + +import com.sipai.dao.user.UserDao; +import com.sipai.entity.user.User; +import com.sipai.service.user.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class UserServiceImpl implements UserService { + + @Autowired + private UserDao userDao; + + @Override + public List listuser2() { + return userDao.listuser2(); + } +} diff --git a/src/main/java/com/sipai/tools/AlarmType.java b/src/main/java/com/sipai/tools/AlarmType.java new file mode 100644 index 0000000..294eed4 --- /dev/null +++ b/src/main/java/com/sipai/tools/AlarmType.java @@ -0,0 +1,23 @@ +package com.sipai.tools; + +public enum AlarmType { + VOLTAGE_ALARM(0, "电压报警"), + WATER_ALARM(1, "水浸报警"), + COVER_ALARM(2, "开盖报警"); + + private final int bitPosition; + private final String description; + + AlarmType(int bitPosition, String description) { + this.bitPosition = bitPosition; + this.description = description; + } + + public boolean isTriggered(int qValue) { + return (qValue & (1 << bitPosition)) != 0; + } + + public String getDescription() { + return description; + } +} diff --git a/src/main/java/com/sipai/tools/CommString.java b/src/main/java/com/sipai/tools/CommString.java new file mode 100644 index 0000000..1777197 --- /dev/null +++ b/src/main/java/com/sipai/tools/CommString.java @@ -0,0 +1,244 @@ +package com.sipai.tools; + +public class CommString { +// public static final String DEFAULT_DATABASE = "021CTWS";//默认生产库 +// public static final String DEFAULT_UNITID = "021CTWS";//默认生产库 + + public static final String DEFAULT_DATABASE = "020GYHB";//默认生产库 + public static final String DEFAULT_UNITID = "020GYHB";//默认生产库 + + public static final String DUBBO_VERSION_BASE = "1"; + public static final String DUBBO_VERSION_EQUIPMENT = "1"; + public static final String DUBBO_VERSION_PATROL = "1"; + public static final String DUBBO_VERSION_VISUAL = "1"; + public static final String DUBBO_VERSION_OPERATION = "2"; + public static final String DUBBO_VERSION_EXPERT = "2"; + + public static final String REDISSON_ALARM_LIST = "AlarmUpdateList"; + + public static final String MQ_ALARM_MSG = "DM_ALARM_MSG"; + + public static final String KEY_ALARM_MSG = "mq.all.send"; + + public static final String MQ_ALARM_MQTT = "DM_ALARM"; + + public static final String FLAG_MON = "MON"; + + public static final String FLAG_DAY = "DAY"; + + public static final String FLAG_YEA = "YEA"; + + // KIO监测接口:获取运维平台所有节点的信息,如:节点名称、地址、端口节点配置信息、cup、内存、运行状态 + public static final String KIO_MONITOR_GETNODEINFOSLIST = "/getNodeInfosList"; + // KIO监测接口:获取已监测节点下的所有实例(KH、KIO、KS)的运行信息。包括:实例的名称、运行状态、cpu使用率,内存使用率,连接数、存储状态、授权类型等 + public static final String KIO_MONITOR_GETALLNODEAPPINFOSLIST = "/getAllNodeAppInfosList"; + // KIO监测接口:获取IOServer的设备状态信息 + public static final String KIO_MONITOR_GETNODEKIODEVICEINFOS = "/getNodeKIODeviceInfos"; + // KIO监测接口:控制指定节点已部署产品的运行状态。如:启动、停止、启动采集、停止采集 + public static final String KIO_MONITOR_CONTRLAPPSTATE = "/contrlappstate"; + // KIO监测CPU报警上限 + public static final int KIO_CPU_ALARM = 90; + // KIO监测内存报警上限 + public static final int KIO_MEMORY_ALARM = 90; + // KIO监测硬盘报警下限 + public static final int KIO_HARDDISK_ALARM = 2048; + + public static final String REDIS_LOCK_RTDB_ALARM = "RTDBALARM"; + + public static final String REDIS_LOCK_MPOINT_PUTIN = "MPOINT_PUTIN"; + + public static final String REDIS_LOCK_EQUIPMENT_FAULT = "EQUIPMENT_FAULT"; + + public static final String REDIS_LOCK_MPOINT_USE_FREQ = "MPOINT_USE_FREQ"; + public static final String REDIS_LOCK_MPOINT_CURRENT_VALUE = "MPOINT_CURENT_VALUE"; + + //管理员ID + public static final String ID_Admin = "emp01";//管理员 + + //启用 禁用 active + public static final String Flag_Active = "1";//启用 + public static final String Flag_Unactive = "0";//禁用 + + //设备标识 构筑物标识 + public static final String Flag_Equipment = "E";//设备标识 + public static final String Flag_Structure = "S";//构筑物标识 + + + //树节点字符串 + public static final String Tree_Root = "-1";//根节点 + + //数据同步字段 + public static final String Sync_Insert = "I";//插入 + public static final String Sync_Edit = "E";//编辑 + public static final String Sync_Delete = "D";//删除 + public static final String Sync_Finish = "F";//同步完成 + + //unit type + public static final String UNIT_TYPE_USER = "U";// 用户 + public static final String UNIT_TYPE_DEPT = "D";//部门 + public static final String UNIT_TYPE_BIZ = "B";//水厂 + public static final String UNIT_TYPE_WORKSHOP = "W";//车间 + public static final String UNIT_TYPE_COMPANY = "C";//公司 + public static final String UNIT_TYPE_Maintainer = "M";//运维商 + public static final String UNIT_TYPE_JOB = "J";//职位 + + //图标 + public static final String UNIT_BIZ_ICON = "fa fa-fw fa-industry";//水厂 fa-cog fa-steam fa-gears + public static final String UNIT_COMPANY_ICON = "fa fa-fw fa-building";//公司 + public static final String UNIT_DEPT_ICON = "fa fa-fw fa-group";//部门 + public static final String UNIT_USER_ICON = "fa fa-fw fa-male";//用户 + public static final String UNIT_Maintainer_ICON = "fa fa-fw fa-wrench";//维护商 + + public static final String Active_True = "1";// 启用 + public static final String Active_False = "0";//禁用 + + //人员类型 + public static final String UserType_Biz = "0";// 水厂人员 + public static final String UserType_Maintainer = "1";//供应商 + public static final String UserType_Other = "2";//其它 + + //miniMES接收工单的命名空间 + public static final String Resp_Success = "pass"; + public static final String Resp_Failure = "resp_fail"; + //工艺导入产品代码标识字符串 + public static final String Flag_Technics_Name = "产品型号"; + public static final String TaskType_Start = "startEvent"; + public static final String TaskType_UserTask = "task"; + public static final String TaskType_End = "endEvent"; + public static final String TaskType_Gateway = "gateway"; + + public static final String NO_CURRENT_PROCESS = "NO_CURRENT_PROCESS"; + public static final String NO_CURRENT_PROCEDURE = "NO_CURRENT_PROCEDURE"; + public static final String NO_CURRENT_WORKORDER = "NO_CURRENT_WORKORDER"; + public static final String NO_TASKDEMANDS = "NO_TASKDEMANDS"; + public static final String NO_TASKS = "NO_TASKS"; + + public static final String NO_WORKSTATION = "NO_WORKSTATION"; + + public static final String ACTI_Condition_PASS = "${pass}"; //activiti判断节点通过条件 + public static final String ACTI_Condition_FAIL = "${!pass}";//activiti判断节点不通过条件 + public static final String ACTI_KEK_Condition = "pass"; + public static final String ACTI_KEK_Assignee = "applicantId"; + public static final String ACTI_KEK_Candidate_Users = "userIds"; + + //测量点功能分类 + public static final String[] MPointFunType = {"启停", "待机", "故障", "启动", "停止"}; + //工序排序分类 + + public static final String Resp_Success_RFID = "true"; + public static final String Resp_Failure_RFID = "false"; + + public static final String[] MaintenanceMethod = {"电脑远程", "上门服务"}; + + //返回结果字段 + public static final int ONE_STRING = 1;//表示数字1 + public static final int TWO_STRING = 2;//表示数字2 + public static final int ZERO_STRING = 0;//表示数字0 + + public static final String Default_Theme = "skin-blue";//默认主题 + + public static final String MainPageType_Produce = "produce";//首页分类-生产 + public static final String MainPageType_Security = "security";//首页分类-安全 + public static final String MainPageType_Efficiency = "efficiency";//首页分类-效率 + + + public static final String ChartType_Base = "base";//图表展示类型-基础 + public static final String ChartType_Gauge = "gauge";//图表展示类型-仪表 + public static final String ChartType_Bar = "bar";//图表展示类型-柱状图 + public static final String ChartType_Line = "line";//图表展示类型-折线 + public static final String Chart_timeIntervalType = "date";//历史曲线时间间隔天 + + public static final String AnalysisChartType_Word = "word";//数据分析图表展示类型-文字 + public static final String AnalysisChartType_WaterLiquid = "waterLiquid";//数据分析图表展示类型-水球图 + public static final String AnalysisChartType_WaterRange = "waterRange";//数据分析图表展示类型-水球图量程 + public static final String AnalysisChartType_Line = "line";//数据分析图表展示类型-线图 + + + //APP接口调取数据是否成功变量 + public static final String Status_Pass = "pass";//获取数据成功 + public static final String Status_Fail = "fail";//获取数据失败 + + //APP接口调用首页配置信息分类 + public static final String Type_Efficiency = "efficiency";//效率 + public static final String Type_Produce = "produce";//生产 + + //APP接口调用KPI grade字段级别筛选 + public static final String KPI_Grade_Important = "1";//效率 + + public static final String JWT_SESSION_HEADER = "jwt_session"; + public static final String TOKEN_HEADER = "token"; + public static final int ERROR_CODE_SERVER = 500; + + public static final String REDIS_LOCK_MPOINT_PROP_SOURCE_DAY = "MPOINT_PROP_SOURCE_DAY"; + public static final String REDIS_LOCK_MPOINT_PROP_SOURCE_HOUR = "MPOINT_PROP_SOURCE_HOUR"; + public static final String REDIS_LOCK_MPOINT_PROP_SOURCE_MINUTE = "MPOINT_PROP_SOURCE_MINUTE"; + public static final String REDIS_UNIT_LIST = "REDIS_UNIT_LIST"; + + + //已订阅 + public static final String SUBSCRIPTION_STATUS_NORMAL = "1"; + //未订阅 + public static final String SUBSCRIPTION_STATUS_CANCEL = "0"; + + //系统曲线方案 + public static final int CURVES_PLAN_SYSTERM = 1; + //用户曲线方案 + public static final int CURVES_PLAN_USER = 2; + //只有层级关系 + public static final int CURVES_PLAN = 3; + + public static final String TABLE_NAME_TB_SCADA_ALARM = "tb_scada_alarm"; + public static final String TABLE_NAME_TB_SCADA_ALARM1 = "tb_scada_alarm"; + + /** + * minio namespace地址 + */ + public static final String MINIO_NAMESPACE_CONFIG_FILE = "mpointidfile"; + + public static final String ALARMANDPUSHMSG_REDIS_LOCK = "AlarmAndPushMsgRedis"; + + // KPI 计算点月开始日期 + public static final int KPI_MPOINT_START_DAY = 21; + // KPI 计算点日开始时间 + public static final int KPI_MPOINT_START_HOUR = 8; + // KPI 计算点分开始时间 + public static final int KPI_MPOINT_START_MINUTE = 0; + + public static final String UseFreqHistoryFlag = "MPUHistoryFreq"; + public static final String UseFreqFlag = "MPUFreq"; + public static final String CollectFreqFlag = "MPCFreq"; + public static final String MPCurrentValueFlag = "MPAlarmValueFlag";//报警 + + public static final String MPFlag = "MPFlag";//测量点(用于查询里面的属性) + public static final String MPFlagTimeStamp = "MPFlagTimeStamp";//测量点(推送队列的时间戳) + + /** + * Redis + */ + public static final String RedisMpointFlag = "mpoint:current:"; + public static final String RedisMpointUnitId = "mpoint:unitId:"; + public static final String RedisEmqxTopic = "EmqxTopic";//存主题和mqtt代理之间的关系 + public static final String RedisBizDatabase = "BizDatabase";//存主题和mqtt代理之间的关系 + public static final String RedisZhuanFaCheck = "ZhuanFaCheck";//用于检查转发的健康状态 y转发正常 n转发异常 异常后启用备用转发服务 + public static final String REDISMqttTopicMpoint = "mpoint:mqttTopicMpoint";//订阅的主题和点位的关系 + public static final String RedisMPointBzw = "MPointBzw";//标志位缓存表 + + /** + * Kafka + */ + public static final String Kafka_topic_MPOINTSTREAM = "MPOINTSTREAM";//kafka 实时数据主题 + public static final String Kafka_topic_Alarm = "ALARM_DATA";//kafka 报警主题 + public static final String Kafka_topic_MSG = "ALARM_MSG";//kafka PLC主题 + + public static final String Kafka_Topic_Data = "topic_data";//kafka PLC主题 + public static final String Kafka_Topic_Alarm = "topic_alarm";//kafka PLC主题 + public static final String Kafka_Topic_Frontend = "topic_frontend";//kafka PLC主题 + + /** + * mqtt主题 + */ + public static final String Mqtt_Topic_DATA = "topic_data";//长农水厂主题 + + + public static final String BIZID_KCGW = "0791KCGW";//南昌管网 +} diff --git a/src/main/java/com/sipai/tools/CommUtil.java b/src/main/java/com/sipai/tools/CommUtil.java new file mode 100644 index 0000000..4589980 --- /dev/null +++ b/src/main/java/com/sipai/tools/CommUtil.java @@ -0,0 +1,245 @@ +package com.sipai.tools; + + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.*; + +/** + * @author Administrator + */ +public class CommUtil { + + private static final SimpleDateFormat dateFormat = new SimpleDateFormat( + "yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE); + + private static final SimpleDateFormat timeFormat = new SimpleDateFormat( + "hh:mm:ss", Locale.SIMPLIFIED_CHINESE); + + private static final SimpleDateFormat longDateFormat = new SimpleDateFormat( + "yyyy-MM-dd HH:mm:ss", Locale.SIMPLIFIED_CHINESE); + + private static final CommUtil util = new CommUtil(); + + /*public static String HTTP_TYPE="http";//http访问server + public static String WEBSERVICE_TYPE="webservice";//webservice访问server +*/ + public CommUtil() { + } + + public static String getwherestr(String unitid) { + String wherestr = ""; + String[] str = null; + if (unitid == null || unitid.trim().equals("") || unitid.trim().equals(",")) { + wherestr = ""; + } else { + str = unitid.split(","); + for (int i = 0; i < str.length; i++) { + wherestr += "'" + str[i].trim() + "',"; + } + wherestr += "''"; + } + str = null; + return wherestr; + } + + + /** + *  * @description: 测量点值格式化,若值不存在则返回 BigDecimal(0.0) + *  * @param numTail 保留位数 形如(2),rate 倍率 + *  * @return + *  * @author WXP + *  * @date 2020/12/26 15:56 + */ + public static BigDecimal formatMPointValue(BigDecimal source, String numTail, BigDecimal rate) { + if (source == null) { + source = new BigDecimal(0.0); + } + // todo 广业去掉这个 +// if (rate!=null){ +// source = source.multiply(rate); +// } + int length = 0; + if (numTail != null && !numTail.isEmpty()) { + if (numTail.contains(".")) { + length = numTail.length() - numTail.indexOf(".0") - 1; + } else { + length = Integer.parseInt(numTail); + } + } + source = source.setScale(length, BigDecimal.ROUND_HALF_DOWN); + return source; + } + + /** + * jep 公式格式化 + * + * @param formula + * @return + */ + public static String formatJepFormula(String formula) { + if (formula == null) { + return ""; + } + formula = formula.replaceAll(" ", "").replace("#", ""); + formula = formula.replaceAll("(", "(").replaceAll(")", ")"); + return formula; + } + + public static String getLastYearMonth() { + java.time.format.DateTimeFormatter fmt = + java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"); + //获取当前年月日 + LocalDate date = LocalDate.now(); + date = date.minusMonths(1); + String dateStr = date.format(fmt); + return dateStr.substring(0, 7); + } + + public static String getTargetMonthLastSecond(String yearMonth) { + java.time.format.DateTimeFormatter fmt = + java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + String timeStr = yearMonth + "-01 00:00:00"; + LocalDateTime time = LocalDateTime.parse(timeStr, fmt); + time = time.plusMonths(1);//加一个月 + time = time.minusSeconds(1);//减一秒 + String res = time.format(fmt); + return res; + } + + /** + * 时间戳转为日期格式 + * + * @param s + * @return + */ + public static String stampToDate(String s) { + String res; + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + long lt = new Long(s); + Date date = new Date(lt); + res = simpleDateFormat.format(date); + return res; + } + + /** + * 获取当前时间 + * + * @return + */ + public static String nowDate() { + return longDateFormat.format(new Date()); + } + + /** + * 得到唯一值 + * + * @return 返回java的util中唯一值函数的值 + */ + public static String getUUID() { + String uuid = null; + uuid = java.util.UUID.randomUUID().toString().replace("-", ""); + return uuid; + } + + /** + * 接口返回结果json处理 + * + * @param result + * @return + * @throws Exception + */ + public static String toJson(Object result) { + + String json = JSON.toJSONString(result, + SerializerFeature.WriteMapNullValue, + SerializerFeature.WriteNullNumberAsZero, + SerializerFeature.WriteNullListAsEmpty, + SerializerFeature.WriteNullStringAsEmpty, + SerializerFeature.WriteNullBooleanAsFalse, + SerializerFeature.DisableCircularReferenceDetect); + return json; + } + + /** + * 时间戳转换成日期格式字符串 + * + * @param seconds 精确到秒的字符串 + * @param format + * @return + */ + public static String timeStamp2Date(String seconds, String format) { + if (seconds == null || seconds.isEmpty() || seconds.equals("null")) { + return ""; + } + if (format == null || format.isEmpty()) { + format = "yyyy-MM-dd HH:mm:ss"; + } + SimpleDateFormat sdf = new SimpleDateFormat(format); + return sdf.format(new Date(Long.valueOf(seconds + "000"))); + } + + /** + * 获取测量点table名称 + * + * @param mpointCode + * @return + */ + public static String getMPointTableName(String mpointCode) { + String tableName = "tb_mp_" + mpointCode.replace(".", "_").replace(" ", "_"); + + return tableName; + } + + public static boolean isBlank(String str) { + int strLen; + if (str != null && (strLen = str.length()) != 0) { + for (int i = 0; i < strLen; ++i) { + if (!Character.isWhitespace(str.charAt(i))) { + return false; + } + } + + return true; + } else { + return true; + } + } + + public static BigDecimal toBigDecimal(Object value) { + if (value == null) { + return null; + } + + if (value instanceof BigDecimal) { + return (BigDecimal) value; + } else if (value instanceof Integer) { + return BigDecimal.valueOf((Integer) value); + } else if (value instanceof Long) { + return BigDecimal.valueOf((Long) value); + } else if (value instanceof Double) { + // 注意:直接使用Double构造BigDecimal可能导致精度问题 + return new BigDecimal(value.toString()); + } else if (value instanceof Float) { + return new BigDecimal(value.toString()); + } else if (value instanceof String) { + try { + return new BigDecimal((String) value); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("Invalid numeric string: " + value, e); + } + } else { + throw new IllegalArgumentException("Unsupported numeric type: " + value.getClass().getName()); + } + } +} + + + + + diff --git a/src/main/java/com/sipai/tools/ConstantString.java b/src/main/java/com/sipai/tools/ConstantString.java new file mode 100644 index 0000000..f0c429e --- /dev/null +++ b/src/main/java/com/sipai/tools/ConstantString.java @@ -0,0 +1,18 @@ +package com.sipai.tools; + +public class ConstantString { + public static final String DUBBO_VERSION_BASE = "1"; + public static final String DUBBO_VERSION_EQUIPMENT = "1"; + public static final String DUBBO_VERSION_PATROL = "1"; + public static final String DUBBO_VERSION_VISUAL = "1"; + public static final String DUBBO_VERSION_OPERATION = "2"; + + public static final String MQ_ALARM_MSG = "DM_ALARM_MSG"; + + public static final String KEY_ALARM_MSG = "mq.all.send"; + + public static final String MQ_ALARM_MQTT = "DM_ALARM";//现场报警 + public static final String MQ_MPOINT_MQTT = "DM_MPOINT";//现场测量点 + + public static final String REDISSON_ALARM_LIST = "AlarmUpdateList"; +} diff --git a/src/main/java/com/sipai/tools/DataSourceAspect.java b/src/main/java/com/sipai/tools/DataSourceAspect.java new file mode 100644 index 0000000..b525273 --- /dev/null +++ b/src/main/java/com/sipai/tools/DataSourceAspect.java @@ -0,0 +1,89 @@ +package com.sipai.tools; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.After; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Method; + +/** + * aop拦截 -- asp + */ +@Component +@Aspect +@Order(-100)//为了保证可以拦截到 +public class DataSourceAspect { + @Pointcut("execution(* com.sipai.*.*..*(..)) " + //这里扫描的切点包是主要是service层,根据service层方法的上边所说的的自定义注解,去判断所使用的数据源类型,并动态切换数据源 + "&& @annotation(com.sipai.tools.DataSourceTypeAnno)") + public void dataSourcePointcut() { + } + + @Around("dataSourcePointcut()") + public Object doAround(ProceedingJoinPoint pjp) { + MethodSignature methodSignature = (MethodSignature) pjp.getSignature(); + Method method = methodSignature.getMethod(); + DataSourceTypeAnno typeAnno = method.getAnnotation(DataSourceTypeAnno.class); + DataSourceEnum sourceEnum = typeAnno.value(); + + Object[] argusObjects = pjp.getArgs(); + Object argus = argusObjects[0]; + +// if (argus == DataSourceEnum.master) { +// DataSourceContextHolder.setDataSourceType(DataSourceEnum.master); +// } else if (sourceEnum == DataSourceEnum.slaver) { +// DataSourceContextHolder.setDataSourceType(DataSourceEnum.slaver); +// } + + if (argus != null && !argus.equals("") && argusObjects.length >= 2) { + //DataSourceContextHolder.setDataSourceType(DataSourceEnum.valueOf("SCADA_" + argus.toString())); + DataSourceContextHolder.setDataSourceType(DataSourceEnum.valueOf("SCADA_" + argus.toString())); + } else { + DataSourceContextHolder.setDataSourceType(DataSourceEnum.master); + } + Object result = null; + try { + result = pjp.proceed(); + } catch (Throwable throwable) { + throwable.printStackTrace(); + } finally { + DataSourceContextHolder.resetDataSourceType(); + } + return result; + } + + /*@Around("dataSourcePointcut()") + public Object before(ProceedingJoinPoint jp) { + Object[] argusObjects = jp.getArgs(); + Object argus = argusObjects[0]; + //若只有一个参数,则默认使用es + *//*if (argusObjects == null || argusObjects.length < 2 || !(argusObjects[0] instanceof String)) { + return; + }*//* + if (argus != null) { + DataSourceContextHolder.setDataSourceType(DataSourceEnum.master); + } else { + DataSourceContextHolder.setDataSourceType(DataSourceEnum.slaver); + } + Object result = null; + try { + result = jp.proceed(); + } catch (Throwable throwable) { + throwable.printStackTrace(); + } finally { + DataSourceContextHolder.resetDataSourceType(); + } + + return result; + } + + @After("dataSourcePointcut()") + public void after(ProceedingJoinPoint jp) { + DataSourceContextHolder.resetDataSourceType(); + }*/ +} diff --git a/src/main/java/com/sipai/tools/DataSourceContextHolder.java b/src/main/java/com/sipai/tools/DataSourceContextHolder.java new file mode 100644 index 0000000..ef1cb9d --- /dev/null +++ b/src/main/java/com/sipai/tools/DataSourceContextHolder.java @@ -0,0 +1,33 @@ +package com.sipai.tools; + +/** + * 枚举类工具 set + */ +public class DataSourceContextHolder { + private static final ThreadLocal CONTEXT_HOLDER = new ThreadLocal() { + @Override + protected DataSourceEnum initialValue() { + return DataSourceEnum.master; + } + }; + + /** + * 设置数据源 + * @param type + */ + public static void setDataSourceType(DataSourceEnum type) { + CONTEXT_HOLDER.set(type); + } + + /** + * 取得当前数据源 + * @return + */ + public static DataSourceEnum getDataSourceType() { + return CONTEXT_HOLDER.get(); + } + + public static void resetDataSourceType() { + CONTEXT_HOLDER.set(DataSourceEnum.master); + } +} diff --git a/src/main/java/com/sipai/tools/DataSourceEnum.java b/src/main/java/com/sipai/tools/DataSourceEnum.java new file mode 100644 index 0000000..8a3fdc5 --- /dev/null +++ b/src/main/java/com/sipai/tools/DataSourceEnum.java @@ -0,0 +1,10 @@ +package com.sipai.tools; + +/** + * 数据源枚举 + */ +public enum DataSourceEnum { + master + // + ,SCADA_JS1C,SCADA_JS2C,SCADA_JSBZ +} diff --git a/src/main/java/com/sipai/tools/DataSourceTypeAnno.java b/src/main/java/com/sipai/tools/DataSourceTypeAnno.java new file mode 100644 index 0000000..c9988bb --- /dev/null +++ b/src/main/java/com/sipai/tools/DataSourceTypeAnno.java @@ -0,0 +1,16 @@ +package com.sipai.tools; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 自定义注解 + */ +@Retention(RetentionPolicy.RUNTIME) // 在运行时可见 +@Target(ElementType.METHOD) // 注解可以用在方法上 +public @interface DataSourceTypeAnno { + //使用方式在service层方法上添加@DataSourceTypeAnno(DataSourceEnum.数据源枚举类型)用于指定所使用的数据源 + DataSourceEnum value() default DataSourceEnum.master; +} diff --git a/src/main/java/com/sipai/tools/DynamicDataSource.java b/src/main/java/com/sipai/tools/DynamicDataSource.java new file mode 100644 index 0000000..e790667 --- /dev/null +++ b/src/main/java/com/sipai/tools/DynamicDataSource.java @@ -0,0 +1,12 @@ +package com.sipai.tools; + +import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; + +/** + * 继承 AbstractRoutingDataSource 类,实现对应数据源key的切换 + */ +public class DynamicDataSource extends AbstractRoutingDataSource { + protected Object determineCurrentLookupKey() { + return DataSourceContextHolder.getDataSourceType(); + } +} diff --git a/src/main/java/com/sipai/tools/EncryptGISUtils.java b/src/main/java/com/sipai/tools/EncryptGISUtils.java new file mode 100644 index 0000000..47965cf --- /dev/null +++ b/src/main/java/com/sipai/tools/EncryptGISUtils.java @@ -0,0 +1,99 @@ +package com.sipai.tools; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +public class EncryptGISUtils { + + // 参数分别代表 算法名称/加密模式/数据填充方式(CBC模式必须指定IV) + private static final String ALGORITHMSTR = "AES/CBC/NoPadding"; // 注意:NoPadding 需手动处理填充 + private static final String KEY = "jP0fD2cJ3tC9xT5k"; // 16字节(128位)密钥,符合AES要求 + private static final String IV = "rA3sN2rJ5uZ7dY4u"; // 自定义IV,必须为16字节(CBC模式块大小为16字节) + + // 封装默认IV的便捷方法 + public static String encrypt(String content) throws Exception { + return encrypt(content, KEY, IV); + } + + public static String decrypt(String encryptStr) throws Exception { + return decrypt(encryptStr, KEY, IV); + } + + /** + * 加密(含IV处理) + */ + public static String encrypt(String content, String encryptKey, String iv) throws Exception { + // 校验IV长度(必须为16字节) + if (iv.getBytes(StandardCharsets.UTF_8).length != 16) { + throw new IllegalArgumentException("IV必须为16字节(128位)"); + } + + SecretKeySpec secretKey = new SecretKeySpec(encryptKey.getBytes(StandardCharsets.UTF_8), "AES"); + IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)); + Cipher cipher = Cipher.getInstance(ALGORITHMSTR); + cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec); + + // 处理NoPadding的填充(明文需为16字节整数倍) + byte[] plaintextBytes = content.getBytes(StandardCharsets.UTF_8); + int blockSize = cipher.getBlockSize(); + int paddingLength = blockSize - (plaintextBytes.length % blockSize); + if (paddingLength != 0 && paddingLength != blockSize) { // 非整数倍时填充 + byte[] paddedBytes = new byte[plaintextBytes.length + paddingLength]; + System.arraycopy(plaintextBytes, 0, paddedBytes, 0, plaintextBytes.length); + plaintextBytes = paddedBytes; + } else if (paddingLength == 0 && blockSize != plaintextBytes.length) { // 若正好整除但非块大小,不填充(仅适用于特殊场景) + // 若业务要求必须填充,可强制添加blockSize字节填充 + } + + byte[] encryptedBytes = cipher.doFinal(plaintextBytes); + return Base64.getEncoder().encodeToString(encryptedBytes); + } + + /** + * 解密(含IV处理) + */ + public static String decrypt(String encryptStr, String decryptKey, String iv) throws Exception { + // 校验IV长度 + if (iv.getBytes(StandardCharsets.UTF_8).length != 16) { + throw new IllegalArgumentException("IV必须为16字节(128位)"); + } + + SecretKeySpec secretKey = new SecretKeySpec(decryptKey.getBytes(StandardCharsets.UTF_8), "AES"); + IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)); + Cipher cipher = Cipher.getInstance(ALGORITHMSTR); + cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec); + + byte[] encryptedBytes = Base64.getDecoder().decode(encryptStr); + byte[] decryptedBytes = cipher.doFinal(encryptedBytes); + + // 去除NoPadding的填充(需与加密逻辑一致) + int blockSize = cipher.getBlockSize(); + int dataLength = decryptedBytes.length; + if (dataLength % blockSize != 0) { + throw new IllegalArgumentException("密文长度非块大小整数倍,解密失败"); + } + // 若加密时未填充,直接返回明文 + return new String(decryptedBytes, StandardCharsets.UTF_8); + } + + + + /*public static void main(String[] args) { + try { + String original = "admin"; + String encrypted = encrypt(original); + String decrypted = decrypt(encrypted); + System.out.println(encrypted); + System.out.println("-----------"); + System.out.println(decrypted); + } catch (Exception e) { + e.printStackTrace(); + } + }*/ + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/tools/HttpUtil.java b/src/main/java/com/sipai/tools/HttpUtil.java new file mode 100644 index 0000000..bb3ce23 --- /dev/null +++ b/src/main/java/com/sipai/tools/HttpUtil.java @@ -0,0 +1,311 @@ +package com.sipai.tools; + +//import org.apache.axis2.addressing.EndpointReference; +//import org.apache.axis2.client.Options; +//import org.apache.axis2.rpc.client.RPCServiceClient; +import org.apache.http.Consts; +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.ParseException; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.protocol.HTTP; +import org.apache.http.util.EntityUtils; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + + +/** + * @author wxp + * + */ +public class HttpUtil { + + private static final CloseableHttpClient httpclient = HttpClients.createDefault(); + private static final String APPLICATION_JSON = "application/json"; + private static final String CONTENT_TYPE_TEXT_JSON = "application/json"; + + /** + * 发送HttpGet请求 + * @param url + * @return + */ + public static String sendGet(String url) { + + HttpGet httpget = new HttpGet(url); + CloseableHttpResponse response = null; + try { + response = httpclient.execute(httpget); + } catch (IOException e1) { + e1.printStackTrace(); + } + String result = null; + if(response!=null){ + try { + HttpEntity entity = response.getEntity(); + if (entity != null) { + result = EntityUtils.toString(entity); + } + } catch (ParseException | IOException e) { + e.printStackTrace(); + } finally { + try { + + response.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return result; + } + + public static String sendGet(String url, Map params, Map headers) { + String result = null; + try { + // 构建带参数的URL + URIBuilder uriBuilder = new URIBuilder(url); + + // 添加查询参数 + if (params != null && !params.isEmpty()) { + for (Map.Entry entry : params.entrySet()) { + uriBuilder.addParameter(entry.getKey(), entry.getValue()); + } + } + + // 创建GET请求 + HttpGet httpGet = new HttpGet(uriBuilder.build()); + + // 设置请求头 + if (headers != null && !headers.isEmpty()) { + for (Map.Entry entry : headers.entrySet()) { + httpGet.setHeader(entry.getKey(), entry.getValue()); + } + } + + // 执行请求 + try (CloseableHttpResponse response = httpclient.execute(httpGet)) { + // 获取响应结果 + if (response.getEntity() != null) { + result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + /** + * 发送HttpPost请求,参数为map + * @param url + * @param map + * @return + */ + public static String sendPost(String url, Map map) { + List formparams = new ArrayList(); + for (Map.Entry entry : map.entrySet()) { + formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); + HttpPost httppost = new HttpPost(url); + httppost.setEntity(entity); + CloseableHttpResponse response = null; + try { + response = httpclient.execute(httppost); + } catch (IOException e) { + e.printStackTrace(); + } + HttpEntity entity1 = response.getEntity(); + String result = null; + try { + result = EntityUtils.toString(entity1); + } catch (ParseException | IOException e) { + e.printStackTrace(); + } + return result; + } + + /** + * 发送带请求头的POST请求 + * @param url 请求地址 + * @param map 请求参数 + * @param headers 请求头信息(可包含token) + * @return 响应结果 + */ + public static String sendPost(String url, Map map, Map headers) { + String result = null; + try { + HttpPost httppost = new HttpPost(url); + + // 读取 Content-Type 决定 body 构造方式 + String ct = null; + if (headers != null && !headers.isEmpty()) { + for (Map.Entry e : headers.entrySet()) { + if (!"Content-Type".equalsIgnoreCase(e.getKey())) { // Content-Type 由实体自动设置 + httppost.setHeader(e.getKey(), e.getValue()); + } else { + ct = e.getValue(); + } + } + } + String ctLower = ct == null ? "" : ct.toLowerCase(); + + HttpEntity entity; + if (ctLower.contains("multipart/form-data")) { + // === form-data (multipart) === + MultipartEntityBuilder mb = MultipartEntityBuilder.create() + .setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + if (map != null) { + for (Map.Entry e : map.entrySet()) { + mb.addTextBody(e.getKey(), + e.getValue() == null ? "" : e.getValue(), + ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8)); + } + } + entity = mb.build(); // 会自动带 boundary 和正确的 Content-Type + } else if (ctLower.contains("application/x-www-form-urlencoded")) { + // === x-www-form-urlencoded === + List formparams = new ArrayList<>(); + if (map != null) { + for (Map.Entry e : map.entrySet()) { + formparams.add(new BasicNameValuePair(e.getKey(), + e.getValue() == null ? "" : e.getValue())); + } + } + entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); + } else { + // === 默认走 JSON === + String jsonParams = mapToJson(map); // 你类里已有 + StringEntity se = new StringEntity(jsonParams, StandardCharsets.UTF_8); + se.setContentType("application/json"); + entity = se; + } + + httppost.setEntity(entity); + + try (CloseableHttpResponse response = httpclient.execute(httppost)) { + if (response.getEntity() != null) { + result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + /** + * 发送HttpPost请求,参数为json + * @param url + * @param json + * @return + */ + public static String sendPost(String url, String json) { + String result = null; + try { + StringEntity entity = new StringEntity(json); + entity.setContentType(CONTENT_TYPE_TEXT_JSON); + entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON)); + HttpPost httppost = new HttpPost(url); + httppost.setEntity(entity); + CloseableHttpResponse response = null; + response = httpclient.execute(httppost); + HttpEntity entity1 = response.getEntity(); + result = EntityUtils.toString(entity1); + } catch (ParseException | IOException e) { + e.printStackTrace(); + } + return result; + } + + /** + * 发送不带参数的HttpPost请求 + * @param url + * @return + */ + public static String sendPost(String url) { + HttpPost httppost = new HttpPost(url); + CloseableHttpResponse response = null; + try { + response = httpclient.execute(httppost); + } catch (IOException e) { + e.printStackTrace(); + } + HttpEntity entity = response.getEntity(); + String result = null; + try { + result = EntityUtils.toString(entity); + } catch (ParseException | IOException e) { + e.printStackTrace(); + } + return result; + } + /** + * 发送webservice请求 + * @param + * @return + *//* + public static String sendWebServie(String server,String method,String[] param ,String namespace,boolean flag) { + String result = null; + EndpointReference targetEPR = new EndpointReference(server); + RPCServiceClient sender; + try { + sender = new RPCServiceClient(); + Options options = sender.getOptions(); + options.setTimeOutInMilliSeconds(1000*5);//超时时间5s + options.setTo(targetEPR); + QName qname = new QName(namespace,method); + int length =param.length; + //String result="{\"res\":"+json+"}"; +// param = new Object[]{CommUtil.GZIPcompress(paramJson)}; + Class[] types = new Class[length]; + //这是针对返值类型的 + + for(int i=0;i map) { + if (map == null || map.isEmpty()) { + return "{}"; + } + // 使用fastjson示例 + return com.alibaba.fastjson.JSONObject.toJSONString(map); + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/tools/MyBatisConfig.java b/src/main/java/com/sipai/tools/MyBatisConfig.java new file mode 100644 index 0000000..2b70d78 --- /dev/null +++ b/src/main/java/com/sipai/tools/MyBatisConfig.java @@ -0,0 +1,110 @@ +package com.sipai.tools; + +import org.apache.ibatis.session.SqlSessionFactory; +import org.mybatis.spring.SqlSessionFactoryBean; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.jdbc.DataSourceBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; + +import javax.sql.DataSource; +import java.util.HashMap; +import java.util.Map; + +@Configuration +@MapperScan(basePackages = "com.sipai.dao")//扫描dao层mapper接口 +public class MyBatisConfig { + /** + * @return + * @throws Exception + * @Primary 必需指定一个且只能有一个主数据源,否则报错 + */ + @Primary + @Bean("masterDataSource") + @ConfigurationProperties(prefix = "spring.datasource.master")//根据数据源前缀到application.yml读取数据源信息//此处改变前缀可以改变默认数据源// + public DataSource masterDataSource() throws Exception { + return DataSourceBuilder.create().build(); + } + + /** + * 下面为管网 + */ + @Bean("SCADA_JS1C") + @ConfigurationProperties(prefix = "spring.datasource.js1") + //根据数据源前缀到application.yml读取数据源信息//可以配置更多数据源,到前提是application.yml中存在,而且也需要在枚举类中添加枚举类型 + public DataSource fssk() throws Exception { + return DataSourceBuilder.create().build(); + } + + /** + * 下面为管网 + */ + @Bean("SCADA_JS2C") + @ConfigurationProperties(prefix = "spring.datasource.js2") + //根据数据源前缀到application.yml读取数据源信息//可以配置更多数据源,到前提是application.yml中存在,而且也需要在枚举类中添加枚举类型 + public DataSource fssk2() throws Exception { + return DataSourceBuilder.create().build(); + } + + /** + * 下面为管网 + */ + @Bean("SCADA_JSBZ") + @ConfigurationProperties(prefix = "spring.datasource.js3") + //根据数据源前缀到application.yml读取数据源信息//可以配置更多数据源,到前提是application.yml中存在,而且也需要在枚举类中添加枚举类型 + public DataSource fssk3() throws Exception { + return DataSourceBuilder.create().build(); + } + + /** + * @Qualifier 根据名称进行注入,通常是在具有相同的多个类型的实例的一个注入(例如有多个DataSource类型的实例) + * @DataSourceTypeAnno(DataSourceEnum.master)事务方法需要指定数据源 + */ + @Bean("dynamicDataSource") + public DynamicDataSource dynamicDataSource(@Qualifier("masterDataSource") DataSource masterDataSource, + @Qualifier("SCADA_JS1C") DataSource SCADA_JS1C, + @Qualifier("SCADA_JS2C") DataSource SCADA_JS2C, + @Qualifier("SCADA_JSBZ") DataSource SCADA_JSBZ) { + Map targetDataSources = new HashMap(); + targetDataSources.put(DataSourceEnum.master, masterDataSource); + + targetDataSources.put(DataSourceEnum.SCADA_JS1C, SCADA_JS1C); + targetDataSources.put(DataSourceEnum.SCADA_JS2C, SCADA_JS2C); + targetDataSources.put(DataSourceEnum.SCADA_JSBZ, SCADA_JSBZ); + + DynamicDataSource dataSource = new DynamicDataSource(); + dataSource.setTargetDataSources(targetDataSources);// 该方法是AbstractRoutingDataSource的方法 + dataSource.setDefaultTargetDataSource(masterDataSource);// 默认的datasource设置为myTestDbDataSource + + return dataSource; + } + + /** + * 根据数据源创建SqlSessionFactory + */ + @Bean + public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DynamicDataSource dynamicDataSource, + @Value("mybatis.type-aliases-package") String typeAliasesPackage) throws Exception { + SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); + factoryBean.setDataSource(dynamicDataSource);// 指定数据源(这个必须有,否则报错) + // 下边两句仅仅用于*.xml文件,如果整个持久层操作不需要使用到xml文件的话(只用注解就可以搞定),则不加 D:\ideawork\emqx\src\main\resources\mybatis\mapper + factoryBean.setTypeAliasesPackage(typeAliasesPackage);// 指定实体类所在的包 + factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/**/*.xml"));//扫描mapper.xml文件包 + return factoryBean.getObject(); + } + + /** + * 配置事务管理器 + */ + @Bean + public DataSourceTransactionManager transactionManager(DynamicDataSource dataSource) throws Exception { + return new DataSourceTransactionManager(dataSource); + } + +} diff --git a/src/main/java/com/sipai/tools/Result.java b/src/main/java/com/sipai/tools/Result.java new file mode 100644 index 0000000..b5337f9 --- /dev/null +++ b/src/main/java/com/sipai/tools/Result.java @@ -0,0 +1,68 @@ +package com.sipai.tools; + +import com.alibaba.fastjson.JSON; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +//@Data +//@AllArgsConstructor +//@NoArgsConstructor +//@Builder +public class Result { + public static final int SUCCESS = 1; + public static final int FAILED = 0; + public static final int REPEATED = 2;//重复添加 + + public Result() { + + } + + public Result(int code, String message, Object result) { + this.code = code; + this.msg = message; + if (result instanceof String) { + this.result = JSON.parse(result.toString()); + } else { + this.result = result; + } + + } + + public static Result success(Object result) { + return new Result(SUCCESS, "", result); + } + + public static Result failed(String msg) { + return new Result(FAILED, msg, null); + } + + public int code; + public String msg; + public Object result; + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public Object getResult() { + return result; + } + + public void setResult(Object result) { + this.result = result; + } +} diff --git a/src/main/java/com/sipai/tools/SpringContextUtil.java b/src/main/java/com/sipai/tools/SpringContextUtil.java new file mode 100644 index 0000000..7d0712b --- /dev/null +++ b/src/main/java/com/sipai/tools/SpringContextUtil.java @@ -0,0 +1,49 @@ +package com.sipai.tools; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +@Component +public class SpringContextUtil implements ApplicationContextAware { + + private static ApplicationContext applicationContext; // Spring应用上下文环境 + + // 下面的这个方法上加了@Override注解,原因是继承ApplicationContextAware接口是必须实现的方法 + @Override + public void setApplicationContext(ApplicationContext applicationContext) + throws BeansException { + SpringContextUtil.applicationContext = applicationContext; + } + + public static ApplicationContext getApplicationContext() { + return applicationContext; + } + + public static Object getBean(String name) throws BeansException { + return applicationContext.getBean(name); + } + + public static Object getBean(String name, Class requiredType) + throws BeansException { + return applicationContext.getBean(name, requiredType); + } + + public static boolean containsBean(String name) { + return applicationContext.containsBean(name); + } + + public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException { + return applicationContext.isSingleton(name); + } + + public static Class getType(String name) throws NoSuchBeanDefinitionException { + return applicationContext.getType(name); + } + + public static String[] getAliases(String name) throws NoSuchBeanDefinitionException { + return applicationContext.getAliases(name); + } +} diff --git a/src/main/java/com/sipai/tools/Test.java b/src/main/java/com/sipai/tools/Test.java new file mode 100644 index 0000000..c7b6541 --- /dev/null +++ b/src/main/java/com/sipai/tools/Test.java @@ -0,0 +1,40 @@ +package com.sipai.tools; + +import java.util.LinkedHashMap; +import java.util.HashMap; +import java.util.Map; + +public class Test { + + // ==== 配置 ==== + private static final String BASE_URL = "http://223.84.61.83:3033/SIPAIIS_DataCenter/work/mPointProp/saveHistory.do"; // TODO: 换成实际 IP + private static final String SDT = "2025-06-01 15:00:00"; + private static final String EDT = "2025-09-06 20:00:00"; + private static final String TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpbk5hbWUiOiJzaXBhaSIsImV4cCI6MTc1NzE4MjgyOSwidXNlcklkIjoiMzUxMDQ1MjA4NzQzNDgxMzQ0IiwiaWF0IjoxNzU3MTMyNDI5fQ.394bRjBQfty7VFxVUWOl97ktQoi-SR8wmMZSAVf3Xr8"; // <<< 常量 token + + public static void main(String[] args) { + // 头:携带 token(以及可选的 Content-Type) + Map headers = new HashMap<>(); + headers.put("token", TOKEN); + headers.put("Content-Type", "multipart/form-data"); + + for (int i = 1; i <= 2; i++) { + String id = String.format("KCGW_220%02d_P1_HOUR", i); + + Map form = new LinkedHashMap<>(); + form.put("id", id); + form.put("sdt", SDT); + form.put("edt", EDT); + form.put("unitId", ""); + form.put("searchChildFlag", "false"); + + String resp = HttpUtil.sendPost(BASE_URL, form, headers); + System.out.println(id + " -> " + cut(resp, 200)); + + try { Thread.sleep(150); } catch (InterruptedException ignored) {} + } + } + + private static String cut(String s, int n) { return s == null ? "" : (s.length() > n ? s.substring(0, n) + "..." : s); } + +} diff --git a/src/main/java/com/sipai/tools/ThreadConfig.java b/src/main/java/com/sipai/tools/ThreadConfig.java new file mode 100644 index 0000000..e13a6cf --- /dev/null +++ b/src/main/java/com/sipai/tools/ThreadConfig.java @@ -0,0 +1,57 @@ +package com.sipai.tools; + +import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.AsyncConfigurer; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.Executor; + +/** + * @Auther: sj + * @Date: 2021/04/25/23:01 + * @Description: + */ +@Configuration +@EnableAsync +public class ThreadConfig implements AsyncConfigurer { + + @Override + public Executor getAsyncExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + // 配置核心线程数 + executor.setCorePoolSize(10); + // 设置最大线程数 + executor.setMaxPoolSize(100); + // 设置队列容量 + executor.setQueueCapacity(9999); + // 设置线程活跃时间(秒) + executor.setKeepAliveSeconds(60); + executor.initialize(); + return executor; + } + + @Bean + public Executor getAsyncMqttHandle() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + // 配置核心线程数 + executor.setCorePoolSize(10); + // 设置最大线程数 + executor.setMaxPoolSize(1000); + // 设置队列容量 + executor.setQueueCapacity(9999); + // 设置线程活跃时间(秒) + executor.setKeepAliveSeconds(60); + // 配置线程池中的线程的名称前缀 + executor.setThreadNamePrefix("mqttHandle"); + executor.initialize(); + return executor; + } + + @Override + public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { + return null; + } +} diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml new file mode 100644 index 0000000..b447ca1 --- /dev/null +++ b/src/main/resources/application-dev.yml @@ -0,0 +1,160 @@ +# 开发环境配置 +server: + # 服务器的HTTP端口,默认为8080 + port: 8092 + servlet: + # 应用的访问路径 + context-path: /sipaiis_data + tomcat: + # tomcat的URI编码 + uri-encoding: UTF-8 + +# DataSource Config +spring: + redis: + mode: single #单服务模式 + host: 132.120.136.19 + port: 6379 + database: 0 + cluster: + nodes: 172.16.242.44:6379,172.16.242.45:6379,172.16.242.46:6379,172.16.242.47:6379,172.16.242.48:6379,172.16.242.49:6379 + max-redirects: 3 + password: zaqwsx + timeout: 100000 + + data: + elasticsearch: + cluster-name: elasticsearch-sipaiis + cluster-nodes: 132.120.136.19:9200 + + datasource: + master: + username: sa + password: ZAQwsx@2016 + jdbc-url: jdbc:sqlserver://132.120.136.19:1433;DatabaseName=JSYW + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + type: com.alibaba.druid.pool.DruidDataSource + + #生产库 + js1: + username: sa + password: ZAQwsx@2016 + jdbc-url: jdbc:sqlserver://132.120.136.19:1433;DatabaseName=EIP_PRD_JS1C + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + type: com.alibaba.druid.pool.DruidDataSource + + #生产库 + js2: + username: sa + password: ZAQwsx@2016 + jdbc-url: jdbc:sqlserver://132.120.136.19:1433;DatabaseName=EIP_PRD_JS1C + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + type: com.alibaba.druid.pool.DruidDataSource + + #生产库 + js3: + username: sa + password: ZAQwsx@2016 + jdbc-url: jdbc:sqlserver://132.120.136.19:1433;DatabaseName=EIP_PRD_JS1C + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + type: com.alibaba.druid.pool.DruidDataSource + + kafka: + # Kafka 服务器地址 (KRaft模式) + bootstrap-servers: 192.168.10.17:9092 + + # 生产者配置 + producer: + key-serializer: org.apache.kafka.common.serialization.StringSerializer + value-serializer: org.apache.kafka.common.serialization.StringSerializer + acks: all + retries: 3 + + # 消费者配置 + consumer: + group-id: my-group-2.2.0 + auto-offset-reset: earliest + key-deserializer: org.apache.kafka.common.serialization.StringDeserializer + value-deserializer: org.apache.kafka.common.serialization.StringDeserializer + enable-auto-commit: false + properties: + missing.topics.fatal: false # 关键修正点 + + listener: + ack-mode: manual # 设置为手动提交 + + # Admin客户端配置(用于topic自动创建) + admin: + fail-fast: true + properties: + auto.create.topics.enable: true + + # 适配Kafka 3.x的额外配置 + properties: + security.protocol: PLAINTEXT + # interceptor.classes: org.apache.kafka.clients.interceptor.ProducerInterceptor + + # rabbitmq: + # host: 10.18.68.10:90 + # port: 5672 + # username: admin + # password: admin + # #虚拟host 可以不设置,使用server默认host + # virtual-host: / + + main: + allow-bean-definition-overriding: true #当遇到同样名字的时候,是否允许覆盖注册 + +mybatis: + mapper-locations: classpath:mybatis/mapper/**/*.xml + type-aliases-package: com.sipai.entity + +#showSql +logging: + config: classpath:log4j2.xml +# level: +# com: +# example: +# mapper: debug + +thymeleaf: + mode: HTML + encoding: utf-8 + cache: false + enabled: false + prefix: classpath:/templates/ + +# PageHelper配置(application.yml) +pagehelper: + helper-dialect: mysql + reasonable: true + support-methods-arguments: true + params: count=countSql + +opcua: + enabled: false # 是否启用OPC UA功能,默认为true + server-url: "opc.tcp://132.120.136.19:49320" # OPC UA服务器地址和端口 + # security-policy: Basic256Sha256 + # security-mode: SignAndEncrypt + security-policy: None # 安全策略设为None + security-mode: None # 安全模式设为None + username: "administrator" # 用户名(可选) + password: "sipai@64368180" # 密码(可选) + +app: + max-points: 200 #实时数据接口一次最多点位数 + +mqtt: + broker-address: "tcp://192.168.10.17:1883" + dashboard-01: "http://192.168.10.17:18083" + username: "admin" + password: "sipai@64368180" + +# udp服务 +udp: + server: + enabled: false # 是否启用UDP服务,默认为true + port: 5006 # UDP服务端口 + +scheduled: + enabled: true # 设置为false即可临时关闭定时任务 \ No newline at end of file diff --git a/src/main/resources/application-pro.yml b/src/main/resources/application-pro.yml new file mode 100644 index 0000000..793ac01 --- /dev/null +++ b/src/main/resources/application-pro.yml @@ -0,0 +1,160 @@ +# 开发环境配置 +server: + # 服务器的HTTP端口,默认为8080 + port: 8092 + servlet: + # 应用的访问路径 + context-path: /sipaiis_data + tomcat: + # tomcat的URI编码 + uri-encoding: UTF-8 + +# DataSource Config +spring: + redis: + mode: single #单服务模式 + host: 172.30.24.104 + port: 6379 + database: 0 + cluster: + nodes: 172.16.242.44:6379,172.16.242.45:6379,172.16.242.46:6379,172.16.242.47:6379,172.16.242.48:6379,172.16.242.49:6379 + max-redirects: 3 + password: zaqwsx + timeout: 100000 + + data: + elasticsearch: + cluster-name: elasticsearch-sipaiis + cluster-nodes: 172.30.24.104:9200 + + datasource: + master: + username: sa + password: ZAQwsx@2016 + jdbc-url: jdbc:sqlserver://172.30.24.104:1433;DatabaseName=SIPAIIS_WMS + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + type: com.alibaba.druid.pool.DruidDataSource + + #生产库 + js1: + username: sa + password: ZAQwsx@2016 + jdbc-url: jdbc:sqlserver://172.30.24.110:1433;DatabaseName=EIP_PRD_JS1C + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + type: com.alibaba.druid.pool.DruidDataSource + + #生产库 + js2: + username: sa + password: ZAQwsx@2016 + jdbc-url: jdbc:sqlserver://172.30.24.110:1433;DatabaseName=EIP_PRD_JS2C + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + type: com.alibaba.druid.pool.DruidDataSource + + #生产库 + js3: + username: sa + password: ZAQwsx@2016 + jdbc-url: jdbc:sqlserver://172.30.24.110:1433;DatabaseName=EIP_PRD_JSBZ + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + type: com.alibaba.druid.pool.DruidDataSource + + kafka: + # Kafka 服务器地址 (KRaft模式) + bootstrap-servers: 192.168.10.17:9092 + + # 生产者配置 + producer: + key-serializer: org.apache.kafka.common.serialization.StringSerializer + value-serializer: org.apache.kafka.common.serialization.StringSerializer + acks: all + retries: 3 + + # 消费者配置 + consumer: + group-id: my-group-2.2.0 + auto-offset-reset: earliest + key-deserializer: org.apache.kafka.common.serialization.StringDeserializer + value-deserializer: org.apache.kafka.common.serialization.StringDeserializer + enable-auto-commit: false + properties: + missing.topics.fatal: false # 关键修正点 + + listener: + ack-mode: manual # 设置为手动提交 + + # Admin客户端配置(用于topic自动创建) + admin: + fail-fast: true + properties: + auto.create.topics.enable: true + + # 适配Kafka 3.x的额外配置 + properties: + security.protocol: PLAINTEXT + # interceptor.classes: org.apache.kafka.clients.interceptor.ProducerInterceptor + + # rabbitmq: + # host: 10.18.68.10:90 + # port: 5672 + # username: admin + # password: admin + # #虚拟host 可以不设置,使用server默认host + # virtual-host: / + + main: + allow-bean-definition-overriding: true #当遇到同样名字的时候,是否允许覆盖注册 + +mybatis: + mapper-locations: classpath:mybatis/mapper/**/*.xml + type-aliases-package: com.sipai.entity + +#showSql +logging: + config: classpath:log4j2.xml +# level: +# com: +# example: +# mapper: debug + +thymeleaf: + mode: HTML + encoding: utf-8 + cache: false + enabled: false + prefix: classpath:/templates/ + +# PageHelper配置(application.yml) +pagehelper: + helper-dialect: mysql + reasonable: true + support-methods-arguments: true + params: count=countSql + +opcua: + enabled: false # 是否启用OPC UA功能,默认为true + server-url: "opc.tcp://172.30.24.110:49320" # OPC UA服务器地址和端口 + # security-policy: Basic256Sha256 + # security-mode: SignAndEncrypt + security-policy: None # 安全策略设为None + security-mode: None # 安全模式设为None + username: "administrator" # 用户名(可选) + password: "sipai@64368180" # 密码(可选) + +app: + max-points: 200 #实时数据接口一次最多点位数 + +mqtt: + broker-address: "tcp://172.30.24.110:1883" + dashboard-01: "http://172.30.24.110:18083" + username: "admin" + password: "sipai@64368180" + +# udp服务 +udp: + server: + enabled: false # 是否启用UDP服务,默认为true + port: 5006 # UDP服务端口 + +scheduled: + enabled: true # 设置为false即可临时关闭定时任务 \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..1728aa5 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,4 @@ +spring: + profiles: +# active: dev + active: pro diff --git a/src/main/resources/generatior-config.xml b/src/main/resources/generatior-config.xml new file mode 100644 index 0000000..5b672f1 --- /dev/null +++ b/src/main/resources/generatior-config.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
\ No newline at end of file diff --git a/src/main/resources/log4j2.xml b/src/main/resources/log4j2.xml new file mode 100644 index 0000000..414b860 --- /dev/null +++ b/src/main/resources/log4j2.xml @@ -0,0 +1,116 @@ + + + + + ${sys:server.port:-unknown} + + ./logs_emqx/${server.port} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mybatis-config.xml b/src/main/resources/mybatis-config.xml new file mode 100644 index 0000000..b2cfc83 --- /dev/null +++ b/src/main/resources/mybatis-config.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/Listener/ListenerHis.xml b/src/main/resources/mybatis/mapper/Listener/ListenerHis.xml new file mode 100644 index 0000000..a399850 --- /dev/null +++ b/src/main/resources/mybatis/mapper/Listener/ListenerHis.xml @@ -0,0 +1,114 @@ + + + + + + + + + + + + id, pointid, value, type, insdt + + + + delete + from Listener_His + where id = #{id,jdbcType=VARCHAR} + + + insert into Listener_His (id, pointid, value, type, insdt) + values (#{id,jdbcType=VARCHAR}, #{pointid,jdbcType=VARCHAR}, #{value,jdbcType=VARCHAR}, + #{type,jdbcType=VARCHAR}, #{insdt,jdbcType=VARCHAR}) + + + insert into Listener_His + + + id, + + + pointid, + + + value, + + + type, + + + insdt + + + + + #{id,jdbcType=VARCHAR}, + + + #{pointid,jdbcType=VARCHAR}, + + + #{value,jdbcType=VARCHAR}, + + + #{type,jdbcType=VARCHAR}, + + + #{insdt,jdbcType=VARCHAR} + + + + + update Listener_His + + + id = #{id,jdbcType=VARCHAR}, + + + pointid = #{pointid,jdbcType=VARCHAR}, + + + value = #{value,jdbcType=VARCHAR}, + + + type = #{type,jdbcType=VARCHAR}, + + + insdt = #{insdt,jdbcType=VARCHAR} + + + where id = #{id,jdbcType=VARCHAR} + + + update Listener_His + set id = #{id,jdbcType=VARCHAR}, + pointid = #{pointid,jdbcType=VARCHAR}, + value = #{value,jdbcType=VARCHAR}, + type = #{type,jdbcType=VARCHAR}, + insdt = #{insdt,jdbcType=VARCHAR} + where id = #{id,jdbcType=VARCHAR} + + + + delete + from Listener_His + ${where} + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/Listener/ListenerInterfaceMapper.xml b/src/main/resources/mybatis/mapper/Listener/ListenerInterfaceMapper.xml new file mode 100644 index 0000000..00b7a95 --- /dev/null +++ b/src/main/resources/mybatis/mapper/Listener/ListenerInterfaceMapper.xml @@ -0,0 +1,108 @@ + + + + + + + + + + + + id, name, type, url, port + + + + delete + from Listener_Interface + where id = #{id,jdbcType=VARCHAR} + + + insert into Listener_interface (id, name, type, url, port) + values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, + #{url,jdbcType=VARCHAR}, #{port,jdbcType=VARCHAR}) + + + insert into Listener_Interface + + + id, + + + name, + + + type, + + + url, + + + port + + + + + #{id,jdbcType=VARCHAR}, + + + #{name,jdbcType=VARCHAR}, + + + #{type,jdbcType=VARCHAR}, + + + #{url,jdbcType=VARCHAR}, + + + #{port,jdbcType=VARCHAR} + + + + + update Listener_Interface + + + id = #{id,jdbcType=VARCHAR}, + + + name = #{name,jdbcType=VARCHAR}, + + + type = #{type,jdbcType=VARCHAR}, + + + url = #{url,jdbcType=VARCHAR}, + + + port = #{port,jdbcType=VARCHAR} + + + where id = #{id,jdbcType=VARCHAR} + + + update Listener_Interface + set id = #{id,jdbcType=VARCHAR}, + name = #{name,jdbcType=VARCHAR}, + type = #{type,jdbcType=VARCHAR}, + url = #{url,jdbcType=VARCHAR}, + port = #{port,jdbcType=VARCHAR} + where id = #{id,jdbcType=VARCHAR} + + + + delete + from Listener_Interface + ${where} + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/Listener/ListenerMessageMapper.xml b/src/main/resources/mybatis/mapper/Listener/ListenerMessageMapper.xml new file mode 100644 index 0000000..738dcaa --- /dev/null +++ b/src/main/resources/mybatis/mapper/Listener/ListenerMessageMapper.xml @@ -0,0 +1,108 @@ + + + + + + + + + + + + id, Cmdtype, Objid, Action, insdt + + + + delete + from listener_message + where id = #{id, jdbcType=VARCHAR} + + + insert into listener_message (id, Cmdtype, Objid, Action, insdt) + values (#{id,jdbcType=VARCHAR}, #{Cmdtype,jdbcType=VARCHAR}, #{Objid,jdbcType=VARCHAR}, + #{Action,jdbcType=VARCHAR}, #{insdt,jdbcType=VARCHAR}) + + + insert into listener_message + + + id, + + + Cmdtype, + + + Objid, + + + Action, + + + insdt, + + + + + #{id,jdbcType=VARCHAR}, + + + #{Cmdtype,jdbcType=VARCHAR}, + + + #{Objid,jdbcType=VARCHAR}, + + + #{Action,jdbcType=VARCHAR}, + + + #{insdt,jdbcType=VARCHAR}, + + + + + update listener_message + + + id = #{id,jdbcType=VARCHAR}, + + + Cmdtype = #{Cmdtype,jdbcType=VARCHAR}, + + + Objid = #{Objid,jdbcType=VARCHAR}, + + + Action = #{Action,jdbcType=VARCHAR}, + + + insdt = #{insdt,jdbcType=VARCHAR}, + + + where id = #{id,jdbcType=VARCHAR} + + + update listener_message + set id = #{id,jdbcType=VARCHAR}, + Cmdtype = #{Cmdtype,jdbcType=VARCHAR}, + Objid = #{Objid,jdbcType=VARCHAR}, + Action = #{Action,jdbcType=VARCHAR}} + insdt = #{insdt,jdbcType=VARCHAR}} + where id = #{id,jdbcType=VARCHAR} + + + + delete + from listener_message + ${where} + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/Listener/ListenerPointMapper.xml b/src/main/resources/mybatis/mapper/Listener/ListenerPointMapper.xml new file mode 100644 index 0000000..3bfb8b9 --- /dev/null +++ b/src/main/resources/mybatis/mapper/Listener/ListenerPointMapper.xml @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + id + , intid, name, address, type, mpcode, datatype, unitid,logi,logi_val,action + + + + delete + from Listener_Point + where id = #{id,jdbcType=VARCHAR} + + + insert into Listener_Point (id, intid, name, address, type, mpcode, datatype, unitid) + values (#{id,jdbcType=VARCHAR}, #{intid,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, + #{address,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, #{mpcode,jdbcType=VARCHAR}, + #{datatype,jdbcType=VARCHAR}, #{unitid,jdbcType=VARCHAR}, #{logi,jdbcType=VARCHAR}, + #{action,jdbcType=VARCHAR}) + + + insert into Listener_Point + + + id, + + + intid, + + + name, + + + address, + + + type, + + + mpcode, + + + datatype + + + unitid + + + logi + + + action + + + + + #{id,jdbcType=VARCHAR}, + + + #{intid,jdbcType=VARCHAR}, + + + #{name,jdbcType=VARCHAR}, + + + #{address,jdbcType=VARCHAR}, + + + #{type,jdbcType=VARCHAR}, + + + #{mpcode,jdbcType=VARCHAR}, + + + #{datatype,jdbcType=VARCHAR} + + + #{unitid,jdbcType=VARCHAR} + + + #{logi,jdbcType=VARCHAR} + + + #{action,jdbcType=VARCHAR} + + + + + update Listener_Point + + + id = #{id,jdbcType=VARCHAR}, + + + intid = #{intid,jdbcType=VARCHAR}, + + + name = #{name,jdbcType=VARCHAR}, + + + address = #{address,jdbcType=VARCHAR}, + + + type = #{type,jdbcType=VARCHAR}, + + + mpcode = #{mpcode,jdbcType=VARCHAR}, + + + datatype = #{datatype,jdbcType=VARCHAR} + + + unitid = #{unitid,jdbcType=VARCHAR} + + + logi = #{logi,jdbcType=VARCHAR} + + + action = #{action,jdbcType=VARCHAR} + + + where id = #{id,jdbcType=VARCHAR} + + + update Listener_Point + set id = #{id,jdbcType=VARCHAR}, + intid = #{intid,jdbcType=VARCHAR}, + name = #{name,jdbcType=VARCHAR}, + address = #{address,jdbcType=VARCHAR}, + type = #{type,jdbcType=VARCHAR}, + mpcode = #{mpcode,jdbcType=VARCHAR}, + datatype = #{datatype,jdbcType=VARCHAR}, + unitid = #{unitid,jdbcType=VARCHAR}, + logi = #{logi,jdbcType=VARCHAR}, + action = #{action,jdbcType=VARCHAR} + where id = #{id,jdbcType=VARCHAR} + + + + delete + from Listener_Point ${where} + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/data/PipeTopicMpointMapper.xml b/src/main/resources/mybatis/mapper/data/PipeTopicMpointMapper.xml new file mode 100644 index 0000000..4a50596 --- /dev/null +++ b/src/main/resources/mybatis/mapper/data/PipeTopicMpointMapper.xml @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + id, point_name, point_code, type, is_constant, constant_value, sort_order + + + + + + delete from tb_pipe_topic_mpoint + where id = #{id,jdbcType=INTEGER} + + + + insert into tb_pipe_topic_mpoint (id, point_name, point_code, + type, is_constant, constant_value, + sort_order + ) + values (#{id,jdbcType=INTEGER}, #{pointName,jdbcType=VARCHAR}, #{pointCode,jdbcType=VARCHAR}, + #{type,jdbcType=VARCHAR}, #{isConstant,jdbcType=INTEGER}, #{constantValue,jdbcType=VARCHAR}, + #{sortOrder,jdbcType=INTEGER} + ) + + + + insert into tb_pipe_topic_mpoint + + + id, + + + point_name, + + + point_code, + + + type, + + + is_constant, + + + constant_value, + + + sort_order, + + + + + #{id,jdbcType=INTEGER}, + + + #{pointName,jdbcType=VARCHAR}, + + + #{pointCode,jdbcType=VARCHAR}, + + + #{type,jdbcType=VARCHAR}, + + + #{isConstant,jdbcType=INTEGER}, + + + #{constantValue,jdbcType=VARCHAR}, + + + #{sortOrder,jdbcType=INTEGER}, + + + + + + update tb_pipe_topic_mpoint + + + point_name = #{pointName,jdbcType=VARCHAR}, + + + point_code = #{pointCode,jdbcType=VARCHAR}, + + + type = #{type,jdbcType=VARCHAR}, + + + is_constant = #{isConstant,jdbcType=INTEGER}, + + + constant_value = #{constantValue,jdbcType=VARCHAR}, + + + sort_order = #{sortOrder,jdbcType=INTEGER}, + + + where id = #{id,jdbcType=INTEGER} + + + + update tb_pipe_topic_mpoint + set point_name = #{pointName,jdbcType=VARCHAR}, + point_code = #{pointCode,jdbcType=VARCHAR}, + type = #{type,jdbcType=VARCHAR}, + is_constant = #{isConstant,jdbcType=INTEGER}, + constant_value = #{constantValue,jdbcType=VARCHAR}, + sort_order = #{sortOrder,jdbcType=INTEGER} + where id = #{id,jdbcType=INTEGER} + + + + + + delete from + tb_pipe_topic_mpoint + ${where} + + + + delete from tb_pipe_topic_mpoint + where id in + + #{id} + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/data/PipelineEquipmentMapper.xml b/src/main/resources/mybatis/mapper/data/PipelineEquipmentMapper.xml new file mode 100644 index 0000000..eedf5b9 --- /dev/null +++ b/src/main/resources/mybatis/mapper/data/PipelineEquipmentMapper.xml @@ -0,0 +1,152 @@ + + + + + + + + + + + + + + + id, station_code, equipment_type, product_model, upload_cycle, upload_cycle_unit, last_upload_time, status + + + + delete from tb_pipeline_equipment + where id = #{id,jdbcType=INTEGER} + + + insert into tb_pipeline_equipment (id, station_code, equipment_type, + product_model, upload_cycle, upload_cycle_unit, + last_upload_time, status + ) + values (#{id,jdbcType=INTEGER}, #{stationCode,jdbcType=VARCHAR}, #{equipmentType,jdbcType=VARCHAR}, + #{productModel,jdbcType=VARCHAR}, #{uploadCycle,jdbcType=INTEGER}, #{uploadCycleUnit,jdbcType=VARCHAR}, + #{lastUploadTime,jdbcType=TIMESTAMP}, #{status,jdbcType=VARCHAR} + ) + + + insert into tb_pipeline_equipment + + + id, + + + station_code, + + + equipment_type, + + + product_model, + + + upload_cycle, + + + upload_cycle_unit, + + + last_upload_time, + + + status, + + + + + #{id,jdbcType=INTEGER}, + + + #{stationCode,jdbcType=VARCHAR}, + + + #{equipmentType,jdbcType=VARCHAR}, + + + #{productModel,jdbcType=VARCHAR}, + + + #{uploadCycle,jdbcType=INTEGER}, + + + #{uploadCycleUnit,jdbcType=VARCHAR}, + + + #{lastUploadTime,jdbcType=TIMESTAMP}, + + + #{status,jdbcType=VARCHAR}, + + + + + update tb_pipeline_equipment + + + station_code = #{stationCode,jdbcType=VARCHAR}, + + + equipment_type = #{equipmentType,jdbcType=VARCHAR}, + + + product_model = #{productModel,jdbcType=VARCHAR}, + + + upload_cycle = #{uploadCycle,jdbcType=INTEGER}, + + + upload_cycle_unit = #{uploadCycleUnit,jdbcType=VARCHAR}, + + + last_upload_time = #{lastUploadTime,jdbcType=TIMESTAMP}, + + + status = #{status,jdbcType=VARCHAR}, + + + where id = #{id,jdbcType=INTEGER} + + + update tb_pipeline_equipment + set station_code = #{stationCode,jdbcType=VARCHAR}, + equipment_type = #{equipmentType,jdbcType=VARCHAR}, + product_model = #{productModel,jdbcType=VARCHAR}, + upload_cycle = #{uploadCycle,jdbcType=INTEGER}, + upload_cycle_unit = #{uploadCycleUnit,jdbcType=VARCHAR}, + last_upload_time = #{lastUploadTime,jdbcType=TIMESTAMP}, + status = #{status,jdbcType=VARCHAR} + where id = #{id,jdbcType=INTEGER} + + + + + + delete from + tb_pipeline_equipment + ${where} + + + + delete from tb_pipeline_equipment + where id in + + #{id} + + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/data/PipelineEquipmentMpointMapper.xml b/src/main/resources/mybatis/mapper/data/PipelineEquipmentMpointMapper.xml new file mode 100644 index 0000000..98bb17a --- /dev/null +++ b/src/main/resources/mybatis/mapper/data/PipelineEquipmentMpointMapper.xml @@ -0,0 +1,102 @@ + + + + + + + + + + + + id, pid, mpcode, tag, mpname + + + + delete from tb_pipeline_equipment_mpoint + where id = #{id,jdbcType=INTEGER} + + + insert into tb_pipeline_equipment_mpoint (id, pid, mpcode, tag, mpname) + values (#{id,jdbcType=INTEGER}, #{pid,jdbcType=INTEGER}, #{mpcode,jdbcType=VARCHAR}, #{tag,jdbcType=VARCHAR}, #{mpname,jdbcType=VARCHAR}) + + + insert into tb_pipeline_equipment_mpoint + + + id, + + + pid, + + + mpcode, + + + tag, + + + mpname, + + + + + #{id,jdbcType=INTEGER}, + + + #{pid,jdbcType=INTEGER}, + + + #{mpcode,jdbcType=VARCHAR}, + + + #{tag,jdbcType=VARCHAR}, + + + #{mpname,jdbcType=VARCHAR}, + + + + + update tb_pipeline_equipment_mpoint + + + pid = #{pid,jdbcType=INTEGER}, + + + mpcode = #{mpcode,jdbcType=VARCHAR}, + + + tag = #{tag,jdbcType=VARCHAR}, + + + mpname = #{mpname,jdbcType=VARCHAR}, + + + where id = #{id,jdbcType=INTEGER} + + + update tb_pipeline_equipment_mpoint + set pid = #{pid,jdbcType=INTEGER}, + mpcode = #{mpcode,jdbcType=VARCHAR}, + tag = #{tag,jdbcType=VARCHAR}, + mpname = #{mpname,jdbcType=VARCHAR} + where id = #{id,jdbcType=INTEGER} + + + + delete from + tb_pipeline_equipment_mpoint + ${where} + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/data/PipelineMpointLibraryMapper.xml b/src/main/resources/mybatis/mapper/data/PipelineMpointLibraryMapper.xml new file mode 100644 index 0000000..dd66dd3 --- /dev/null +++ b/src/main/resources/mybatis/mapper/data/PipelineMpointLibraryMapper.xml @@ -0,0 +1,102 @@ + + + + + + + + + + + + id, equipment_type, code, name, morder + + + + delete from tb_pipeline_mpoint_library + where id = #{id,jdbcType=VARCHAR} + + + insert into tb_pipeline_mpoint_library (id, equipment_type, code, name, morder) + values (#{id,jdbcType=VARCHAR}, #{equipmentType,jdbcType=VARCHAR}, #{code,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{morder,jdbcType=INTEGER}) + + + insert into tb_pipeline_mpoint_library + + + id, + + + equipment_type, + + + code, + + + name, + + + morder, + + + + + #{id,jdbcType=VARCHAR}, + + + #{equipmentType,jdbcType=VARCHAR}, + + + #{code,jdbcType=VARCHAR}, + + + #{name,jdbcType=VARCHAR}, + + + #{morder,jdbcType=INTEGER}, + + + + + update tb_pipeline_mpoint_library + + + equipment_type = #{equipmentType,jdbcType=VARCHAR}, + + + code = #{code,jdbcType=VARCHAR}, + + + name = #{name,jdbcType=VARCHAR}, + + + morder = #{morder,jdbcType=INTEGER}, + + + where id = #{id,jdbcType=VARCHAR} + + + update tb_pipeline_mpoint_library + set equipment_type = #{equipmentType,jdbcType=VARCHAR}, + code = #{code,jdbcType=VARCHAR}, + name = #{name,jdbcType=VARCHAR}, + morder = #{morder,jdbcType=INTEGER} + where id = #{id,jdbcType=VARCHAR} + + + + delete from + tb_pipeline_mpoint_library + ${where} + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/mqtt/MqttConfigMapper.xml b/src/main/resources/mybatis/mapper/mqtt/MqttConfigMapper.xml new file mode 100644 index 0000000..f4247e4 --- /dev/null +++ b/src/main/resources/mybatis/mapper/mqtt/MqttConfigMapper.xml @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + id, insdt, client_id, client_name, broker_ip, tomcat_port, username, password, morder + + + + delete from tb_mqtt_config + where id = #{id,jdbcType=VARCHAR} + + + insert into tb_mqtt_config (id, insdt, client_id, + client_name, broker_ip, tomcat_port, + username, password, morder + ) + values (#{id,jdbcType=VARCHAR}, #{insdt,jdbcType=TIMESTAMP}, #{clientId,jdbcType=VARCHAR}, + #{clientName,jdbcType=VARCHAR}, #{brokerIp,jdbcType=VARCHAR}, #{tomcatPort,jdbcType=VARCHAR}, + #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{morder,jdbcType=INTEGER} + ) + + + insert into tb_mqtt_config + + + id, + + + insdt, + + + client_id, + + + client_name, + + + broker_ip, + + + tomcat_port, + + + username, + + + password, + + + morder, + + + + + #{id,jdbcType=VARCHAR}, + + + #{insdt,jdbcType=TIMESTAMP}, + + + #{clientId,jdbcType=VARCHAR}, + + + #{clientName,jdbcType=VARCHAR}, + + + #{brokerIp,jdbcType=VARCHAR}, + + + #{tomcatPort,jdbcType=VARCHAR}, + + + #{username,jdbcType=VARCHAR}, + + + #{password,jdbcType=VARCHAR}, + + + #{morder,jdbcType=INTEGER}, + + + + + update tb_mqtt_config + + + insdt = #{insdt,jdbcType=TIMESTAMP}, + + + client_id = #{clientId,jdbcType=VARCHAR}, + + + client_name = #{clientName,jdbcType=VARCHAR}, + + + broker_ip = #{brokerIp,jdbcType=VARCHAR}, + + + tomcat_port = #{tomcatPort,jdbcType=VARCHAR}, + + + username = #{username,jdbcType=VARCHAR}, + + + password = #{password,jdbcType=VARCHAR}, + + + morder = #{morder,jdbcType=INTEGER}, + + + where id = #{id,jdbcType=VARCHAR} + + + update tb_mqtt_config + set insdt = #{insdt,jdbcType=TIMESTAMP}, + client_id = #{clientId,jdbcType=VARCHAR}, + client_name = #{clientName,jdbcType=VARCHAR}, + broker_ip = #{brokerIp,jdbcType=VARCHAR}, + tomcat_port = #{tomcatPort,jdbcType=VARCHAR}, + username = #{username,jdbcType=VARCHAR}, + password = #{password,jdbcType=VARCHAR}, + morder = #{morder,jdbcType=INTEGER} + where id = #{id,jdbcType=VARCHAR} + + + + delete from + tb_mqtt_config + ${where} + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/mqtt/MqttConfigTopicMapper.xml b/src/main/resources/mybatis/mapper/mqtt/MqttConfigTopicMapper.xml new file mode 100644 index 0000000..ede96ec --- /dev/null +++ b/src/main/resources/mybatis/mapper/mqtt/MqttConfigTopicMapper.xml @@ -0,0 +1,123 @@ + + + + + + + + + + + + + id, name, topic, status, pid, morder + + + + delete from tb_mqtt_config_topic + where id = #{id,jdbcType=VARCHAR} + + + insert into tb_mqtt_config_topic (id, name, topic, + status, pid, morder + ) + values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{topic,jdbcType=VARCHAR}, + #{status,jdbcType=VARCHAR}, #{pid,jdbcType=VARCHAR}, #{morder,jdbcType=INTEGER} + ) + + + insert into tb_mqtt_config_topic + + + id, + + + name, + + + topic, + + + status, + + + pid, + + + morder, + + + + + #{id,jdbcType=VARCHAR}, + + + #{name,jdbcType=VARCHAR}, + + + #{topic,jdbcType=VARCHAR}, + + + #{status,jdbcType=VARCHAR}, + + + #{pid,jdbcType=VARCHAR}, + + + #{morder,jdbcType=INTEGER}, + + + + + update tb_mqtt_config_topic + + + name = #{name,jdbcType=VARCHAR}, + + + topic = #{topic,jdbcType=VARCHAR}, + + + status = #{status,jdbcType=VARCHAR}, + + + pid = #{pid,jdbcType=VARCHAR}, + + + morder = #{morder,jdbcType=INTEGER}, + + + where id = #{id,jdbcType=VARCHAR} + + + update tb_mqtt_config_topic + set name = #{name,jdbcType=VARCHAR}, + topic = #{topic,jdbcType=VARCHAR}, + status = #{status,jdbcType=VARCHAR}, + pid = #{pid,jdbcType=VARCHAR}, + morder = #{morder,jdbcType=INTEGER} + where id = #{id,jdbcType=VARCHAR} + + + + delete from + tb_mqtt_config_topic + ${where} + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/scada/MPointBzw.xml b/src/main/resources/mybatis/mapper/scada/MPointBzw.xml new file mode 100644 index 0000000..8c4ef70 --- /dev/null +++ b/src/main/resources/mybatis/mapper/scada/MPointBzw.xml @@ -0,0 +1,78 @@ + + + + + + + + + + mpoint_id, mpointbzw_Id + + + + + + delete from tb_measurepoint_bzw + where mpoint_id = #{mpointId,jdbcType=VARCHAR} + + + + insert into tb_measurepoint_bzw (mpoint_id, mpointbzw_Id) + values (#{mpointId,jdbcType=VARCHAR}, #{mpointbzwId,jdbcType=VARCHAR}) + + + + insert into tb_measurepoint_bzw + + + mpoint_id, + + + mpointbzw_Id, + + + + + #{mpointId,jdbcType=VARCHAR}, + + + #{mpointbzwId,jdbcType=VARCHAR}, + + + + + + update tb_measurepoint_bzw + + + mpointbzw_Id = #{mpointbzwId,jdbcType=VARCHAR}, + + + where mpoint_id = #{mpointId,jdbcType=VARCHAR} + + + + update tb_measurepoint_bzw + set mpointbzw_Id = #{mpointbzwId,jdbcType=VARCHAR} + where mpoint_id = #{mpointId,jdbcType=VARCHAR} + + + + + + delete from tb_measurepoint_bzw + ${where} + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/scada/MPointHistoryMapper.xml b/src/main/resources/mybatis/mapper/scada/MPointHistoryMapper.xml new file mode 100644 index 0000000..bc773ec --- /dev/null +++ b/src/main/resources/mybatis/mapper/scada/MPointHistoryMapper.xml @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + insert into `${tbName}` (ParmValue, MeasureDT, + memotype, memo, userid, + insdt) + values (#{parmvalue,jdbcType=DECIMAL}, #{measuredt,jdbcType=TIMESTAMP}, + #{memotype,jdbcType=VARCHAR}, #{memo,jdbcType=VARCHAR}, #{userid,jdbcType=VARCHAR}, + #{insdt,jdbcType=VARCHAR}) + + + + + + delete + from ${table} ${where} + + + + + + + + CREATE TABLE `${table}` + ( + `ItemID` bigint NOT NULL AUTO_INCREMENT, + `ParmValue` decimal(18, 4) NOT NULL, + `MeasureDT` datetime NOT NULL, + `memotype` varchar(100) NULL, + `memo` varchar(50) NULL, + `userid` varchar(50) NULL, + `insdt` datetime NULL ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`ItemID`), + INDEX `index_dt`(`MeasureDT`) + ); + + + + update `${tbName}` + set ParmValue = #{parmvalue,jdbcType=DECIMAL}, memotype = #{memotype,jdbcType=VARCHAR} + where MeasureDT = #{measuredt,jdbcType=TIMESTAMP} + + + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/scada/MPointMapper.xml b/src/main/resources/mybatis/mapper/scada/MPointMapper.xml new file mode 100644 index 0000000..6f390d1 --- /dev/null +++ b/src/main/resources/mybatis/mapper/scada/MPointMapper.xml @@ -0,0 +1,718 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ID, MPointID, MPointCode, ParmName, Unit, alarmmax, alarmmin, ParmValue, MeasureDT, + Rate, Freq, FreqUnit, SignalType, SignalTag, LEDType, LEDColor, DirectType, BizId, BizType, + NumTail, prochour, procday, procmonth, ShowName, exp, forcemin, forcemax, avgmax, + avgmin, remoteup, morder, TriggerAlarm, ConfirmAlarm, flowset, triggerCycle, cyclemax, + cyclemin, triggerMutation, mutationset, causeset, operateset, resultset, triggerEquOff, + mathop, valuetype, valueMeaning, active, SoundAlarm, scdtype, spanrange, modbusfigid, + register, processSectionCode, equipmentId, source_type, patrol_type, remark, alarm_level, disname + + + + delete from TB_MeasurePoint + where ID = #{id,jdbcType=VARCHAR} + + + insert into TB_MeasurePoint (ID, MPointID, MPointCode, + ParmName, Unit, alarmmax, + alarmmin, ParmValue, MeasureDT, + Rate, Freq, SignalType, + LEDType, LEDColor, DirectType, + BizId, BizType, NumTail, + prochour, procday, procmonth, + ShowName, exp, forcemin, + forcemax, avgmax, avgmin, + remoteup, morder, TriggerAlarm, + ConfirmAlarm, flowset, triggerCycle, + cyclemax, cyclemin, triggerMutation, + mutationset, causeset, operateset, + resultset, triggerEquOff, mathop, + valuetype, active, SoundAlarm, + scdtype, spanrange, modbusfigid, + register, processSectionCode, equipmentId, + pointfunctiondefinition, type + ) + values (#{id,jdbcType=VARCHAR}, #{mpointid,jdbcType=VARCHAR}, #{mpointcode,jdbcType=VARCHAR}, + #{parmname,jdbcType=VARCHAR}, #{unit,jdbcType=VARCHAR}, #{alarmmax,jdbcType=DECIMAL}, + #{alarmmin,jdbcType=DECIMAL}, #{parmvalue,jdbcType=DECIMAL}, #{measuredt,jdbcType=TIMESTAMP}, + #{rate,jdbcType=DECIMAL}, #{freq,jdbcType=INTEGER}, #{signaltype,jdbcType=VARCHAR}, + #{ledtype,jdbcType=CHAR}, #{ledcolor,jdbcType=CHAR}, #{directtype,jdbcType=CHAR}, + #{bizid,jdbcType=VARCHAR}, #{biztype,jdbcType=VARCHAR}, #{numtail,jdbcType=VARCHAR}, + #{prochour,jdbcType=VARCHAR}, #{procday,jdbcType=VARCHAR}, #{procmonth,jdbcType=VARCHAR}, + #{showname,jdbcType=CHAR}, #{exp,jdbcType=VARCHAR}, #{forcemin,jdbcType=DECIMAL}, + #{forcemax,jdbcType=DECIMAL}, #{avgmax,jdbcType=DECIMAL}, #{avgmin,jdbcType=DECIMAL}, + #{remoteup,jdbcType=CHAR}, #{morder,jdbcType=INTEGER}, #{triggeralarm,jdbcType=CHAR}, + #{confirmalarm,jdbcType=CHAR}, #{flowset,jdbcType=DECIMAL}, #{triggercycle,jdbcType=CHAR}, + #{cyclemax,jdbcType=DECIMAL}, #{cyclemin,jdbcType=DECIMAL}, #{triggermutation,jdbcType=CHAR}, + #{mutationset,jdbcType=DECIMAL}, #{causeset,jdbcType=DECIMAL}, #{operateset,jdbcType=DECIMAL}, + #{resultset,jdbcType=DECIMAL}, #{triggerequoff,jdbcType=CHAR}, #{mathop,jdbcType=CHAR}, + #{valuetype,jdbcType=VARCHAR}, #{active,jdbcType=VARCHAR}, #{soundalarm,jdbcType=CHAR}, + #{scdtype,jdbcType=VARCHAR}, #{spanrange,jdbcType=DECIMAL}, #{modbusfigid,jdbcType=VARCHAR}, + #{register,jdbcType=VARCHAR}, #{processsectioncode,jdbcType=VARCHAR}, #{equipmentid,jdbcType=VARCHAR}, + #{pointfunctiondefinition,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR} + ) + + + insert into TB_MeasurePoint + + + ID, + + + MPointID, + + + MPointCode, + + + ParmName, + + + Unit, + + + alarmmax, + + + alarmmin, + + + ParmValue, + + + MeasureDT, + + + Rate, + + + Freq, + + + SignalType, + + + LEDType, + + + LEDColor, + + + DirectType, + + + BizId, + + + BizType, + + + NumTail, + + + prochour, + + + procday, + + + procmonth, + + + ShowName, + + + exp, + + + forcemin, + + + forcemax, + + + avgmax, + + + avgmin, + + + remoteup, + + + morder, + + + TriggerAlarm, + + + ConfirmAlarm, + + + flowset, + + + triggerCycle, + + + cyclemax, + + + cyclemin, + + + triggerMutation, + + + mutationset, + + + causeset, + + + operateset, + + + resultset, + + + triggerEquOff, + + + mathop, + + + valuetype, + + + active, + + + SoundAlarm, + + + scdtype, + + + spanrange, + + + modbusfigid, + + + register, + + + processSectionCode, + + + equipmentId, + + + pointfunctiondefinition, + + + type, + + + + + #{id,jdbcType=VARCHAR}, + + + #{mpointid,jdbcType=VARCHAR}, + + + #{mpointcode,jdbcType=VARCHAR}, + + + #{parmname,jdbcType=VARCHAR}, + + + #{unit,jdbcType=VARCHAR}, + + + #{alarmmax,jdbcType=DECIMAL}, + + + #{alarmmin,jdbcType=DECIMAL}, + + + #{parmvalue,jdbcType=DECIMAL}, + + + #{measuredt,jdbcType=TIMESTAMP}, + + + #{rate,jdbcType=DECIMAL}, + + + #{freq,jdbcType=INTEGER}, + + + #{signaltype,jdbcType=VARCHAR}, + + + #{ledtype,jdbcType=CHAR}, + + + #{ledcolor,jdbcType=CHAR}, + + + #{directtype,jdbcType=CHAR}, + + + #{bizid,jdbcType=VARCHAR}, + + + #{biztype,jdbcType=VARCHAR}, + + + #{numtail,jdbcType=VARCHAR}, + + + #{prochour,jdbcType=VARCHAR}, + + + #{procday,jdbcType=VARCHAR}, + + + #{procmonth,jdbcType=VARCHAR}, + + + #{showname,jdbcType=CHAR}, + + + #{exp,jdbcType=VARCHAR}, + + + #{forcemin,jdbcType=DECIMAL}, + + + #{forcemax,jdbcType=DECIMAL}, + + + #{avgmax,jdbcType=DECIMAL}, + + + #{avgmin,jdbcType=DECIMAL}, + + + #{remoteup,jdbcType=CHAR}, + + + #{morder,jdbcType=INTEGER}, + + + #{triggeralarm,jdbcType=CHAR}, + + + #{confirmalarm,jdbcType=CHAR}, + + + #{flowset,jdbcType=DECIMAL}, + + + #{triggercycle,jdbcType=CHAR}, + + + #{cyclemax,jdbcType=DECIMAL}, + + + #{cyclemin,jdbcType=DECIMAL}, + + + #{triggermutation,jdbcType=CHAR}, + + + #{mutationset,jdbcType=DECIMAL}, + + + #{causeset,jdbcType=DECIMAL}, + + + #{operateset,jdbcType=DECIMAL}, + + + #{resultset,jdbcType=DECIMAL}, + + + #{triggerequoff,jdbcType=CHAR}, + + + #{mathop,jdbcType=CHAR}, + + + #{valuetype,jdbcType=VARCHAR}, + + + #{active,jdbcType=VARCHAR}, + + + #{soundalarm,jdbcType=CHAR}, + + + #{scdtype,jdbcType=VARCHAR}, + + + #{spanrange,jdbcType=DECIMAL}, + + + #{modbusfigid,jdbcType=VARCHAR}, + + + #{register,jdbcType=VARCHAR}, + + + #{processsectioncode,jdbcType=VARCHAR}, + + + #{equipmentid,jdbcType=VARCHAR}, + + + #{pointfunctiondefinition,jdbcType=VARCHAR}, + + + #{type,jdbcType=VARCHAR}, + + + + + update TB_MeasurePoint + + + MPointID = #{mpointid,jdbcType=VARCHAR}, + + + MPointCode = #{mpointcode,jdbcType=VARCHAR}, + + + ParmName = #{parmname,jdbcType=VARCHAR}, + + + Unit = #{unit,jdbcType=VARCHAR}, + + + alarmmax = #{alarmmax,jdbcType=DECIMAL}, + + + alarmmin = #{alarmmin,jdbcType=DECIMAL}, + + + ParmValue = #{parmvalue,jdbcType=DECIMAL}, + + + MeasureDT = #{measuredt,jdbcType=TIMESTAMP}, + + + Rate = #{rate,jdbcType=DECIMAL}, + + + Freq = #{freq,jdbcType=INTEGER}, + + + FreqUnit = #{frequnit,jdbcType=VARCHAR}, + + + SignalType = #{signaltype,jdbcType=VARCHAR}, + + + LEDType = #{ledtype,jdbcType=CHAR}, + + + LEDColor = #{ledcolor,jdbcType=CHAR}, + + + DirectType = #{directtype,jdbcType=CHAR}, + + + BizId = #{bizid,jdbcType=VARCHAR}, + + + BizType = #{biztype,jdbcType=VARCHAR}, + + + NumTail = #{numtail,jdbcType=VARCHAR}, + + + prochour = #{prochour,jdbcType=VARCHAR}, + + + procday = #{procday,jdbcType=VARCHAR}, + + + procmonth = #{procmonth,jdbcType=VARCHAR}, + + + ShowName = #{showname,jdbcType=CHAR}, + + + exp = #{exp,jdbcType=VARCHAR}, + + + forcemin = #{forcemin,jdbcType=DECIMAL}, + + + forcemax = #{forcemax,jdbcType=DECIMAL}, + + + avgmax = #{avgmax,jdbcType=DECIMAL}, + + + avgmin = #{avgmin,jdbcType=DECIMAL}, + + + remoteup = #{remoteup,jdbcType=CHAR}, + + + morder = #{morder,jdbcType=INTEGER}, + + + TriggerAlarm = #{triggeralarm,jdbcType=CHAR}, + + + ConfirmAlarm = #{confirmalarm,jdbcType=CHAR}, + + + flowset = #{flowset,jdbcType=DECIMAL}, + + + triggerCycle = #{triggercycle,jdbcType=CHAR}, + + + cyclemax = #{cyclemax,jdbcType=DECIMAL}, + + + cyclemin = #{cyclemin,jdbcType=DECIMAL}, + + + triggerMutation = #{triggermutation,jdbcType=CHAR}, + + + mutationset = #{mutationset,jdbcType=DECIMAL}, + + + causeset = #{causeset,jdbcType=DECIMAL}, + + + operateset = #{operateset,jdbcType=DECIMAL}, + + + resultset = #{resultset,jdbcType=DECIMAL}, + + + triggerEquOff = #{triggerequoff,jdbcType=CHAR}, + + + mathop = #{mathop,jdbcType=CHAR}, + + + valuetype = #{valuetype,jdbcType=VARCHAR}, + + + valueMeaning = #{valuemeaning,jdbcType=VARCHAR}, + + + active = #{active,jdbcType=VARCHAR}, + + + SoundAlarm = #{soundalarm,jdbcType=CHAR}, + + + scdtype = #{scdtype,jdbcType=VARCHAR}, + + + spanrange = #{spanrange,jdbcType=DECIMAL}, + + + modbusfigid = #{modbusfigid,jdbcType=VARCHAR}, + + + register = #{register,jdbcType=VARCHAR}, + + + processSectionCode = #{processsectioncode,jdbcType=VARCHAR}, + + + equipmentId = #{equipmentid,jdbcType=VARCHAR}, + + + source_type = #{sourceType,jdbcType=VARCHAR}, + + + patrol_type = #{patrolType,jdbcType=VARCHAR}, + + + remark = #{remark,jdbcType=VARCHAR}, + + + alarm_level = #{alarmLevel,jdbcType=INTEGER}, + + + disname = #{disname,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=VARCHAR} + + + update TB_MeasurePoint + set MPointID = #{mpointid,jdbcType=VARCHAR}, + MPointCode = #{mpointcode,jdbcType=VARCHAR}, + ParmName = #{parmname,jdbcType=VARCHAR}, + Unit = #{unit,jdbcType=VARCHAR}, + alarmmax = #{alarmmax,jdbcType=DECIMAL}, + alarmmin = #{alarmmin,jdbcType=DECIMAL}, + ParmValue = #{parmvalue,jdbcType=DECIMAL}, + MeasureDT = #{measuredt,jdbcType=TIMESTAMP}, + Rate = #{rate,jdbcType=DECIMAL}, + Freq = #{freq,jdbcType=INTEGER}, + SignalType = #{signaltype,jdbcType=VARCHAR}, + LEDType = #{ledtype,jdbcType=CHAR}, + LEDColor = #{ledcolor,jdbcType=CHAR}, + DirectType = #{directtype,jdbcType=CHAR}, + BizId = #{bizid,jdbcType=VARCHAR}, + BizType = #{biztype,jdbcType=VARCHAR}, + NumTail = #{numtail,jdbcType=VARCHAR}, + prochour = #{prochour,jdbcType=VARCHAR}, + procday = #{procday,jdbcType=VARCHAR}, + procmonth = #{procmonth,jdbcType=VARCHAR}, + ShowName = #{showname,jdbcType=CHAR}, + exp = #{exp,jdbcType=VARCHAR}, + forcemin = #{forcemin,jdbcType=DECIMAL}, + forcemax = #{forcemax,jdbcType=DECIMAL}, + avgmax = #{avgmax,jdbcType=DECIMAL}, + avgmin = #{avgmin,jdbcType=DECIMAL}, + remoteup = #{remoteup,jdbcType=CHAR}, + morder = #{morder,jdbcType=INTEGER}, + TriggerAlarm = #{triggeralarm,jdbcType=CHAR}, + ConfirmAlarm = #{confirmalarm,jdbcType=CHAR}, + flowset = #{flowset,jdbcType=DECIMAL}, + triggerCycle = #{triggercycle,jdbcType=CHAR}, + cyclemax = #{cyclemax,jdbcType=DECIMAL}, + cyclemin = #{cyclemin,jdbcType=DECIMAL}, + triggerMutation = #{triggermutation,jdbcType=CHAR}, + mutationset = #{mutationset,jdbcType=DECIMAL}, + causeset = #{causeset,jdbcType=DECIMAL}, + operateset = #{operateset,jdbcType=DECIMAL}, + resultset = #{resultset,jdbcType=DECIMAL}, + triggerEquOff = #{triggerequoff,jdbcType=CHAR}, + mathop = #{mathop,jdbcType=CHAR}, + valuetype = #{valuetype,jdbcType=VARCHAR}, + active = #{active,jdbcType=VARCHAR}, + SoundAlarm = #{soundalarm,jdbcType=CHAR}, + scdtype = #{scdtype,jdbcType=VARCHAR}, + spanrange = #{spanrange,jdbcType=DECIMAL}, + modbusfigid = #{modbusfigid,jdbcType=VARCHAR}, + register = #{register,jdbcType=VARCHAR}, + processSectionCode = #{processsectioncode,jdbcType=VARCHAR}, + equipmentId = #{equipmentid,jdbcType=VARCHAR}, + pointfunctiondefinition = #{pointfunctiondefinition,jdbcType=VARCHAR}, + type = #{type,jdbcType=VARCHAR} + where ID = #{id,jdbcType=VARCHAR} + + + + delete from + tb_measurepoint + ${where} + + + + + + + + + ${where} + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/user/CompanyDao.xml b/src/main/resources/mybatis/mapper/user/CompanyDao.xml new file mode 100644 index 0000000..1c184d5 --- /dev/null +++ b/src/main/resources/mybatis/mapper/user/CompanyDao.xml @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + id, name, pid, address, tel, website, taskid, post, insdt, insuser, version, morder, + sname, active, type, ename, longitude, latitude,is_count + + + + delete from tb_company + where id = #{id,jdbcType=VARCHAR} + + + insert into tb_company (id, name, pid, + address, tel, website, + taskid, post, insdt, + insuser, version, morder, + sname, active, type, + ename, longitude, latitude,is_count + ) + values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{pid,jdbcType=VARCHAR}, + #{address,jdbcType=VARCHAR}, #{tel,jdbcType=VARCHAR}, #{website,jdbcType=VARCHAR}, + #{taskid,jdbcType=VARCHAR}, #{post,jdbcType=VARCHAR}, #{insdt,jdbcType=TIMESTAMP}, + #{insuser,jdbcType=VARCHAR}, #{version,jdbcType=INTEGER}, #{morder,jdbcType=INTEGER}, + #{sname,jdbcType=VARCHAR}, #{active,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, + #{ename,jdbcType=VARCHAR}, #{longitude,jdbcType=DECIMAL}, #{latitude,jdbcType=DECIMAL}, + #{isCount,jdbcType=VARCHAR} + ) + + + insert into tb_company + + + id, + + + name, + + + pid, + + + address, + + + tel, + + + website, + + + taskid, + + + post, + + + insdt, + + + insuser, + + + version, + + + morder, + + + sname, + + + active, + + + type, + + + ename, + + + longitude, + + + latitude, + + + is_count, + + + + + #{id,jdbcType=VARCHAR}, + + + #{name,jdbcType=VARCHAR}, + + + #{pid,jdbcType=VARCHAR}, + + + #{address,jdbcType=VARCHAR}, + + + #{tel,jdbcType=VARCHAR}, + + + #{website,jdbcType=VARCHAR}, + + + #{taskid,jdbcType=VARCHAR}, + + + #{post,jdbcType=VARCHAR}, + + + #{insdt,jdbcType=TIMESTAMP}, + + + #{insuser,jdbcType=VARCHAR}, + + + #{version,jdbcType=INTEGER}, + + + #{morder,jdbcType=INTEGER}, + + + #{sname,jdbcType=VARCHAR}, + + + #{active,jdbcType=VARCHAR}, + + + #{type,jdbcType=VARCHAR}, + + + #{ename,jdbcType=VARCHAR}, + + + #{longitude,jdbcType=DECIMAL}, + + + #{latitude,jdbcType=DECIMAL}, + + + #{isCount,jdbcType=VARCHAR}, + + + + + update tb_company + + + name = #{name,jdbcType=VARCHAR}, + + + pid = #{pid,jdbcType=VARCHAR}, + + + address = #{address,jdbcType=VARCHAR}, + + + tel = #{tel,jdbcType=VARCHAR}, + + + website = #{website,jdbcType=VARCHAR}, + + + taskid = #{taskid,jdbcType=VARCHAR}, + + + post = #{post,jdbcType=VARCHAR}, + + + insdt = #{insdt,jdbcType=TIMESTAMP}, + + + insuser = #{insuser,jdbcType=VARCHAR}, + + + version = #{version,jdbcType=INTEGER}, + + + morder = #{morder,jdbcType=INTEGER}, + + + sname = #{sname,jdbcType=VARCHAR}, + + + active = #{active,jdbcType=VARCHAR}, + + + type = #{type,jdbcType=VARCHAR}, + + + ename = #{ename,jdbcType=VARCHAR}, + + + longitude = #{longitude,jdbcType=DECIMAL}, + + + latitude = #{latitude,jdbcType=DECIMAL}, + + + is_count = #{isCount,jdbcType=VARCHAR}, + + + where id = #{id,jdbcType=VARCHAR} + + + update tb_company + set name = #{name,jdbcType=VARCHAR}, + pid = #{pid,jdbcType=VARCHAR}, + address = #{address,jdbcType=VARCHAR}, + tel = #{tel,jdbcType=VARCHAR}, + website = #{website,jdbcType=VARCHAR}, + taskid = #{taskid,jdbcType=VARCHAR}, + post = #{post,jdbcType=VARCHAR}, + insdt = #{insdt,jdbcType=TIMESTAMP}, + insuser = #{insuser,jdbcType=VARCHAR}, + version = #{version,jdbcType=INTEGER}, + morder = #{morder,jdbcType=INTEGER}, + sname = #{sname,jdbcType=VARCHAR}, + active = #{active,jdbcType=VARCHAR}, + type = #{type,jdbcType=VARCHAR}, + ename = #{ename,jdbcType=VARCHAR}, + longitude = #{longitude,jdbcType=DECIMAL}, + latitude = #{latitude,jdbcType=DECIMAL}, + is_count = #{isCount,jdbcType=VARCHAR} + where id = #{id,jdbcType=VARCHAR} + + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/user/UserDao.xml b/src/main/resources/mybatis/mapper/user/UserDao.xml new file mode 100644 index 0000000..31c3945 --- /dev/null +++ b/src/main/resources/mybatis/mapper/user/UserDao.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/index.html b/src/main/resources/templates/index.html new file mode 100644 index 0000000..ac72820 --- /dev/null +++ b/src/main/resources/templates/index.html @@ -0,0 +1,10 @@ + + + + + 首页 + + + + + \ No newline at end of file diff --git a/src/test/java/com/sipai/SpringbootApplicationTests.java b/src/test/java/com/sipai/SpringbootApplicationTests.java new file mode 100644 index 0000000..be6f534 --- /dev/null +++ b/src/test/java/com/sipai/SpringbootApplicationTests.java @@ -0,0 +1,13 @@ +package com.sipai; + +//import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class EmqxTests { + +// @Test +// void contextLoads() { +// } + +}