Compare commits

..

1 Commits

  1. 210
      2024数据库脚本.sql
  2. 135
      algorithm/pom.xml
  3. 8
      algorithm/src/main/java/com/mh/algorithm/bpnn/ActivationFunction.java
  4. 111
      algorithm/src/main/java/com/mh/algorithm/bpnn/BPModel.java
  5. 262
      algorithm/src/main/java/com/mh/algorithm/bpnn/BPNeuralNetworkFactory.java
  6. 106
      algorithm/src/main/java/com/mh/algorithm/bpnn/BPParameter.java
  7. 15
      algorithm/src/main/java/com/mh/algorithm/bpnn/Sigmoid.java
  8. 24
      algorithm/src/main/java/com/mh/algorithm/constants/OrderEnum.java
  9. 88
      algorithm/src/main/java/com/mh/algorithm/knn/KNN.java
  10. 646
      algorithm/src/main/java/com/mh/algorithm/matrix/Matrix.java
  11. 53
      algorithm/src/main/java/com/mh/algorithm/utils/CsvInfo.java
  12. 66
      algorithm/src/main/java/com/mh/algorithm/utils/CsvUtil.java
  13. 20
      algorithm/src/main/java/com/mh/algorithm/utils/DoubleUtil.java
  14. 297
      algorithm/src/main/java/com/mh/algorithm/utils/MatrixUtil.java
  15. 32
      algorithm/src/main/java/com/mh/algorithm/utils/SerializationUtil.java
  16. 71
      algorithm/src/test/java/com/mh/algorithm/bpnn/bpnnTest.java
  17. 46
      algorithm/src/test/java/com/mh/algorithm/knn/knnTest.java
  18. 26
      common/pom.xml
  19. 26
      common/src/main/java/com/mh/common/annotation/SysLogger.java
  20. 84
      common/src/main/java/com/mh/common/utils/FileUtils.java
  21. 28
      pom.xml
  22. 63
      user-service/pom.xml
  23. 2
      user-service/src/main/java/com/mh/user/aspect/SysLogAspect.java
  24. 12
      user-service/src/main/java/com/mh/user/config/RestTemplateConfig.java
  25. 10
      user-service/src/main/java/com/mh/user/constants/Constant.java
  26. 2
      user-service/src/main/java/com/mh/user/constants/DeviceEnum.java
  27. 2
      user-service/src/main/java/com/mh/user/constants/DeviceStrategyEnum.java
  28. 2
      user-service/src/main/java/com/mh/user/controller/AnalysisController.java
  29. 199
      user-service/src/main/java/com/mh/user/controller/AreaController.java
  30. 39
      user-service/src/main/java/com/mh/user/controller/BuildingController.java
  31. 6
      user-service/src/main/java/com/mh/user/controller/ControlSetController.java
  32. 8
      user-service/src/main/java/com/mh/user/controller/DeviceFloorController.java
  33. 41
      user-service/src/main/java/com/mh/user/controller/DeviceInstallController.java
  34. 252
      user-service/src/main/java/com/mh/user/controller/EnergyController.java
  35. 36
      user-service/src/main/java/com/mh/user/controller/EnergyPreController.java
  36. 63
      user-service/src/main/java/com/mh/user/controller/KnowledgeDataController.java
  37. 211
      user-service/src/main/java/com/mh/user/controller/NowDataController.java
  38. 4
      user-service/src/main/java/com/mh/user/controller/NowPublicDataController.java
  39. 4
      user-service/src/main/java/com/mh/user/controller/SerialPortController.java
  40. 23
      user-service/src/main/java/com/mh/user/controller/SummaryController.java
  41. 27
      user-service/src/main/java/com/mh/user/dto/EnergyPreDTO.java
  42. 37
      user-service/src/main/java/com/mh/user/dto/EnergyPreEchartDataDTO.java
  43. 37
      user-service/src/main/java/com/mh/user/dto/EnergyPreTopDataDTO.java
  44. 32
      user-service/src/main/java/com/mh/user/entity/AreaEntity.java
  45. 3
      user-service/src/main/java/com/mh/user/entity/BuildingEntity.java
  46. 3
      user-service/src/main/java/com/mh/user/entity/DeviceCodeParamEntity.java
  47. 168
      user-service/src/main/java/com/mh/user/entity/HistoryDataPre.java
  48. 38
      user-service/src/main/java/com/mh/user/entity/KnowledgeDataEntity.java
  49. 1
      user-service/src/main/java/com/mh/user/entity/MaintainInfoEntity.java
  50. 6
      user-service/src/main/java/com/mh/user/entity/NowDataEntity.java
  51. 1
      user-service/src/main/java/com/mh/user/entity/SysParamEntity.java
  52. 1
      user-service/src/main/java/com/mh/user/entity/WaterLevelEntity.java
  53. 2
      user-service/src/main/java/com/mh/user/entity/WaterTempEntity.java
  54. 43
      user-service/src/main/java/com/mh/user/factory/BackTempControl.java
  55. 5
      user-service/src/main/java/com/mh/user/job/CollectionLoopRunner.java
  56. 44
      user-service/src/main/java/com/mh/user/job/DealDataJob.java
  57. 64
      user-service/src/main/java/com/mh/user/job/GetWeatherInfoJob.java
  58. 8
      user-service/src/main/java/com/mh/user/mapper/AnalysisMapper.java
  59. 77
      user-service/src/main/java/com/mh/user/mapper/AreaMapper.java
  60. 42
      user-service/src/main/java/com/mh/user/mapper/BuildingMapper.java
  61. 19
      user-service/src/main/java/com/mh/user/mapper/ControlSetMapper.java
  62. 2
      user-service/src/main/java/com/mh/user/mapper/DealDataMapper.java
  63. 12
      user-service/src/main/java/com/mh/user/mapper/DeviceCodeParamMapper.java
  64. 34
      user-service/src/main/java/com/mh/user/mapper/DeviceInstallMapper.java
  65. 304
      user-service/src/main/java/com/mh/user/mapper/EnergyMapper.java
  66. 233
      user-service/src/main/java/com/mh/user/mapper/HistoryDataPreMapper.java
  67. 57
      user-service/src/main/java/com/mh/user/mapper/KnowledgeDataMapper.java
  68. 8
      user-service/src/main/java/com/mh/user/mapper/MaintainInfoMapper.java
  69. 147
      user-service/src/main/java/com/mh/user/mapper/NowDataMapper.java
  70. 10
      user-service/src/main/java/com/mh/user/mapper/NowPublicDataMapper.java
  71. 26
      user-service/src/main/java/com/mh/user/mapper/provider/BuildingProvider.java
  72. 28
      user-service/src/main/java/com/mh/user/mapper/provider/DeviceInstallProvider.java
  73. 2
      user-service/src/main/java/com/mh/user/mapper/provider/EnergyProvider.java
  74. 8
      user-service/src/main/java/com/mh/user/mapper/provider/NowDataProvider.java
  75. 2
      user-service/src/main/java/com/mh/user/mapper/provider/SysLogProvider.java
  76. 88
      user-service/src/main/java/com/mh/user/model/AreaBuildingTreeModel.java
  77. 10
      user-service/src/main/java/com/mh/user/model/AreaModel.java
  78. 5
      user-service/src/main/java/com/mh/user/model/SerialPortModel.java
  79. 7
      user-service/src/main/java/com/mh/user/serialport/SendAndReceiveByCom.java
  80. 68
      user-service/src/main/java/com/mh/user/serialport/SerialPortSingle2.java
  81. 15
      user-service/src/main/java/com/mh/user/serialport/SerialPortThread.java
  82. 19
      user-service/src/main/java/com/mh/user/service/AreaService.java
  83. 13
      user-service/src/main/java/com/mh/user/service/BuildingService.java
  84. 2
      user-service/src/main/java/com/mh/user/service/ControlSetService.java
  85. 13
      user-service/src/main/java/com/mh/user/service/DeviceInstallService.java
  86. 8
      user-service/src/main/java/com/mh/user/service/EnergyService.java
  87. 54
      user-service/src/main/java/com/mh/user/service/HistoryDataPreService.java
  88. 23
      user-service/src/main/java/com/mh/user/service/KnowledgeDataService.java
  89. 30
      user-service/src/main/java/com/mh/user/service/NowDataService.java
  90. 2
      user-service/src/main/java/com/mh/user/service/SummaryService.java
  91. 8
      user-service/src/main/java/com/mh/user/service/impl/AnalysisServiceImpl.java
  92. 58
      user-service/src/main/java/com/mh/user/service/impl/AreaServiceImpl.java
  93. 129
      user-service/src/main/java/com/mh/user/service/impl/BuildingServiceImpl.java
  94. 16
      user-service/src/main/java/com/mh/user/service/impl/ControlSetServiceImpl.java
  95. 285
      user-service/src/main/java/com/mh/user/service/impl/DeviceControlServiceImpl.java
  96. 141
      user-service/src/main/java/com/mh/user/service/impl/DeviceInstallServiceImpl.java
  97. 85
      user-service/src/main/java/com/mh/user/service/impl/EnergyServiceImpl.java
  98. 253
      user-service/src/main/java/com/mh/user/service/impl/HistoryDataPreServiceImpl.java
  99. 47
      user-service/src/main/java/com/mh/user/service/impl/KnowledgeDataServiceImpl.java
  100. 144
      user-service/src/main/java/com/mh/user/service/impl/NowDataServiceImpl.java
  101. Some files were not shown because too many files have changed in this diff Show More

210
2024数据库脚本.sql

@ -1,210 +0,0 @@
-- 2024-05-07 维修表缺少字段
ALTER TABLE maintain_info
ADD cost numeric(2, 0) NULL;
EXEC sys.sp_addextendedproperty 'MS_Description', N'材料费用', 'schema', N'dbo', 'table', N'maintain_info', 'column', N'cost';
ALTER TABLE maintain_info
ADD contents varchar(100) NULL;
EXEC sys.sp_addextendedproperty 'MS_Description', N'维保内容', 'schema', N'dbo', 'table', N'maintain_info', 'column', N'contents';
ALTER TABLE maintain_info
ADD evaluate varchar(10) NULL;
EXEC sys.sp_addextendedproperty 'MS_Description', N'评价内容', 'schema', N'dbo', 'table', N'maintain_info', 'column', N'evaluate';
-- 训练集合:
begin tran
insert into history_data_pre(cur_date,building_id,water_value,elect_value,water_level,env_min_temp,env_max_temp)
select eds.cur_date,
eds.building_id,
isnull(eds.water_value,
0) as water_value,
isnull(eds.elect_value,
0) as elect_value,
isnull(convert(numeric (24, 2), t1.water_level),
0) as water_level,
th.tempmin,
th.tempmax
from energy_day_sum eds
left join (select convert(date,
cur_date) as cur_date,
building_id,
avg(isnull(convert(numeric (24, 2), water_level), 0)) as water_level
from history_data
group by convert(date,
cur_date),
building_id) t1 on
eds.cur_date = t1.cur_date and eds.building_id = t1.building_id
left join temp_history th
on eds.cur_date = th.cur_date
where eds.building_id != '所有'
order by
eds.building_id,
eds.cur_date
rollback
-- 2024-05-09 创建历史预测表
-- 历史水电用量以及预测值
CREATE TABLE history_data_pre
(
cur_date date NULL,
building_id varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
env_min_temp numeric(24, 2) NULL,
env_max_temp numeric(24, 2) NULL,
water_value numeric(24, 2) NULL,
elect_value numeric(24, 2) NULL,
water_level numeric(24, 2) NULL,
id bigint IDENTITY(1,1) NOT NULL,
water_value_pre numeric(24, 2) NULL,
elect_value_pre numeric(24, 2) NULL,
water_level_pre numeric(24, 2) NULL,
remark varchar(200) COLLATE Chinese_PRC_CI_AS NULL,
CONSTRAINT PK_history_data_pre PRIMARY KEY (id)
);
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'历史水电用量以及预测值', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'history_data_pre';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'日期', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'history_data_pre', @level2type=N'Column', @level2name=N'cur_date';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'楼栋编号', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'history_data_pre', @level2type=N'Column', @level2name=N'building_id';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'环境最低温度', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'history_data_pre', @level2type=N'Column', @level2name=N'env_min_temp';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'环境最高温度', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'history_data_pre', @level2type=N'Column', @level2name=N'env_max_temp';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'实际用水量', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'history_data_pre', @level2type=N'Column', @level2name=N'water_value';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'实际用电量', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'history_data_pre', @level2type=N'Column', @level2name=N'elect_value';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'平均水位', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'history_data_pre', @level2type=N'Column', @level2name=N'water_level';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'id', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'history_data_pre', @level2type=N'Column', @level2name=N'id';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'用水量预测值', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'history_data_pre', @level2type=N'Column', @level2name=N'water_value_pre';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'用电量预测值', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'history_data_pre', @level2type=N'Column', @level2name=N'elect_value_pre';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'平均水位预测值', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'history_data_pre', @level2type=N'Column', @level2name=N'water_level_pre';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'备注', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'history_data_pre', @level2type=N'Column', @level2name=N'remark';
create index history_data_pre_building_id on history_data_pre (building_id);
create index history_data_pre_cur_date on history_data_pre (cur_date);
-- 2024-05-09 系统参数表增加天气区域
ALTER TABLE SysParam
ADD proArea varchar(100) NULL;
EXEC sp_addextendedproperty 'MS_Description', N'天气区域', 'schema', N'dbo', 'table', N'SysParam', 'column', N'proArea';
-- 2024-05-15 热泵使用时间表(月表)
CREATE TABLE analysis_runtime_month (
id bigint IDENTITY(1,1) NOT NULL,
cur_date varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
item_type varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day01 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day02 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day03 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day04 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day05 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day06 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day07 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day08 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day09 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day10 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day11 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day12 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day13 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day14 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day15 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day16 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day17 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day18 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day19 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day20 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day21 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day22 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day23 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day24 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day25 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day26 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day27 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day28 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day29 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day30 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
day31 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
total_value varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
building_id varchar(50) COLLATE Chinese_PRC_CI_AS NULL
);
-- 使用时间年表
CREATE TABLE analysis_runtime_year (
id bigint IDENTITY(1,1) NOT NULL,
cur_date varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
item_type varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
month01 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
month02 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
month03 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
month04 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
month05 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
month06 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
month07 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
month08 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
month09 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
month10 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
month11 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
month12 varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
total_value varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
building_id varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
building_name varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
CONSTRAINT analysis_runtime_year_id PRIMARY KEY (id)
);
-- Extended properties
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'序号', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'id';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'日期', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'cur_date';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'类型', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'item_type';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'1月用量或比值', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'month01';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'2月用量或比值', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'month02';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'3月用量或比值', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'month03';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'4月用量或比值', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'month04';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'5月用量或比值', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'month05';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'6月用量或比值', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'month06';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'7月用量或比值', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'month07';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'8月用量或比值', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'month08';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'9月用量或比值', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'month09';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'10月用量或比值', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'month10';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'11月用量或比值', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'month11';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'12月用量或比值', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'month12';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'合计用量', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'total_value';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'楼栋编号', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'building_id';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'楼栋名称', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'analysis_runtime_year', @level2type=N'Column', @level2name=N'building_name';
-- 2024-06-24 添加楼栋人数
alter table history_data_pre add people_num numeric(24,2) not null default 0;
exec sp_addextendedproperty N'MS_Description', N'每栋楼人数', N'schema', N'dbo',N'table', N'history_data_pre', N'column', N'people_num';
-- 2024-06-26 添加知识库
CREATE TABLE knowledge_data
(
id bigint IDENTITY(1,1) NOT NULL,
title varchar(100) COLLATE Chinese_PRC_CI_AS NULL,
description varchar(200) COLLATE Chinese_PRC_CI_AS NULL,
content varchar(2000) COLLATE Chinese_PRC_CI_AS NULL,
create_time datetime NULL,
status int NULL,
remark varchar(200) COLLATE Chinese_PRC_CI_AS NULL,
CONSTRAINT pk_knowledge_data PRIMARY KEY (id)
);
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'知识库数据', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'knowledge_data';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'id', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'knowledge_data', @level2type=N'Column', @level2name=N'id';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'标题', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'knowledge_data', @level2type=N'Column', @level2name=N'title';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'描述', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'knowledge_data', @level2type=N'Column', @level2name=N'description';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'内容', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'knowledge_data', @level2type=N'Column', @level2name=N'content';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'创建时间', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'knowledge_data', @level2type=N'Column', @level2name=N'create_time';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'状态', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'knowledge_data', @level2type=N'Column', @level2name=N'status';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'备注', @level0type=N'Schema', @level0name=N'dbo', @level1type=N'Table', @level1name=N'knowledge_data', @level2type=N'Column', @level2name=N'remark';
create index knowledge_data_create_time on history_data_pre (create_time);
-- 2024-07-01 水位变换添加
ALTER TABLE chws_gsh.dbo.waterLevel ADD level14 varchar(50) NULL;
EXEC chws_gsh.sys.sp_addextendedproperty 'MS_Description', N'14点水位', 'schema', N'dbo', 'table', N'waterLevel', 'column', N'level14';
ALTER TABLE chws_gsh.dbo.building ADD low_tank_height numeric(24,2) NULL;
EXEC chws_gsh.sys.sp_addextendedproperty 'MS_Description', N'低区域水箱高度', 'schema', N'dbo', 'table', N'building', 'column', N'low_tank_height';
-- 2024-10-11 添加供水,补水,回水状态
ALTER TABLE now_data ADD up_water_state varchar(50) NULL;
EXEC sp_addextendedproperty 'MS_Description', N'供水状态', 'schema', N'dbo', 'table', N'now_data', 'column', N'up_water_state';
ALTER TABLE now_data ADD use_water_state varchar(50) NULL;
EXEC sp_addextendedproperty 'MS_Description', N'补水状态', 'schema', N'dbo', 'table', N'now_data', 'column', N'use_water_state';
ALTER TABLE now_data ADD back_water_state varchar(50) NULL;
EXEC sp_addextendedproperty 'MS_Description', N'回水状态', 'schema', N'dbo', 'table', N'now_data', 'column', N'back_water_state';
-- 2024-11-19 添加是否是单箱
ALTER TABLE building ADD is_single_box bit NULL;
EXEC sp_addextendedproperty 'MS_Description', N'是否是单箱温度', 'schema', N'dbo', 'table', N'device_install', 'column', N'is_single_box';

135
algorithm/pom.xml

@ -1,135 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.mh</groupId>
<artifactId>chws</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mh</groupId>
<artifactId>algorithm</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<encoding>UTF-8</encoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/net.sourceforge.javacsv/javacsv -->
<dependency>
<groupId>net.sourceforge.javacsv</groupId>
<artifactId>javacsv</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>gov.nist.math</groupId>
<artifactId>jama</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.9.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>default</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<!-- java版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- 这是javadoc打包插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9.1</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
<!-- 该处屏蔽jdk1.8后javadoc的严格校验 -->
<configuration>
<additionalparam>-Xdoclint:none</additionalparam>
</configuration>
</execution>
</executions>
</plugin>
<!-- 打包源码插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<!--签名插件-->
<!-- <plugin>-->
<!-- <groupId>org.apache.maven.plugins</groupId>-->
<!-- <artifactId>maven-gpg-plugin</artifactId>-->
<!-- <version>1.4</version>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <id>sign-artifacts</id>-->
<!-- <phase>verify</phase>-->
<!-- <goals>-->
<!-- <goal>sign</goal>-->
<!-- </goals>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- </plugin>-->
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<classesDirectory>target/classes</classesDirectory>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

8
algorithm/src/main/java/com/mh/algorithm/bpnn/ActivationFunction.java

@ -1,8 +0,0 @@
package com.mh.algorithm.bpnn;
public interface ActivationFunction {
//计算值
double computeValue(double val);
//计算导数
double computeDerivative(double val);
}

111
algorithm/src/main/java/com/mh/algorithm/bpnn/BPModel.java

@ -1,111 +0,0 @@
package com.mh.algorithm.bpnn;
import com.mh.algorithm.matrix.Matrix;
import java.io.Serializable;
public class BPModel implements Serializable {
//BP神经网络权值与阈值
private Matrix weightIJ;
private Matrix b1;
private Matrix weightJP;
private Matrix b2;
/*用于反归一化*/
private Matrix inputMax;
private Matrix inputMin;
private Matrix outputMax;
private Matrix outputMin;
/*BP神经网络训练参数*/
private BPParameter bpParameter;
/*BP神经网络训练情况*/
private double error;
private int times;
public Matrix getWeightIJ() {
return weightIJ;
}
public void setWeightIJ(Matrix weightIJ) {
this.weightIJ = weightIJ;
}
public Matrix getB1() {
return b1;
}
public void setB1(Matrix b1) {
this.b1 = b1;
}
public Matrix getWeightJP() {
return weightJP;
}
public void setWeightJP(Matrix weightJP) {
this.weightJP = weightJP;
}
public Matrix getB2() {
return b2;
}
public void setB2(Matrix b2) {
this.b2 = b2;
}
public Matrix getInputMax() {
return inputMax;
}
public void setInputMax(Matrix inputMax) {
this.inputMax = inputMax;
}
public Matrix getInputMin() {
return inputMin;
}
public void setInputMin(Matrix inputMin) {
this.inputMin = inputMin;
}
public Matrix getOutputMax() {
return outputMax;
}
public void setOutputMax(Matrix outputMax) {
this.outputMax = outputMax;
}
public Matrix getOutputMin() {
return outputMin;
}
public void setOutputMin(Matrix outputMin) {
this.outputMin = outputMin;
}
public BPParameter getBpParameter() {
return bpParameter;
}
public void setBpParameter(BPParameter bpParameter) {
this.bpParameter = bpParameter;
}
public double getError() {
return error;
}
public void setError(double error) {
this.error = error;
}
public int getTimes() {
return times;
}
public void setTimes(int times) {
this.times = times;
}
}

262
algorithm/src/main/java/com/mh/algorithm/bpnn/BPNeuralNetworkFactory.java

@ -1,262 +0,0 @@
package com.mh.algorithm.bpnn;
import com.mh.algorithm.matrix.Matrix;
import com.mh.algorithm.utils.MatrixUtil;
import java.util.*;
public class BPNeuralNetworkFactory {
/**
* 训练BP神经网络模型
* @param bpParameter
* @param inputAndOutput
* @return
*/
public BPModel trainBP(BPParameter bpParameter, Matrix inputAndOutput) throws Exception {
ActivationFunction activationFunction = bpParameter.getActivationFunction();
int inputCount = bpParameter.getInputLayerNeuronCount();
int hiddenCount = bpParameter.getHiddenLayerNeuronCount();
int outputCount = bpParameter.getOutputLayerNeuronCount();
double normalizationMin = bpParameter.getNormalizationMin();
double normalizationMax = bpParameter.getNormalizationMax();
double step = bpParameter.getStep();
double momentumFactor = bpParameter.getMomentumFactor();
double precision = bpParameter.getPrecision();
int maxTimes = bpParameter.getMaxTimes();
if(inputAndOutput.getMatrixColCount() != inputCount + outputCount){
throw new Exception("神经元个数不符,请修改");
}
// 初始化权值
Matrix weightIJ = initWeight(inputCount, hiddenCount);
Matrix weightJP = initWeight(hiddenCount, outputCount);
// 初始化阈值
Matrix b1 = initThreshold(hiddenCount);
Matrix b2 = initThreshold(outputCount);
// 动量项
Matrix deltaWeightIJ0 = new Matrix(inputCount, hiddenCount);
Matrix deltaWeightJP0 = new Matrix(hiddenCount, outputCount);
Matrix deltaB10 = new Matrix(1, hiddenCount);
Matrix deltaB20 = new Matrix(1, outputCount);
// 截取输入矩阵和输出矩阵
Matrix input = inputAndOutput.subMatrix(0,inputAndOutput.getMatrixRowCount(),0,inputCount);
Matrix output = inputAndOutput.subMatrix(0,inputAndOutput.getMatrixRowCount(),inputCount,outputCount);
// 归一化
Map<String,Object> inputAfterNormalize = MatrixUtil.normalize(input, normalizationMin, normalizationMax);
input = (Matrix) inputAfterNormalize.get("res");
Map<String,Object> outputAfterNormalize = MatrixUtil.normalize(output, normalizationMin, normalizationMax);
output = (Matrix) outputAfterNormalize.get("res");
int times = 1;
double E = 0;//误差
while (times < maxTimes) {
/*-----------------正向传播---------------------*/
// 隐含层输入
Matrix jIn = input.multiple(weightIJ);
// 扩充阈值
Matrix b1Copy = b1.extend(2,jIn.getMatrixRowCount());
// 加上阈值
jIn = jIn.plus(b1Copy);
// 隐含层输出
Matrix jOut = computeValue(jIn,activationFunction);
// 输出层输入
Matrix pIn = jOut.multiple(weightJP);
// 扩充阈值
Matrix b2Copy = b2.extend(2, pIn.getMatrixRowCount());
// 加上阈值
pIn = pIn.plus(b2Copy);
// 输出层输出
Matrix pOut = computeValue(pIn,activationFunction);
// 计算误差
Matrix e = output.subtract(pOut);
E = computeE(e);//误差
// 判断是否符合精度
if (Math.abs(E) <= precision) {
System.out.println("满足精度");
break;
}
/*-----------------反向传播---------------------*/
// J与P之间权值修正量
Matrix deltaWeightJP = e.multiple(step);
deltaWeightJP = deltaWeightJP.pointMultiple(computeDerivative(pIn,activationFunction));
deltaWeightJP = deltaWeightJP.transpose().multiple(jOut);
deltaWeightJP = deltaWeightJP.transpose();
// P层神经元阈值修正量
Matrix deltaThresholdP = e.multiple(step);
deltaThresholdP = deltaThresholdP.transpose().multiple(computeDerivative(pIn, activationFunction));
// I与J之间的权值修正量
Matrix deltaO = e.pointMultiple(computeDerivative(pIn,activationFunction));
Matrix tmp = weightJP.multiple(deltaO.transpose()).transpose();
Matrix deltaWeightIJ = tmp.pointMultiple(computeDerivative(jIn, activationFunction));
deltaWeightIJ = input.transpose().multiple(deltaWeightIJ);
deltaWeightIJ = deltaWeightIJ.multiple(step);
// J层神经元阈值修正量
Matrix deltaThresholdJ = tmp.transpose().multiple(computeDerivative(jIn, activationFunction));
deltaThresholdJ = deltaThresholdJ.multiple(-step);
if (times == 1) {
// 更新权值与阈值
weightIJ = weightIJ.plus(deltaWeightIJ);
weightJP = weightJP.plus(deltaWeightJP);
b1 = b1.plus(deltaThresholdJ);
b2 = b2.plus(deltaThresholdP);
}else{
// 加动量项
weightIJ = weightIJ.plus(deltaWeightIJ).plus(deltaWeightIJ0.multiple(momentumFactor));
weightJP = weightJP.plus(deltaWeightJP).plus(deltaWeightJP0.multiple(momentumFactor));
b1 = b1.plus(deltaThresholdJ).plus(deltaB10.multiple(momentumFactor));
b2 = b2.plus(deltaThresholdP).plus(deltaB20.multiple(momentumFactor));
}
deltaWeightIJ0 = deltaWeightIJ;
deltaWeightJP0 = deltaWeightJP;
deltaB10 = deltaThresholdJ;
deltaB20 = deltaThresholdP;
times++;
}
// BP神经网络的输出
BPModel result = new BPModel();
result.setInputMax((Matrix) inputAfterNormalize.get("max"));
result.setInputMin((Matrix) inputAfterNormalize.get("min"));
result.setOutputMax((Matrix) outputAfterNormalize.get("max"));
result.setOutputMin((Matrix) outputAfterNormalize.get("min"));
result.setWeightIJ(weightIJ);
result.setWeightJP(weightJP);
result.setB1(b1);
result.setB2(b2);
result.setError(E);
result.setTimes(times);
result.setBpParameter(bpParameter);
System.out.println("循环次数:" + times + ",误差:" + E);
return result;
}
/**
* 计算BP神经网络的值
* @param bpModel
* @param input
* @return
*/
public Matrix computeBP(BPModel bpModel,Matrix input) throws Exception {
if (input.getMatrixColCount() != bpModel.getBpParameter().getInputLayerNeuronCount()) {
throw new Exception("输入矩阵纬度有误");
}
ActivationFunction activationFunction = bpModel.getBpParameter().getActivationFunction();
Matrix weightIJ = bpModel.getWeightIJ();
Matrix weightJP = bpModel.getWeightJP();
Matrix b1 = bpModel.getB1();
Matrix b2 = bpModel.getB2();
double[][] normalizedInput = new double[input.getMatrixRowCount()][input.getMatrixColCount()];
for (int i = 0; i < input.getMatrixRowCount(); i++) {
for (int j = 0; j < input.getMatrixColCount(); j++) {
if ((input.getValOfIdx(i,j) - bpModel.getInputMin().getValOfIdx(0,j)) == 0
|| (bpModel.getInputMax().getValOfIdx(0,j) - bpModel.getInputMin().getValOfIdx(0,j)) == 0) {
normalizedInput[i][j] = bpModel.getBpParameter().getNormalizationMin();
continue;
}
normalizedInput[i][j] = bpModel.getBpParameter().getNormalizationMin()
+ (input.getValOfIdx(i,j) - bpModel.getInputMin().getValOfIdx(0,j))
/ (bpModel.getInputMax().getValOfIdx(0,j) - bpModel.getInputMin().getValOfIdx(0,j))
* (bpModel.getBpParameter().getNormalizationMax() - bpModel.getBpParameter().getNormalizationMin());
}
}
Matrix normalizedInputMatrix = new Matrix(normalizedInput);
Matrix jIn = normalizedInputMatrix.multiple(weightIJ);
// 扩充阈值
Matrix b1Copy = b1.extend(2,jIn.getMatrixRowCount());
// 加上阈值
jIn = jIn.plus(b1Copy);
// 隐含层输出
Matrix jOut = computeValue(jIn,activationFunction);
// 输出层输入
Matrix pIn = jOut.multiple(weightJP);
// 扩充阈值
Matrix b2Copy = b2.extend(2,pIn.getMatrixRowCount());
// 加上阈值
pIn = pIn.plus(b2Copy);
// 输出层输出
Matrix pOut = computeValue(pIn,activationFunction);
// 反归一化
return MatrixUtil.inverseNormalize(pOut, bpModel.getBpParameter().getNormalizationMax(), bpModel.getBpParameter().getNormalizationMin(), bpModel.getOutputMax(), bpModel.getOutputMin());
}
// 初始化权值
private Matrix initWeight(int x,int y){
Random random=new Random();
double[][] weight = new double[x][y];
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
weight[i][j] = 2*random.nextDouble()-1;
}
}
return new Matrix(weight);
}
// 初始化阈值
private Matrix initThreshold(int x){
Random random = new Random();
double[][] result = new double[1][x];
for (int i = 0; i < x; i++) {
result[0][i] = 2*random.nextDouble()-1;
}
return new Matrix(result);
}
/**
* 计算激活函数的值
* @param a
* @return
*/
private Matrix computeValue(Matrix a, ActivationFunction activationFunction) throws Exception {
if (a.getMatrix() == null) {
throw new Exception("参数值为空");
}
double[][] result = new double[a.getMatrixRowCount()][a.getMatrixColCount()];
for (int i = 0; i < a.getMatrixRowCount(); i++) {
for (int j = 0; j < a.getMatrixColCount(); j++) {
result[i][j] = activationFunction.computeValue(a.getValOfIdx(i,j));
}
}
return new Matrix(result);
}
/**
* 激活函数导数的值
* @param a
* @return
*/
private Matrix computeDerivative(Matrix a , ActivationFunction activationFunction) throws Exception {
if (a.getMatrix() == null) {
throw new Exception("参数值为空");
}
double[][] result = new double[a.getMatrixRowCount()][a.getMatrixColCount()];
for (int i = 0; i < a.getMatrixRowCount(); i++) {
for (int j = 0; j < a.getMatrixColCount(); j++) {
result[i][j] = activationFunction.computeDerivative(a.getValOfIdx(i,j));
}
}
return new Matrix(result);
}
/**
* 计算误差
* @param e
* @return
*/
private double computeE(Matrix e){
e = e.square();
return 0.5*e.sumAll();
}
}

106
algorithm/src/main/java/com/mh/algorithm/bpnn/BPParameter.java

@ -1,106 +0,0 @@
package com.mh.algorithm.bpnn;
import java.io.Serializable;
public class BPParameter implements Serializable {
//输入层神经元个数
private int inputLayerNeuronCount = 3;
//隐含层神经元个数
private int hiddenLayerNeuronCount = 3;
//输出层神经元个数
private int outputLayerNeuronCount = 1;
//归一化区间
private double normalizationMin = 0.2;
private double normalizationMax = 0.8;
//学习步长
private double step = 0.05;
//动量因子
private double momentumFactor = 0.2;
//激活函数
private ActivationFunction activationFunction = new Sigmoid();
//精度
private double precision = 0.000001;
//最大循环次数
private int maxTimes = 1000000;
public double getMomentumFactor() {
return momentumFactor;
}
public void setMomentumFactor(double momentumFactor) {
this.momentumFactor = momentumFactor;
}
public double getStep() {
return step;
}
public void setStep(double step) {
this.step = step;
}
public double getNormalizationMin() {
return normalizationMin;
}
public void setNormalizationMin(double normalizationMin) {
this.normalizationMin = normalizationMin;
}
public double getNormalizationMax() {
return normalizationMax;
}
public void setNormalizationMax(double normalizationMax) {
this.normalizationMax = normalizationMax;
}
public int getInputLayerNeuronCount() {
return inputLayerNeuronCount;
}
public void setInputLayerNeuronCount(int inputLayerNeuronCount) {
this.inputLayerNeuronCount = inputLayerNeuronCount;
}
public int getHiddenLayerNeuronCount() {
return hiddenLayerNeuronCount;
}
public void setHiddenLayerNeuronCount(int hiddenLayerNeuronCount) {
this.hiddenLayerNeuronCount = hiddenLayerNeuronCount;
}
public int getOutputLayerNeuronCount() {
return outputLayerNeuronCount;
}
public void setOutputLayerNeuronCount(int outputLayerNeuronCount) {
this.outputLayerNeuronCount = outputLayerNeuronCount;
}
public ActivationFunction getActivationFunction() {
return activationFunction;
}
public void setActivationFunction(ActivationFunction activationFunction) {
this.activationFunction = activationFunction;
}
public double getPrecision() {
return precision;
}
public void setPrecision(double precision) {
this.precision = precision;
}
public int getMaxTimes() {
return maxTimes;
}
public void setMaxTimes(int maxTimes) {
this.maxTimes = maxTimes;
}
}

15
algorithm/src/main/java/com/mh/algorithm/bpnn/Sigmoid.java

@ -1,15 +0,0 @@
package com.mh.algorithm.bpnn;
import java.io.Serializable;
public class Sigmoid implements ActivationFunction, Serializable {
@Override
public double computeValue(double val) {
return 1 / (1 + Math.exp(-val));
}
@Override
public double computeDerivative(double val) {
return computeValue(val) * (1 - computeValue(val));
}
}

24
algorithm/src/main/java/com/mh/algorithm/constants/OrderEnum.java

@ -1,24 +0,0 @@
package com.mh.algorithm.constants;
/**
* 排序枚举类
*/
public enum OrderEnum {
ASC(1,"升序"),
DESC(2,"降序");
OrderEnum(int flag, String name) {
this.flag = flag;
this.name = name;
}
private int flag;
private String name;
}

88
algorithm/src/main/java/com/mh/algorithm/knn/KNN.java

@ -1,88 +0,0 @@
package com.mh.algorithm.knn;
import com.mh.algorithm.constants.OrderEnum;
import com.mh.algorithm.matrix.Matrix;
import com.mh.algorithm.utils.MatrixUtil;
import java.util.*;
/**
* @program: top-algorithm-set
* @description: KNN k-临近算法进行分类
* @author: Mr.Zhao
* @create: 2020-10-13 22:03
**/
public class KNN {
public static Matrix classify(Matrix input, Matrix dataSet, Matrix labels, int k) throws Exception {
if (dataSet.getMatrixRowCount() != labels.getMatrixRowCount()) {
throw new IllegalArgumentException("矩阵训练集与标签维度不一致");
}
if (input.getMatrixColCount() != dataSet.getMatrixColCount()) {
throw new IllegalArgumentException("待分类矩阵列数与训练集列数不一致");
}
if (dataSet.getMatrixRowCount() < k) {
throw new IllegalArgumentException("训练集样本数小于k");
}
// 归一化
int trainCount = dataSet.getMatrixRowCount();
int testCount = input.getMatrixRowCount();
Matrix trainAndTest = dataSet.splice(2, input);
Map<String, Object> normalize = MatrixUtil.normalize(trainAndTest, 0, 1);
trainAndTest = (Matrix) normalize.get("res");
dataSet = trainAndTest.subMatrix(0, trainCount, 0, trainAndTest.getMatrixColCount());
input = trainAndTest.subMatrix(0, testCount, 0, trainAndTest.getMatrixColCount());
// 获取标签信息
List<Double> labelList = new ArrayList<>();
for (int i = 0; i < labels.getMatrixRowCount(); i++) {
if (!labelList.contains(labels.getValOfIdx(i, 0))) {
labelList.add(labels.getValOfIdx(i, 0));
}
}
Matrix result = new Matrix(new double[input.getMatrixRowCount()][1]);
for (int i = 0; i < input.getMatrixRowCount(); i++) {
// 计算向量间的欧式距离
// 将labels矩阵扩展
Matrix labelMatrixCopied = input.getRowOfIdx(i).extend(2, dataSet.getMatrixRowCount());
// 前面是计算欧氏距离,splice(1,labels)是将距离矩阵与labels矩阵合并
Matrix distanceMatrix = dataSet.subtract(labelMatrixCopied).square().sumRow().pow(0.5).splice(1, labels);
// 将计算出的距离矩阵按照距离升序排序
distanceMatrix.sort(0, OrderEnum.ASC);
// 遍历最近的k个变量
Map<Double, Integer> map = new HashMap<>();
for (int j = 0; j < k; j++) {
// 遍历标签种类数
for (Double label : labelList) {
if (distanceMatrix.getValOfIdx(j, 1) == label) {
map.put(label, map.getOrDefault(label, 0) + 1);
}
}
}
result.setValue(i, 0, getKeyOfMaxValue(map));
}
return result;
}
/**
* 取map中值最大的key
*
* @param map
* @return
*/
private static Double getKeyOfMaxValue(Map<Double, Integer> map) {
if (map == null)
return null;
Double keyOfMaxValue = 0.0;
Integer maxValue = 0;
for (Double key : map.keySet()) {
if (map.get(key) > maxValue) {
keyOfMaxValue = key;
maxValue = map.get(key);
}
}
return keyOfMaxValue;
}
}

646
algorithm/src/main/java/com/mh/algorithm/matrix/Matrix.java

@ -1,646 +0,0 @@
package com.mh.algorithm.matrix;
import com.mh.algorithm.constants.OrderEnum;
import java.io.Serializable;
public class Matrix implements Serializable {
private double[][] matrix;
//矩阵列数
private int matrixColCount;
//矩阵行数
private int matrixRowCount;
/**
* 构造一个空矩阵
*/
public Matrix() {
this.matrix = null;
this.matrixColCount = 0;
this.matrixRowCount = 0;
}
/**
* 构造一个matrix矩阵
* @param matrix
*/
public Matrix(double[][] matrix) {
this.matrix = matrix;
this.matrixRowCount = matrix.length;
this.matrixColCount = matrix[0].length;
}
/**
* 构造一个rowCount行colCount列值为0的矩阵
* @param rowCount
* @param colCount
*/
public Matrix(int rowCount,int colCount) {
double[][] matrix = new double[rowCount][colCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
matrix[i][j] = 0;
}
}
this.matrix = matrix;
this.matrixRowCount = rowCount;
this.matrixColCount = colCount;
}
/**
* 构造一个rowCount行colCount列值为val的矩阵
* @param val
* @param rowCount
* @param colCount
*/
public Matrix(double val,int rowCount,int colCount) {
double[][] matrix = new double[rowCount][colCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
matrix[i][j] = val;
}
}
this.matrix = matrix;
this.matrixRowCount = rowCount;
this.matrixColCount = colCount;
}
public double[][] getMatrix() {
return matrix;
}
public void setMatrix(double[][] matrix) {
this.matrix = matrix;
this.matrixRowCount = matrix.length;
this.matrixColCount = matrix[0].length;
}
public int getMatrixColCount() {
return matrixColCount;
}
public int getMatrixRowCount() {
return matrixRowCount;
}
/**
* 获取矩阵指定位置的值
*
* @param x
* @param y
* @return
*/
public double getValOfIdx(int x, int y) throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
if (x > matrixRowCount - 1) {
throw new IllegalArgumentException("索引x越界");
}
if (y > matrixColCount - 1) {
throw new IllegalArgumentException("索引y越界");
}
return matrix[x][y];
}
/**
* 获取矩阵指定行
*
* @param x
* @return
*/
public Matrix getRowOfIdx(int x) throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
if (x > matrixRowCount - 1) {
throw new IllegalArgumentException("索引x越界");
}
double[][] result = new double[1][matrixColCount];
result[0] = matrix[x];
return new Matrix(result);
}
/**
* 获取矩阵指定列
*
* @param y
* @return
*/
public Matrix getColOfIdx(int y) throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
if (y > matrixColCount - 1) {
throw new IllegalArgumentException("索引y越界");
}
double[][] result = new double[matrixRowCount][1];
for (int i = 0; i < matrixRowCount; i++) {
result[i][0] = matrix[i][y];
}
return new Matrix(result);
}
/**
* 设置矩阵中x,y位置元素的值
* @param x
* @param y
* @param val
*/
public void setValue(int x, int y, double val) {
if (x > this.matrixRowCount - 1) {
throw new IllegalArgumentException("行索引越界");
}
if (y > this.matrixColCount - 1) {
throw new IllegalArgumentException("列索引越界");
}
this.matrix[x][y] = val;
}
/**
* 矩阵乘矩阵
*
* @param a
* @return
* @throws IllegalArgumentException
*/
public Matrix multiple(Matrix a) throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
if (a.getMatrix() == null || a.getMatrixRowCount() == 0 || a.getMatrixColCount() == 0) {
throw new IllegalArgumentException("参数矩阵为空");
}
if (matrixColCount != a.getMatrixRowCount()) {
throw new IllegalArgumentException("矩阵纬度不同,不可计算");
}
double[][] result = new double[matrixRowCount][a.getMatrixColCount()];
for (int i = 0; i < matrixRowCount; i++) {
for (int j = 0; j < a.getMatrixColCount(); j++) {
for (int k = 0; k < matrixColCount; k++) {
result[i][j] = result[i][j] + matrix[i][k] * a.getMatrix()[k][j];
}
}
}
return new Matrix(result);
}
/**
* 矩阵乘一个数字
*
* @param a
* @return
*/
public Matrix multiple(double a) throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
double[][] result = new double[matrixRowCount][matrixColCount];
for (int i = 0; i < matrixRowCount; i++) {
for (int j = 0; j < matrixColCount; j++) {
result[i][j] = matrix[i][j] * a;
}
}
return new Matrix(result);
}
/**
* 矩阵点乘
*
* @param a
* @return
*/
public Matrix pointMultiple(Matrix a) throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
if (a.getMatrix() == null || a.getMatrixRowCount() == 0 || a.getMatrixColCount() == 0) {
throw new IllegalArgumentException("参数矩阵为空");
}
if (matrixRowCount != a.getMatrixRowCount() && matrixColCount != a.getMatrixColCount()) {
throw new IllegalArgumentException("矩阵纬度不同,不可计算");
}
double[][] result = new double[matrixRowCount][matrixColCount];
for (int i = 0; i < matrixRowCount; i++) {
for (int j = 0; j < matrixColCount; j++) {
result[i][j] = matrix[i][j] * a.getMatrix()[i][j];
}
}
return new Matrix(result);
}
/**
* 矩阵除一个数字
* @param a
* @return
* @throws IllegalArgumentException
*/
public Matrix divide(double a) throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
double[][] result = new double[matrixRowCount][matrixColCount];
for (int i = 0; i < matrixRowCount; i++) {
for (int j = 0; j < matrixColCount; j++) {
result[i][j] = matrix[i][j] / a;
}
}
return new Matrix(result);
}
/**
* 矩阵加法
*
* @param a
* @return
*/
public Matrix plus(Matrix a) throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
if (a.getMatrix() == null || a.getMatrixRowCount() == 0 || a.getMatrixColCount() == 0) {
throw new IllegalArgumentException("参数矩阵为空");
}
if (matrixRowCount != a.getMatrixRowCount() && matrixColCount != a.getMatrixColCount()) {
throw new IllegalArgumentException("矩阵纬度不同,不可计算");
}
double[][] result = new double[matrixRowCount][matrixColCount];
for (int i = 0; i < matrixRowCount; i++) {
for (int j = 0; j < matrixColCount; j++) {
result[i][j] = matrix[i][j] + a.getMatrix()[i][j];
}
}
return new Matrix(result);
}
/**
* 矩阵加一个数字
* @param a
* @return
* @throws IllegalArgumentException
*/
public Matrix plus(double a) throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
double[][] result = new double[matrixRowCount][matrixColCount];
for (int i = 0; i < matrixRowCount; i++) {
for (int j = 0; j < matrixColCount; j++) {
result[i][j] = matrix[i][j] + a;
}
}
return new Matrix(result);
}
/**
* 矩阵减法
*
* @param a
* @return
*/
public Matrix subtract(Matrix a) throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
if (a.getMatrix() == null || a.getMatrixRowCount() == 0 || a.getMatrixColCount() == 0) {
throw new IllegalArgumentException("参数矩阵为空");
}
if (matrixRowCount != a.getMatrixRowCount() && matrixColCount != a.getMatrixColCount()) {
throw new IllegalArgumentException("矩阵纬度不同,不可计算");
}
double[][] result = new double[matrixRowCount][matrixColCount];
for (int i = 0; i < matrixRowCount; i++) {
for (int j = 0; j < matrixColCount; j++) {
result[i][j] = matrix[i][j] - a.getMatrix()[i][j];
}
}
return new Matrix(result);
}
/**
* 矩阵减一个数字
* @param a
* @return
* @throws IllegalArgumentException
*/
public Matrix subtract(double a) throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
double[][] result = new double[matrixRowCount][matrixColCount];
for (int i = 0; i < matrixRowCount; i++) {
for (int j = 0; j < matrixColCount; j++) {
result[i][j] = matrix[i][j] - a;
}
}
return new Matrix(result);
}
/**
* 矩阵行求和
*
* @return
*/
public Matrix sumRow() throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
double[][] result = new double[matrixRowCount][1];
for (int i = 0; i < matrixRowCount; i++) {
for (int j = 0; j < matrixColCount; j++) {
result[i][0] += matrix[i][j];
}
}
return new Matrix(result);
}
/**
* 矩阵列求和
*
* @return
*/
public Matrix sumCol() throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
double[][] result = new double[1][matrixColCount];
for (int i = 0; i < matrixRowCount; i++) {
for (int j = 0; j < matrixColCount; j++) {
result[0][j] += matrix[i][j];
}
}
return new Matrix(result);
}
/**
* 矩阵所有元素求和
*
* @return
*/
public double sumAll() throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
double result = 0;
for (double[] doubles : matrix) {
for (int j = 0; j < matrixColCount; j++) {
result += doubles[j];
}
}
return result;
}
/**
* 矩阵所有元素求平方
*
* @return
*/
public Matrix square() throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
double[][] result = new double[matrixRowCount][matrixColCount];
for (int i = 0; i < matrixRowCount; i++) {
for (int j = 0; j < matrixColCount; j++) {
result[i][j] = matrix[i][j] * matrix[i][j];
}
}
return new Matrix(result);
}
/**
* 矩阵所有元素求N次方
*
* @return
*/
public Matrix pow(double n) throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
double[][] result = new double[matrixRowCount][matrixColCount];
for (int i = 0; i < matrixRowCount; i++) {
for (int j = 0; j < matrixColCount; j++) {
result[i][j] = Math.pow(matrix[i][j],n);
}
}
return new Matrix(result);
}
/**
* 矩阵转置
*
* @return
*/
public Matrix transpose() throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
double[][] result = new double[matrixColCount][matrixRowCount];
for (int i = 0; i < matrixRowCount; i++) {
for (int j = 0; j < matrixColCount; j++) {
result[j][i] = matrix[i][j];
}
}
return new Matrix(result);
}
/**
* 截取矩阵
* @param startRowIndex 开始行索引
* @param rowCount 截取行数
* @param startColIndex 开始列索引
* @param colCount 截取列数
* @return
* @throws IllegalArgumentException
*/
public Matrix subMatrix(int startRowIndex,int rowCount,int startColIndex,int colCount) throws IllegalArgumentException {
if (startRowIndex + rowCount > matrixRowCount) {
throw new IllegalArgumentException("行索引越界");
}
if (startColIndex + colCount> matrixColCount) {
throw new IllegalArgumentException("列索引越界");
}
double[][] result = new double[rowCount][colCount];
for (int i = startRowIndex; i < startRowIndex + rowCount; i++) {
if (startColIndex + colCount - startColIndex >= 0)
System.arraycopy(matrix[i], startColIndex, result[i - startRowIndex], 0, colCount);
}
return new Matrix(result);
}
/**
* 矩阵合并
* @param direction 合并方向1为横向2为竖向
* @param a
* @return
* @throws IllegalArgumentException
*/
public Matrix splice(int direction, Matrix a) throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
if (a.getMatrix() == null || a.getMatrixRowCount() == 0 || a.getMatrixColCount() == 0) {
throw new IllegalArgumentException("参数矩阵为空");
}
if(direction == 1){
//横向拼接
if (matrixRowCount != a.getMatrixRowCount()) {
throw new IllegalArgumentException("矩阵行数不一致,无法拼接");
}
double[][] result = new double[matrixRowCount][matrixColCount + a.getMatrixColCount()];
for (int i = 0; i < matrixRowCount; i++) {
System.arraycopy(matrix[i],0,result[i],0,matrixColCount);
System.arraycopy(a.getMatrix()[i],0,result[i],matrixColCount,a.getMatrixColCount());
}
return new Matrix(result);
}else if(direction == 2){
//纵向拼接
if (matrixColCount != a.getMatrixColCount()) {
throw new IllegalArgumentException("矩阵列数不一致,无法拼接");
}
double[][] result = new double[matrixRowCount + a.getMatrixRowCount()][matrixColCount];
for (int i = 0; i < matrixRowCount; i++) {
result[i] = matrix[i];
}
for (int i = 0; i < a.getMatrixRowCount(); i++) {
result[matrixRowCount + i] = a.getMatrix()[i];
}
return new Matrix(result);
}else{
throw new IllegalArgumentException("方向参数有误");
}
}
/**
* 扩展矩阵
* @param direction 扩展方向1为横向2为竖向
* @param a
* @return
* @throws IllegalArgumentException
*/
public Matrix extend(int direction , int a) throws IllegalArgumentException {
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
if(direction == 1){
//横向复制
double[][] result = new double[matrixRowCount][matrixColCount*a];
for (int i = 0; i < matrixRowCount; i++) {
for (int j = 0; j < a; j++) {
System.arraycopy(matrix[i],0,result[i],j*matrixColCount,matrixColCount);
}
}
return new Matrix(result);
}else if(direction == 2){
//纵向复制
double[][] result = new double[matrixRowCount*a][matrixColCount];
for (int i = 0; i < matrixRowCount*a; i++) {
result[i] = matrix[i%matrixRowCount];
}
return new Matrix(result);
}else{
throw new IllegalArgumentException("方向参数有误");
}
}
/**
* 获取每列的平均值
* @return
* @throws IllegalArgumentException
*/
public Matrix getColAvg() throws IllegalArgumentException {
Matrix tmp = this.sumCol();
return tmp.divide(matrixRowCount);
}
/**
* 矩阵行排序
* @param index 根据第几列的数进行行排序
* @param order 排序顺序升序或降序
* @return
* @throws IllegalArgumentException
*/
public void sort(int index, OrderEnum order) throws IllegalArgumentException{
if (matrix == null || matrixRowCount == 0 || matrixColCount == 0) {
throw new IllegalArgumentException("矩阵为空");
}
if(index >= matrixColCount){
throw new IllegalArgumentException("排序索引index越界");
}
sort(index,order,0,this.matrixRowCount - 1);
}
/**
* 判断是否是方阵
* 行列数相等并且不等于0
* @return
*/
public boolean isSquareMatrix(){
return matrixColCount == matrixRowCount && matrixColCount != 0;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("\r\n");
for (int i = 0; i < matrixRowCount; i++) {
stringBuilder.append("# ");
for (int j = 0; j < matrixColCount; j++) {
stringBuilder.append(matrix[i][j]).append("\t ");
}
stringBuilder.append("#\r\n");
}
stringBuilder.append("\r\n");
return stringBuilder.toString();
}
private void sort(int index,OrderEnum order,int start,int end){
if(start >= end){
return;
}
int tmp = partition(index,order,start,end);
sort(index,order, start, tmp - 1);
sort(index,order, tmp + 1, end);
}
private int partition(int index,OrderEnum order,int start,int end){
int l = start + 1,r = end;
double v = matrix[start][index];
switch (order){
case ASC:
while(true){
while(matrix[r][index] >= v && r > start){
r--;
}
while(matrix[l][index] <= v && l < end){
l++;
}
if(l >= r){
break;
}
double[] tmp = matrix[r];
matrix[r] = matrix[l];
matrix[l] = tmp;
}
break;
case DESC:
while(true){
while(matrix[r][index] <= v && r > start){
r--;
}
while(matrix[l][index] >= v && l < end){
l++;
}
if(l >= r){
break;
}
double[] tmp = matrix[r];
matrix[r] = matrix[l];
matrix[l] = tmp;
}
break;
}
double[] tmp = matrix[r];
matrix[r] = matrix[start];
matrix[start] = tmp;
return r;
}
}

53
algorithm/src/main/java/com/mh/algorithm/utils/CsvInfo.java

@ -1,53 +0,0 @@
package com.mh.algorithm.utils;
import com.mh.algorithm.matrix.Matrix;
import java.util.ArrayList;
public class CsvInfo {
private String[] header;
private int csvRowCount;
private int csvColCount;
private ArrayList<String[]> csvFileList;
public String[] getHeader() {
return header;
}
public void setHeader(String[] header) {
this.header = header;
}
public int getCsvRowCount() {
return csvRowCount;
}
public int getCsvColCount() {
return csvColCount;
}
public ArrayList<String[]> getCsvFileList() {
return csvFileList;
}
public void setCsvFileList(ArrayList<String[]> csvFileList) {
this.csvFileList = csvFileList;
this.csvColCount = csvFileList.get(0) != null?csvFileList.get(0).length:0;
this.csvRowCount = csvFileList.size();
}
public Matrix toMatrix() throws Exception {
double[][] arr = new double[csvFileList.size()][csvFileList.get(0).length];
for (int i = 0; i < csvFileList.size(); i++) {
for (int j = 0; j < csvFileList.get(0).length; j++) {
try {
arr[i][j] = Double.parseDouble(csvFileList.get(i)[j]);
}catch (NumberFormatException e){
throw new Exception("Csv中含有非数字字符,无法转换成Matrix对象");
}
}
}
return new Matrix(arr);
}
}

66
algorithm/src/main/java/com/mh/algorithm/utils/CsvUtil.java

@ -1,66 +0,0 @@
package com.mh.algorithm.utils;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import com.mh.algorithm.matrix.Matrix;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
public class CsvUtil {
/**
* 获取CSV中的信息
* @param hasHeader 是否含有表头
* @param path CSV文件的路径
* @return
* @throws IOException
*/
public static CsvInfo getCsvInfo(boolean hasHeader , String path) throws IOException {
//创建csv对象,存储csv中的信息
CsvInfo csvInfo = new CsvInfo();
//获取CsvReader流
CsvReader csvReader = new CsvReader(path, ',', StandardCharsets.UTF_8);
if(hasHeader){
csvReader.readHeaders();
}
//获取Csv中的所有记录
ArrayList<String[]> csvFileList = new ArrayList<String[]>();
while (csvReader.readRecord()) {
csvFileList.add(csvReader.getValues());
}
//赋值
csvInfo.setHeader(csvReader.getHeaders());
csvInfo.setCsvFileList(csvFileList);
//关闭流
csvReader.close();
return csvInfo;
}
/**
* 将矩阵写入到csv文件中
* @param header 表头
* @param data 以矩阵形式存放的数据
* @param path 写入的文件地址
* @throws Exception
*/
public static void createCsvFile(String[] header,Matrix data,String path) throws Exception {
if (header!=null && header.length != data.getMatrixColCount()) {
throw new Exception("表头列数与数据列数不符");
}
CsvWriter csvWriter = new CsvWriter(path, ',', StandardCharsets.UTF_8);
if (header != null) {
csvWriter.writeRecord(header);
}
for (int i = 0; i < data.getMatrixRowCount(); i++) {
String[] record = new String[data.getMatrixColCount()];
for (int j = 0; j < data.getMatrixColCount(); j++) {
record[j] = data.getValOfIdx(i, j)+"";
}
csvWriter.writeRecord(record);
}
csvWriter.close();
}
}

20
algorithm/src/main/java/com/mh/algorithm/utils/DoubleUtil.java

@ -1,20 +0,0 @@
package com.mh.algorithm.utils;
/**
* @program: top-algorithm-set
* @description: DoubleTool
* @author: Mr.Zhao
* @create: 2020-11-12 21:54
**/
public class DoubleUtil {
private static final Double MAX_ERROR = 0.0001;
public static boolean equals(Double a, Double b) {
return Math.abs(a - b)< MAX_ERROR;
}
public static boolean equals(Double a, Double b,Double maxError) {
return Math.abs(a - b)< maxError;
}
}

297
algorithm/src/main/java/com/mh/algorithm/utils/MatrixUtil.java

@ -1,297 +0,0 @@
package com.mh.algorithm.utils;
import Jama.EigenvalueDecomposition;
import com.mh.algorithm.matrix.Matrix;
import java.util.*;
public class MatrixUtil {
/**
* 创建一个单位矩阵
* @param matrixRowCount 单位矩阵的纬度
* @return
*/
public static Matrix eye(int matrixRowCount){
double[][] result = new double[matrixRowCount][matrixRowCount];
for (int i = 0; i < matrixRowCount; i++) {
for (int j = 0; j < matrixRowCount; j++) {
if(i == j){
result[i][j] = 1;
}else{
result[i][j] = 0;
}
}
}
return new Matrix(result);
}
/**
* 求矩阵的逆
* 原理:AE=EA^-1
* @param a
* @return
* @throws Exception
*/
public static Matrix inv(Matrix a) throws Exception {
if (!invable(a)) {
throw new Exception("矩阵不可逆");
}
// [a|E]
Matrix b = a.splice(1, eye(a.getMatrixRowCount()));
double[][] data = b.getMatrix();
int rowCount = b.getMatrixRowCount();
int colCount = b.getMatrixColCount();
//此处应用a的列数,为简化,直接用b的行数
for (int j = 0; j < rowCount; j++) {
//若遇到0则交换两行
int notZeroRow = -2;
if(data[j][j] == 0){
notZeroRow = -1;
for (int l = j; l < rowCount; l++) {
if (data[l][j] != 0) {
notZeroRow = l;
break;
}
}
}
if (notZeroRow == -1) {
throw new Exception("矩阵不可逆");
}else if(notZeroRow != -2){
//交换j与notZeroRow两行
double[] tmp = data[j];
data[j] = data[notZeroRow];
data[notZeroRow] = tmp;
}
//将第data[j][j]化为1
if (data[j][j] != 1) {
double multiple = data[j][j];
for (int colIdx = j; colIdx < colCount; colIdx++) {
data[j][colIdx] /= multiple;
}
}
//行与行相减
for (int i = 0; i < rowCount; i++) {
if (i != j) {
double multiple = data[i][j] / data[j][j];
//遍历行中的列
for (int k = j; k < colCount; k++) {
data[i][k] = data[i][k] - multiple * data[j][k];
}
}
}
}
Matrix result = new Matrix(data);
return result.subMatrix(0, rowCount, rowCount, rowCount);
}
/**
* 求矩阵的伴随矩阵
* 原理:A*=|A|A^-1
* @param a
* @return
* @throws Exception
*/
public static Matrix adj(Matrix a) throws Exception {
return inv(a).multiple(det(a));
}
/**
* 矩阵转成上三角矩阵
* @param a
* @return
* @throws Exception
*/
public static Matrix getTopTriangle(Matrix a) throws Exception {
if (!a.isSquareMatrix()) {
throw new Exception("不是方阵无法进行计算");
}
int matrixHeight = a.getMatrixRowCount();
double[][] result = a.getMatrix();
//遍历列
for (int j = 0; j < matrixHeight; j++) {
//遍历行
for (int i = j+1; i < matrixHeight; i++) {
//若遇到0则交换两行
int notZeroRow = -2;
if(result[j][j] == 0){
notZeroRow = -1;
for (int l = i; l < matrixHeight; l++) {
if (result[l][j] != 0) {
notZeroRow = l;
break;
}
}
}
if (notZeroRow == -1) {
throw new Exception("矩阵不可逆");
}else if(notZeroRow != -2){
//交换j与notZeroRow两行
double[] tmp = result[j];
result[j] = result[notZeroRow];
result[notZeroRow] = tmp;
}
double multiple = result[i][j]/result[j][j];
//遍历行中的列
for (int k = j; k < matrixHeight; k++) {
result[i][k] = result[i][k] - multiple * result[j][k];
}
}
}
return new Matrix(result);
}
/**
* 计算矩阵的行列式
* @param a
* @return
* @throws Exception
*/
public static double det(Matrix a) throws Exception {
//将矩阵转成上三角矩阵
Matrix b = MatrixUtil.getTopTriangle(a);
double result = 1;
//计算矩阵行列式
for (int i = 0; i < b.getMatrixRowCount(); i++) {
result *= b.getValOfIdx(i, i);
}
return result;
}
/**
* 获取协方差矩阵
* @param a
* @return
* @throws Exception
*/
public static Matrix cov(Matrix a) throws Exception {
if (a.getMatrix() == null) {
throw new Exception("矩阵为空");
}
Matrix avg = a.getColAvg().extend(2, a.getMatrixRowCount());
Matrix tmp = a.subtract(avg);
return tmp.transpose().multiple(tmp).multiple(1/((double) a.getMatrixRowCount() -1));
}
/**
* 判断矩阵是否可逆
* 如果可转为上三角矩阵则可逆
* @param a
* @return
*/
public static boolean invable(Matrix a) {
try {
getTopTriangle(a);
return true;
} catch (Exception e) {
return false;
}
}
/**
* 获取矩阵的特征值矩阵调用Jama中的getV方法
* @param a
* @return
*/
public static Matrix getV(Matrix a) {
EigenvalueDecomposition eig = new EigenvalueDecomposition(new Jama.Matrix(a.getMatrix()));
return new Matrix(eig.getV().getArray());
}
/**
* 取特征值实部
* @param a
* @return
*/
public double[] getRealEigenvalues(Matrix a){
EigenvalueDecomposition eig = new EigenvalueDecomposition(new Jama.Matrix(a.getMatrix()));
return eig.getRealEigenvalues();
}
/**
* 取特征值虚部
* @param a
* @return
*/
public double[] getImagEigenvalues(Matrix a){
EigenvalueDecomposition eig = new EigenvalueDecomposition(new Jama.Matrix(a.getMatrix()));
return eig.getImagEigenvalues();
}
/**
* 取块对角特征值矩阵
* @param a
* @return
*/
public static Matrix getD(Matrix a) {
EigenvalueDecomposition eig = new EigenvalueDecomposition(new Jama.Matrix(a.getMatrix()));
return new Matrix(eig.getD().getArray());
}
/**
* 数据归一化
* @param a 要归一化的数据
* @param normalizationMin 要归一化的区间下限
* @param normalizationMax 要归一化的区间上限
* @return
*/
public static Map<String, Object> normalize(Matrix a, double normalizationMin, double normalizationMax) throws Exception {
HashMap<String, Object> result = new HashMap<>();
double[][] maxArr = new double[1][a.getMatrixColCount()];
double[][] minArr = new double[1][a.getMatrixColCount()];
double[][] res = new double[a.getMatrixRowCount()][a.getMatrixColCount()];
for (int i = 0; i < a.getMatrixColCount(); i++) {
List tmp = new ArrayList();
for (int j = 0; j < a.getMatrixRowCount(); j++) {
tmp.add(a.getValOfIdx(j,i));
}
double max = (double) Collections.max(tmp);
double min = (double) Collections.min(tmp);
//数据归一化(注:若max与min均为0则不需要归一化)
if (max != 0 || min != 0) {
for (int j = 0; j < a.getMatrixRowCount(); j++) {
try {
if ((a.getValOfIdx(j,i) - min) == 0 || (max - min) == 0) {
res[j][i] = normalizationMin;
continue;
}
res[j][i] = normalizationMin + (a.getValOfIdx(j,i) - min) / (max - min) * (normalizationMax - normalizationMin);
} catch (IllegalArgumentException e) {
res[j][i] = 0;
}
}
}
maxArr[0][i] = max;
minArr[0][i] = min;
}
result.put("max", new Matrix(maxArr));
result.put("min", new Matrix(minArr));
result.put("res", new Matrix(res));
return result;
}
/**
* 反归一化
* @param a 要反归一化的数据
* @param normalizationMin 要反归一化的区间下限
* @param normalizationMax 要反归一化的区间上限
* @param dataMax 数据最大值
* @param dataMin 数据最小值
* @return
*/
public static Matrix inverseNormalize(Matrix a, double normalizationMax, double normalizationMin , Matrix dataMax,Matrix dataMin){
double[][] res = new double[a.getMatrixRowCount()][a.getMatrixColCount()];
for (int i = 0; i < a.getMatrixColCount(); i++) {
//数据反归一化
if (dataMin.getValOfIdx(0,i) != 0 || dataMax.getValOfIdx(0,i) != 0) {
for (int j = 0; j < a.getMatrixRowCount(); j++) {
if ((a.getValOfIdx(j,i) - normalizationMin) == 0 || (normalizationMax - normalizationMin) == 0) {
res[j][i] = dataMin.getValOfIdx(0,i);
continue;
}
res[j][i] = dataMin.getValOfIdx(0,i) + (dataMax.getValOfIdx(0,i) - dataMin.getValOfIdx(0,i)) * (a.getValOfIdx(j,i) - normalizationMin) / (normalizationMax - normalizationMin);
}
}
}
return new Matrix(res);
}
}

32
algorithm/src/main/java/com/mh/algorithm/utils/SerializationUtil.java

@ -1,32 +0,0 @@
package com.mh.algorithm.utils;
import java.io.*;
public class SerializationUtil {
/**
* 对象序列化到本地
* @param object
* @throws IOException
*/
public static void serialize(Object object, String path) throws IOException {
File file = new File(path);
System.out.println(file.getAbsolutePath());
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
out.writeObject(object);
out.close();
}
/**
* 对象反序列化
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
public static Object deSerialization(String path) throws IOException, ClassNotFoundException {
File file = new File(path);
ObjectInputStream oin = new ObjectInputStream(new FileInputStream(file));
Object object = oin.readObject();
oin.close();
return object;
}
}

71
algorithm/src/test/java/com/mh/algorithm/bpnn/bpnnTest.java

@ -1,71 +0,0 @@
package com.mh.algorithm.bpnn;
import com.mh.algorithm.matrix.Matrix;
import com.mh.algorithm.utils.CsvInfo;
import com.mh.algorithm.utils.CsvUtil;
import com.mh.algorithm.utils.SerializationUtil;
import org.junit.Test;
import java.util.Date;
public class bpnnTest {
@Test
public void test() throws Exception {
// 创建训练集矩阵
CsvInfo csvInfo = CsvUtil.getCsvInfo(true, "D:\\ljf\\my_pro\\top-algorithm-set-dev\\src\\trainDataElec.csv");
Matrix trainSet = csvInfo.toMatrix();
// 创建BPNN工厂对象
BPNeuralNetworkFactory factory = new BPNeuralNetworkFactory();
// 创建BP参数对象
BPParameter bpParameter = new BPParameter();
bpParameter.setInputLayerNeuronCount(2);
bpParameter.setHiddenLayerNeuronCount(2);
bpParameter.setOutputLayerNeuronCount(2);
bpParameter.setPrecision(0.01);
bpParameter.setMaxTimes(10000);
// 训练BP神经网络
System.out.println(new Date());
BPModel bpModel = factory.trainBP(bpParameter, trainSet);
System.out.println(new Date());
// 将BPModel序列化到本地
SerializationUtil.serialize(bpModel, "elec");
CsvInfo csvInfo2 = CsvUtil.getCsvInfo(true, "D:\\ljf\\my_pro\\top-algorithm-set-dev\\src\\testDataElec.csv");
Matrix testSet = csvInfo2.toMatrix();
Matrix testData1 = testSet.subMatrix(0, testSet.getMatrixRowCount(), 0, testSet.getMatrixColCount() - 2);
Matrix testLabel = testSet.subMatrix(0, testSet.getMatrixRowCount(), testSet.getMatrixColCount() - 2, 1);
// 将BPModel反序列化
BPModel bpModel1 = (BPModel) SerializationUtil.deSerialization("elec");
Matrix result = factory.computeBP(bpModel1, testData1);
int total = result.getMatrixRowCount();
int correct = 0;
for (int i = 0; i < result.getMatrixRowCount(); i++) {
if(Math.round(result.getValOfIdx(i,0)) == testLabel.getValOfIdx(i,0)){
correct++;
}
}
double correctRate = Double.valueOf(correct) / Double.valueOf(total);
System.out.println(correctRate);
}
/**
* 使用示例
* @throws Exception
*/
@Test
public void bpnnUsing() throws Exception{
CsvInfo csvInfo = CsvUtil.getCsvInfo(false, "D:\\ljf\\my_pro\\top-algorithm-set-dev\\src\\dataElec.csv");
Matrix data = csvInfo.toMatrix();
// 将BPModel反序列化
BPModel bpModel1 = (BPModel) SerializationUtil.deSerialization("elec");
// 创建工厂
BPNeuralNetworkFactory factory = new BPNeuralNetworkFactory();
Matrix result = factory.computeBP(bpModel1, data);
CsvUtil.createCsvFile(null,result,"D:\\ljf\\my_pro\\top-algorithm-set-dev\\src\\computeResult.csv");
}
}

46
algorithm/src/test/java/com/mh/algorithm/knn/knnTest.java

@ -1,46 +0,0 @@
//package com.mh.algorithm.knn;
//
//import com.mh.algorithm.matrix.Matrix;
//import com.mh.algorithm.utils.CsvInfo;
//import com.mh.algorithm.utils.CsvUtil;
//import com.mh.algorithm.utils.DoubleUtil;
//import org.junit.Test;
//
///**
// * @program: top-algorithm-set
// * @description:
// * @author: Mr.Zhao
// * @create: 2020-10-26 22:04
// **/
//public class knnTest {
// @Test
// public void test() throws Exception {
// // 训练集
// CsvInfo csvInfo = CsvUtil.getCsvInfo(false, "E:\\jarTest\\trainData.csv");
// Matrix trainSet = csvInfo.toMatrix();
// Matrix trainSetLabels = trainSet.getColOfIdx(trainSet.getMatrixColCount() - 1);
// Matrix trainSetData = trainSet.subMatrix(0, trainSet.getMatrixRowCount(), 0, trainSet.getMatrixColCount() - 1);
//
// CsvInfo csvInfo1 = CsvUtil.getCsvInfo(false, "E:\\jarTest\\testData.csv");
// Matrix testSet = csvInfo1.toMatrix();
// Matrix testSetData = trainSet.subMatrix(0, testSet.getMatrixRowCount(), 0, testSet.getMatrixColCount() - 1);
// Matrix testSetLabels = trainSet.getColOfIdx(testSet.getMatrixColCount() - 1);
//
// // 分类
// long startTime = System.currentTimeMillis();
// Matrix result = KNN.classify(testSetData, trainSetData, trainSetLabels, 5);
// long endTime = System.currentTimeMillis();
// System.out.println("run time:" + (endTime - startTime));
// // 正确率
// Matrix error = result.subtract(testSetLabels);
// int total = error.getMatrixRowCount();
// int correct = 0;
// for (int i = 0; i < error.getMatrixRowCount(); i++) {
// if (DoubleUtil.equals(error.getValOfIdx(i, 0), 0.0)) {
// correct++;
// }
// }
// double correctRate = Double.valueOf(correct) / Double.valueOf(total);
// System.out.println("correctRate:"+ correctRate);
// }
//}

26
common/pom.xml

@ -34,24 +34,13 @@
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>2.1.0</version>
<exclusions>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
</exclusion>
</exclusions>
<version>1.4.7</version>
</dependency>
<!-- web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
@ -70,11 +59,12 @@
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
<!-- poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
<version>5.2.4</version>
</dependency>
</dependencies>
</project>

26
common/src/main/java/com/mh/common/annotation/SysLogger.java

@ -1,13 +1,13 @@
//package com.mh.common.annotation;
//
//import java.lang.annotation.*;
//
///**
// * Created by fangzhipeng on 2017/7/12.
// */
//@Target(ElementType.METHOD)
//@Retention(RetentionPolicy.RUNTIME)
//@Documented
//public @interface SysLogger {
// String value() default "";
//}
package com.mh.common.annotation;
import java.lang.annotation.*;
/**
* Created by fangzhipeng on 2017/7/12.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLogger {
String value() default "";
}

84
common/src/main/java/com/mh/common/utils/FileUtils.java

@ -1,42 +1,42 @@
//package com.mh.common.utils;
//
//import javax.servlet.http.HttpServletResponse;
//import java.io.BufferedInputStream;
//import java.io.BufferedOutputStream;
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.InputStream;
//
///**
// * 文件相关操作
// * @author Louis
// * @date Jan 14, 2019
// */
//public class FileUtils {
//
// /**
// * 下载文件
// * @param response
// * @param file
// * @param newFileName
// */
// public static void downloadFile(HttpServletResponse response, File file, String newFileName) {
// try {
// response.setHeader("Content-Disposition", "attachment; filename=" + new String(newFileName.getBytes("ISO-8859-1"), "UTF-8"));
// BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
// InputStream is = new FileInputStream(file.getAbsolutePath());
// BufferedInputStream bis = new BufferedInputStream(is);
// int length = 0;
// byte[] temp = new byte[1 * 1024 * 10];
// while ((length = bis.read(temp)) != -1) {
// bos.write(temp, 0, length);
// }
// bos.flush();
// bis.close();
// bos.close();
// is.close();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//}
package com.mh.common.utils;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
/**
* 文件相关操作
* @author Louis
* @date Jan 14, 2019
*/
public class FileUtils {
/**
* 下载文件
* @param response
* @param file
* @param newFileName
*/
public static void downloadFile(HttpServletResponse response, File file, String newFileName) {
try {
response.setHeader("Content-Disposition", "attachment; filename=" + new String(newFileName.getBytes("ISO-8859-1"), "UTF-8"));
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
InputStream is = new FileInputStream(file.getAbsolutePath());
BufferedInputStream bis = new BufferedInputStream(is);
int length = 0;
byte[] temp = new byte[1 * 1024 * 10];
while ((length = bis.read(temp)) != -1) {
bos.write(temp, 0, length);
}
bos.flush();
bis.close();
bos.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

28
pom.xml

@ -11,7 +11,6 @@
<modules>
<module>common</module>
<module>user-service</module>
<module>algorithm</module>
</modules>
<parent>
@ -30,10 +29,37 @@
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jolokia</groupId>
<artifactId>jolokia-core</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- 添加consul依赖-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-consul-discovery</artifactId>-->
<!-- </dependency>-->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.rxtx</groupId>
<artifactId>rxtx</artifactId>

63
user-service/pom.xml

@ -58,6 +58,11 @@
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version>
</dependency>
<!-- &lt;!&ndash; mysql数据库链接&ndash;&gt;-->
<!-- <dependency>-->
<!-- <groupId>mysql</groupId>-->
<!-- <artifactId>mysql-connector-java</artifactId>-->
<!-- </dependency>-->
<!-- druid配置-->
<dependency>
<groupId>com.alibaba</groupId>
@ -69,6 +74,11 @@
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<!-- <dependency>-->
<!-- <groupId>io.netty</groupId>-->
<!-- <artifactId>netty-all</artifactId>-->
<!-- <version>5.0.0.Alpha2</version>-->
<!-- </dependency>-->
<!-- 登录验证码-->
<dependency>
<groupId>com.github.penggle</groupId>
@ -95,22 +105,17 @@
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- 添加consul依赖-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-consul-discovery</artifactId>-->
<!-- </dependency>-->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop -->
<!--spring-boot-admin -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.2.5.RELEASE</version>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.2.2</version>
</dependency>
<!-- Lombok-->
<dependency>
@ -143,36 +148,6 @@
<version>4.4</version>
</dependency>
<!--解决高版本JDK问题-->
<!--javax.xml.bind.DatatypeConverter错误-->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!-- 算法包 -->
<dependency>
<groupId>com.mh</groupId>
<artifactId>algorithm</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>

2
user-service/src/main/java/com/mh/user/aspect/SysLogAspect.java

@ -16,7 +16,6 @@ import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@ -28,7 +27,6 @@ import java.util.Date;
*/
@Aspect
@Component
@Lazy(value = false)
public class SysLogAspect {
@Autowired

12
user-service/src/main/java/com/mh/user/config/RestTemplateConfig.java

@ -1,22 +1,14 @@
package com.mh.user.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @author LJF
* @author ljf
* @title
* @description 请求数据
* @description redis配置
* @updateTime 2020-08-20
* @throws
*/
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

10
user-service/src/main/java/com/mh/user/constants/Constant.java

@ -9,10 +9,8 @@ package com.mh.user.constants;
*/
public class Constant {
public static final CharSequence CUSTOM_NAME_HUAXIA = "华夏";
public static final CharSequence CUSTOM_NAME_GUANGSHANG = "广州商学院";
public static final CharSequence CUSTOM_NAME_HUARUAN = "广州软件学院";
public static final String WEATHER_DATA = "weather_data";
public static final CharSequence CUSTOM_NAME_HUAXIA = "华厦";
public static final CharSequence CUSTOM_NAME_GUANGSHANG = "广商";
public static boolean CONTROL_WEB_FLAG = false;
public static boolean SEND_STATUS = false; // 指令发送状态
public static volatile boolean FLAG = false;
@ -44,16 +42,12 @@ public class Constant {
public static final String BRAND_RUI_XING = "瑞星";
public static final String BRAND_HAI_ER = "海尔";
public static final String BRAND_YUAN_XIANG = "远向";
public static final String BRAND_DING_WEI = "顶威";
public static final String BRAND_ZHONG_KAI = "中凯";
public static final String BRAND_ALITA = "阿丽塔";
private static final String RUNNING = "运行";
private static final String NOT_RUNNING = "不运行";

2
user-service/src/main/java/com/mh/user/constants/DeviceEnum.java

@ -16,9 +16,7 @@ public enum DeviceEnum {
PressureTransEnum("压变", PressureTrans.getInstance()),
HeatPumpEnum("热泵", HeatPump.getInstance()),
TempControlEnum("温控", TempControl.getInstance()),
BackTempControlEnum("回水温控", BackTempControl.getInstance()),
TimeControlEnum("时控", TimeControl.getInstance()),
ALiTaControlEnum("阿丽塔时控", TimeControl.getInstance()),
WaterLevelSwitchEnum("水位开关", WaterLevelSwitch.getInstance()),
StatusCheckEnum("状态检测", StatusCheck.getInstance()),
TempTransEnum("温度变送器", TempTrans.getInstance()),

2
user-service/src/main/java/com/mh/user/constants/DeviceStrategyEnum.java

@ -17,9 +17,7 @@ public enum DeviceStrategyEnum {
PressureTransEnum("压变", PressureTransStrategy.getInstance()),
HeatPumpEnum("热泵", HeatPumpStrategy.getInstance()),
TempControlEnum("温控", TempControlStrategy.getInstance()),
BackTempControlEnum("回水温控", BackTempControlStrategy.getInstance()),
TimeControlEnum("时控", TimeControlStrategy.getInstance()),
ALitaTimeControlEnum("阿丽塔时控", TimeControlStrategy.getInstance()),
WaterLevelSwitchEnum("水位开关", WaterLevelSwitchStrategy.getInstance()),
StatusCheckEnum("状态检测", StatusCheckStrategy.getInstance()),
TempTransEnum("温度变送器", TempTransStrategy.getInstance()),

2
user-service/src/main/java/com/mh/user/controller/AnalysisController.java

@ -39,7 +39,7 @@ public class AnalysisController {
}
@PostMapping("/queryMonth") //type=1(水),2(电),3(能耗),4(维保),5(使用时间)
@PostMapping("/queryMonth") //type=1(水),2(电),3(能耗)
public HttpResult queryAnalysisMonth(@RequestParam(value = "curDate",required = true) String curDate,
@RequestParam(value = "buildingId",required = true) String buildingId,
@RequestParam(value = "type",defaultValue = "3") int type) {

199
user-service/src/main/java/com/mh/user/controller/AreaController.java

@ -1,26 +1,16 @@
package com.mh.user.controller;
import com.mh.common.http.HttpResult;
import com.mh.user.annotation.SysLogger;
import com.mh.user.entity.AreaEntity;
import com.mh.user.entity.BuildingEntity;
import com.mh.user.model.AreaModel;
import com.mh.user.entity.ExceptionTableData;
import com.mh.user.service.AreaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
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 javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
@ -30,7 +20,6 @@ import java.util.List;
* @updateTime 2022-06-09
* @throws
*/
@Slf4j
@RestController
@RequestMapping("area")
public class AreaController {
@ -41,183 +30,9 @@ public class AreaController {
@PreAuthorize("hasAuthority('sys:area:view')")
@PostMapping(value = "/findArea")
public HttpResult findArea() {
List<AreaEntity> list = areaService.findAll();
List<AreaEntity> list=areaService.findAll();
// System.out.println("test");
return HttpResult.ok("500", list);
}
//保存
@SysLogger(title = "区域信息", optDesc = "保存区域信息")
@PostMapping(value = "/save")
public HttpResult saveArea(@RequestBody AreaEntity areaEntity) {
try {
int count = areaService.saveArea(areaEntity);
if (count > 0) {
return HttpResult.ok("保存成功");
} else {
return HttpResult.error(500, "区域id或者区域名称已存在");
}
} catch (Exception e) {
log.error("保存区域信息异常:{}", e);
return HttpResult.error();
}
}
//修改
@SysLogger(title = "区域信息", optDesc = "修改区域信息")
@PostMapping(value = "/update")
public HttpResult updateBuilding(@RequestBody AreaEntity areaEntity) {
return HttpResult.ok("success", areaService.updateArea(areaEntity));
}
//查询所有
@SysLogger(title = "区域信息", optDesc = "查询区域信息")
@PostMapping(value = "/query")
public HttpResult queryBuilding(@RequestParam(value = "areaId", required = false) String areaId,
@RequestParam(value = "page", required = true) Integer page,
@RequestParam(value = "limit", required = true) Integer limit) {
try {
int count = areaService.getCount(areaId, page, limit);
List<AreaEntity> records = areaService.queryArea(areaId, page, limit);
return HttpResult.ok(count, records);
} catch (Exception e) {
e.printStackTrace();
return HttpResult.error();
}
}
//查询区域名称
@PostMapping(value = "/name")
public HttpResult selectAreaName() {
try {
List<AreaModel> list = areaService.selectAreaName();
return HttpResult.ok(list);
} catch (Exception e) {
e.printStackTrace();
return HttpResult.error();
}
}
// 删除多
@PostMapping(value = "/deletes")
public HttpResult deleteDevices(@RequestBody List<AreaEntity> records) {
return HttpResult.ok(areaService.deleteArea(records));
}
// 删除单个
@SysLogger(title = "区域信息", optDesc = "删除区域信息")
@PostMapping(value = "/delete")
public HttpResult deleteDevice(@RequestParam String id) {
return HttpResult.ok(areaService.deleteAreaById(id));
}
// 资料批量上传
@SysLogger(title = "区域信息", optDesc = "批量导入区域信息")
@PostMapping("/import_area")
public HttpResult importExcel(@RequestParam(value = "file") MultipartFile file, HttpServletRequest req) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
HttpResult httpResult = new HttpResult();
try {
int is = 0; //判断是否有重复
String msg = "";
List<String> a = new ArrayList();
InputStream inputStream = file.getInputStream();
//创建工作簿
//如果是xls,使用HSSFWorkbook;如果是xlsx,使用XSSFWorkbook
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(inputStream);
System.out.println("xssfWorkbook对象:" + hssfWorkbook);
//读取第一个工作表
HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
System.out.println("sheet对象:" + sheet);
//获取最后一行的num,即总行数。此处从0开始计数
int maxRow = sheet.getLastRowNum();
System.out.println("总行数为:" + maxRow);
if (maxRow >= 500) {
msg = "总行数不能超出500行";
httpResult.setMsg(msg);
httpResult.setCode(500);
return httpResult;
}
if (maxRow == 0) {
msg = "请先录入数据到excel文件";
httpResult.setMsg(msg);
httpResult.setCode(500);
return httpResult;
}
// 创建数组集合
List<AreaEntity> uploadEntityList = new ArrayList<>();
List<String> deviceList = new ArrayList<>();
for (int row = 1; row <= maxRow; row++) {
//获取最后单元格num,即总单元格数 ***注意:此处从1开始计数***
int maxRol = sheet.getRow(row).getLastCellNum();
System.out.println("总列数为:" + maxRol);
System.out.println("--------第" + row + "行的数据如下--------");
for (int rol = 0; rol < maxRol; rol++) {
String sCell;
if (sheet.getRow(row).getCell(rol) == null) {
sCell = "";
} else {
HSSFCell cell = sheet.getRow(row).getCell(rol);
cell.setCellType(CellType.STRING);
sCell = cell.getStringCellValue();
}
sCell = sCell.trim(); //去首尾空格
sCell = sCell.replaceAll(" ", ""); //去掉所有空格,包括首尾、中间
sCell = sCell.replaceAll("\\s*", ""); //可以替换大部分空白字符, 不限于空格,\s 可以匹配空格、制表符、换页符等空白字符的其中任意一个
System.out.print(sCell + " ");
deviceList.add(sCell);
String rolName = "";
switch (rol) {
case 2:
rolName = "区域ID";
break;
case 1:
rolName = "区域名称";
break;
case 3:
rolName = "排序";
break;
}
if ((rol >= 1) && (rol <= 4) && (sCell.equals(""))) {
msg = rolName + "不能为空";
httpResult.setMsg(msg);
httpResult.setCode(500);
return httpResult;
}
}
// 创建实体类
AreaEntity uploadEntity = new AreaEntity();
uploadEntity.setAreaId(deviceList.get(1)); // 区域ID编号
uploadEntity.setAreaName(deviceList.get(0)); // 区域名称
uploadEntity.setSort(Integer.parseInt(deviceList.get(2))); // 排序
deviceList.clear();
uploadEntityList.add(uploadEntity);
is = areaService.selectByAreaName(uploadEntity.getAreaName());
if (is > 0) {
httpResult.setMsg("楼栋名称有重复!");
httpResult.setCode(500);
}
}
if (is == 0) {
for (AreaEntity val : uploadEntityList) {
areaService.saveArea(val);
}
httpResult.setMsg("success");
httpResult.setCode(200);
return httpResult;
}
} catch (IOException e) {
// TODO Auto-generated catch block
log.error("批量导入区域异常:{}", e);
}
return httpResult;
return HttpResult.ok("500",list);
}
}

39
user-service/src/main/java/com/mh/user/controller/BuildingController.java

@ -3,7 +3,6 @@ package com.mh.user.controller;
import com.mh.common.http.HttpResult;
import com.mh.user.annotation.SysLogger;
import com.mh.user.entity.BuildingEntity;
import com.mh.user.model.AreaBuildingTreeModel;
import com.mh.user.model.BuildingModel;
import com.mh.user.service.BuildingService;
import org.apache.poi.hssf.usermodel.HSSFCell;
@ -53,11 +52,10 @@ public class BuildingController {
@PostMapping(value = "/query")
public HttpResult queryBuilding(@RequestParam(value = "buildingId", required = false)String buildingId,
@RequestParam(value= "page", required=true)Integer page,
@RequestParam(value = "level", required = false, defaultValue = "0")int level,
@RequestParam(value= "limit", required=true)Integer limit) {
try{
List<BuildingEntity> records=buildingService.queryBuilding(buildingId, page,limit, level);
int count=buildingService.getCount(buildingId, page,limit, level);
int count=buildingService.getCount(buildingId, page,limit);
List<BuildingEntity> records=buildingService.queryBuilding(buildingId, page,limit);
return HttpResult.ok(count,records);
}catch (Exception e){
e.printStackTrace();
@ -69,8 +67,6 @@ public class BuildingController {
@PostMapping(value="/name")
public HttpResult selectBuildingName() {
try{
// List<AreaBuildingTreeModel> list=buildingService.queryTree();
// return HttpResult.ok(list);
List<BuildingModel> list=buildingService.selectBuildingName();
return HttpResult.ok(list);
}catch (Exception e){
@ -82,14 +78,14 @@ public class BuildingController {
// 删除多
@PostMapping(value="/deletes")
public HttpResult deleteDevices(@RequestBody List<BuildingEntity> records) {
public HttpResult delete(@RequestBody List<BuildingEntity> records) {
return HttpResult.ok(buildingService.deleteBuilding(records));
}
// 删除单个
@SysLogger(title="楼栋信息",optDesc = "删除楼栋信息")
@PostMapping(value="/delete")
public HttpResult deleteDevice(@RequestParam String id ) {
public HttpResult delete(@RequestParam String id ) {
return HttpResult.ok(buildingService.deleteBuilding(id));
}
@ -180,9 +176,6 @@ public class BuildingController {
rolName = "水箱高度";
break;
case 8 :
rolName = "水箱高度(低区)";
break;
case 9 :
rolName = "热泵个数";
break;
}
@ -197,14 +190,13 @@ public class BuildingController {
// 创建实体类
BuildingEntity uploadEntity = new BuildingEntity();
uploadEntity.setBuildingName(deviceList.get(0));//楼栋名称
uploadEntity.setLevelsCount(Integer.parseInt(deviceList.get(1))); //楼层数
uploadEntity.setBeginLevel(Integer.parseInt(deviceList.get(2))); //起始楼层
uploadEntity.setHouseCount(Integer.parseInt(deviceList.get(3))); //每层宿舍数
uploadEntity.setBedCount(Integer.parseInt(deviceList.get(4))); //床位数
uploadEntity.setCheckInCount(Integer.parseInt(deviceList.get(5))); //实际入住数
uploadEntity.setTankHeight(Double.parseDouble(deviceList.get(6))); //默认(高区)水箱高度
uploadEntity.setLowTankHeight(Double.parseDouble(deviceList.get(7))); //低区水箱高度
uploadEntity.setPumpCount(Integer.parseInt(deviceList.get(8))); //热泵个数
uploadEntity.setLevelsCount(Integer.parseInt(deviceList.get(1))); //楼层数
uploadEntity.setBeginLevel(Integer.parseInt(deviceList.get(2))); //起始楼层
uploadEntity.setHouseCount(Integer.parseInt(deviceList.get(3))); //每层宿舍数
uploadEntity.setBedCount(Integer.parseInt(deviceList.get(4))); //床位数
uploadEntity.setCheckInCount(Integer.parseInt(deviceList.get(5))); //实际入住数
uploadEntity.setTankHeight(Double.parseDouble(deviceList.get(6))); //实际入住数
uploadEntity.setPumpCount(Integer.parseInt(deviceList.get(7))); //实际入住数
deviceList.clear();
@ -240,13 +232,4 @@ public class BuildingController {
return HttpResult.ok("success",count);
}
/**
* 查询树形结构楼栋信息
*/
@PostMapping(value="/tree")
public HttpResult queryTree() {
List<AreaBuildingTreeModel> list=buildingService.queryTree();
return HttpResult.ok(list);
}
}

6
user-service/src/main/java/com/mh/user/controller/ControlSetController.java

@ -46,11 +46,11 @@ public class ControlSetController {
}
//查询设置表
@SysLogger(title="控制设置",optDesc = "查询时控设置值")
@SysLogger(title="控制设置",optDesc = "查询设置值")
@PostMapping(value="/query")
public HttpResult queryControlSet(@RequestParam("buildingId") String buildingId, @RequestParam(value = "timeName",required = false) String timeName) {
public HttpResult queryControlSet(@RequestParam("buildingId") String buildingId) {
try{
ControlSetEntity control=controlSetService.queryControlSet(buildingId, timeName);
ControlSetEntity control=controlSetService.queryControlSet(buildingId);
return HttpResult.ok(control);
}catch (Exception e){
// e.printStackTrace();

8
user-service/src/main/java/com/mh/user/controller/DeviceFloorController.java

@ -7,6 +7,7 @@ import com.mh.user.entity.*;
import com.mh.user.model.DeviceModel;
import com.mh.user.service.BuildingService;
import com.mh.user.service.DeviceFloorService;
import com.mh.user.service.DeviceInstallService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@ -18,9 +19,12 @@ import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("floor")
@ -83,9 +87,9 @@ public class DeviceFloorController {
}
// 删除单个
@PostMapping(value="/delete")
@SysLogger(title="楼面设备",optDesc = "删除楼面设备信息")
public HttpResult deleteDevice(@RequestParam String id ) {
@PostMapping(value="/delete")
public HttpResult delete(@RequestParam String id ) {
return HttpResult.ok(deviceFloorService.deleteDevice(id));
}

41
user-service/src/main/java/com/mh/user/controller/DeviceInstallController.java

@ -7,7 +7,10 @@ import com.mh.user.annotation.SysLogger;
import com.mh.user.entity.BuildingEntity;
import com.mh.user.entity.DeviceInstallEntity;
import com.mh.user.model.DeviceModel;
import com.mh.user.service.*;
import com.mh.user.service.BuildingService;
import com.mh.user.service.DealDataService;
import com.mh.user.service.DeviceInstallService;
import com.mh.user.service.SummaryService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@ -31,10 +34,6 @@ public class DeviceInstallController {
@Autowired
BuildingService buildingService;
@Autowired
private NowDataService nowDataService;
private final DealDataService dealDataService;
public DeviceInstallController(DealDataService dealDataService)
@ -55,21 +54,6 @@ public class DeviceInstallController {
public HttpResult updateDevice(@RequestBody DeviceInstallEntity deviceInstallEntity) {
// 根据id查询对应的deviceInstall
DeviceInstallEntity oldEntity = deviceInstallService.selectDeviceById(deviceInstallEntity.getId());
// 更新对应的实时记录内容
if (oldEntity.getDeviceType().equals("热泵")) {
String oldPumpId = oldEntity.getDeviceAddr();
String oldPumpName = oldEntity.getDeviceName();
String oldBuildingId = oldEntity.getBuildingId();
String pumpId = deviceInstallEntity.getDeviceAddr();
String pumpName = deviceInstallEntity.getDeviceName();
String buildingId = deviceInstallEntity.getBuildingId();
String buildingName = deviceInstallEntity.getBuildingName();
nowDataService.updatePumpName(oldPumpId, oldPumpName, oldBuildingId, pumpId, pumpName, buildingId, buildingName);
}
// 删除全部的device_code_param值
deviceInstallService.deleteParamCode(oldEntity);
// 设置校验位
@ -108,14 +92,14 @@ public class DeviceInstallController {
// 删除多
@PostMapping(value="/deletes")
public HttpResult deleteDevices(@RequestBody List<DeviceInstallEntity> records) {
public HttpResult delete(@RequestBody List<DeviceInstallEntity> records) {
return HttpResult.ok(deviceInstallService.deleteDevice(records));
}
// 删除单个
@SysLogger(title="基表信息",optDesc = "删除基表信息")
@PostMapping(value="/delete")
public HttpResult deleteDevice(@RequestParam String id ) {
public HttpResult delete(@RequestParam String id ) {
return HttpResult.ok(deviceInstallService.deleteDevice(id));
}
@ -129,7 +113,6 @@ public class DeviceInstallController {
@RequestParam(value = "isOnline", required=false)String isOnline,
@RequestParam(value = "isUse", required=false)String isUse,
@RequestParam(value = "isFault", required=false)String isFault,
@RequestParam(value = "level", required=false, defaultValue = "0")int level,
@RequestParam(value = "page", required=true)Integer page,
@RequestParam(value = "limit", required=true)Integer limit) {
try{
@ -138,8 +121,8 @@ public class DeviceInstallController {
String curDate=sdf1.format(date);
dealDataService.proDeviceState(curDate); //刷新统计设备状态数据
int count=deviceInstallService.getCount(buildingId,deviceType, startDate, endDate,isOnline,isUse,isFault, page,limit, level);
List<DeviceInstallEntity> records=deviceInstallService.queryDevice(buildingId,deviceType, startDate, endDate,isOnline,isUse,isFault, page,limit, level);
int count=deviceInstallService.getCount(buildingId,deviceType, startDate, endDate,isOnline,isUse,isFault, page,limit);
List<DeviceInstallEntity> records=deviceInstallService.queryDevice(buildingId,deviceType, startDate, endDate,isOnline,isUse,isFault, page,limit);
return HttpResult.ok(count,records);
}catch (Exception e){
//e.printStackTrace();
@ -258,9 +241,6 @@ public class DeviceInstallController {
case 10 :
rolName = "所属楼栋";
break;
case 11 :
rolName = "是否启用";
break;
}
if ((rol >= 1)&&(rol <= 4)&&(sCell.equals(""))){
msg = rolName + "不能为空" ;
@ -281,11 +261,6 @@ public class DeviceInstallController {
uploadEntity.setModel(deviceList.get(7));//型号
uploadEntity.setInstaller(deviceList.get(8));//安装人员
uploadEntity.setBuildingId(deviceList.get(9));//所属楼栋
if (deviceList.get(10).equals("是")){
uploadEntity.setIsUse(1);
}else{
uploadEntity.setIsUse(0);
}
deviceList.clear();
uploadEntityList.add(uploadEntity);

252
user-service/src/main/java/com/mh/user/controller/EnergyController.java

@ -2,14 +2,12 @@ package com.mh.user.controller;
import com.mh.common.http.HttpResult;
import com.mh.user.annotation.SysLogger;
import com.mh.user.entity.BuildingEntity;
import com.mh.user.entity.EnergyEntity;
import com.mh.user.model.SumModel;
import com.mh.user.service.BuildingService;
import com.mh.user.service.EnergyService;
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;
@ -25,196 +23,192 @@ public class EnergyController {
@Autowired
BuildingService buildingService;
@SysLogger(title = "用能分析", optDesc = "保存能耗信息")
@SysLogger(title="用能分析",optDesc = "保存能耗信息")
@PostMapping("/save")
public HttpResult saveEnergy(@RequestBody EnergyEntity energyEntity, @RequestParam(value = "type") int type) {
try {
energyService.saveEnergy(energyEntity, type);
return HttpResult.ok();
} catch (Exception e) {
return HttpResult.error("保存出错!");
}
public HttpResult saveEnergy(@RequestBody EnergyEntity energyEntity, @RequestParam(value = "type") int type){
try{
energyService.saveEnergy(energyEntity,type);
return HttpResult.ok();
}catch (Exception e){
return HttpResult.error("保存出错!");
}
}
@SysLogger(title = "用能分析", optDesc = "修改能耗信息")
@SysLogger(title="用能分析",optDesc = "修改能耗信息")
@PostMapping("/update")
public HttpResult updateEnergy(@RequestBody EnergyEntity energyEntity, @RequestParam(value = "type") int type) {
try {
energyService.updateEnergy(energyEntity, type);
return HttpResult.ok();
} catch (Exception e) {
return HttpResult.error("修改出错!");
public HttpResult updateEnergy(@RequestBody EnergyEntity energyEntity, @RequestParam(value = "type") int type){
try{
energyService.updateEnergy(energyEntity,type);
return HttpResult.ok();
}catch (Exception e){
return HttpResult.error("修改出错!");
}
}
@PostMapping("/delete")
@SysLogger(title = "用能分析", optDesc = "删除能耗信息")
@SysLogger(title="用能分析",optDesc = "删除能耗信息")
public HttpResult deleteEnergy(@RequestParam(value = "curDate") String curDate,
@RequestParam(value = "buildingId") String buildingId,
@RequestParam(value = "type") int type) {
try {
@RequestParam(value = "type") int type){
try{
energyService.deleteEnergy(curDate, buildingId, type);
return HttpResult.ok();
} catch (Exception e) {
return HttpResult.error("删除出错!");
energyService.deleteEnergy(curDate,buildingId,type);
return HttpResult.ok();
}catch (Exception e){
return HttpResult.error("删除出错!");
}
}
@SysLogger(title = "用能分析", optDesc = "查询能耗信息")
@SysLogger(title="用能分析",optDesc = "查询能耗信息")
@PostMapping("/query")
public HttpResult queryEnergy(@RequestParam(value = "buildingId", required = false) String buildingId,
@RequestParam(value = "startDate", required = false) String startDate,
@RequestParam(value = "endDate", required = false) String endDate,
@RequestParam(value = "level", required = false, defaultValue = "0") int level,
public HttpResult queryEnergy(@RequestParam(value = "buildingId",required = false) String buildingId,
@RequestParam(value = "startDate",required = false) String startDate,
@RequestParam(value = "endDate",required = false) String endDate,
@RequestParam(value = "page") int page,
@RequestParam(value = "limit") int limit,
@RequestParam(value = "type") int type) {
try {
// String areaId="";
// if (buildingId!=null && buildingId.length()>0){
// if (!buildingId.equals("所有")){
// areaId=buildingService.queryAreaId(Integer.parseInt(buildingId));
// }
// }
List<EnergyEntity> list = new ArrayList<>();
int count = 0;
// if (areaId!=null && areaId.length()>0){
list = energyService.queryEnergy(buildingId, startDate, endDate, page, limit, type, level);
count = energyService.getEnergyCount(buildingId, startDate, endDate, page, limit, type, level);
// }else{
// list=energyService.queryEnergy(buildingId,startDate,endDate,page,limit,type, level);
// count=energyService.getEnergyCount(buildingId,startDate,endDate,page,limit,type, level);
// }
@RequestParam(value = "type") int type){
try{
String areaId="";
if (buildingId!=null && buildingId.length()>0){
if (!buildingId.equals("所有")){
areaId=buildingService.queryAreaId(Integer.parseInt(buildingId));
}
}
List<EnergyEntity> list=new ArrayList<>();
int count=0;
if (areaId!=null && areaId.length()>0){
list=energyService.queryEnergy(areaId,startDate,endDate,page,limit,type);
count=energyService.getEnergyCount(areaId,startDate,endDate,page,limit,type);
}else{
list=energyService.queryEnergy(buildingId,startDate,endDate,page,limit,type);
count=energyService.getEnergyCount(buildingId,startDate,endDate,page,limit,type);
}
// System.out.println("返回前端数据:"+list);
return HttpResult.ok(count, list);
} catch (Exception e) {
e.printStackTrace();
return HttpResult.error("查询出错!");
return HttpResult.ok(count,list);
}catch (Exception e){
// e.printStackTrace();
return HttpResult.error("查询出错!");
}
}
//主界面水、电、单耗查询
@SysLogger(title = "项目概况", optDesc = "查询能耗信息")
@SysLogger(title="项目概况",optDesc = "查询能耗信息")
@PostMapping("/queryGroup")
public HttpResult queryEnergyGroup(@RequestParam(value = "curDate", required = true) String curDate,
@RequestParam(value = "type", required = true, defaultValue = "1") int type) {
try {
List<EnergyEntity> list = new ArrayList<EnergyEntity>();
list = energyService.queryEnergyGroup(curDate, type);
return HttpResult.ok(list);
} catch (Exception e) {
public HttpResult queryEnergyGroup(@RequestParam(value = "curDate",required = true) String curDate,
@RequestParam(value = "type",required = true,defaultValue = "1") int type){
try{
List<EnergyEntity> list=new ArrayList<EnergyEntity>();
list=energyService.queryEnergyGroup(curDate,type);
return HttpResult.ok(list);
}catch (Exception e){
e.printStackTrace();
return HttpResult.error("查询出错!");
return HttpResult.error("查询出错!");
}
}
//查询每天的用量
@SysLogger(title = "用能分析", optDesc = "查询每天的用量")
@SysLogger(title="用能分析",optDesc = "查询每天的用量")
@PostMapping("/queryDay")
public HttpResult queryDayEnergy(@RequestParam(value = "buildingId", required = false) String buildingId,
@RequestParam(value = "startDate", required = false) String startDate,
@RequestParam(value = "endDate", required = false) String endDate,
public HttpResult queryDayEnergy(@RequestParam(value = "buildingId",required = false) String buildingId,
@RequestParam(value = "startDate",required = false) String startDate,
@RequestParam(value = "endDate",required = false) String endDate,
@RequestParam(value = "page") int page,
@RequestParam(value = "limit") int limit) {
try {
String areaId = "";
if (buildingId != null && buildingId.length() > 0) {
if (!buildingId.equals("所有")) {
areaId = buildingService.queryAreaId(Integer.parseInt(buildingId));
@RequestParam(value = "limit") int limit){
try{
String areaId="";
if (buildingId!=null && buildingId.length()>0){
if (!buildingId.equals("所有")){
areaId=buildingService.queryAreaId(Integer.parseInt(buildingId));
}
}
List<EnergyEntity> list;
int count = 0;
if (areaId != null && areaId.length() > 0) {
list = energyService.queryDayEnergy(areaId, startDate, endDate, page, limit);
count = energyService.getDayEnergyCount(areaId, startDate, endDate, page, limit);
} else {
list = energyService.queryDayEnergy(buildingId, startDate, endDate, page, limit);
count = energyService.getDayEnergyCount(buildingId, startDate, endDate, page, limit);
int count=0;
if (areaId!=null && areaId.length()>0){
list=energyService.queryDayEnergy(areaId,startDate,endDate,page,limit);
count=energyService.getDayEnergyCount(areaId,startDate,endDate,page,limit);
}else{
list=energyService.queryDayEnergy(buildingId,startDate,endDate,page,limit);
count=energyService.getDayEnergyCount(buildingId,startDate,endDate,page,limit);
}
return HttpResult.ok(count, list);
} catch (Exception e) {
return HttpResult.ok(count,list);
}catch (Exception e){
e.printStackTrace();
return HttpResult.error("查询出错!");
return HttpResult.error("查询出错!");
}
}
//查询小时的用量
@SysLogger(title = "用能分析", optDesc = "查询小时的用量")
@SysLogger(title="用能分析",optDesc = "查询小时的用量")
@PostMapping("/queryHour")
public HttpResult queryHourEnergy(@RequestParam(value = "buildingId", required = false) String buildingId,
@RequestParam(value = "curDate", required = false) String curDate,
@RequestParam(value = "level", required = false, defaultValue = "0") int level,
@RequestParam(value = "page") int page,
@RequestParam(value = "limit") int limit) {
try {
// String areaId = "";
// if (buildingId != null && buildingId.length() > 0) {
// if (!buildingId.equals("所有")) {
// areaId = buildingService.queryAreaId(Integer.parseInt(buildingId));
// }
// }
public HttpResult queryHourEnergy(@RequestParam(value = "buildingId",required = false) String buildingId,
@RequestParam(value = "curDate",required = false) String curDate,
@RequestParam(value = "page") int page,
@RequestParam(value = "limit") int limit){
try{
String areaId="";
if (buildingId!=null && buildingId.length()>0){
if (!buildingId.equals("所有")){
areaId=buildingService.queryAreaId(Integer.parseInt(buildingId));
}
}
List<EnergyEntity> list;
int count = 0;
// if (areaId != null && areaId.length() > 0) {
// list = energyService.queryHourEnergy(areaId, curDate, page, limit, level);
//// count=energyService.getHourEnergyCount(areaId,curDate, level);
// count = list.size();
// } else {
list = energyService.queryHourEnergy(buildingId, curDate, page, limit, level);
// count=energyService.getHourEnergyCount(buildingId,curDate, level);
count = list.size();
// }
return HttpResult.ok(count, list);
} catch (Exception e) {
int count=0;
if (areaId!=null && areaId.length()>0){
list=energyService.queryHourEnergy(areaId,curDate,page,limit);
count=energyService.getHourEnergyCount(areaId,curDate);
}else{
list=energyService.queryHourEnergy(buildingId,curDate,page,limit);
count=energyService.getHourEnergyCount(buildingId,curDate);
}
return HttpResult.ok(count,list);
}catch (Exception e){
e.printStackTrace();
return HttpResult.error("查询出错!");
return HttpResult.error("查询出错!");
}
}
//查询楼栋时段用量对比
@SysLogger(title = "用能分析", optDesc = "查询楼栋时段用量对比")
@SysLogger(title="用能分析",optDesc = "查询楼栋时段用量对比")
@PostMapping("/queryBuild")
public HttpResult queryEnergyBuilding(@RequestParam(value = "curDate", required = false) String curDate,
@RequestParam(value = "endDate", required = false) String endDate,
@RequestParam(value = "type", required = false) int type,
public HttpResult queryEnergyBuilding(@RequestParam(value = "curDate",required = false) String curDate,
@RequestParam(value = "endDate",required = false) String endDate,
@RequestParam(value = "type",required = false) int type,
@RequestParam(value = "page") int page,
@RequestParam(value = "limit") int limit) {
try {
energyService.proEnergyBuilding(curDate, endDate, type);
List<EnergyEntity> list = energyService.queryEnergyBuilding(page, limit);
SumModel list2 = energyService.queryEnergySum();
Map map = new HashMap<>();
map.put("a", list);
map.put("b", list2);
int count = energyService.getEnergyBuildingCount();
return HttpResult.ok(count, map);
} catch (Exception e) {
@RequestParam(value = "limit") int limit){
try{
energyService.proEnergyBuilding(curDate,endDate,type);
List<EnergyEntity> list=energyService.queryEnergyBuilding(page,limit);
SumModel list2=energyService.queryEnergySum();
Map map=new HashMap<>();
map.put("a",list);
map.put("b",list2);
int count=energyService.getEnergyBuildingCount();
return HttpResult.ok(count,map);
}catch (Exception e){
e.printStackTrace();
return HttpResult.error("查询出错!");
return HttpResult.error("查询出错!");
}
}
//查询合计
@SysLogger(title = "用能分析", optDesc = "查询合计")
@SysLogger(title="用能分析",optDesc = "查询合计")
@PostMapping("/querySum")
public HttpResult queryEnergySum() {
try {
SumModel list = energyService.queryEnergySum();
return HttpResult.ok(list);
} catch (Exception e) {
public HttpResult queryEnergySum(){
try{
SumModel list=energyService.queryEnergySum();
return HttpResult.ok(list);
}catch (Exception e){
e.printStackTrace();
return HttpResult.error("查询出错!");
return HttpResult.error("查询出错!");
}
}

36
user-service/src/main/java/com/mh/user/controller/EnergyPreController.java

@ -1,36 +0,0 @@
package com.mh.user.controller;
import com.mh.common.http.HttpResult;
import com.mh.user.dto.EnergyPreDTO;
import com.mh.user.service.HistoryDataPreService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author LJF
* @version 1.0
* @project CHWS
* @description 用能预测controller
* @date 2024-05-09 17:24:48
*/
@RestController
@RequestMapping("/energyPre")
public class EnergyPreController {
@Resource
private HistoryDataPreService historyDataPreService;
@PostMapping("/topData")
public HttpResult getTopData(String buildingId, String type) {
return HttpResult.ok(historyDataPreService.getTopData(buildingId, type));
}
@PostMapping("/echartData")
public HttpResult getEnergyPre(String buildingId, String beginDate, String endDate, String type) {
return HttpResult.ok(historyDataPreService.getEnergyPre(buildingId, beginDate, endDate, type));
}
}

63
user-service/src/main/java/com/mh/user/controller/KnowledgeDataController.java

@ -1,63 +0,0 @@
package com.mh.user.controller;
import com.mh.common.http.HttpResult;
import com.mh.common.page.PageRequest;
import com.mh.common.page.PageResult;
import com.mh.user.entity.KnowledgeDataEntity;
import com.mh.user.service.KnowledgeDataService;
import io.jsonwebtoken.lang.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* @author LJF
* @version 1.0
* @project CHWS
* @description 知识库管理
* @date 2024-06-26 14:39:24
*/
@RestController
@RequestMapping("/knowledge")
public class KnowledgeDataController {
@Resource
private KnowledgeDataService knowledgeDataService;
@GetMapping("/query")
public HttpResult queryKnowledgeData(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize) {
PageRequest pageRequest = new PageRequest();
pageRequest.setPageNum(pageNum);
pageRequest.setPageSize(pageSize);
return HttpResult.ok(knowledgeDataService.queryKnowledgeData(pageRequest));
}
@GetMapping("/{id}")
public HttpResult detail(@PathVariable(name = "id") Long id) {
KnowledgeDataEntity knowledgeData = knowledgeDataService.getById(id);
Assert.notNull(knowledgeData, "该文章已被删除");
return HttpResult.ok(knowledgeData);
}
@PostMapping("/update")
public HttpResult updateData(@Validated @RequestBody KnowledgeDataEntity knowledgeData) {
try {
knowledgeDataService.updateData(knowledgeData);
} catch (Exception e) {
throw new RuntimeException(e);
}
return HttpResult.ok();
}
@PostMapping("/insert")
public HttpResult insertKnowledgeData(@Validated @RequestBody KnowledgeDataEntity knowledgeData) {
try {
knowledgeDataService.insertKnowledgeData(knowledgeData);
} catch (Exception e) {
throw new RuntimeException(e);
}
return HttpResult.ok();
}
}

211
user-service/src/main/java/com/mh/user/controller/NowDataController.java

@ -8,8 +8,6 @@ import com.mh.user.model.DeviceModel;
import com.mh.user.model.PumpModel;
import com.mh.user.model.WaterLevelModel;
import com.mh.user.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@ -25,7 +23,6 @@ import java.util.List;
@RequestMapping("monitor")
public class NowDataController {
private static final Logger log = LoggerFactory.getLogger(NowDataController.class);
@Autowired
NowDataService nowDataService;
@ -41,42 +38,38 @@ public class NowDataController {
@Autowired
DeviceFloorService deviceFloorService;
@SysLogger(title = "实时监控", optDesc = "实时查看每楼栋热水运行情况")
@SysLogger(title="实时监控",optDesc = "实时查看每楼栋热水运行情况")
@PostMapping("/queryNow")
public HttpResult queryNowData(@RequestParam(value = "buildingId") String buildingId) {
try {
public HttpResult queryNowData(@RequestParam(value = "buildingId") String buildingId){
try{
//把热泵的水温保存到公共信息中中的用水温度和回水温度
String avgWaterTemp = nowDataService.selectAve(buildingId);
String maxWaterTemp = nowDataService.selectMaxTemp(buildingId);
String buildingName = buildingService.queryBuildingName(buildingId);//获取楼栋名称
String avgWaterTemp=nowDataService.selectAve(buildingId);
String buildingName=buildingService.queryBuildingName(buildingId);//获取楼栋名称
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String curDate = sdf1.format(date);
curDate = curDate.substring(0, 13) + ":00:00";
Date date=new Date();
String curDate=sdf1.format(date);
curDate=curDate.substring(0,13)+":00:00";
NowPublicDataEntity nowPublicData = new NowPublicDataEntity();
NowPublicDataEntity nowPublicData=new NowPublicDataEntity();
nowPublicData.setBuildingId(buildingId);
nowPublicData.setBuildingName(buildingName);
if (avgWaterTemp != null) {
if (avgWaterTemp!=null){
nowPublicData.setBackWaterTemp(avgWaterTemp);
} else {
nowPublicData.setUseWaterTemp(avgWaterTemp);
}else{
nowPublicData.setBackWaterTemp("0");
}
if (maxWaterTemp != null) {
nowPublicData.setUseWaterTemp(maxWaterTemp);
} else {
nowPublicData.setUseWaterTemp("0");
}
nowPublicDataService.saveNowHistoryPublicData(nowPublicData);
//监视表生成初始记录
List<NowDataEntity> list = nowDataService.queryNowData(buildingId);
if (list.size() == 0) {//实时表生成记录
List<DeviceModel> deviceList = deviceInstallService.selectDevices(buildingId, "热泵");
if (deviceList.size() > 0) {
for (DeviceModel list2 : deviceList) {
NowDataEntity nowData = new NowDataEntity();
List<NowDataEntity> list=nowDataService.queryNowData(buildingId);
if (list.size()==0){//实时表生成记录
List<DeviceModel> deviceList=deviceInstallService.selectDevices(buildingId,"热泵");
if (deviceList.size()>0){
for (DeviceModel list2:deviceList){
NowDataEntity nowData=new NowDataEntity();
nowData.setPumpId(list2.getDeviceAddr());
nowData.setPumpName(list2.getDeviceName());
nowData.setBuildingId(buildingId);
@ -85,10 +78,10 @@ public class NowDataController {
nowDataService.saveNowData(nowData); //当前状态表
nowDataService.saveHistoryData(nowData); //历史状态表
}
} else {
NowDataEntity nowData = new NowDataEntity();
PumpModel pump = deviceFloorService.selectDeviceId2("热泵", buildingId);
if (pump != null) {
}else{
NowDataEntity nowData=new NowDataEntity();
PumpModel pump=deviceFloorService.selectDeviceId2("热泵",buildingId);
if (pump!=null){
nowData.setPumpId(pump.getPumpId());
nowData.setPumpName(pump.getPumpName());
nowData.setBuildingId(buildingId);
@ -99,144 +92,140 @@ public class NowDataController {
}
}
}
list = nowDataService.queryNowData(buildingId);
return HttpResult.ok(list);
} catch (Exception e) {
log.error("查询当前监控状态出错!", e);
return HttpResult.error("查询当前监控状态出错!");
list=nowDataService.queryNowData(buildingId);
return HttpResult.ok(list);
}catch (Exception e){
// e.printStackTrace();
return HttpResult.error("查询当前监控状态出错!");
}
}
@SysLogger(title = "实时监控", optDesc = "分别查看热泵运行情况")
@SysLogger(title="实时监控",optDesc = "分别查看热泵运行情况")
@PostMapping("/queryNowByPump")
public HttpResult queryNowByPump(@RequestParam(value = "buildingId") String buildingId, @RequestParam(value = "pumpId") String pumpId) {
try {
NowDataEntity nowDataEntity = nowDataService.queryNowDataByPump(buildingId, pumpId);
return HttpResult.ok(nowDataEntity);
} catch (Exception e) {
public HttpResult queryNowByPump(@RequestParam(value = "buildingId") String buildingId,@RequestParam(value = "pumpId") String pumpId){
try{
NowDataEntity nowDataEntity=nowDataService.queryNowDataByPump(buildingId,pumpId);
return HttpResult.ok(nowDataEntity);
}catch (Exception e){
e.printStackTrace();
return HttpResult.error("按热泵查询当前监控状态出错!");
return HttpResult.error("按热泵查询当前监控状态出错!");
}
}
@SysLogger(title = "运行信息", optDesc = "热泵历史状态查询")
@SysLogger(title="运行信息",optDesc = "热泵历史状态查询")
@PostMapping("/query")
public HttpResult queryHistoryData(@RequestParam(value = "curDate") String curDate,
@RequestParam(value = "buildingId") String buildingId,
@RequestParam(value = "pumpId", required = false) String pumpId,
@RequestParam(value = "tankId", required = false) String tankId,
@RequestParam(value = "pumpId",required = false) String pumpId,
@RequestParam(value = "tankId",required = false) String tankId,
@RequestParam(value = "page") int page,
@RequestParam(value = "limit") int limit) {
try {
@RequestParam(value = "limit") int limit){
try{
List<NowDataEntity> list;
list = nowDataService.queryHistoryData(curDate, buildingId, pumpId, tankId, page, limit);
int count = nowDataService.getHistoryDataCount(curDate, buildingId, pumpId, tankId, page, limit);
return HttpResult.ok(count, list);
} catch (Exception e) {
list=nowDataService.queryHistoryData(curDate,buildingId,pumpId,tankId,page,limit);
int count=nowDataService.getHistoryDataCount(curDate,buildingId,pumpId,tankId,page,limit);
return HttpResult.ok(count,list);
}catch (Exception e){
// e.printStackTrace();
return HttpResult.error("查询出错!");
return HttpResult.error("查询出错!");
}
}
//查询水位开始
@SysLogger(title = "水位变化表", optDesc = "水位变化查询")
@SysLogger(title="水位变化表",optDesc = "水位变化查询")
@PostMapping("/waterLevel")
public HttpResult queryWaterLevel(@RequestParam(value = "curDate") String curDate,
@RequestParam(value = "buildingID") String buildingID,
@RequestParam(value = "level", defaultValue = "0") int level,
@RequestParam(value = "page") int page,
@RequestParam(value = "limit") int limit) {
try {
if (buildingID == null || buildingID.equals("") || buildingID.equals("所有楼栋") || level == 0 || level == 1) {
List<WaterLevelEntity> list = nowDataService.queryBuildWaterLevel(curDate, page, limit, level, buildingID);
// int count = nowDataService.buildWaterLevelCount(curDate);
int count = list.size();
return HttpResult.ok(count, list);
} else {
List<WaterLevelEntity> list = nowDataService.queryWaterLevel(curDate, buildingID, page, limit);
int count = nowDataService.getWaterLevelCount(curDate, buildingID);
return HttpResult.ok(count, list);
@RequestParam(value = "buildingID") String buildingID,
@RequestParam(value = "page") int page,
@RequestParam(value = "limit") int limit){
try{
if (buildingID==null || buildingID.equals("") || buildingID.equals("所有楼栋")){
List<WaterLevelEntity> list=nowDataService.queryBuildWaterLevel(curDate, page, limit);
int count=nowDataService.buildWaterLevelCount(curDate);
return HttpResult.ok(count,list);
}else{
List<WaterLevelEntity> list=nowDataService.queryWaterLevel(curDate,buildingID,page,limit);
int count=nowDataService.getWaterLevelCount(curDate,buildingID);
return HttpResult.ok(count,list);
}
} catch (Exception e) {
}catch (Exception e){
// e.printStackTrace();
return HttpResult.error("查询出错!");
return HttpResult.error("查询出错!");
}
}
@PostMapping("/levelByTime")
public HttpResult queryWaterLevelByTime(@RequestParam(value = "curDate") String curDate,
@RequestParam(value = "page") int page,
@RequestParam(value = "limit") int limit) {
try {
int count = nowDataService.waterLevelByTimeCount(curDate);
List<WaterLevelModel> list = nowDataService.queryWaterLevelByTime(curDate, page, limit);
return HttpResult.ok(count, list);
} catch (Exception e) {
@RequestParam(value = "limit") int limit){
try{
int count=nowDataService.waterLevelByTimeCount(curDate);
List<WaterLevelModel> list=nowDataService.queryWaterLevelByTime(curDate,page,limit);
return HttpResult.ok(count,list);
}catch (Exception e){
// e.printStackTrace();
return HttpResult.error("查询出错!");
return HttpResult.error("查询出错!");
}
}
//查询水位结束
//查询水温,每天24小时情况
@SysLogger(title = "温度变化表", optDesc = "温度变化查询")
@SysLogger(title="温度变化表",optDesc = "温度变化查询")
@PostMapping("/waterTemp")
public HttpResult queryWaterTemp(@RequestParam(value = "buildingID") String buildingID,
@RequestParam(value = "curDate") String curDate,
@RequestParam(value = "level", defaultValue = "0") int level,
@RequestParam(value = "page") int page,
@RequestParam(value = "limit") int limit) {
try {
@RequestParam(value = "limit") int limit){
try{
List<WaterTempEntity> list;
int count;
// 校区或者区域
if (buildingID == null || buildingID.equals("") || buildingID.equals("所有楼栋") || level == 0 || level == 1) {
list = nowDataService.queryWaterTemp2(curDate, page, limit, level, buildingID);
// count = nowDataService.queryWaterTempCount2(curDate, level, buildingID);
count = list.size();
} else {
list = nowDataService.queryWaterTemp(buildingID, curDate, page, limit);
count = nowDataService.queryWaterTempCount(buildingID, curDate);
if (buildingID==null || buildingID.equals("") || buildingID.equals("所有楼栋")){
list=nowDataService.queryWaterTemp2(curDate,page,limit);
count=nowDataService.queryWaterTempCount2(curDate);
}else{
list=nowDataService.queryWaterTemp(buildingID,curDate,page,limit);
count=nowDataService.queryWaterTempCount(buildingID,curDate);
}
return HttpResult.ok(count, list);
} catch (Exception e) {
return HttpResult.ok(count,list);
}catch (Exception e){
// e.printStackTrace();
return HttpResult.error("查询出错!");
return HttpResult.error("查询出错!");
}
}
//查询运行时长
@SysLogger(title = "运行时长", optDesc = "热泵运行时长查询")
@SysLogger(title="运行时长",optDesc = "热泵运行时长查询")
@PostMapping("/minutes")
public HttpResult pumpMinutes(@RequestParam(value = "startDate") String startDate,
@RequestParam(value = "endDate") String endDate,
@RequestParam(value = "buildingId", required = false) String buildingId,
@RequestParam(value = "pumpId", required = false) String pumpId,
@RequestParam(value = "buildingId",required = false) String buildingId,
@RequestParam(value = "pumpId",required = false) String pumpId,
@RequestParam(value = "type") int type,
@RequestParam(value = "page") int page,
@RequestParam(value = "limit") int limit) {
try {
int count = 0;
@RequestParam(value = "limit") int limit){
try{
int count=0;
List<PumpMinutesEntity> list;
if (type == 1) {
list = nowDataService.pumpMinutes(startDate, endDate, buildingId, pumpId, page, limit);
count = nowDataService.pumpMinutesCount(startDate, endDate, buildingId, pumpId);
} else if (type == 2) {
list = nowDataService.pumpWeekMinutes(startDate, endDate, buildingId, pumpId, page, limit);
count = nowDataService.pumpWeekMinutesCount(startDate, endDate, buildingId, pumpId);
} else if (type == 3) {
list = nowDataService.pumpMonthMinutes(startDate, endDate, buildingId, pumpId, page, limit);
count = nowDataService.pumpMonthMinutesCount(startDate, endDate, buildingId, pumpId);
} else {
list = nowDataService.pumpMinutes(startDate, endDate, buildingId, pumpId, page, limit);
count = nowDataService.pumpMinutesCount(startDate, endDate, buildingId, pumpId);
if(type==1){
list=nowDataService.pumpMinutes(startDate,endDate,buildingId,pumpId,page,limit);
count=nowDataService.pumpMinutesCount(startDate,endDate,buildingId,pumpId);
}else if(type==2){
list=nowDataService.pumpWeekMinutes(startDate,endDate,buildingId,pumpId,page,limit);
count=nowDataService.pumpWeekMinutesCount(startDate,endDate,buildingId,pumpId);
}else if(type==3){
list=nowDataService.pumpMonthMinutes(startDate,endDate,buildingId,pumpId,page,limit);
count=nowDataService.pumpMonthMinutesCount(startDate,endDate,buildingId,pumpId);
}else{
list=nowDataService.pumpMinutes(startDate,endDate,buildingId,pumpId,page,limit);
count=nowDataService.pumpMinutesCount(startDate,endDate,buildingId,pumpId);
}
return HttpResult.ok(count, list);
} catch (Exception e) {
return HttpResult.ok(count,list);
}catch (Exception e){
// e.printStackTrace();
return HttpResult.error("查询出错!");
return HttpResult.error("查询出错!");
}
}
}

4
user-service/src/main/java/com/mh/user/controller/NowPublicDataController.java

@ -9,7 +9,6 @@ import com.mh.user.model.TempModel;
import com.mh.user.service.BuildingService;
import com.mh.user.service.NowDataService;
import com.mh.user.service.NowPublicDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@ -21,7 +20,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("monitor_public")
public class NowPublicDataController {
@ -41,7 +39,7 @@ public class NowPublicDataController {
NowPublicDataEntity nowPublicDataEntity=nowPublicDataService.queryNowPublicData(buildingId);
return HttpResult.ok(nowPublicDataEntity);
}catch (Exception e){
log.error("查询公共信息出错!",e);
//e.printStackTrace();
return HttpResult.error("查询公共信息出错!");
}
}

4
user-service/src/main/java/com/mh/user/controller/SerialPortController.java

@ -424,9 +424,9 @@ public class SerialPortController {
}
@PostMapping(value = "/control")
public HttpResult queryControlSet(@RequestParam(value = "buildingId") String buildingId, @RequestParam(value = "timeName", required = false) String timeName) {
public HttpResult queryControlSet(@RequestParam(value = "buildingId") String buildingId) {
try {
ControlSetEntity list = controlSetService.queryControlSet(buildingId, timeName);
ControlSetEntity list = controlSetService.queryControlSet(buildingId);
return HttpResult.ok(list);
} catch (Exception e) {
// e.printStackTrace();

23
user-service/src/main/java/com/mh/user/controller/SummaryController.java

@ -40,21 +40,20 @@ public class SummaryController {
@PostMapping(value="/energySum")
public HttpResult queryEnergySum(@RequestParam(value= "buildingId", required=false)String buildingId,
@RequestParam(value= "curDate", required=false)String curDate,
@RequestParam(value= "level", required=false, defaultValue="0") int level,
@RequestParam(value= "type", required=true)Integer type) {
try{
// String areaId="";
// if (buildingId!=null && buildingId.length()>0){
// if (!buildingId.equals("所有")){
// areaId=buildingService.queryAreaId(Integer.parseInt(buildingId));
// }
// }
String areaId="";
if (buildingId!=null && buildingId.length()>0){
if (!buildingId.equals("所有")){
areaId=buildingService.queryAreaId(Integer.parseInt(buildingId));
}
}
EnergySumEntity record;
// if (areaId!=null && areaId.length()>0){
// record=summaryService.queryEnergySum(areaId,curDate,type);
// }else{
record=summaryService.queryEnergySum(buildingId,curDate,type, level);
// }
if (areaId!=null && areaId.length()>0){
record=summaryService.queryEnergySum(areaId,curDate,type);
}else{
record=summaryService.queryEnergySum(buildingId,curDate,type);
}
return HttpResult.ok(record);
}catch (Exception e){
//e.printStackTrace();

27
user-service/src/main/java/com/mh/user/dto/EnergyPreDTO.java

@ -1,27 +0,0 @@
package com.mh.user.dto;
import lombok.Getter;
import lombok.Setter;
/**
* @author LJF
* @version 1.0
* @project CHWS
* @description 用能预测前端类
* @date 2024-05-09 17:31:27
*/
@Setter
@Getter
public class EnergyPreDTO {
/**
* 顶部数据
*/
private EnergyPreTopDataDTO topData;
/**
* 折线图数据
*/
private EnergyPreEchartDataDTO echartData;
}

37
user-service/src/main/java/com/mh/user/dto/EnergyPreEchartDataDTO.java

@ -1,37 +0,0 @@
package com.mh.user.dto;
import lombok.Getter;
import lombok.Setter;
/**
* @author LJF
* @version 1.0
* @project CHWS
* @description 用能预测前端类
* @date 2024-05-09 17:31:27
*/
@Setter
@Getter
public class EnergyPreEchartDataDTO {
/**
* 时间
*/
private String curDate;
/**
* 实际值
*/
private String curData;
/**
* 预测值
*/
private String preData;
/**
* 误差值
*/
private String errorData;
}

37
user-service/src/main/java/com/mh/user/dto/EnergyPreTopDataDTO.java

@ -1,37 +0,0 @@
package com.mh.user.dto;
import lombok.Getter;
import lombok.Setter;
/**
* @author LJF
* @version 1.0
* @project CHWS
* @description 用能预测前端类
* @date 2024-05-09 17:31:27
*/
@Setter
@Getter
public class EnergyPreTopDataDTO {
/**
* 昨日实际值
*/
private String yesData;
/**
* 昨日预测值
*/
private String preYesData;
/**
* 今日预测值
*/
private String curYesData;
/**
* 误差值
*/
private String errorData;
}

32
user-service/src/main/java/com/mh/user/entity/AreaEntity.java

@ -1,33 +1,11 @@
package com.mh.user.entity;
import java.util.StringJoiner;
public class AreaEntity {
private Long id;
private String areaId;
private String areaName;
private int sort;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public String getAreaId() {
return areaId;
}
@ -46,11 +24,9 @@ public class AreaEntity {
@Override
public String toString() {
return new StringJoiner(", ", AreaEntity.class.getSimpleName() + "[", "]")
.add("id=" + id)
.add("areaId='" + areaId + "'")
.add("areaName='" + areaName + "'")
.add("sort=" + sort)
.toString();
return "AreaEntity{" +
"areaId='" + areaId + '\'' +
", areaName='" + areaName + '\'' +
'}';
}
}

3
user-service/src/main/java/com/mh/user/entity/BuildingEntity.java

@ -14,11 +14,8 @@ public class BuildingEntity {
private int bedCount;
private int checkInCount;
private String areaId;
private String areaName;
private String remarks;
private Double tankHeight;
private Double lowTankHeight;
private int pumpCount;
private int sort;
}

3
user-service/src/main/java/com/mh/user/entity/DeviceCodeParamEntity.java

@ -25,7 +25,4 @@ public class DeviceCodeParamEntity {
private String param;
// 寄存器大小
private int registerSize;
}

168
user-service/src/main/java/com/mh/user/entity/HistoryDataPre.java

@ -1,168 +0,0 @@
package com.mh.user.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.math.BigDecimal;
import java.util.Date;
/**
* @author LJF
* @version 1.0
* @project CHWS
* @description 历史预测数据表
* @date 2024-05-09 09:55:09
*/
public class HistoryDataPre {
private Long id;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date curDate;
private String buildingId;
private BigDecimal envMinTemp;
private BigDecimal envMaxTemp;
private BigDecimal waterValue;
private BigDecimal electValue;
private BigDecimal waterLevel;
/**
* 每栋楼人数
*/
private BigDecimal peopleNum;
private BigDecimal waterValuePre;
private BigDecimal electValuePre;
private BigDecimal waterLevelPre;
private String remark;
public BigDecimal getPeopleNum() {
return peopleNum;
}
public void setPeopleNum(BigDecimal peopleNum) {
this.peopleNum = peopleNum;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getCurDate() {
return curDate;
}
public void setCurDate(Date curDate) {
this.curDate = curDate;
}
public String getBuildingId() {
return buildingId;
}
public void setBuildingId(String buildingId) {
this.buildingId = buildingId;
}
public BigDecimal getEnvMinTemp() {
return envMinTemp;
}
public void setEnvMinTemp(BigDecimal envMinTemp) {
this.envMinTemp = envMinTemp;
}
public BigDecimal getEnvMaxTemp() {
return envMaxTemp;
}
public void setEnvMaxTemp(BigDecimal envMaxTemp) {
this.envMaxTemp = envMaxTemp;
}
public BigDecimal getWaterValue() {
return waterValue;
}
public void setWaterValue(BigDecimal waterValue) {
this.waterValue = waterValue;
}
public BigDecimal getElectValue() {
return electValue;
}
public void setElectValue(BigDecimal electValue) {
this.electValue = electValue;
}
public BigDecimal getWaterLevel() {
return waterLevel;
}
public void setWaterLevel(BigDecimal waterLevel) {
this.waterLevel = waterLevel;
}
public BigDecimal getWaterValuePre() {
return waterValuePre;
}
public void setWaterValuePre(BigDecimal waterValuePre) {
this.waterValuePre = waterValuePre;
}
public BigDecimal getElectValuePre() {
return electValuePre;
}
public void setElectValuePre(BigDecimal electValuePre) {
this.electValuePre = electValuePre;
}
public BigDecimal getWaterLevelPre() {
return waterLevelPre;
}
public void setWaterLevelPre(BigDecimal waterLevelPre) {
this.waterLevelPre = waterLevelPre;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Override
public String toString() {
return "HistoryDataPre{" +
"id=" + id +
", curDate=" + curDate +
", buildingId='" + buildingId + '\'' +
", envMinTemp=" + envMinTemp +
", envMaxTemp=" + envMaxTemp +
", waterValue=" + waterValue +
", electValue=" + electValue +
", waterLevel=" + waterLevel +
", waterValuePre=" + waterValuePre +
", electValuePre=" + electValuePre +
", waterLevelPre=" + waterLevelPre +
", remark='" + remark + '\'' +
'}';
}
}

38
user-service/src/main/java/com/mh/user/entity/KnowledgeDataEntity.java

@ -1,38 +0,0 @@
package com.mh.user.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
import java.util.Date;
/**
* @author LJF
* @version 1.0
* @project CHWS
* @description 知识库管理
* @date 2024-06-26 14:18:28
*/
@Data
public class KnowledgeDataEntity implements Serializable {
private Long id;
@NotBlank(message = "标题不能为空")
private String title;
@NotBlank(message = "摘要不能为空")
private String description;
@NotBlank(message = "内容不能为空")
private String content;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
private Integer status;
private String remark;
}

1
user-service/src/main/java/com/mh/user/entity/MaintainInfoEntity.java

@ -18,7 +18,6 @@ public class MaintainInfoEntity {
private String maintainPeople; //维护人员
private Double cost; //费用
private String contents; //维保内容
private String evaluate; // 评价分数
}

6
user-service/src/main/java/com/mh/user/entity/NowDataEntity.java

@ -23,10 +23,4 @@ public class NowDataEntity {
private String tankName; //水箱名称
private String envTemp; //环境温度
private String upWaterState; // 供水状态
private String useWaterState; // 补水状态
private String backWaterState; // 回水状态
}

1
user-service/src/main/java/com/mh/user/entity/SysParamEntity.java

@ -7,5 +7,4 @@ public class SysParamEntity {
private String customName; //公司或者单位名称
private String logo; //logo地址
private String proArea; // 区域编码
}

1
user-service/src/main/java/com/mh/user/entity/WaterLevelEntity.java

@ -16,7 +16,6 @@ public class WaterLevelEntity {
private String level08;
private String level11;
private String level13;
private String level14;
private String level15;
private String level16;
private String level17;

2
user-service/src/main/java/com/mh/user/entity/WaterTempEntity.java

@ -25,7 +25,7 @@ public class WaterTempEntity {
private String temp11;
// private String temp12;
private String temp13;
private String temp14;
// private String temp14;
private String temp15;
private String temp16;
private String temp17;

43
user-service/src/main/java/com/mh/user/factory/BackTempControl.java

@ -1,43 +0,0 @@
package com.mh.user.factory;
import com.mh.user.entity.DeviceCodeParamEntity;
import com.mh.user.strategy.DeviceStrategy;
/**
* @author LJF
* @version 1.0
* @project CHWS
* @description 回水温度控制器
* @date 2024-03-18 16:53:35
*/
public class BackTempControl implements Device {
private DeviceStrategy strategy;
private static class SingletonHolder {
private static final BackTempControl INSTANCE = new BackTempControl();
}
private BackTempControl() {
// 防止外部直接实例化
}
public static BackTempControl getInstance() {
return BackTempControl.SingletonHolder.INSTANCE;
}
@Override
public void setStrategy(DeviceStrategy strategy) {
this.strategy = strategy;
}
@Override
public String createOrders(DeviceCodeParamEntity deviceCodeParamEntity) {
return strategy.createOrders(deviceCodeParamEntity);
}
@Override
public String analysisReceiveData(String dateStr, String deviceType, String registerAddr, String brand, String buildingId, String buildingName, String dataStr) {
return strategy.analysisReceiveData(dateStr, deviceType, registerAddr, brand, buildingId, buildingName, dataStr);
}
}

5
user-service/src/main/java/com/mh/user/job/CollectionLoopRunner.java

@ -38,9 +38,6 @@ public class CollectionLoopRunner implements ApplicationRunner {
@Resource
private DeviceCodeParamService deviceCodeParamService;
@Resource
private GetWeatherInfoJob getWeatherInfoJob;
@Override
public void run(ApplicationArguments args) throws Exception {
// collectionMeterAndCloud();//采集
@ -49,8 +46,6 @@ public class CollectionLoopRunner implements ApplicationRunner {
initialDeviceCodeParams();
// 模拟采集
//simulationCollection();
// 获取天气数据
getWeatherInfoJob.getWeatherInfo();
}
private void simulationCollection() throws Exception {

44
user-service/src/main/java/com/mh/user/job/DealDataJob.java

@ -2,17 +2,13 @@ package com.mh.user.job;
import com.mh.user.constants.Constant;
import com.mh.user.entity.DeviceCodeParamEntity;
import com.mh.user.model.BuildingModel;
import com.mh.user.serialport.SerialPortThread;
import com.mh.user.service.BuildingService;
import com.mh.user.service.DealDataService;
import com.mh.user.service.HistoryDataPreService;
import com.mh.user.utils.CacheUtil;
import com.mh.user.utils.ComThreadPoolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import java.text.SimpleDateFormat;
import java.util.Date;
@ -35,14 +31,8 @@ public class DealDataJob {
private final DealDataService dealDataService;
private final BuildingService buildingService;
private final HistoryDataPreService historyDataPreService;
public DealDataJob(DealDataService dealDataService, BuildingService buildingService, HistoryDataPreService historyDataPreService) {
public DealDataJob(DealDataService dealDataService) {
this.dealDataService = dealDataService;
this.buildingService = buildingService;
this.historyDataPreService = historyDataPreService;
}
ThreadPoolExecutor comThreadPool = ComThreadPoolService.getInstance();
@ -58,7 +48,7 @@ public class DealDataJob {
String curDate = sdf1.format(date);
String name = dealDataService.customName();
if (name != null
&& (name.contains(Constant.CUSTOM_NAME_HUAXIA))) {
&& (name.contains(Constant.CUSTOM_NAME_HUAXIA) || name.contains(Constant.CUSTOM_NAME_GUANGSHANG))) {
dealDataService.proEnergy2(curDate);
} else {
dealDataService.proEnergy(curDate); //yyyy-MM-dd HH:00:00
@ -109,7 +99,7 @@ public class DealDataJob {
if (Constant.WEB_FLAG) {
break;
}
CountDownLatch countDownLatch = new CountDownLatch(Math.min(batchSize, dataComMap.size() - k));
CountDownLatch countDownLatch = new CountDownLatch(Math.min(batchSize, dataComMap.size() - k));
index = k;
for (int j = 0; j < Math.min(batchSize, dataComMap.size() - k); j++) {
if (Constant.WEB_FLAG) {
@ -151,15 +141,12 @@ public class DealDataJob {
@Scheduled(cron = "0 0/15 * * * ?")
public void dealData() {
try {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String curDate = sdf1.format(date);
String name = dealDataService.customName();
if (name != null
&& (name.contains(Constant.CUSTOM_NAME_HUAXIA))) {
&& (name.contains(Constant.CUSTOM_NAME_HUAXIA) || name.contains(Constant.CUSTOM_NAME_GUANGSHANG))) {
dealDataService.proEnergySum2(curDate);
} else {
dealDataService.proEnergySum(curDate);
@ -172,34 +159,11 @@ public class DealDataJob {
dealDataService.proDeviceState(curDate); //汇总设备状态
dealDataService.proTotalPumpMinutes(curDate); //统计周\月热泵运行时长
log.info("进入定时调试数据库过程汇总数据!yyyy-MM-dd");
stopWatch.stop();
log.info("定时处理数据以及预测数据结束!耗时:" + stopWatch.getTotalTimeSeconds() + "秒");
} catch (Exception e) {
log.error("定时处理数据异常==>", e);
}
}
// @Scheduled(cron = "0 0 0/12 * * ?")
// public void preUseData() {
// // 每12时预测一次数据
// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
// Date date = new Date();
// String curDate = sdf1.format(date);
// List<BuildingModel> buildingModels = buildingService.selectBuildingName();
// for (BuildingModel buildingModel : buildingModels) {
// String buildingId = String.valueOf(buildingModel.getBuildingId());
// try {
// // 训练数据
// historyDataPreService.startTrainData(buildingId);
// // 预测数据
// historyDataPreService.startPredictData(buildingId, curDate);
// } catch (Exception e) {
// log.error("定时处理数据以及预测数据异常==>", e);
// }
// }
// }
/**
* 定时删除历史流水记录删除前三个月的记录
*/

64
user-service/src/main/java/com/mh/user/job/GetWeatherInfoJob.java

@ -1,64 +0,0 @@
package com.mh.user.job;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.benmanes.caffeine.cache.Cache;
import com.mh.common.utils.StringUtils;
import com.mh.user.entity.SysParamEntity;
import com.mh.user.service.SysParamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
/**
* @author LJF
* @version 1.0
* @project NewZhujiang_Server
* @description 定期获取时间
* @date 2023-12-05 14:12:56
*/
@Component
@Slf4j
public class GetWeatherInfoJob {
@Resource
private SysParamService sysParamService;
@Resource
private RestTemplate restTemplate;
@Resource
@Qualifier("caffeineCache")
private Cache caffeineCache;
@Value("${amap.key}")
String amapKey;
/**
* 定时获取每天天气
*/
@Scheduled(cron = "0 0 0 0/1 * ? ")
public void getWeatherInfo() {
// 从系统参数中获取对应的项目区域
SysParamEntity sysParam = sysParamService.selectSysParam();
if (null != sysParam) {
String url = "https://restapi.amap.com/v3/weather/weatherInfo?extensions=all&key="+amapKey+"&city="+sysParam.getProArea();
String returnResult = restTemplate.getForObject(url, String.class);
if (!StringUtils.isBlank(returnResult)) {
JSONObject jsonObject = JSON.parseObject(returnResult);
if ("1".equals(jsonObject.get("status"))) {
Object wetTemp = caffeineCache.getIfPresent(sysParam.getProArea());
if (wetTemp != null) {
caffeineCache.invalidate(sysParam.getProArea());
}
caffeineCache.put(sysParam.getProArea(), jsonObject.toString());
}
}
}
}
}

8
user-service/src/main/java/com/mh/user/mapper/AnalysisMapper.java

@ -46,6 +46,7 @@ public interface AnalysisMapper {
@Result(column = "item_type", property = "itemType"),
@Result(column = "total_value", property = "totalValue")
})
@Select("select * from analysis_elect_month where cur_date=#{curDate} and building_id=#{buildingId}")
List<AnalysisMonthEntity> queryAnalysisElectMonth(@Param("curDate") String curDate, @Param("buildingId") String buildingId);
@ -61,11 +62,4 @@ public interface AnalysisMapper {
@Select("select * from analysis_maintain_month where cur_date=#{curDate} and building_id=#{buildingId}")
List<AnalysisMonthEntity> queryAnalysisMaintainMonth(@Param("curDate") String curDate, @Param("buildingId") String buildingId);
@ResultMap("rs_day")
@Select("select * from analysis_runtime_month where cur_date=#{curDate} and building_id=#{buildingId}")
List<AnalysisMonthEntity> queryAnalysisRuntimeMonth(@Param("curDate") String curDate, @Param("buildingId") String buildingId);
@ResultMap("rs_month")
@Select("select * from analysis_runtime_year where cur_date=#{curDate} and building_id=#{buildingId}")
List<AnalysisYearEntity> queryAnalysisRuntimeYear(@Param("curDate") String curDate, @Param("buildingId") String buildingId);
}

77
user-service/src/main/java/com/mh/user/mapper/AreaMapper.java

@ -1,79 +1,18 @@
package com.mh.user.mapper;
import com.mh.user.entity.AreaEntity;
import com.mh.user.model.AreaModel;
import org.apache.ibatis.annotations.*;
import tk.mybatis.mapper.common.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface AreaMapper extends BaseMapper<AreaEntity> {
public interface AreaMapper {
@Results({
@Result(property = "areaId", column = "area_id"),
@Result(property = "areaName", column = "area_name"),
@Result(property = "sort", column = "sort"),
})
@Select("select * from area order by sort ")
@Results({ @Result(property = "areaId", column = "area_id"),
@Result(property = "areaName", column = "area_name")})
@Select("select * from area ")
List<AreaEntity> findAll();
@Select("select count(*) from area where area_id=#{areaId} and area_name=#{areaName}")
int selectCountByAreaIdAndAreaName(String areaId, String areaName);
@Select("select count(*) from area where id= #{areaId}")
int getCount(String areaId, Integer page, Integer limit);
@Select({
"<script>",
"select * from (",
" select *, ROW_NUMBER() over(order by id) as rn from area ",
" where 1=1 ",
" <if test='areaId != null and areaId != \"\"'>",
" AND id = #{areaId}",
" </if>",
" ) T",
" <if test='page != 0 and limit != 0'>",
" where T.rn &gt; (#{page}-1)*#{limit} and T.rn &lt;= #{page}*#{limit} ",
" </if>",
" <if test='page == 0'>",
" </if>",
" order by sort ",
"</script>"
})
@Results(value = {
@Result(property="id",column="id"),
@Result(property="areaName",column="area_name"),
@Result(property="areaId",column="area_id")
})
List<AreaEntity> queryArea(String areaId, Integer page, Integer limit);
//查询所有楼栋编号和名称
@Select("select * from area order by sort ")
@Results(value = {
@Result(property="areaId",column="id"),
@Result(property="areaName",column="area_name")
})
List<AreaModel> selectAreaName();
@Delete("delete from area where id=#{id} ")
int deleteArea(String id);
@Select("select count(*) from area where area_name= #{areaName}")
int selectByAreaName(String areaName);
@Results({
@Result(property = "areaId", column = "area_id"),
@Result(property = "areaName", column = "area_name"),
@Result(property = "sort", column = "sort"),
@Result(property = "id", column = "id")
})
@Select("select * from area where id= #{id} ")
AreaEntity selectById(String buildingId);
@Insert("insert into area(area_id,area_name,sort) values(#{areaId},#{areaName},#{sort})")
int insertArea(AreaEntity areaEntity);
@Update("update area set area_id=#{areaId},area_name=#{areaName},sort=#{sort} where id=#{id}")
int updateArea(AreaEntity areaEntity);
}

42
user-service/src/main/java/com/mh/user/mapper/BuildingMapper.java

@ -15,8 +15,8 @@ public interface BuildingMapper {
* 保存楼栋信息
* @param buildingEntity
*/
@Insert("insert into building(building_name,levels_count,begin_level,house_count,bed_count,check_in_count,area_id,remarks,tankHeight,pump_count,low_tank_height) values (" +
"#{buildingName},#{levelsCount},#{beginLevel},#{houseCount},#{bedCount},#{checkInCount},#{areaId},#{remarks},#{tankHeight}, #{pumpCount}, #{lowTankHeight})")
@Insert("insert into building(building_name,levels_count,begin_level,house_count,bed_count,check_in_count,area_id,remarks,tankHeight,pump_count) values (" +
"#{buildingName},#{levelsCount},#{beginLevel},#{houseCount},#{bedCount},#{checkInCount},#{areaId},#{remarks},#{tankHeight}, #{pumpCount})")
int saveBuilding(BuildingEntity buildingEntity);
/**
@ -35,7 +35,6 @@ public interface BuildingMapper {
" <if test='areaId!=null'> , area_id = #{areaId} </if>" +
" <if test='remarks!=null'> , remarks = #{remarks} </if>" +
" <if test='tankHeight!=null'> , tankHeight = #{tankHeight} </if>" +
" <if test='lowTankHeight!=null'> , low_tank_height = #{lowTankHeight} </if>" +
" <if test='pumpCount!=null'> , pump_count = #{pumpCount} </if>" +
" where id = #{id} " +
"</script>")
@ -58,13 +57,11 @@ public interface BuildingMapper {
@Result(property="checkInCount",column="check_in_count"),
@Result(property="areaId",column="area_id"),
@Result(property="pumpCount",column="pump_count"),
@Result(property="remarks",column="remarks"),
@Result(property="tankHeight",column="tankHeight"),
@Result(property="lowTankHeight",column="low_tank_height"),
@Result(property="areaName",column="area_name")
@Result(property="remarks",column="remarks")
})
@SelectProvider(type = BuildingProvider.class,method = "queryBuilding")
List<BuildingEntity> queryBuilding(@Param("buildingId") String buildingId,@Param("page") int page, @Param("limit") int limit, @Param("level") int level);
List<BuildingEntity> queryBuilding(@Param("buildingId") String buildingId,@Param("page") int page, @Param("limit") int limit);
/**
* 楼栋管理模块
@ -72,7 +69,7 @@ public interface BuildingMapper {
* @return
*/
@SelectProvider(type = BuildingProvider.class,method = "getCount")
int getCount(@Param("buildingId") String buildingId,@Param("page") int page, @Param("limit") int limit, @Param("level") int level);
int getCount(@Param("buildingId") String buildingId,@Param("page") int page, @Param("limit") int limit);
//查询所有楼栋编号和名称
@Results(value = {
@ -119,31 +116,4 @@ public interface BuildingMapper {
@Select("select building_name from building where id = #{buildingId} ")
String selectBuildingNameById(@Param("buildingId") String buildingId);
@Select("select low_tank_height from building where id=#{id}" )
Double queryLowTankHeight(@Param("id") String buildingId);
@Results(value = {
@Result(property="id",column="id"),
@Result(property="buildingName",column="building_name"),
@Result(property="levelsCount",column="levels_count"),
@Result(property="beginLevel",column="begin_level"),
@Result(property ="houseCount",column ="house_count"),
@Result(property ="bedCount",column ="bed_count"),
@Result(property="checkInCount",column="check_in_count"),
@Result(property="areaId",column="area_id"),
@Result(property="pumpCount",column="pump_count"),
@Result(property="remarks",column="remarks"),
@Result(property="tankHeight",column="tankHeight"),
@Result(property="lowTankHeight",column="low_tank_height"),
@Result(property="sort",column="sort"),
})
@Select("select * from building ")
List<BuildingEntity> selectAll();
@Select("select id from building where area_id = #{areaId} order by sort ")
List<String> queryBuildingIdListByAreaId(String areaId);
@Select("select sum(check_in_count) from building where area_id = #{areaId} ")
int queryCheckInCount(@Param("areaId") String areaId);
}

19
user-service/src/main/java/com/mh/user/mapper/ControlSetMapper.java

@ -60,21 +60,6 @@ public interface ControlSetMapper {
@Result(column = "back_water_temp", property = "backWaterTemp"),
@Result(column = "up_water_temp", property = "upWaterTemp"),
})
@Select("select " +
" top 1 " +
" * " +
"from " +
" control_Set cs " +
"where " +
" cs.building_id = #{buildingId} " +
" and exists ( " +
" select " +
" 1 " +
" from " +
" device_install di " +
" where " +
" di.building_id = cs.building_id " +
" and di.device_name like concat('%',#{timeName}, '%') " +
") ")
ControlSetEntity queryControlSet(@Param("buildingId") String buildingId, @Param("timeName") String timeName);
@Select("select * from control_Set where building_id=#{buildingId}")
ControlSetEntity queryControlSet(@Param("buildingId") String buildingId);
}

2
user-service/src/main/java/com/mh/user/mapper/DealDataMapper.java

@ -68,7 +68,7 @@ public interface DealDataMapper {
void deleteDataHistory();
//查询学校名称
@Select("select top 1 customName from SysParam ")
@Select("select customName from SysParam ")
String customName();
//判断网关在线状态

12
user-service/src/main/java/com/mh/user/mapper/DeviceCodeParamMapper.java

@ -158,21 +158,15 @@ public interface DeviceCodeParamMapper {
void insertDeviceCodeParamList3(@Param("deviceCodeParamEntityList") List<DeviceCodeParamEntity> deviceCodeParamEntityList);
//查询插入压变、温控
@Insert("insert into device_code_param(device_addr,device_name,device_type,data_com,baudrate,parity,brand,create_time,building_id,isuse,thread) " +
" select device_addr,device_name,device_type,data_com,baudrate,parity,brand,getDate(),building_id,is_use,SUBSTRING(data_com, PATINDEX('%[0-9]%', data_com), LEN(data_com)) from device_install " +
" where device_type='压变' or device_type='温控' or device_type='温度变送器' or device_type = '回水温控' ")
@Insert("insert into device_code_param(device_addr,device_name,device_type,data_com,baudrate,parity,brand,create_time,building_id) select device_addr,device_name,device_type,data_com,baudrate,parity,brand,getDate(),building_id from device_install where device_type='压变' or device_type='温控' or device_type='温度变送器' ")
void selectInsertDeviceCodeParam();
//查询插入水、电表、状态检测
@Insert("insert into device_code_param2(device_addr,device_name,device_type,data_com,baudrate,parity,brand,create_time,building_id,isuse,thread) " +
" select device_addr,device_name,device_type,data_com,baudrate,parity,brand,getDate(),building_id,is_use,SUBSTRING(data_com, PATINDEX('%[0-9]%', data_com), LEN(data_com)) from device_install " +
" where device_type='电表' or device_type='水表' or device_type='状态检测' or device_type='热泵状态' ")
@Insert("insert into device_code_param2(device_addr,device_name,device_type,data_com,baudrate,parity,brand,create_time,building_id) select device_addr,device_name,device_type,data_com,baudrate,parity,brand,getDate(),building_id from device_install where device_type='电表' or device_type='水表' or device_type='状态检测' or device_type='热泵状态' ")
void selectInsertDeviceCodeParam2();
//查询插入水位开关
@Insert("insert into device_code_param3(device_addr,device_name,device_type,data_com,baudrate,parity,brand,create_time,building_id,isuse,thread) " +
" select device_addr,device_name,device_type,data_com,baudrate,parity,brand,getDate(),building_id,is_use,SUBSTRING(data_com, PATINDEX('%[0-9]%', data_com), LEN(data_com)) from device_install " +
" where device_type='水位开关' ")
@Insert("insert into device_code_param3(device_addr,device_name,device_type,data_com,baudrate,parity,brand,create_time,building_id) select device_addr,device_name,device_type,data_com,baudrate,parity,brand,getDate(),building_id from device_install where device_type='水位开关' ")
void selectInsertDeviceCodeParam3();
@Delete("delete from device_code_param " +

34
user-service/src/main/java/com/mh/user/mapper/DeviceInstallMapper.java

@ -19,8 +19,8 @@ public interface DeviceInstallMapper extends BaseMapper<DeviceInstallEntity> {
* 保存设备信息
* @param deviceInstallEntity
*/
@Insert("insert into device_install(device_addr,device_name,device_type,data_com,ratio,baudrate,brand,model,building_id,building_name,installer,install_date,is_use,parity) values (" +
" #{deviceAddr},#{deviceName},#{deviceType},#{dataCom},#{ratio},#{baudRate},#{brand},#{model},#{buildingId},#{buildingName},#{installer},getDate(),#{use},#{parity})")
@Insert("insert into device_install(device_addr,device_name,device_type,data_com,ratio,baudrate,brand,model,building_id,building_name,installer,install_date,is_use) values (" +
" #{deviceAddr},#{deviceName},#{deviceType},#{dataCom},#{ratio},#{baudRate},#{brand},#{model},#{buildingId},#{buildingName},#{installer},getDate(),#{use})")
int saveDevice(DeviceInstallEntity deviceInstallEntity);
/**
@ -118,8 +118,7 @@ public interface DeviceInstallMapper extends BaseMapper<DeviceInstallEntity> {
@Param("isUse")String isUse,
@Param("isFault")String isFault,
@Param("page") int page,
@Param("limit") int limit,
@Param("level") int level);
@Param("limit") int limit);
/**
* 设备管理模块
* 根据条件获取设备查询的总条数
@ -134,8 +133,7 @@ public interface DeviceInstallMapper extends BaseMapper<DeviceInstallEntity> {
@Param("isUse")String isUse,
@Param("isFault")String isFault,
@Param("page") int page,
@Param("limit") int limit,
@Param("level") int level);
@Param("limit") int limit);
//查询设备故障情况
@SelectProvider(type = DeviceInstallProvider.class,method = "getIsFaultCount")
@ -162,7 +160,7 @@ public interface DeviceInstallMapper extends BaseMapper<DeviceInstallEntity> {
//根据通讯地址和设备类型查询对应的设备信息
@ResultMap("rs")
@Select("select top 1 * from device_install where device_addr=#{deviceAddr} and device_type=#{deviceType} and building_id=#{buildingId}")
@Select("select * from device_install where device_addr=#{deviceAddr} and device_type=#{deviceType} and building_id=#{buildingId}")
DeviceInstallEntity selectDevice(@Param("deviceAddr") String deviceAddr,@Param("deviceType") String deviceType,@Param("buildingId") String buildingId);
//查询通讯编号是否存在
@ -253,18 +251,9 @@ public interface DeviceInstallMapper extends BaseMapper<DeviceInstallEntity> {
@Result(column = "device_name", property = "deviceName"),
@Result(column = "id", property = "id")
})
@Select("select * from device_install where building_id=#{buildingId} and device_type=#{deviceType} ")
@Select("select * from device_install where building_id=#{buildingId} and device_type=#{deviceType}")
List<DeviceModel> selectDevices(@Param("buildingId") String buildingId, @Param("deviceType") String deviceType);
//查询设备
@Results({
@Result(column = "device_addr",property = "deviceAddr" ),
@Result(column = "device_name", property = "deviceName"),
@Result(column = "id", property = "id")
})
@Select("select * from device_install where building_id=#{buildingId} and device_type=#{deviceType} and device_name like concat('%',#{deviceName},'时控')")
List<DeviceModel> selectDevicesByOthers(@Param("buildingId") String buildingId, @Param("deviceType") String deviceType, @Param("deviceName") String deviceName);
//修改故障状态
@Update("update device_install set is_fault=#{isFault} where device_addr=#{deviceAddr} and device_type=#{deviceType}")
@ -323,11 +312,11 @@ public interface DeviceInstallMapper extends BaseMapper<DeviceInstallEntity> {
@Select("select seat from device_install where device_type=#{deviceType} and device_addr=#{deviceAddr} and building_id=#{buildingId} ")
String selectSeat(@Param("deviceType") String deviceType,@Param("deviceAddr") String deviceAddr,@Param("buildingId") String buildingId);
@Update("update device_install set deviation_value = #{realValue}-isnull(last_value,0) where device_type = #{deviceType} and building_id = #{buildingId}")
@Update("update device_install set deviation_value = #{dataValue} where device_type = #{deviceType} and building_id = #{buildingId}")
void updateDeviation(@Param("buildingId") Integer buildingId,
@Param("deviceType") String deviceType,
@Param("param") Integer param,
@Param("realValue") String realValue);
@Param("dataValue") String dataValue);
@Select("select isnull(deviation_value,0) from device_install where device_addr = #{deviceAddr} and device_type = #{deviceType} and building_id = #{buildingId}")
Double selectDeviceDeviation(@Param("deviceAddr") String deviceAddr,
@ -343,11 +332,4 @@ public interface DeviceInstallMapper extends BaseMapper<DeviceInstallEntity> {
@Param("lastValue") String strWtLevel,
@Param("deviceType") String deviceType,
@Param("buildingId") String buildingId);
@Select("select top 1 device_addr from device_install where device_type = '热泵' " +
" and is_single_box = 1 " +
" and building_id = #{buildingId}" +
" and device_addr = #{pumpId} ")
String selectSinglePumpId(@Param("buildingId") String buildingId,
@Param("pumpId") String pumpId);
}

304
user-service/src/main/java/com/mh/user/mapper/EnergyMapper.java

@ -230,308 +230,4 @@ public interface EnergyMapper {
SumModel queryEnergySum();
@Select({
"<script>",
"SELECT count(1) FROM (",
" SELECT " +
" cur_date, " +
" sum(use_hot_water) as use_hot_water, " +
" sum(elect_value) as elect_value, " +
" CASE WHEN sum(use_hot_water) = 0 THEN 0 ELSE sum(elect_value)/ sum(use_hot_water) END as elect_water, " +
" sum(check_in_count) as check_in_count, " +
" CASE WHEN sum(check_in_count) = 0 THEN 0 ELSE sum(use_hot_water) / sum(check_in_count) END as per_water, " +
" CASE WHEN sum(check_in_count) = 0 THEN 0 ELSE sum(elect_value)/ sum(check_in_count) END as per_elect , " +
" ROW_NUMBER() OVER(ORDER BY cur_date DESC) AS rn " +
" FROM energy_day",
" WHERE 1=1",
" <if test='buildingIds != null and !buildingIds.isEmpty()'>",
" AND building_id IN",
" <foreach collection='buildingIds' item='id' open='(' separator=',' close=')'>",
" #{id}",
" </foreach>",
" </if>",
" <if test='startDate != null and startDate != \"\"'>",
" AND LEFT(cur_date,10) &gt;= #{startDate}",
" </if>",
" <if test='endDate != null and endDate != \"\"'>",
" AND LEFT(cur_date,10) &lt;= #{endDate}",
" </if>",
" group by cur_date ) T",
"</script>"
})
int getAreaEnergyDayCount(@Param("buildingIds") List<String> buildingIds,
@Param("startDate") String startDate,
@Param("endDate") String endDate,
@Param("page") int page,
@Param("limit") int limit);
@Select({
"<script>",
"SELECT T.cur_date, " +
" T.use_hot_water , " +
" T.elect_value, " +
" T.elect_water, " +
" t.check_in_count , " +
" t.per_water , " +
" t.per_elect , " +
" t.rn, " +
" #{areaName} as building_name FROM (",
" SELECT " +
" cur_date, " +
" sum(use_hot_water) as use_hot_water, " +
" sum(elect_value) as elect_value, " +
" CASE WHEN sum(use_hot_water) = 0 THEN 0 ELSE sum(elect_value)/ sum(use_hot_water) END as elect_water, " +
" sum(check_in_count) as check_in_count, " +
" CASE WHEN sum(check_in_count) = 0 THEN 0 ELSE sum(use_hot_water) / sum(check_in_count) END as per_water, " +
" CASE WHEN sum(check_in_count) = 0 THEN 0 ELSE sum(elect_value)/ sum(check_in_count) END as per_elect , " +
" ROW_NUMBER() OVER(ORDER BY cur_date DESC) AS rn " +
" FROM energy_day",
" WHERE 1=1",
" <if test='buildingIds != null and !buildingIds.isEmpty()'>",
" AND building_id IN",
" <foreach collection='buildingIds' item='id' open='(' separator=',' close=')'>",
" #{id}",
" </foreach>",
" </if>",
" <if test='startDate != null and startDate != \"\"'>",
" AND LEFT(cur_date,10) &gt;= #{startDate}",
" </if>",
" <if test='endDate != null and endDate != \"\"'>",
" AND LEFT(cur_date,10) &lt;= #{endDate}",
" </if>",
" group by cur_date ) T",
"<where>",
" <if test='page != 0 and limit != 0'>",
" T.rn &gt; (#{page}-1)*#{limit} AND T.rn &lt;= #{page}*#{limit}",
" </if>",
"</where>",
"ORDER BY T.cur_date DESC",
"</script>"
})
@ResultMap("rs")
List<EnergyEntity> getAreaEnergyDay(@Param("buildingIds") List<String> buildingIds,
@Param("startDate") String startDate,
@Param("endDate") String endDate,
@Param("page") int page,
@Param("limit") int limit,
@Param("areaName") String areaName);
@Select({
"<script>",
"SELECT count(1) FROM (",
" SELECT " +
" cur_date, " +
" sum(use_hot_water) as use_hot_water, " +
" sum(elect_value) as elect_value, " +
" CASE WHEN sum(use_hot_water) = 0 THEN 0 ELSE sum(elect_value)/ sum(use_hot_water) END as elect_water, " +
" sum(check_in_count) as check_in_count, " +
" CASE WHEN sum(check_in_count) = 0 THEN 0 ELSE sum(use_hot_water) / sum(check_in_count) END as per_water, " +
" CASE WHEN sum(check_in_count) = 0 THEN 0 ELSE sum(elect_value)/ sum(check_in_count) END as per_elect , " +
" ROW_NUMBER() OVER(ORDER BY cur_date DESC) AS rn " +
" FROM energy_month",
" WHERE 1=1",
" <if test='buildingIds != null and !buildingIds.isEmpty()'>",
" AND building_id IN",
" <foreach collection='buildingIds' item='id' open='(' separator=',' close=')'>",
" #{id}",
" </foreach>",
" </if>",
" <if test='startDate != null and startDate != \"\"'>",
" AND LEFT(cur_date,7) &gt;= #{startDate}",
" </if>",
" <if test='endDate != null and endDate != \"\"'>",
" AND LEFT(cur_date,7) &lt;= #{endDate}",
" </if>",
" group by cur_date ) T",
"</script>"
})
int getAreaEnergyMonthCount(@Param("buildingIds") List<String> buildingIds,
@Param("startDate") String startDate,
@Param("endDate") String endDate,
@Param("page") int page,
@Param("limit") int limit);
@Select({
"<script>",
"SELECT T.cur_date, " +
" T.use_hot_water , " +
" T.elect_value, " +
" T.elect_water, " +
" t.check_in_count , " +
" t.per_water , " +
" t.per_elect , " +
" t.rn, " +
" #{areaName} as building_name FROM (",
" SELECT " +
" cur_date, " +
" sum(use_hot_water) as use_hot_water, " +
" sum(elect_value) as elect_value, " +
" CASE WHEN sum(use_hot_water) = 0 THEN 0 ELSE sum(elect_value)/ sum(use_hot_water) END as elect_water, " +
" sum(check_in_count) as check_in_count, " +
" CASE WHEN sum(check_in_count) = 0 THEN 0 ELSE sum(use_hot_water) / sum(check_in_count) END as per_water, " +
" CASE WHEN sum(check_in_count) = 0 THEN 0 ELSE sum(elect_value)/ sum(check_in_count) END as per_elect , " +
" ROW_NUMBER() OVER(ORDER BY cur_date DESC) AS rn " +
" FROM energy_month ",
" WHERE 1=1",
" <if test='buildingIds != null and !buildingIds.isEmpty()'>",
" AND building_id IN",
" <foreach collection='buildingIds' item='id' open='(' separator=',' close=')'>",
" #{id}",
" </foreach>",
" </if>",
" <if test='startDate != null and startDate != \"\"'>",
" AND LEFT(cur_date,7) &gt;= #{startDate}",
" </if>",
" <if test='endDate != null and endDate != \"\"'>",
" AND LEFT(cur_date,7) &lt;= #{endDate}",
" </if>",
" group by cur_date ) T",
"<where>",
" <if test='page != 0 and limit != 0'>",
" T.rn &gt; (#{page}-1)*#{limit} AND T.rn &lt;= #{page}*#{limit}",
" </if>",
"</where>",
"ORDER BY T.cur_date DESC",
"</script>"
})
@ResultMap("rs")
List<EnergyEntity> getAreaEnergyMonth(@Param("buildingIds") List<String> buildingIds,
@Param("startDate") String startDate,
@Param("endDate") String endDate,
@Param("page") int page,
@Param("limit") int limit,
@Param("areaName") String areaName);
@Select({
"<script>",
"SELECT count(1) FROM (",
" SELECT " +
" cur_date, " +
" sum(use_hot_water) as use_hot_water, " +
" sum(elect_value) as elect_value, " +
" CASE WHEN sum(use_hot_water) = 0 THEN 0 ELSE sum(elect_value)/ sum(use_hot_water) END as elect_water, " +
" sum(check_in_count) as check_in_count, " +
" CASE WHEN sum(check_in_count) = 0 THEN 0 ELSE sum(use_hot_water) / sum(check_in_count) END as per_water, " +
" CASE WHEN sum(check_in_count) = 0 THEN 0 ELSE sum(elect_value)/ sum(check_in_count) END as per_elect , " +
" ROW_NUMBER() OVER(ORDER BY cur_date DESC) AS rn " +
" FROM energy_year",
" WHERE 1=1",
" <if test='buildingIds != null and !buildingIds.isEmpty()'>",
" AND building_id IN",
" <foreach collection='buildingIds' item='id' open='(' separator=',' close=')'>",
" #{id}",
" </foreach>",
" </if>",
" <if test='startDate != null and startDate != \"\"'>",
" AND LEFT(cur_date,4) &gt;= #{startDate}",
" </if>",
" <if test='endDate != null and endDate != \"\"'>",
" AND LEFT(cur_date,4) &lt;= #{endDate}",
" </if>",
" group by cur_date ) T",
"</script>"
})
int getAreaEnergyYearCount(@Param("buildingIds") List<String> buildingIds,
@Param("startDate") String startDate,
@Param("endDate") String endDate,
@Param("page") int page,
@Param("limit") int limit);
@Select({
"<script>",
"SELECT T.cur_date, " +
" T.use_hot_water , " +
" T.elect_value, " +
" T.elect_water, " +
" t.check_in_count , " +
" t.per_water , " +
" t.per_elect , " +
" t.rn, " +
" #{areaName} as building_name FROM (",
" SELECT " +
" cur_date, " +
" sum(use_hot_water) as use_hot_water, " +
" sum(elect_value) as elect_value, " +
" CASE WHEN sum(use_hot_water) = 0 THEN 0 ELSE sum(elect_value)/ sum(use_hot_water) END as elect_water, " +
" sum(check_in_count) as check_in_count, " +
" CASE WHEN sum(check_in_count) = 0 THEN 0 ELSE sum(use_hot_water) / sum(check_in_count) END as per_water, " +
" CASE WHEN sum(check_in_count) = 0 THEN 0 ELSE sum(elect_value)/ sum(check_in_count) END as per_elect , " +
" ROW_NUMBER() OVER(ORDER BY cur_date DESC) AS rn " +
" FROM energy_year ",
" WHERE 1=1",
" <if test='buildingIds != null and !buildingIds.isEmpty()'>",
" AND building_id IN",
" <foreach collection='buildingIds' item='id' open='(' separator=',' close=')'>",
" #{id}",
" </foreach>",
" </if>",
" <if test='startDate != null and startDate != \"\"'>",
" AND LEFT(cur_date,4) &gt;= #{startDate}",
" </if>",
" <if test='endDate != null and endDate != \"\"'>",
" AND LEFT(cur_date,4) &lt;= #{endDate}",
" </if>",
" group by cur_date ) T",
"<where>",
" <if test='page != 0 and limit != 0'>",
" T.rn &gt; (#{page}-1)*#{limit} AND T.rn &lt;= #{page}*#{limit}",
" </if>",
"</where>",
"ORDER BY T.cur_date DESC",
"</script>"
})
@ResultMap("rs")
List<EnergyEntity> getAreaEnergyYear(@Param("buildingIds") List<String> buildingIds,
@Param("startDate") String startDate,
@Param("endDate") String endDate,
@Param("page") int page,
@Param("limit") int limit,
@Param("areaName") String areaName);
@Select({
"<script>",
"SELECT T.cur_date, " +
" T.use_hot_water , " +
" T.elect_value, " +
" T.elect_water, " +
" t.check_in_count , " +
" t.per_water , " +
" t.per_elect , " +
" t.rn, " +
" #{areaName} as building_name FROM (",
" SELECT " +
" cur_date, " +
" sum(use_hot_water) as use_hot_water, " +
" sum(elect_value) as elect_value, " +
" CASE WHEN sum(use_hot_water) = 0 THEN 0 ELSE sum(elect_value)/ sum(use_hot_water) END as elect_water, " +
" sum(check_in_count) as check_in_count, " +
" CASE WHEN sum(check_in_count) = 0 THEN 0 ELSE sum(use_hot_water) / sum(check_in_count) END as per_water, " +
" CASE WHEN sum(check_in_count) = 0 THEN 0 ELSE sum(elect_value)/ sum(check_in_count) END as per_elect , " +
" ROW_NUMBER() OVER(ORDER BY cur_date DESC) AS rn " +
" FROM energy_hour ",
" WHERE 1=1",
" <if test='buildingIds != null and !buildingIds.isEmpty()'>",
" AND building_id IN",
" <foreach collection='buildingIds' item='id' open='(' separator=',' close=')'>",
" #{id}",
" </foreach>",
" </if>",
" <if test='curDate != null and curDate != \"\"'>",
" AND LEFT(cur_date,10) = #{curDate}",
" </if>",
" group by cur_date ) T",
"<where>",
" <if test='page != 0 and limit != 0'>",
" T.rn &gt; (#{page}-1)*#{limit} AND T.rn &lt;= #{page}*#{limit}",
" </if>",
"</where>",
"ORDER BY T.cur_date DESC",
"</script>"
})
@ResultMap("rs")
List<EnergyEntity> getAreaEnergyHour(@Param("buildingIds") List<String> buildingIds,
@Param("curDate") String curDate,
@Param("page") int page,
@Param("limit") int limit,
@Param("areaName") String areaName);
}

233
user-service/src/main/java/com/mh/user/mapper/HistoryDataPreMapper.java

@ -1,233 +0,0 @@
package com.mh.user.mapper;
import com.mh.user.dto.EnergyPreEchartDataDTO;
import com.mh.user.dto.EnergyPreTopDataDTO;
import com.mh.user.entity.HistoryDataPre;
import org.apache.ibatis.annotations.*;
import org.springframework.security.core.parameters.P;
import tk.mybatis.mapper.common.BaseMapper;
import java.util.List;
/**
* @author LJF
* @version 1.0
* @project CHWS
* @description 预测历史数据mapper
* @date 2024-05-09 10:01:46
*/
@Mapper
public interface HistoryDataPreMapper extends BaseMapper<HistoryDataPre> {
@Results(id ="rs_train_data",value ={
@Result(column = "env_min_temp", property = "envMinTemp"),
@Result(column = "env_max_temp", property = "envMaxTemp"),
@Result(column = "water_value", property = "waterValue"),
@Result(column = "elect_value", property = "electValue"),
@Result(column = "water_level", property = "waterLevel"),
@Result(column = "people_num", property = "peopleNum")
})
@Select("select env_min_temp, env_max_temp, water_value, elect_value, water_level, people_num from history_data_pre where building_id = #{buildingId} " +
" and env_min_temp > 0 and env_max_temp >0 and water_value > 0 and elect_value > 0 and water_level >0 " +
" order by cur_date ")
List<HistoryDataPre> getTrainData(@Param("buildingId") String buildingId);
@Results(id ="rs_recent_data",value ={
@Result(column = "id",property = "id" ),
@Result(column = "building_id", property = "buildingId"),
@Result(column = "cur_date", property = "curDate"),
@Result(column = "env_min_temp", property = "envMinTemp"),
@Result(column = "env_max_temp", property = "envMaxTemp"),
@Result(column = "water_value", property = "waterValue"),
@Result(column = "elect_value", property = "electValue"),
@Result(column = "water_level", property = "waterLevel"),
@Result(column = "water_value_pre", property = "waterValuePre"),
@Result(column = "elect_value_pre", property = "electValuePre"),
@Result(column = "water_level_pre", property = "waterLevelPre"),
@Result(column = "remark", property = "remark")
})
@Select("select * from history_date_pre where building_id = #{buildingId} and cur_date = #{curDate} order by cur_date ")
List<HistoryDataPre> getRecentData(@Param("buildingId") String buildingId,
@Param("curDate") String curDate);
@Update("update history_data_pre set water_value_pre = #{waterValuePre},elect_value_pre = #{electValuePre},water_level_pre = #{waterLevelPre}," +
" water_value = #{waterValue},elect_value = #{electValue},water_level = #{waterLevel} " +
" where id = #{id} and building_id = #{buildingId}")
void updateById(HistoryDataPre preHistoryData);
@Select("select count(*) from history_data_pre where building_id = #{buildingId} and cur_date = #{curDate} and env_min_temp is not null ")
int selectIsPre(@Param("buildingId") String buildingId,
@Param("curDate") String curDate);
@Results(id ="rs_cur_data",value ={
@Result(column = "id",property = "id" ),
@Result(column = "building_id", property = "buildingId"),
@Result(column = "cur_date", property = "curDate"),
@Result(column = "env_min_temp", property = "envMinTemp"),
@Result(column = "env_max_temp", property = "envMaxTemp"),
@Result(column = "water_value", property = "waterValue"),
@Result(column = "elect_value", property = "electValue"),
@Result(column = "water_level", property = "waterLevel"),
@Result(column = "check_in_count", property = "peopleNum")
})
@Select("select top 1 " +
" convert(date,eds.cur_date) as cur_date, " +
" eds.building_id, " +
" isnull(eds.water_value, " +
" 0) as water_value, " +
" isnull(eds.elect_value, " +
" 0) as elect_value, " +
" isnull(convert(numeric(24, " +
" 2), " +
" t1.water_level), " +
" 0) as water_level," +
" b.check_in_count " +
"from " +
" energy_day_sum eds " +
"left join ( " +
" select " +
" convert(date, " +
" cur_date) as cur_date, " +
" building_id, " +
" avg(isnull(convert(numeric(24, 2), water_level), 0)) as water_level " +
" from " +
" history_data " +
" where " +
" building_id = #{buildingId} " +
" and cur_date = #{curDate} " +
" group by " +
" convert(date, " +
" cur_date), " +
" building_id " +
" ) t1 on " +
" eds.cur_date = t1.cur_date " +
" and eds.building_id = t1.building_id " +
" left join building b " +
" on b.id = eds.building_id " +
"where " +
" eds.building_id != '所有' " +
" and eds.building_id = #{buildingId} " +
" and eds.cur_date = #{curDate} " +
"order by " +
" eds.building_id, " +
" eds.cur_date ")
HistoryDataPre selectCurData(@Param("buildingId") String buildingId,
@Param("curDate") String curDate);
@Insert("insert into history_data_pre(cur_date, building_id, env_min_temp, env_max_temp, water_value, elect_value, water_level, people_num) values(" +
"convert(date,#{curDate}), #{buildingId}, #{envMinTemp}, #{envMaxTemp}, #{waterValue}, #{electValue}, #{waterLevel}, #{peopleNum}" +
")")
void insertData(HistoryDataPre curHistoryData);
@Results(id ="rs_one_data",value ={
@Result(column = "id",property = "id" ),
@Result(column = "building_id", property = "buildingId"),
@Result(column = "cur_date", property = "curDate"),
@Result(column = "env_min_temp", property = "envMinTemp"),
@Result(column = "env_max_temp", property = "envMaxTemp"),
@Result(column = "people_num", property = "peopleNum")
})
@Select("select top 1 id, building_id, cur_date, env_min_temp, env_max_temp, people_num from history_data_pre where building_id = #{buildingId} and cur_date = #{curDate} ")
HistoryDataPre selectOneData(@Param("buildingId") String buildingId,
@Param("curDate") String curDate);
@Results({
@Result(column = "cur_yes_data",property = "curYesData" ),
@Result(column = "yes_data", property = "yesData"),
@Result(column = "pre_yes_data", property = "preYesData"),
@Result(column = "error_data", property = "errorData")
})
@Select("<script>" +
"SELECT " +
" <choose>" +
" <when test='type == \"2\"'>" +
" isnull(t.water_value_pre, 0) as cur_yes_data, " +
" isnull(t1.water_value, 0) as yes_data, " +
" isnull(t1.water_value_pre, 0) as pre_yes_data, " +
" CASE WHEN t1.water_value_pre > 0 THEN CONVERT(decimal(18, 2), ABS(isnull(t1.water_value_pre, 0) - isnull(t1.water_value, 0)) / t1.water_value_pre * 100) ELSE '0' END as error_data" +
" </when>" +
" <when test='type == \"1\"'>" +
" isnull(t.elect_value_pre, 0) as cur_yes_data, " +
" isnull(t1.elect_value, 0) as yes_data, " +
" isnull(t1.elect_value_pre, 0) as pre_yes_data, " +
" CASE WHEN t1.elect_value_pre > 0 THEN CONVERT(decimal(18, 2), ABS(isnull(t1.elect_value_pre, 0) - isnull(t1.elect_value, 0)) / t1.elect_value_pre * 100) ELSE '0' END as error_data" +
" </when>" +
" <when test='type == \"3\"'>" +
" isnull(t.water_level_pre, 0) as cur_yes_data, " +
" isnull(t1.water_level, 0) as yes_data, " +
" isnull(t1.water_level_pre, 0) as pre_yes_data, " +
" CASE WHEN t1.water_level_pre > 0 THEN CONVERT(decimal(18, 2), ABS(isnull(t1.water_level_pre, 0) - isnull(t1.water_level, 0)) / t1.water_level_pre * 100) ELSE '0' END as error_data" +
" </when>" +
" <otherwise>null</otherwise>" +
" </choose>" +
"FROM (" +
" SELECT " +
" building_id, " +
" water_value, " +
" elect_value, " +
" water_level, " +
" water_value_pre, " +
" elect_value_pre, " +
" water_level_pre " +
" FROM history_data_pre " +
" WHERE cur_date = CONVERT(varchar(10), GETDATE(), 120) AND building_id = #{buildingId}" +
") t " +
"JOIN (" +
" SELECT " +
" building_id, " +
" water_value, " +
" elect_value, " +
" water_level, " +
" water_value_pre, " +
" elect_value_pre, " +
" water_level_pre " +
" FROM history_data_pre " +
" WHERE cur_date = CONVERT(varchar(10), DATEADD(day, -1, GETDATE()), 120) AND building_id = #{buildingId}" +
") t1 ON t.building_id = t1.building_id " +
"</script>")
List<EnergyPreTopDataDTO> getTopData(@Param("buildingId") String buildingId, @Param("type") String type);
@Results({
@Result(column = "cur_date",property = "curDate" ),
@Result(column = "cur_data", property = "curData"),
@Result(column = "pre_data", property = "preData"),
@Result(column = "error_data", property = "errorData")
})
@Select("<script>" +
"SELECT " +
" hdp.cur_date, " +
" <choose>" +
" <when test='type == \"2\"'>isnull(hdp.water_value, 0)</when>" +
" <when test='type == \"1\"'>isnull(hdp.elect_value, 0)</when>" +
" <when test='type == \"3\"'>isnull(hdp.water_level, 0)</when>" +
" <otherwise>0</otherwise>" +
" </choose> as cur_data, " +
" <choose>" +
" <when test='type == \"2\"'>isnull(hdp.water_value_pre, 0)</when>" +
" <when test='type == \"1\"'>isnull(hdp.elect_value_pre, 0)</when>" +
" <when test='type == \"3\"'>isnull(hdp.water_level_pre, 0)</when>" +
" <otherwise>0</otherwise>" +
" </choose> as pre_data, " +
" CASE " +
" <when test='type == \"2\"'>" +
" WHEN hdp.water_value_pre > 0 THEN CONVERT(decimal(18, 2), ABS(isnull(hdp.water_value_pre, 0) - isnull(hdp.water_value, 0)) / hdp.water_value_pre * 100) else 0 " +
" </when>" +
" <when test='type == \"1\"'>" +
" WHEN hdp.elect_value_pre > 0 THEN CONVERT(decimal(18, 2), ABS(isnull(hdp.elect_value_pre, 0) - isnull(hdp.elect_value, 0)) / hdp.elect_value_pre * 100) else 0 " +
" </when>" +
" <when test='type == \"3\"'>" +
" WHEN hdp.water_level_pre > 0 THEN CONVERT(decimal(18, 2), ABS(isnull(hdp.water_level_pre, 0) - isnull(hdp.water_level, 0)) / hdp.water_level_pre * 100) else 0 " +
" </when>" +
" END as error_data " +
"FROM history_data_pre hdp " +
"WHERE hdp.building_id = #{buildingId} " +
" AND cur_date BETWEEN #{beginDate} AND #{endDate} " +
"ORDER BY cur_date" +
"</script>")
List<EnergyPreEchartDataDTO> getEnergyPre(@Param("buildingId") String buildingId,
@Param("beginDate") String beginDate,
@Param("endDate") String endDate,
@Param("type") String type);
}

57
user-service/src/main/java/com/mh/user/mapper/KnowledgeDataMapper.java

@ -1,57 +0,0 @@
package com.mh.user.mapper;
import com.mh.user.entity.KnowledgeDataEntity;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @author LJF
* @version 1.0
* @project CHWS
* @description 知识库管理
* @date 2024-06-26 14:21:47
*/
@Mapper
public interface KnowledgeDataMapper {
@Insert("insert into knowledge_data(title,description,content,create_time,status,remark) " +
" values(#{title},#{description},#{content},getDate(),#{status},#{remark})")
void insertKnowledgeData(KnowledgeDataEntity knowledgeData);
@Results({
@Result(column = "id",property = "id" ),
@Result(column = "title", property = "title"),
@Result(column = "description", property = "description"),
@Result(column = "content", property = "content"),
@Result(column = "create_time", property = "createTime"),
@Result(column = "status", property = "status"),
@Result(column = "remark", property = "remark")
})
@Select("select id,title,description,content,create_time,status,remark from knowledge_data order by create_time desc")
List<KnowledgeDataEntity> findPage();
@Update("<script>" +
" update knowledge_data set " +
" <if test='title!=null'> title = #{title} </if>" +
" <if test='description!=null'> , description = #{description} </if>" +
" <if test='content!=null'> , content = #{content} </if>" +
" <if test='createTime!=null'> , create_time = #{createTime} </if>" +
" <if test='status!=null'> , status = #{status} </if>" +
" <if test='remark!=null'> , remark = #{remark} </if>" +
" where id = #{id} " +
"</script>")
void updateData(KnowledgeDataEntity knowledgeData);
@Results({
@Result(column = "id",property = "id" ),
@Result(column = "title", property = "title"),
@Result(column = "description", property = "description"),
@Result(column = "content", property = "content"),
@Result(column = "create_time", property = "createTime"),
@Result(column = "status", property = "status"),
@Result(column = "remark", property = "remark")
})
@Select("select id,title,description,content,create_time,status,remark from knowledge_data where id = #{id} order by create_time desc")
KnowledgeDataEntity getById(@Param("id") Long id);
}

8
user-service/src/main/java/com/mh/user/mapper/MaintainInfoMapper.java

@ -18,8 +18,8 @@ public interface MaintainInfoMapper {
* 维修保养信息
* @param maintainInfoEntity
*/
@Insert("insert into maintain_info(cur_date,building_id,device_type,device_addr,maintain_type,maintain_people,cost,contents, evaluate) values (" +
" getDate(),#{buildingId},#{deviceType},#{deviceAddr},#{maintainType},#{maintainPeople},#{cost},#{contents}, #{evaluate})")
@Insert("insert into maintain_info(cur_date,building_id,device_type,device_addr,maintain_type,maintain_people,cost,contents) values (" +
" getDate(),#{buildingId},#{deviceType},#{deviceAddr},#{maintainType},#{maintainPeople},#{cost},#{contents})")
int saveMaintainInfo(MaintainInfoEntity maintainInfoEntity);
/**
@ -36,7 +36,6 @@ public interface MaintainInfoMapper {
" <if test='maintainPeople!=null'> , maintain_people = #{maintainPeople} </if>" +
" <if test='cost!=null'> , cost = #{cost} </if>" +
" <if test='contents!=null'> , contents = #{contents} </if>" +
" <if test='evaluate!=null'> , evaluate = #{evaluate} </if>" +
" where id = #{id} " +
"</script>")
int updateMaintainInfo(MaintainInfoEntity maintainInfoEntity);
@ -62,8 +61,7 @@ public interface MaintainInfoMapper {
@Result(property="maintainPeople",column="maintain_people"),
@Result(property="id",column="id"),
@Result(property="cost",column="cost"),
@Result(property="contents",column="contents"),
@Result(property="evaluate",column="evaluate")
@Result(property="contents",column="contents")
})
List<MaintainInfoEntity> queryMaintainInfo(@Param("curDate") String curDate,
@Param("buildingId") String buildingId,

147
user-service/src/main/java/com/mh/user/mapper/NowDataMapper.java

@ -10,7 +10,6 @@ import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.StatementType;
import java.util.List;
import java.util.Map;
@Mapper
@ -24,16 +23,16 @@ public interface NowDataMapper {
//修改监控界面实时信息(热泵)
@Update("<script>" +
" update now_data set cur_date=getDate()" +
" <if test='buildingName!=null and buildingName != \"\"'> , building_name = #{buildingName} </if>" +
" <if test='pumpName!=null and pumpName != \"\"'> , pump_name = #{pumpName} </if>" +
" <if test='tempSet!=null and tempSet != \"\"'> , temp_set = #{tempSet} </if>" +
" <if test='waterTemp!=null and waterTemp != \"\"'> , water_temp = #{waterTemp} </if>" +
" <if test='runState!=null and runState != \"\"'> , run_state = #{runState} </if>" +
" <if test='isFault!=null and isFault != \"\"'> , is_fault = #{isFault} </if>" +
" <if test='levelSet!=null and levelSet != \"\"'> , level_set = #{levelSet} </if>" +
" <if test='waterLevel!=null and waterLevel != \"\"'> , water_level = #{waterLevel} </if>" +
" <if test='tankId!=null and tankId != \"\"'> , tank_id = #{tankId} </if>" +
" <if test='tankName!=null and tankName != \"\"'> , tank_name = #{tankName} </if>" +
" <if test='buildingName!=null'> , building_name = #{buildingName} </if>" +
" <if test='pumpName!=null'> , pump_name = #{pumpName} </if>" +
" <if test='tempSet!=null'> , temp_set = #{tempSet} </if>" +
" <if test='waterTemp!=null'> , water_temp = #{waterTemp} </if>" +
" <if test='runState!=null'> , run_state = #{runState} </if>" +
" <if test='isFault!=null'> , is_fault = #{isFault} </if>" +
" <if test='levelSet!=null'> , level_set = #{levelSet} </if>" +
" <if test='waterLevel!=null'> , water_level = #{waterLevel} </if>" +
" <if test='tankId!=null'> , tank_id = #{tankId} </if>" +
" <if test='tankName!=null'> , tank_name = #{tankName} </if>" +
" where building_id = #{buildingId} and pump_id = #{pumpId} " +
"</script>")
void updateNowData(NowDataEntity nowDataEntity);
@ -41,17 +40,17 @@ public interface NowDataMapper {
//修改监控界面实时信息(不包含热泵)
@Update("<script>" +
" update now_data set cur_date=getDate()" +
" <if test='buildingName!=null and buildingName != \"\"'> , building_name = #{buildingName} </if>" +
" <if test='pumpId!=null and pumpId != \"\"'> , pump_id = #{pumpId} </if>" +
" <if test='pumpName!=null and pumpName != \"\"'> , pump_name = #{pumpName} </if>" +
" <if test='tempSet!=null and tempSet != \"\"'> , temp_set = #{tempSet} </if>" +
" <if test='waterTemp!=null and waterTemp != \"\"'> , water_temp = #{waterTemp} </if>" +
" <if test='runState!=null and runState != \"\"'> , run_state = #{runState} </if>" +
" <if test='isFault!=null and isFault != \"\"'> , is_fault = #{isFault} </if>" +
" <if test='levelSet!=null and levelSet != \"\"'> , level_set = #{levelSet} </if>" +
" <if test='waterLevel!=null and waterLevel != \"\"'> , water_level = #{waterLevel} </if>" +
" <if test='tankId!=null and tankId != \"\"'> , tank_id = #{tankId} </if>" +
" <if test='tankName!=null and tankName != \"\"'> , tank_name = #{tankName} </if>" +
" <if test='buildingName!=null'> , building_name = #{buildingName} </if>" +
" <if test='pumpId!=null'> , pump_id = #{pumpId} </if>" +
" <if test='pumpName!=null'> , pump_name = #{pumpName} </if>" +
" <if test='tempSet!=null'> , temp_set = #{tempSet} </if>" +
" <if test='waterTemp!=null'> , water_temp = #{waterTemp} </if>" +
" <if test='runState!=null'> , run_state = #{runState} </if>" +
" <if test='isFault!=null'> , is_fault = #{isFault} </if>" +
" <if test='levelSet!=null'> , level_set = #{levelSet} </if>" +
" <if test='waterLevel!=null'> , water_level = #{waterLevel} </if>" +
" <if test='tankId!=null'> , tank_id = #{tankId} </if>" +
" <if test='tankName!=null'> , tank_name = #{tankName} </if>" +
" where building_id = #{buildingId} " +
"</script>")
void updateNowData2(NowDataEntity nowDataEntity);
@ -66,9 +65,6 @@ public interface NowDataMapper {
@Result(property ="tempSet",column ="temp_set"),
@Result(property="waterTemp",column="water_temp"),
@Result(property ="runState",column ="run_state"),
@Result(property ="upWaterState",column ="up_water_state"),
@Result(property ="useWaterState",column ="use_water_state"),
@Result(property ="backWaterState",column ="back_water_state"),
@Result(property ="isFault",column ="is_fault"),
@Result(property ="levelSet",column ="level_set"),
@Result(property ="waterLevel",column ="water_level"),
@ -146,8 +142,7 @@ public interface NowDataMapper {
@Results({
@Result(property="curDate",column="cur_date"),
@Result(property="buildingID",column="building_id"),
@Result(property="buildingName",column="building_name"),
@Result(property="deviceName",column="device_name")
@Result(property="buildingName",column="building_name")
})
@SelectProvider(type = NowDataProvider.class,method = "queryWaterLevel")
List<WaterLevelEntity> queryWaterLevel(@Param("curDate") String curDate,
@ -244,7 +239,7 @@ public interface NowDataMapper {
//求热泵平均温度
@Select("<script>" +
"select Convert(decimal(18,1),avg(CAST(water_temp as FLOAT))) from now_data where building_id=#{buildingId} and run_state != '离线' " +
"select Convert(decimal(18,1),avg(CAST(water_temp as FLOAT))) from now_data where building_id=#{buildingId} " +
"<if test='temp != null'>" +
" and water_temp >= #{temp} " +
"</if>" +
@ -400,26 +395,20 @@ public interface NowDataMapper {
//按高低区更新water_Level
@Update("update now_data SET now_data.water_Level=#{waterLevel} FROM device_install " +
" where now_data.pump_id =device_install.device_addr AND device_install.seat=#{seat} and now_data.building_id=#{buildingId} " +
" and now_data.building_id = device_install.building_id ")
@Update("update now_data SET now_data.water_Level=#{waterLevel} FROM device_install where now_data.pump_id =device_install.device_addr AND device_install.seat=#{seat} and now_data.building_id=#{buildingId} ")
void nowDataWaterLevel(@Param("waterLevel") String waterLevel,
@Param("seat") String seat,
@Param("buildingId") String buildingId);
//按高低区更新levelSet
@Update("update now_data SET now_data.level_set=#{levelSet} FROM device_install " +
" where now_data.pump_id =device_install.device_addr AND device_install.seat=#{seat} and now_data.building_id=#{buildingId} " +
" and now_data.building_id = device_install.building_id ")
@Update("update now_data SET now_data.level_set=#{levelSet} FROM device_install where now_data.pump_id =device_install.device_addr AND device_install.seat=#{seat} and now_data.building_id=#{buildingId} ")
void nowDataLevelSet(@Param("levelSet") String levelSet,
@Param("seat") String seat,
@Param("buildingId") String buildingId);
//按高低区更新water_Level
@Update("update history_Data SET history_Data.water_Level=#{waterLevel} FROM device_install where history_Data.pump_id =device_install.device_addr AND device_install.seat=#{seat} " +
" and history_Data.building_id=#{buildingId} " +
" and convert(varchar(13),cur_date,121)=left(#{curDate},13)" +
" and history_Data.building_id = device_install.building_id ")
" and history_Data.building_id=#{buildingId} and convert(varchar(13),cur_date,121)=left(#{curDate},13) ")
void historyDataWaterLevel(@Param("waterLevel") String waterLevel,
@Param("seat") String seat,
@Param("buildingId") String buildingId,
@ -427,9 +416,7 @@ public interface NowDataMapper {
//按高低区更新levelSet
@Update("update history_Data SET history_Data.level_set=#{levelSet} FROM device_install where history_Data.pump_id =device_install.device_addr AND device_install.seat=#{seat} " +
" and history_Data.building_id=#{buildingId} " +
" and convert(varchar(13),cur_date,121)=left(#{curDate},13) " +
" and history_Data.building_id = device_install.building_id ")
" and history_Data.building_id=#{buildingId} and convert(varchar(13),cur_date,121)=left(#{curDate},13) ")
void historyDataLevelSet(@Param("levelSet") String levelSet,
@Param("seat") String seat,
@Param("buildingId") String buildingId,
@ -437,84 +424,4 @@ public interface NowDataMapper {
@Select("select count(1) from now_data where pump_name like '%热泵%' ")
int selectPumpCount(@Param("buildingId") String buildingId);
@Update("<script>" +
"update now_data set use_water_state=#{useWater},back_water_state=#{backWater},up_water_state=#{upWater} " +
" where building_id=#{buildingId} " +
"<if test='pumpName != null and pumpName != \"\"'>" +
" and pump_name like ('%'+#{pumpName}+'%') " +
"</if>" +
"</script>")
void updateNowDataByPumpName(@Param("pumpName") String pumpName,
@Param("buildingId") String buildingId,
@Param("useWater") String useWater,
@Param("backWater") String backWater,
@Param("upWater") String upWater);
/**
* 查询对应的钱
* @return
*/
@Select("SELECT " +
" TOP 1 " +
" CASE " +
" WHEN EXISTS ( " +
" SELECT " +
" 1 " +
" FROM " +
" now_data " +
" WHERE " +
" up_water_state = '运行') THEN '运行' " +
" ELSE '不运行' " +
" END AS up_water_state, " +
" CASE " +
" WHEN EXISTS ( " +
" SELECT " +
" 1 " +
" FROM " +
" now_data " +
" WHERE " +
" use_water_state = '运行') THEN '运行' " +
" ELSE '不运行' " +
" END AS use_water_state, " +
" CASE " +
" WHEN EXISTS ( " +
" SELECT " +
" 1 " +
" FROM " +
" now_data " +
" WHERE " +
" back_water_state = '运行') THEN '运行' " +
" ELSE '不运行' " +
" END AS back_water_state " +
"FROM " +
" now_data " +
"where " +
" building_id = #{buildingId} and convert(varchar(10), cur_date, 120) = convert(varchar(10), getdate(), 120) ")
Map<String, Object> selectTopOneState(@Param("buildingId") String buildingId);
@Select("<script>" +
"select Convert(decimal(18,1),max(CAST(water_temp as FLOAT))) from now_data where building_id=#{buildingId} " +
"<if test='temp != null'>" +
" and water_temp >= #{temp} " +
"</if>" +
"</script>")
String selectMaxTemp(@Param("buildingId") String buildingId, @Param("temp") Integer temp);
@Update("update now_data set " +
" pump_name=#{pumpName}, " +
" pump_id = #{pumpId}, " +
" building_id = #{buildingId}" +
" where pump_id=#{oldPumpId} and pump_name=#{oldPumpName} and building_id=#{oldBuildingId} ")
void updatePumpName(@Param("oldPumpId") String oldPumpId,
@Param("oldPumpName") String oldPumpName,
@Param("oldBuildingId") String oldBuildingId,
@Param("pumpId") String pumpId,
@Param("pumpName") String pumpName,
@Param("buildingId") String buildingId,
@Param("buildingName") String buildingName);
@Delete("delete from now_data where pump_id=#{pumpId} and building_id=#{buildingId}")
void deleteNowDataByDeviceAddr(@Param("pumpId") String pumpId,
@Param("buildingId") String buildingId);
}

10
user-service/src/main/java/com/mh/user/mapper/NowPublicDataMapper.java

@ -87,10 +87,7 @@ public interface NowPublicDataMapper {
@Result(property ="singleTemp",column ="single_temp"),
@Result(property ="avgTemp",column ="use_water_temp")
})
@Select("select building_id,building_name," +
" convert(numeric(23,2),use_water_temp)+3 as use_water_temp, " +
" convert(numeric(23,2),single_temp)+3 as single_temp" +
" from now_public_data order by building_id ")
@Select("select building_id,building_name,use_water_temp+3,single_temp+3 from now_public_data order by building_id ")
List<TempModel> queryWtTemp();
//查询单个楼栋水箱平均温度
@ -100,10 +97,7 @@ public interface NowPublicDataMapper {
@Result(property ="singleTemp",column ="single_temp"),
@Result(property ="avgTemp",column ="use_water_temp")
})
@Select("select building_id,building_name," +
" convert(numeric(23,2),use_water_temp)+3 as use_water_temp, " +
" convert(numeric(23,2),single_temp)+3 as single_temp" +
" from now_public_data where building_id=#{buildingId} ")
@Select("select building_id,building_name,use_water_temp,single_temp from now_public_data where building_id=#{buildingId} ")
TempModel queryWtTemp2(@Param("buildingId") String buildingId);
//更新单箱温度

26
user-service/src/main/java/com/mh/user/mapper/provider/BuildingProvider.java

@ -2,20 +2,14 @@ package com.mh.user.mapper.provider;
public class BuildingProvider {
public String queryBuilding(String buildingId, int page, int limit, int level){
public String queryBuilding(String buildingId, int page, int limit){
StringBuffer sql = new StringBuffer("");
sql.append("select * from (" +
" select bd.*,ar.area_name,ROW_NUMBER() over(order by bd.id) as rn from building bd left join area ar on bd.area_id = ar.id " +
" select *,ROW_NUMBER() over(order by id) as rn from building " +
" where 1=1 ");
if (level == 2) {
if (buildingId != null && !buildingId.equals("")) {
sql.append(" AND bd.id = #{buildingId} ");
}
} else if (level == 1) {
if (buildingId != null && !buildingId.equals("")) {
sql.append(" AND ar.id = #{buildingId} ");
}
if (buildingId != null && !buildingId.equals("")){
sql.append(" AND id = #{buildingId} ");
}
if ((page != 0) && (limit != 0)){
sql.append(" ) T where T.rn>(#{page}-1)*#{limit} and T.rn<=#{page}*#{limit}");
@ -26,20 +20,14 @@ public class BuildingProvider {
return sql.toString();
}
public String getCount(String buildingId, int page, int limit, int level){
public String getCount(String buildingId, int page, int limit){
StringBuffer sql = new StringBuffer("");
sql.append("select count(*) from (" +
" select *,ROW_NUMBER() over(order by id) as rn from building " +
" where 1=1 ");
if (level == 2) {
if (buildingId != null && !buildingId.equals("")) {
sql.append(" AND id = #{buildingId} ");
}
} else if (level == 1) {
if (buildingId != null && !buildingId.equals("")) {
sql.append(" AND area_id = #{buildingId} ");
}
if (buildingId != null && !buildingId.equals("")){
sql.append(" AND id = #{buildingId} ");
}
sql.append(" ) T ");

28
user-service/src/main/java/com/mh/user/mapper/provider/DeviceInstallProvider.java

@ -2,19 +2,13 @@ package com.mh.user.mapper.provider;
public class DeviceInstallProvider {
public String queryDevice(String buildingId,String deviceType,String startDate,String endDate,String isOnline,String isUse,String isFault, int page, int limit, int level){
public String queryDevice(String buildingId,String deviceType,String startDate,String endDate,String isOnline,String isUse,String isFault, int page, int limit){
StringBuffer sql = new StringBuffer("");
sql.append("select * from (" +
" select top 1000 *,ROW_NUMBER() over(order by T.sort) as rn from (select top 1000 t1.*,t2.sort from device_install t1 " +
" join building t2 on t1.building_id=t2.id left join area ar on ar.id = t2.area_id where 1=1 ");
if (level == 2) {
if (buildingId != null && !buildingId.equals("")) {
sql.append(" AND t1.building_id = #{buildingId} ");
}
} else if (level == 1) {
if (buildingId != null && !buildingId.equals("")) {
sql.append(" AND ar.id = #{buildingId} ");
}
" join building t2 on t1.building_id=t2.id where 1=1 ");
if (buildingId != null && !buildingId.equals("")){
sql.append(" AND t1.building_id = #{buildingId} ");
}
if (deviceType != null && !deviceType.equals("")){
sql.append(" AND t1.device_type = #{deviceType} ");
@ -40,19 +34,13 @@ public class DeviceInstallProvider {
return sql.toString();
}
public String getCount(String buildingId,String deviceType,String startDate,String endDate,String isOnline,String isUse,String isFault, int page, int limit, int level){
public String getCount(String buildingId,String deviceType,String startDate,String endDate,String isOnline,String isUse,String isFault, int page, int limit){
StringBuffer sql = new StringBuffer("");
sql.append("select count(*) from (" +
" select top 1000 *,ROW_NUMBER() over(order by T.sort) as rn from (select top 1000 t1.*,t2.sort from device_install t1 " +
" join building t2 on t1.building_id=t2.id left join area ar on ar.id = t2.area_id where 1=1 ");
if (level == 2) {
if (buildingId != null && !buildingId.equals("")) {
sql.append(" AND t1.building_id = #{buildingId} ");
}
} else if (level == 1) {
if (buildingId != null && !buildingId.equals("")) {
sql.append(" AND ar.id = #{buildingId} ");
}
" join building t2 on t1.building_id=t2.id where 1=1 ");
if (buildingId != null && !buildingId.equals("")){
sql.append(" AND t1.building_id = #{buildingId} ");
}
if (deviceType != null && !deviceType.equals("")){
sql.append(" AND t1.device_type = #{deviceType} ");

2
user-service/src/main/java/com/mh/user/mapper/provider/EnergyProvider.java

@ -23,7 +23,7 @@ public class EnergyProvider {
if(buildingId.equals("所有")){
if ((page != 0) && (limit != 0)){
sql.append(" )T where T.rn>(#{page}-1)*#{limit} and T.rn<=#{page}*#{limit} order by T.cur_date desc");
} else if (page == 0 || limit == 0){
} else if (page == 0){
sql.append(" )T order by T.cur_date desc");
}
}else{

8
user-service/src/main/java/com/mh/user/mapper/provider/NowDataProvider.java

@ -176,9 +176,7 @@ public class NowDataProvider {
"convert(decimal(8,1),AVG(convert(float,t1.temp02)))as temp02," +
"convert(decimal(8,1),AVG(convert(float,t1.temp06)))as temp06," +
"convert(decimal(8,1),AVG(convert(float,t1.temp08)))as temp08,convert(decimal(8,1),AVG(convert(float,t1.temp11)))as temp11," +
"convert(decimal(8,1),AVG(convert(float,t1.temp13)))as temp13," +
"convert(decimal(8,1),AVG(convert(float,t1.temp14)))as temp14," +
"convert(decimal(8,1),AVG(convert(float,t1.temp15)))as temp15," +
"convert(decimal(8,1),AVG(convert(float,t1.temp13)))as temp13,convert(decimal(8,1),AVG(convert(float,t1.temp15)))as temp15," +
"convert(decimal(8,1),AVG(convert(float,t1.temp16)))as temp16,convert(decimal(8,1),AVG(convert(float,t1.temp17)))as temp17," +
"convert(decimal(8,1),AVG(convert(float,t1.temp18)))as temp18,convert(decimal(8,1),AVG(convert(float,t1.temp19)))as temp19," +
"convert(decimal(8,1),AVG(convert(float,t1.temp20)))as temp20,convert(decimal(8,1),AVG(convert(float,t1.temp21)))as temp21," +
@ -202,9 +200,7 @@ public class NowDataProvider {
"select t1.cur_date,t1.building_id,t2.building_name,t2.sort,convert(decimal(8,1),AVG(convert(float,t1.temp00)))as temp00," +
"convert(decimal(8,1),AVG(convert(float,t1.temp02)))as temp02,convert(decimal(8,1),AVG(convert(float,t1.temp06)))as temp06," +
"convert(decimal(8,1),AVG(convert(float,t1.temp08)))as temp08,convert(decimal(8,1),AVG(convert(float,t1.temp11)))as temp11," +
"convert(decimal(8,1),AVG(convert(float,t1.temp13)))as temp13," +
"convert(decimal(8,1),AVG(convert(float,t1.temp14)))as temp14," +
"convert(decimal(8,1),AVG(convert(float,t1.temp15)))as temp15," +
"convert(decimal(8,1),AVG(convert(float,t1.temp13)))as temp13,convert(decimal(8,1),AVG(convert(float,t1.temp15)))as temp15," +
"convert(decimal(8,1),AVG(convert(float,t1.temp16)))as temp16,convert(decimal(8,1),AVG(convert(float,t1.temp17)))as temp17," +
"convert(decimal(8,1),AVG(convert(float,t1.temp18)))as temp18,convert(decimal(8,1),AVG(convert(float,t1.temp19)))as temp19," +
"convert(decimal(8,1),AVG(convert(float,t1.temp20)))as temp20,convert(decimal(8,1),AVG(convert(float,t1.temp21)))as temp21," +

2
user-service/src/main/java/com/mh/user/mapper/provider/SysLogProvider.java

@ -5,7 +5,7 @@ public class SysLogProvider {
public String findLogs(String userName, int page, int limit){
StringBuffer sql = new StringBuffer("");
sql.append("select * from (" +
" select *,ROW_NUMBER() over(order by create_time desc) as rn from sys_log " +
" select *,ROW_NUMBER() over(order by id) as rn from sys_log " +
" where 1=1 ");
if (userName != null && !userName.equals("")){
sql.append(" AND user_name = #{userName} ");

88
user-service/src/main/java/com/mh/user/model/AreaBuildingTreeModel.java

@ -1,88 +0,0 @@
package com.mh.user.model;
import java.util.List;
import java.util.StringJoiner;
/**
* @author LJF
* @version 1.0
* @project CHWS
* @description 区域楼栋树形结构数据
* @date 2025-09-08 17:28:47
*/
public class AreaBuildingTreeModel {
private Long id;
private String name;
private Long parentId;
private int sort;
/**
* 层级0学校1区域2楼栋
*/
private int level;
private List<AreaBuildingTreeModel> children;
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public List<AreaBuildingTreeModel> getChildren() {
return children;
}
public void setChildren(List<AreaBuildingTreeModel> children) {
this.children = children;
}
@Override
public String toString() {
return new StringJoiner(", ", AreaBuildingTreeModel.class.getSimpleName() + "[", "]")
.add("id=" + id)
.add("name='" + name + "'")
.add("parentId='" + parentId + "'")
.add("children=" + children)
.toString();
}
}

10
user-service/src/main/java/com/mh/user/model/AreaModel.java

@ -1,10 +0,0 @@
package com.mh.user.model;
import lombok.Data;
@Data
public class AreaModel {
private Long areaId;
private String areaName;
}

5
user-service/src/main/java/com/mh/user/model/SerialPortModel.java

@ -20,11 +20,6 @@ public class SerialPortModel {
*/
private String deviceType;
/**
* 设备名称
*/
private String deviceName;
/**
* 操作类型
*/

7
user-service/src/main/java/com/mh/user/serialport/SendAndReceiveByCom.java

@ -37,6 +37,9 @@ public class SendAndReceiveByCom {
DeviceInstallService deviceInstallService = context.getBean(DeviceInstallService.class);
NowDataService nowDataService = context.getBean(NowDataService.class);
BuildingService buildingService = context.getBean(BuildingService.class);
AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
SysParamService sysParamService = context.getBean(SysParamService.class);
public void sendAndReceive(String sort, String thread) {
SerialPort serialPort = null;
@ -59,7 +62,7 @@ public class SendAndReceiveByCom {
log.info("有指令下发退出定时采集");
break;
}
String comName = deviceManageEntityList.get(i).getDataCom().toUpperCase();
String comName = deviceManageEntityList.get(i).getDataCom();
if (StringUtils.isBlank(comName)) {
log.info("-------------串口:" + comName + "不存在!-------------");
continue;
@ -184,7 +187,7 @@ public class SendAndReceiveByCom {
//去掉空格和null
receiveStr = receiveStr.replace("null", "");
receiveStr = receiveStr.replace(" ", "");
log.info("串口" + serialPort.getName() + "接受第" + i + "数据:" + receiveStr + ",大小: " + receiveStr.length());
log.info("串口" + serialPort + "接受第" + i + "数据:" + receiveStr + ",大小: " + receiveStr.length());
//返回值全部变成大写
String receiveData = receiveStr.toUpperCase();
//截取去掉FE

68
user-service/src/main/java/com/mh/user/serialport/SerialPortSingle2.java

@ -18,6 +18,8 @@ import java.io.IOException;
import java.util.Date;
import purejavacomm.SerialPort;
import purejavacomm.SerialPortEvent;
import purejavacomm.SerialPortEventListener;
/**
* @author nxr
@ -31,6 +33,7 @@ public class SerialPortSingle2 {
// 调用service
ApplicationContext context = SpringBeanUtil.getApplicationContext();
AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
DeviceInstallService deviceInstallService = context.getBean(DeviceInstallService.class);
NowDataService nowDataService = context.getBean(NowDataService.class);
BuildingService buildingService = context.getBean(BuildingService.class);
@ -39,9 +42,6 @@ public class SerialPortSingle2 {
SerialPort serialPort = null;
String rtData = "fail";
String comName = deviceCodeParamEntity.getDataCom().toUpperCase();
if (StringUtils.isBlank(comName)) {
return rtData;
}
try {
int baudrate = deviceCodeParamEntity.getBaudrate();
String parity = deviceCodeParamEntity.getParity();
@ -50,42 +50,44 @@ public class SerialPortSingle2 {
} else {
serialPort = SerialTool.openPort(comName, baudrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_EVEN);
}
if (serialPort == null) {
log.info("串口为空,无法进行采集控制");
return "fail";
}
// 创建设备报文
Device device = DeviceFactory.createDevice(deviceCodeParamEntity.getDeviceType());
//向串口发送指令
log.info("-----------------------------单抄向串口" + serialPort.getName() + "发送指令!-----------------------------");
if (serialPort != null) {
//向串口发送指令
log.info("-----------------------------单抄向串口" + serialPort.getName() + "发送指令!-----------------------------");
// String sendStr = SendOrderUtils.getSendStr(deviceCodeParamEntity);
DeviceStrategy strategy = DeviceStrategyFactory.createStrategy(deviceCodeParamEntity.getDeviceType());
if (null == strategy) {
return rtData;
}
device.setStrategy(strategy);
String sendStr = device.createOrders(deviceCodeParamEntity);
DeviceStrategy strategy = DeviceStrategyFactory.createStrategy(deviceCodeParamEntity.getDeviceType());
if (null == strategy) {
return rtData;
}
device.setStrategy(strategy);
String sendStr = device.createOrders(deviceCodeParamEntity);
SerialTool.sendToPort(SerialTool.HexString2Bytes(sendStr), serialPort, sendStr, deviceCodeParamEntity.getDeviceType());
CacheTools.initReceiveMsg(serialPort.getName());
SerialPort finalSerialPort = serialPort;
SerialTool.addListener(serialPortEvent -> {
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
byte[] bytes = SerialTool.readFromPort(finalSerialPort);
if (bytes!= null && bytes.length > 0) {
if (Constant.WEB_FLAG) {
CacheTools.setReceiveMsg(finalSerialPort.getName(), ExchangeStringUtil.printHexString(bytes));
break;
SerialTool.sendToPort(SerialTool.HexString2Bytes(sendStr), serialPort, sendStr, deviceCodeParamEntity.getDeviceType());
CacheTools.initReceiveMsg(serialPort.getName());
SerialPort finalSerialPort = serialPort;
SerialTool.addListener(serialPortEvent -> {
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
byte[] bytes = SerialTool.readFromPort(finalSerialPort);
if (bytes!= null && bytes.length > 0) {
if (Constant.WEB_FLAG) {
CacheTools.setReceiveMsg(finalSerialPort.getName(), ExchangeStringUtil.printHexString(bytes));
break;
}
}
}
} catch (Exception e) {
log.error("单抄串口" + finalSerialPort + "异常,关闭串口", e);
}
} catch (Exception e) {
log.error("单抄串口" + finalSerialPort + "异常,关闭串口", e);
}
}, serialPort);
String receiveStr = "";
}, serialPort);
}
String receiveStr;
if (serialPort == null) {
log.info("串口为空,无法进行采集控制");
return "fail";
}
receiveStr = CacheTools.waitReceiveMsg(serialPort.getName());
//去掉空格和null
if (StringUtils.isBlank(receiveStr)) {
@ -150,6 +152,8 @@ public class SerialPortSingle2 {
// }
rtData = device.analysisReceiveData(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"),
deviceType, registerAddr, brand, buildingId, buildingName, dataStr);
SerialTool.closePort(serialPort);
Thread.sleep(200);
log.info("-----------------------------" + serialPort.getName() + "单抄结束!-----------------------------");
return rtData;
} catch (Exception e) {

15
user-service/src/main/java/com/mh/user/serialport/SerialPortThread.java

@ -18,6 +18,8 @@ public class SerialPortThread implements Runnable{
private String thread = "1";
public static SerialPort serialPort = null;
private String name;
// 调用service
//ApplicationContext context = SpringBeanUtil.getApplicationContext();
private CountDownLatch countDownLatch;
@ -34,14 +36,11 @@ public class SerialPortThread implements Runnable{
}
public void run(){
log.info("创建发送接收数据线程>>>>>>>>>>>>>>" + thread);
log.info("创建发送接收数据线程>>>>>>>>>>>>>>"+thread);
// SerialPortSendReceive2 serial=new SerialPortSendReceive2();
// serial.serialPortSend(name,thread);
SendAndReceiveByCom sendAndReceiveByCom = new SendAndReceiveByCom();
try {
sendAndReceiveByCom.sendAndReceive(name, thread);
} catch (Exception e) {
log.error("串口通信发生异常: ", e);
} finally {
this.countDownLatch.countDown();
}
sendAndReceiveByCom.sendAndReceive(name,thread);
this.countDownLatch.countDown();
}
}

19
user-service/src/main/java/com/mh/user/service/AreaService.java

@ -1,29 +1,10 @@
package com.mh.user.service;
import com.mh.user.entity.AreaEntity;
import com.mh.user.model.AreaModel;
import java.util.List;
public interface AreaService {
List<AreaEntity> findAll();
int saveArea(AreaEntity areaEntity);
int updateArea(AreaEntity areaEntity);
int getCount(String areaId, Integer page, Integer limit);
List<AreaEntity> queryArea(String areaId, Integer page, Integer limit);
List<AreaModel> selectAreaName();
int deleteArea(List<AreaEntity> records);
int deleteAreaById(String id);
int selectByAreaName(String areaName);
AreaEntity selectById(String buildingId);
}

13
user-service/src/main/java/com/mh/user/service/BuildingService.java

@ -1,7 +1,6 @@
package com.mh.user.service;
import com.mh.user.entity.BuildingEntity;
import com.mh.user.model.AreaBuildingTreeModel;
import com.mh.user.model.BuildingModel;
import org.apache.ibatis.annotations.Param;
@ -30,14 +29,14 @@ public interface BuildingService {
* @param limit
* @return
*/
List<BuildingEntity> queryBuilding(String buildingId,int page, int limit, int level);
List<BuildingEntity> queryBuilding(String buildingId,int page, int limit);
/**
* 楼栋管理模块
* 获取楼栋信息查询的总条数
* @return
*/
int getCount(String buildingId,int page, int limit, int level);
int getCount(String buildingId,int page, int limit);
//查询楼栋名称
List<BuildingModel> selectBuildingName();
@ -73,12 +72,4 @@ public interface BuildingService {
int selectPumpCount(String buildingId);
String selectBuildingNameById(String buildingId);
Double queryLowTankHeight(String buildingId);
List<AreaBuildingTreeModel> queryTree();
List<String> queryBuildingIdListByAreaId(String areaId);
int queryCheckInCount(String areaId);
}

2
user-service/src/main/java/com/mh/user/service/ControlSetService.java

@ -6,5 +6,5 @@ public interface ControlSetService {
void saveControlSet(ControlSetEntity controlSetEntity);
ControlSetEntity queryControlSet(String buildingId, String timeName);
ControlSetEntity queryControlSet(String buildingId);
}

13
user-service/src/main/java/com/mh/user/service/DeviceInstallService.java

@ -67,7 +67,7 @@ public interface DeviceInstallService {
* @param limit
* @return
*/
List<DeviceInstallEntity> queryDevice(String buildingId,String deviceType, String startDate, String endDate,String isOnline, String isUse, String isFault, int page, int limit, int level);
List<DeviceInstallEntity> queryDevice(String buildingId,String deviceType, String startDate, String endDate,String isOnline, String isUse, String isFault, int page, int limit);
/**
* 设备管理模块
@ -75,7 +75,7 @@ public interface DeviceInstallService {
*
* @return
*/
int getCount(String buildingId,String deviceType, String startDate, String endDate,String isOnline, String isUse, String isFault, int page, int limit, int level);
int getCount(String buildingId,String deviceType, String startDate, String endDate,String isOnline, String isUse, String isFault, int page, int limit);
//查询设备故障情况
int getIsFaultCount(String isFault,String deviceType);
@ -135,8 +135,6 @@ public interface DeviceInstallService {
//查询设备
List<DeviceModel> selectDevices(String buildingId,String deviceType);
List<DeviceModel> selectDevicesByOthers(String buildingId,String deviceType, String deviceName);
//修改故障状态
void updateDeviceFault(String isFault, String deviceAddr, String deviceType);
@ -185,11 +183,4 @@ public interface DeviceInstallService {
void deleteParamCode(DeviceInstallEntity oldEntity);
void updateLastValueByOther(String addr, String strWtLevel, String deviceType, String buildingId);
/**
* 获取单箱热泵id
* @param buildingId
* @return
*/
String selectSinglePumpId(String buildingId, String pumpId);
}

8
user-service/src/main/java/com/mh/user/service/EnergyService.java

@ -41,7 +41,7 @@ public interface EnergyService {
* @return
*/
List<EnergyEntity> queryEnergy(String buildingId, String startDate,String endDate,
int page, int limit,int type, int level);
int page, int limit,int type);
/**
* 生产信息
@ -49,7 +49,7 @@ public interface EnergyService {
* @return
*/
int getEnergyCount( String buildingId, String startDate,String endDate,
int page, int limit,int type, int level);
int page, int limit,int type);
/**
* 生产信息
@ -66,9 +66,9 @@ public interface EnergyService {
int getDayEnergyCount(String buildingId, String startDate, String endDate, int page, int limit);
//查询小时的用量
List<EnergyEntity> queryHourEnergy(String buildingId,String curDate, int page, int limit, int level);
List<EnergyEntity> queryHourEnergy(String buildingId,String curDate, int page, int limit);
int getHourEnergyCount(String buildingId, String curDate, int level);
int getHourEnergyCount(String buildingId, String curDate);
//查询记录
List<EnergyEntity> queryEnergyBuilding(int page,int limit);

54
user-service/src/main/java/com/mh/user/service/HistoryDataPreService.java

@ -1,54 +0,0 @@
package com.mh.user.service;
import com.mh.user.dto.EnergyPreDTO;
import com.mh.user.dto.EnergyPreEchartDataDTO;
import com.mh.user.dto.EnergyPreTopDataDTO;
import com.mh.user.entity.HistoryDataPre;
import java.util.HashMap;
import java.util.List;
/**
* @author LJF
* @version 1.0
* @project CHWS
* @description 预测历史数据服务类
* @date 2024-05-09 10:02:54
*/
public interface HistoryDataPreService {
/**
* 获取训练数据
* @param buildingId
* @throws Exception
*/
void startTrainData(String buildingId) throws Exception;
/**
* 开始预测数据
* @param buildingId
* @param curDate
* @throws Exception
*/
void startPredictData(String buildingId, String curDate) throws Exception;
/**
* 获取每栋楼的数据
* @param buildingId
* @param curDate
* @return
*/
List<HistoryDataPre> getRecentData(String buildingId, String curDate);
/**
* 获取预测数据
* @param buildingId
* @param beginDate
* @param endDate
* @param type
* @return
*/
List<HashMap<String, Object>> getEnergyPre(String buildingId, String beginDate, String endDate, String type);
List<EnergyPreTopDataDTO> getTopData(String buildingId, String type);
}

23
user-service/src/main/java/com/mh/user/service/KnowledgeDataService.java

@ -1,23 +0,0 @@
package com.mh.user.service;
import com.mh.common.page.PageRequest;
import com.mh.common.page.PageResult;
import com.mh.user.entity.KnowledgeDataEntity;
/**
* @author LJF
* @version 1.0
* @project CHWS
* @description 知识库服务
* @date 2024-06-26 14:32:06
*/
public interface KnowledgeDataService {
void insertKnowledgeData(KnowledgeDataEntity knowledgeData);
PageResult queryKnowledgeData(PageRequest pageRequest);
void updateData(KnowledgeDataEntity knowledgeData);
KnowledgeDataEntity getById(Long id);
}

30
user-service/src/main/java/com/mh/user/service/NowDataService.java

@ -1,13 +1,15 @@
package com.mh.user.service;
import com.mh.user.annotation.SysLogger;
import com.mh.user.entity.*;
import com.mh.common.annotation.SysLogger;
import com.mh.user.entity.NowDataEntity;
import com.mh.user.entity.PumpMinutesEntity;
import com.mh.user.entity.WaterLevelEntity;
import com.mh.user.entity.WaterTempEntity;
import com.mh.user.model.WaterLevelModel;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
public interface NowDataService {
@ -57,7 +59,7 @@ public interface NowDataService {
int waterLevelByTimeCount(String curDate);
//查询每天楼栋水位变化
List<WaterLevelEntity> queryBuildWaterLevel(String curDate, int page, int limit, int level, String buildingID);
List<WaterLevelEntity> queryBuildWaterLevel(String curDate, int page, int limit);
//查询每天楼栋水位变化记录数
int buildWaterLevelCount(String curDate);
@ -65,13 +67,6 @@ public interface NowDataService {
//从监视表查询热泵温度平均值
String selectAve(String buildingId);
/**
* 查询最高温度
* @param buildingId
* @return
*/
String selectMaxTemp(String buildingId);
//求单个热泵温度
String selectSingleTemp(String pumpId,String buildingId);
@ -91,15 +86,15 @@ public interface NowDataService {
void upTempSet2(String buildingId,String tempSet,String pumpID);
//查询每天24小时每个热泵温度变化情况
@SysLogger(optDesc = "查询每天24小时每个热泵温度变化情况",title = "查询每天24小时每个热泵温度变化情况")
@SysLogger
List<WaterTempEntity> queryWaterTemp(String buildingID,String curDate,int page,int limit);
int queryWaterTempCount(String buildingID,String curDate);
//查询每天24小时每个热泵温度变化情况2
List<WaterTempEntity> queryWaterTemp2(String curDate,int page,int limit, int level, String buildingID);
List<WaterTempEntity> queryWaterTemp2(String curDate,int page,int limit);
int queryWaterTempCount2(String curDate, int level, String buildingID);
int queryWaterTempCount2(String curDate);
//生成楼栋温度
void proWaterTemp(String curDate,String buildingID,String pumpID);
@ -140,12 +135,5 @@ public interface NowDataService {
//通过楼栋编号获取最小热泵id号,规定最小热泵号为单箱
String selectMinPumpId(String buildingId);
void updateNowDataByPumpName(String pumpName, String buildingId, String useWater, String backWater, String upWater);
Map<String, Object> selectTopOneState(String buildingId);
void updateNowPublicData(NowPublicDataEntity publicData);
void updatePumpName(String oldPumpId, String oldPumpName, String oldBuildingId, String pumpId, String pumpName, String buildingId, String buildingName);
}

2
user-service/src/main/java/com/mh/user/service/SummaryService.java

@ -11,7 +11,7 @@ public interface SummaryService {
DeviceStateEntity queryDeviceState();
//查询用量汇总比较
EnergySumEntity queryEnergySum(String buildingId,String curDate,int type, int level);
EnergySumEntity queryEnergySum(String buildingId,String curDate,int type);
//查询维修量汇总
MaintainSumEntity queryMaintainSum(String buildingId, String curDate);

8
user-service/src/main/java/com/mh/user/service/impl/AnalysisServiceImpl.java

@ -23,10 +23,8 @@ public class AnalysisServiceImpl implements AnalysisService {
return analysisMapper.queryAnalysisElectYear(curDate,buildingId);
}else if(type==3){
return analysisMapper.queryAnalysisEnergyYear(curDate,buildingId);
}else if (type==4){
}else {
return analysisMapper.queryAnalysisMaintainYear(curDate,buildingId);
} else {
return analysisMapper.queryAnalysisRuntimeYear(curDate,buildingId);
}
}
@ -38,10 +36,8 @@ public class AnalysisServiceImpl implements AnalysisService {
return analysisMapper.queryAnalysisElectMonth(curDate,buildingId);
}else if (type==3){
return analysisMapper.queryAnalysisEnergyMonth(curDate,buildingId);
}else if (type==4){
}else{
return analysisMapper.queryAnalysisMaintainMonth(curDate,buildingId);
} else {
return analysisMapper.queryAnalysisRuntimeMonth(curDate,buildingId);
}
}
}

58
user-service/src/main/java/com/mh/user/service/impl/AreaServiceImpl.java

@ -2,7 +2,6 @@ package com.mh.user.service.impl;
import com.mh.user.entity.AreaEntity;
import com.mh.user.mapper.AreaMapper;
import com.mh.user.model.AreaModel;
import com.mh.user.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -15,61 +14,8 @@ public class AreaServiceImpl implements AreaService {
@Autowired
AreaMapper areaMapper;
public List<AreaEntity> findAll() {
public List<AreaEntity> findAll(){
return areaMapper.findAll();
}
@Override
public int saveArea(AreaEntity areaEntity) {
// 判断区域id和区域名称是否存在
int count = areaMapper.selectCountByAreaIdAndAreaName(areaEntity.getAreaId(), areaEntity.getAreaName());
if (count > 0) {
return 0;
}
return areaMapper.insertArea(areaEntity);
}
@Override
public int updateArea(AreaEntity areaEntity) {
return areaMapper.updateArea(areaEntity);
}
@Override
public int getCount(String areaId, Integer page, Integer limit) {
return areaMapper.getCount(areaId, page, limit);
}
@Override
public List<AreaEntity> queryArea(String areaId, Integer page, Integer limit) {
return areaMapper.queryArea(areaId, page, limit);
}
@Override
public List<AreaModel> selectAreaName() {
return areaMapper.selectAreaName();
}
@Override
public int deleteArea(List<AreaEntity> records) {
for(AreaEntity record:records) {
areaMapper.deleteArea(record.getId().toString());
}
return 0;
}
@Override
public int deleteAreaById(String id) {
return areaMapper.deleteArea(String.valueOf(id));
}
@Override
public int selectByAreaName(String areaName) {
return areaMapper.selectByAreaName(areaName);
}
@Override
public AreaEntity selectById(String buildingId) {
return areaMapper.selectById(buildingId);
return areaMapper.findAll();
}
}

129
user-service/src/main/java/com/mh/user/service/impl/BuildingServiceImpl.java

@ -2,25 +2,14 @@ package com.mh.user.service.impl;
import com.mh.common.http.HttpResult;
import com.mh.user.constants.SysConstants;
import com.mh.user.entity.AreaEntity;
import com.mh.user.entity.BuildingEntity;
import com.mh.user.entity.SysParamEntity;
import com.mh.user.mapper.AreaMapper;
import com.mh.user.mapper.BuildingMapper;
import com.mh.user.model.AreaBuildingTreeModel;
import com.mh.user.model.BuildingModel;
import com.mh.user.service.BuildingService;
import com.mh.user.service.SysParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.Comparator.*;
@Service
public class BuildingServiceImpl implements BuildingService {
@ -28,12 +17,6 @@ public class BuildingServiceImpl implements BuildingService {
@Autowired
private BuildingMapper buildingMapper;
@Autowired
private AreaMapper areaMapper;
@Autowired
private SysParamService sysParamService;
@Override
public int saveBuilding(BuildingEntity buildingEntity) {
return buildingMapper.saveBuilding(buildingEntity);
@ -45,13 +28,13 @@ public class BuildingServiceImpl implements BuildingService {
}
@Override
public List<BuildingEntity> queryBuilding(String buildingId,int page, int limit, int level) {
return buildingMapper.queryBuilding(buildingId,page,limit, level);
public List<BuildingEntity> queryBuilding(String buildingId,int page, int limit) {
return buildingMapper.queryBuilding(buildingId,page,limit);
}
@Override
public int getCount(String buildingId,int page, int limit, int level) {
return buildingMapper.getCount(buildingId,page,limit, level);
public int getCount(String buildingId,int page, int limit) {
return buildingMapper.getCount(buildingId,page,limit);
}
@Override
@ -110,108 +93,4 @@ public class BuildingServiceImpl implements BuildingService {
public String selectBuildingNameById(String buildingId) {
return buildingMapper.selectBuildingNameById(buildingId);
}
@Override
public Double queryLowTankHeight(String buildingId) {
return buildingMapper.queryLowTankHeight(buildingId);
}
@Override
public List<AreaBuildingTreeModel> queryTree() {
// 查询项目名称和id
SysParamEntity sysParamEntity = sysParamService.selectSysParam();
// 获取区域并按sort排序
List<AreaEntity> areaList = areaMapper.findAll().stream()
.sorted(comparing(AreaEntity::getSort))
.collect(Collectors.toList());
// 获取楼栋并按sort排序
List<BuildingEntity> buildingList = buildingMapper.selectAll().stream()
.sorted(comparing(BuildingEntity::getSort))
.collect(Collectors.toList());
// 创建结果列表
List<AreaBuildingTreeModel> treeList = new ArrayList<>();
// 项目名称
AreaBuildingTreeModel projectNode = new AreaBuildingTreeModel();
projectNode.setId(0L);
projectNode.setName(sysParamEntity.getCustomName());
projectNode.setSort(0);
projectNode.setParentId(-1L);
projectNode.setLevel(0);
projectNode.setChildren(new ArrayList<>());
// 判断区域是否有数据
if (areaList.isEmpty()) {
// 没有数据只能遍历楼栋
// 为该区域添加对应的楼栋
List<AreaBuildingTreeModel> buildingNodes = buildingList.stream()
.map(building -> {
AreaBuildingTreeModel buildingNode = new AreaBuildingTreeModel();
buildingNode.setId(building.getId());
buildingNode.setName(building.getBuildingName());
buildingNode.setParentId(0L);
buildingNode.setSort(building.getSort());
buildingNode.setLevel(2);
buildingNode.setChildren(null);
return buildingNode;
})
.collect(Collectors.toList());
projectNode.setChildren(buildingNodes);
treeList.add(projectNode);
} else {
List<AreaBuildingTreeModel> areaTreeList = new ArrayList<>();
// 将区域转换为树节点
for (AreaEntity area : areaList) {
AreaBuildingTreeModel areaNode = new AreaBuildingTreeModel();
areaNode.setId(area.getId());
areaNode.setName(area.getAreaName());
areaNode.setSort(area.getSort());
areaNode.setLevel(1);
areaNode.setParentId(projectNode.getId()); // 修改为projectNode的ID
areaNode.setChildren(new ArrayList<>());
// 为该区域添加对应的楼栋
List<AreaBuildingTreeModel> buildingNodes = buildingList.stream()
.filter(building -> building.getAreaId() != null &&
building.getAreaId().equals(area.getId().toString()))
.map(building -> {
AreaBuildingTreeModel buildingNode = new AreaBuildingTreeModel();
buildingNode.setId(building.getId());
buildingNode.setName(building.getBuildingName());
buildingNode.setParentId(area.getId());
buildingNode.setSort(building.getSort());
buildingNode.setLevel(2);
buildingNode.setChildren(null);
return buildingNode;
})
.collect(Collectors.toList());
areaNode.setChildren(buildingNodes);
areaTreeList.add(areaNode);
}
// 将projectNode添加到树的根节点
projectNode.setChildren(areaTreeList.stream()
.filter(node -> !node.getId().equals(0L)) // 过滤掉projectNode自身
.collect(Collectors.toList()));
}
treeList.add(projectNode);
return treeList;
}
@Override
public List<String> queryBuildingIdListByAreaId(String areaId) {
return buildingMapper.queryBuildingIdListByAreaId(areaId);
}
@Override
public int queryCheckInCount(String areaId) {
return buildingMapper.queryCheckInCount(areaId);
}
}

16
user-service/src/main/java/com/mh/user/service/impl/ControlSetServiceImpl.java

@ -1,6 +1,5 @@
package com.mh.user.service.impl;
import com.mh.common.utils.StringUtils;
import com.mh.user.entity.ControlSetEntity;
import com.mh.user.mapper.ControlSetMapper;
import com.mh.user.service.ControlSetService;
@ -27,17 +26,8 @@ public class ControlSetServiceImpl implements ControlSetService {
}
@Override
public ControlSetEntity queryControlSet(String buildingId, String timeName) {
if (StringUtils.isBlank(timeName)) {
return null;
}
if (timeName.contains("时控")) {
timeName = timeName.replaceAll("时控","");
}
ControlSetEntity controlSetEntity = controlSetMapper.queryControlSet(buildingId, timeName + "时控");
if (null == controlSetEntity) {
controlSetEntity = controlSetMapper.queryControlSet(buildingId, timeName + "温控");
}
return controlSetEntity;
public ControlSetEntity queryControlSet(String buildingId) {
return controlSetMapper.queryControlSet(buildingId);
}
}

285
user-service/src/main/java/com/mh/user/service/impl/DeviceControlServiceImpl.java

@ -11,14 +11,12 @@ import com.mh.user.model.DeviceModel;
import com.mh.user.model.SerialPortModel;
import com.mh.user.serialport.SerialPortSingle2;
import com.mh.user.service.*;
import com.mh.user.utils.ExchangeStringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author LJF
@ -58,17 +56,9 @@ public class DeviceControlServiceImpl implements DeviceControlService {
String deviceType = serialPortModel.getDeviceType();
String buildingId = serialPortModel.getBuildingId();
String param = serialPortModel.getParam();
String deviceName = serialPortModel.getDeviceName();
if (StringUtils.isBlank(deviceAddr)) {
List<DeviceModel> list = null;
if (StringUtils.isBlank(deviceName)) {
list = deviceInstallService.selectDevices(buildingId, deviceType);
// 过滤掉deviceName='补水时控'的值
list = list.stream().filter(val -> !val.getDeviceName().equals("补水时控")).collect(Collectors.toList());
} else {
list = deviceInstallService.selectDevicesByOthers(buildingId, deviceType, deviceName);
}
List<DeviceModel> list = deviceInstallService.selectDevices(buildingId, deviceType);
deviceAddr = list.get(0).getDeviceAddr();
}
if (deviceAddr == null || deviceAddr.length() == 0) {
@ -98,18 +88,9 @@ public class DeviceControlServiceImpl implements DeviceControlService {
// 根据设备类型和参数执行相应的操作
switch (deviceType) {
case "时控":
case "阿丽塔时控":
rtData = handleTimeControl(serialPortModel, deviceCodeParam, controlData, rtData, type, serialPortSingle);
log.info("设备类型为时控==>{}", rtData);
break;
case "温控":
rtData = handleTempControl(serialPortModel, deviceCodeParam, controlData, rtData, type, serialPortSingle);
log.info("设备类型为温控==>{}", rtData);
break;
case "回水温控":
rtData = handleBackTempControl(serialPortModel, deviceCodeParam, controlData, rtData, type, serialPortSingle);
log.info("设备类型为回水温控==>{}", rtData);
break;
case "水位开关":
rtData = handleWaterLevelSwitch(serialPortModel, deviceCodeParam, controlData, rtData, type, serialPortSingle);
log.info("设备类型为水位开关==>{}", rtData);
@ -143,16 +124,10 @@ public class DeviceControlServiceImpl implements DeviceControlService {
// 开启热泵定时
if ("0028".equals(deviceCodeParam.getRegisterAddr())) {
deviceCodeParam.setRegisterAddr("00230001");
}
if ("002A".equals(deviceCodeParam.getRegisterAddr())) {
} if ("002A".equals(deviceCodeParam.getRegisterAddr())) {
deviceCodeParam.setRegisterAddr("00240001");
}
rtData = serialPortSingle.serialPortSend(deviceCodeParam);
} else if (!StringUtils.isBlank(brand) && brand.equals("阿丽塔") && !rtData.equals(Constant.FAIL)) {
// 需要继续发送指令
deviceCodeParam.setFunCode("10");
deviceCodeParam.setRegisterAddr("010C");
rtData = serialPortSingle.serialPortSend(deviceCodeParam);
}
}
}
@ -163,84 +138,6 @@ public class DeviceControlServiceImpl implements DeviceControlService {
}
}
private String handleBackTempControl(SerialPortModel serialPortModel, DeviceCodeParamEntity deviceCodeParam, ControlSetEntity controlData, String rtData, String type, SerialPortSingle2 serialPortSingle) {
switch (deviceCodeParam.getParam()) {
case "controlTemp":
// 目标温度控制值
deviceCodeParam.setRegisterAddr("0001");
break;
case "correctionTemp":
// 误差修正值
deviceCodeParam.setRegisterAddr("000E");
break;
case "curTemp":
// 当前温度
deviceCodeParam.setRegisterAddr("0000");
break;
}
if (Constant.READ.equals(type)) {
deviceCodeParam.setFunCode("03"); //功能码读数据
rtData = serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
} else {
// 只能输入整数
int setValue = new BigDecimal(serialPortModel.getDataValue()).intValue();
deviceCodeParam.setDataValue(String.valueOf(setValue));
deviceCodeParam.setFunCode("06"); //功能码写数据
}
return rtData;
}
private String handleTempControl(SerialPortModel serialPortModel, DeviceCodeParamEntity deviceCodeParam, ControlSetEntity controlData, String rtData, String type, SerialPortSingle2 serialPortSingle) {
switch (deviceCodeParam.getParam()) {
case "upperLimit":
// 上限
deviceCodeParam.setRegisterAddr("0100");
break;
case "lowerLimit":
// 下限
deviceCodeParam.setRegisterAddr("0108");
break;
case "upperUpperLimit":
// 上上限
deviceCodeParam.setRegisterAddr("0110");
break;
case "lowerLowerLimit":
// 下下限
deviceCodeParam.setRegisterAddr("0118");
break;
case "curTemp":
// 当前温度
deviceCodeParam.setRegisterAddr("0000");
break;
case "upperLimitDiff":
// 上限回差
deviceCodeParam.setRegisterAddr("0104");
break;
case "lowerLimitDiff":
// 下限回差
deviceCodeParam.setRegisterAddr("010C");
break;
case "upperUpperLimitDiff":
// 上上限回差
deviceCodeParam.setRegisterAddr("0114");
break;
case "lowerLowerLimitDiff":
// 下下限回差
deviceCodeParam.setRegisterAddr("011C");
break;
}
if (Constant.READ.equals(type)) {
deviceCodeParam.setFunCode("03"); //功能码读数据
} else {
// 传入值,小数点保留一位,需要乘以10倍
int setValue = new BigDecimal(serialPortModel.getDataValue()).multiply(new BigDecimal(10)).intValue();
deviceCodeParam.setDataValue(String.valueOf(setValue));
deviceCodeParam.setFunCode("10"); //功能码写数据
}
rtData = serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
return rtData;
}
private String handleElectricMeter(SerialPortModel serialPortModel, DeviceCodeParamEntity deviceCodeParam, ControlSetEntity controlData, String rtData, String type, SerialPortSingle2 serialPortSingle) {
rtData = serialPortSingle.serialPortSend(deviceCodeParam);
return rtData;
@ -249,7 +146,7 @@ public class DeviceControlServiceImpl implements DeviceControlService {
private String handleWaterMeter(SerialPortModel serialPortModel, DeviceCodeParamEntity deviceCodeParam, ControlSetEntity controlData, String rtData, String type, SerialPortSingle2 serialPortSingle) {
rtData = serialPortSingle.serialPortSend(deviceCodeParam);
// 要添加校准值
Double deviationValue = deviceInstallService.selectDeviceDeviation(deviceCodeParam.getDeviceAddr(), deviceCodeParam.getDeviceType(), deviceCodeParam.getBuildingId());
Double deviationValue = deviceInstallService.selectDeviceDeviation(deviceCodeParam.getDeviceAddr(),deviceCodeParam.getDeviceType(), deviceCodeParam.getBuildingId());
if (null != deviationValue && !StringUtils.isBlank(rtData) && !"fail".equals(rtData)) {
rtData = new BigDecimal(rtData).add(BigDecimal.valueOf(deviationValue)).toString();
}
@ -318,95 +215,25 @@ public class DeviceControlServiceImpl implements DeviceControlService {
return rtData;
}
private String handleTimeControl(SerialPortModel serialPortModel, DeviceCodeParamEntity deviceCodeParam,
ControlSetEntity controlData, String rtData, String type, SerialPortSingle2 serialPortSingle) {
if ("阿丽塔".equals(deviceCodeParam.getBrand())) {
rtData = handleAlitaTimeControl(serialPortModel, deviceCodeParam, type, serialPortSingle);
} else {
rtData = handleDefaultTimeControl(serialPortModel, deviceCodeParam, controlData, rtData, type, serialPortSingle);
}
return rtData;
}
private String handleAlitaTimeControl(SerialPortModel serialPortModel, DeviceCodeParamEntity deviceCodeParam, String type, SerialPortSingle2 serialPortSingle) {
// 设置值前面两位是场景选择,_隔开,后面是传入实际操作值
String[] split = serialPortModel.getDataValue().split("_");
if (split.length < 1) {
return Constant.FAIL;
}
// 场景
int scene = Integer.parseInt(split[0]);
if (Constant.WRITE.equals(type)) {
// 实际操作值
deviceCodeParam.setDataValue(split[1]);
serialPortModel.setDataValue(split[1]);
}
// 根据读写类型设置功能码
deviceCodeParam.setFunCode(Constant.READ.equals(type) ? "03" : "06");
// 根据参数类型设置寄存器地址
String registerStr = "";
switch (deviceCodeParam.getParam()) {
case "switching":
// 开关动作
registerStr = ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex(String.valueOf(64 + (scene - 1) * 6)), 4);
deviceCodeParam.setRegisterSize(1);
break;
case "timeSet":
// 开关时间设置
registerStr = ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex(String.valueOf(65 + (scene - 1) * 6)), 4);
deviceCodeParam.setRegisterSize(2);
if (Constant.WRITE.equals(type)) {
deviceCodeParam.setFunCode("10");
}
break;
case "channelSet":
// 多路设置
registerStr = ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex(String.valueOf(68 + (scene - 1) * 6)), 4);
deviceCodeParam.setRegisterSize(2);
if (Constant.WRITE.equals(type)) {
deviceCodeParam.setFunCode("10");
}
break;
case "weekSet":
// 星期设置
registerStr = ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex(String.valueOf(67 + (scene - 1) * 6)), 4);
if (Constant.WRITE.equals(type)) {
String dataValue = ExchangeStringUtil.addZeroForNum(deviceCodeParam.getDataValue(), 8);
dataValue = ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.parseByte2HexStr(dataValue), 4);
dataValue = ExchangeStringUtil.hexToDec(dataValue);
deviceCodeParam.setDataValue(dataValue);
serialPortModel.setDataValue(dataValue);
}
deviceCodeParam.setRegisterSize(1);
break;
case "dateCalibrationSet":
// 时间设置
int registerValue = Constant.READ.equals(type) ? 16 : 264;
deviceCodeParam.setRegisterSize(7);
registerStr = ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex(String.valueOf(registerValue)), 4);
if (Constant.WRITE.equals(type)) {
deviceCodeParam.setFunCode("10");
}
break;
default:
return Constant.FAIL;
}
deviceCodeParam.setRegisterAddr(registerStr);
return serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
}
private String handleDefaultTimeControl(SerialPortModel serialPortModel, DeviceCodeParamEntity deviceCodeParam,
ControlSetEntity controlData, String rtData, String type, SerialPortSingle2 serialPortSingle) {
private String handleTimeControl(SerialPortModel serialPortModel, DeviceCodeParamEntity deviceCodeParam, ControlSetEntity controlData, String rtData, String type, SerialPortSingle2 serialPortSingle) {
String time = serialPortModel.getDataValue();
if (Constant.READ.equals(type)) {
deviceCodeParam.setFunCode("03"); //功能码读数据
setRegisterAddressForRead(deviceCodeParam);
switch (deviceCodeParam.getParam()) {
case "L1":
deviceCodeParam.setRegisterAddr("0009"); //寄存器地址,L3路,L1(0009),L2(000D)
break;
case "L2":
deviceCodeParam.setRegisterAddr("000D");
break;
case "L3":
deviceCodeParam.setRegisterAddr("0011");
break;
case "checkTime":
// 时控校准时间读取
deviceCodeParam.setRegisterAddr("0000");
break;
}
rtData = serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
time = rtData;
} else {
@ -415,72 +242,37 @@ public class DeviceControlServiceImpl implements DeviceControlService {
}
deviceCodeParam.setFunCode("10"); //功能码写数据
}
processTimeData(time, deviceCodeParam, controlData);
controlSetService.saveControlSet(controlData); //保存设置内容
return rtData;
}
private void setRegisterAddressForRead(DeviceCodeParamEntity deviceCodeParam) {
switch (deviceCodeParam.getParam()) {
case "L1":
deviceCodeParam.setRegisterAddr("0009"); //寄存器地址,L3路,L1(0009),L2(000D)
break;
case "L2":
deviceCodeParam.setRegisterAddr("000D");
break;
case "L3":
deviceCodeParam.setRegisterAddr("0011");
break;
case "checkTime":
// 时控校准时间读取
deviceCodeParam.setRegisterAddr("0000");
break;
}
}
private void processTimeData(String time, DeviceCodeParamEntity deviceCodeParam, ControlSetEntity controlData) {
if (time != null && time.length() == 16) {
if (time.length() == 16) {
//时段1 HHmmHHmm
String statTime1 = time.substring(0, 2) + ":" + time.substring(2, 4); //HH:mm
String closeTime1 = time.substring(4, 6) + ":" + time.substring(6, 8); //HH:mm
//时段2
String statTime2 = time.substring(8, 10) + ":" + time.substring(10, 12);
String closeTime2 = time.substring(12, 14) + ":" + time.substring(14, 16);
setTimeDataForControl(deviceCodeParam, controlData, statTime1, closeTime1, statTime2, closeTime2);
}
}
private void setTimeDataForControl(DeviceCodeParamEntity deviceCodeParam, ControlSetEntity controlData,
String statTime1, String closeTime1, String statTime2, String closeTime2) {
switch (deviceCodeParam.getParam()) {
case "L1":
if ("L1".equals(deviceCodeParam.getParam())) {
deviceCodeParam.setRegisterAddr("0009"); //寄存器地址,L3路,L1(0009),L2(000D)
controlData.setUseStartTime1(statTime1);
controlData.setUseCloseTime1(closeTime1);
controlData.setUseStartTime2(statTime2);
controlData.setUseCloseTime2(closeTime2);
break;
case "L2":
} else if ("L2".equals(deviceCodeParam.getParam())) {
deviceCodeParam.setRegisterAddr("000D");
controlData.setUseStartTime3(statTime1);
controlData.setUseCloseTime3(closeTime1);
controlData.setUseStartTime4(statTime2);
controlData.setUseCloseTime4(closeTime2);
break;
case "L3":
} else {
deviceCodeParam.setRegisterAddr("0011");
controlData.setUseStartTime5(statTime1);
controlData.setUseCloseTime5(closeTime1);
controlData.setUseStartTime6(statTime2);
controlData.setUseCloseTime6(closeTime2);
break;
}
}
controlSetService.saveControlSet(controlData); //保存设置内容
return rtData;
}
private String handleHotPump(SerialPortModel serialPortModel, DeviceCodeParamEntity deviceCodeParam, ControlSetEntity controlData, String rtData, String type, SerialPortSingle2 serialPortSingle) {
//设置热泵实体对象
PumpSetEntity pumpData = new PumpSetEntity();
@ -494,8 +286,6 @@ public class DeviceControlServiceImpl implements DeviceControlService {
deviceCodeParam.setRegisterAddr("0642"); //寄存器地址
} else if ("瑞星".equals(deviceCodeParam.getBrand())) {
deviceCodeParam.setRegisterAddr("000A"); //寄存器地址
} else if ("海尔".equals(deviceCodeParam.getBrand())) {
deviceCodeParam.setRegisterAddr(ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex("20003"), 4));
} else {
deviceCodeParam.setRegisterAddr("0003"); //寄存器地址
}
@ -513,9 +303,6 @@ public class DeviceControlServiceImpl implements DeviceControlService {
} else if (deviceCodeParam.getBrand().equals("瑞星")) {
deviceCodeParam.setRegisterAddr("000A"); //寄存器地址
deviceCodeParam.setFunCode("10"); //功能码写数据
} else if ("海尔".equals(deviceCodeParam.getBrand())) {
deviceCodeParam.setRegisterAddr(ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex("20003"), 4)); //寄存器地址
deviceCodeParam.setFunCode("06"); //功能码写数据
} else {
deviceCodeParam.setRegisterAddr("0003"); //寄存器地址
deviceCodeParam.setFunCode("06"); //功能码写数据
@ -552,15 +339,6 @@ public class DeviceControlServiceImpl implements DeviceControlService {
if (rtData.length() == 8) {
String statTime = rtData.substring(0, 2) + ":" + rtData.substring(2, 4);
String closeTime = rtData.substring(4, 6) + ":" + rtData.substring(6, 8);
if ("美的".equals(deviceCodeParam.getBrand())) {
String convertData = ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.hexToDec(rtData.substring(0, 2)), 2)
+ ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.hexToDec(rtData.substring(2, 4)), 2)
+ ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.hexToDec(rtData.substring(4, 6)), 2)
+ ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.hexToDec(rtData.substring(6, 8)), 2);
statTime = convertData.substring(0, 2) + ":" + convertData.substring(2, 4);
closeTime = convertData.substring(4, 6) + ":" + convertData.substring(6, 8);
rtData = convertData;
}
if ("时段1".equals(deviceCodeParam.getParam())) {
pumpData.setStartTime1(statTime);
pumpData.setCloseTime1(closeTime);
@ -579,8 +357,6 @@ public class DeviceControlServiceImpl implements DeviceControlService {
deviceCodeParam.setRegisterAddr("0007"); //寄存器地址
} else if ("瑞星".equals(deviceCodeParam.getBrand())) {
deviceCodeParam.setRegisterAddr("0046"); //寄存器地址
} else if ("海尔".equals(deviceCodeParam.getBrand())) {
deviceCodeParam.setRegisterAddr(ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex("20026"), 4));
} else {
deviceCodeParam.setRegisterAddr("0064"); //寄存器地址
}
@ -596,8 +372,6 @@ public class DeviceControlServiceImpl implements DeviceControlService {
deviceCodeParam.setRegisterAddr("0641"); //寄存器地址
} else if ("瑞星".equals(deviceCodeParam.getBrand())) {
deviceCodeParam.setRegisterAddr("0001");
} else if ("海尔".equals(deviceCodeParam.getBrand())) {
deviceCodeParam.setRegisterAddr(ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex("20001"), 4));
} else {
deviceCodeParam.setRegisterAddr("0BBD"); //寄存器地址
}
@ -611,13 +385,6 @@ public class DeviceControlServiceImpl implements DeviceControlService {
} else {
deviceCodeParam.setRegisterAddr("00240000"); //寄存器地址
}
} else if ("startOrStop".equals(deviceCodeParam.getParam())) {
deviceCodeParam.setFunCode("06"); //功能码读数据
if ("瑞星".equals(deviceCodeParam.getBrand())) {
deviceCodeParam.setRegisterAddr("0001" + ExchangeStringUtil.addZeroForNum(deviceCodeParam.getDataValue(), 4));
} else if ("海尔".equals(deviceCodeParam.getBrand())) {
deviceCodeParam.setRegisterAddr(ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex("20001"), 4) + ExchangeStringUtil.addZeroForNum(deviceCodeParam.getDataValue(), 4));
}
}
return rtData;
}

141
user-service/src/main/java/com/mh/user/service/impl/DeviceInstallServiceImpl.java

@ -6,12 +6,10 @@ import com.mh.user.entity.DeviceInstallTempEntity;
import com.mh.user.entity.UploadDeviceInstallEntity;
import com.mh.user.mapper.DeviceCodeParamMapper;
import com.mh.user.mapper.DeviceInstallMapper;
import com.mh.user.mapper.NowDataMapper;
import com.mh.user.model.DeviceModel;
import com.mh.user.service.BuildingService;
import com.mh.user.service.DeviceInstallService;
import com.mh.user.utils.CacheUtil;
import com.mh.user.utils.ExchangeStringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
@ -35,42 +33,30 @@ public class DeviceInstallServiceImpl implements DeviceInstallService {
@Autowired
private DeviceCodeParamMapper deviceCodeParamMapper;
@Autowired
private NowDataMapper nowDataMapper;
@Override
public int saveDevice(DeviceInstallEntity deviceInstallEntity) {
String buildingName = buildingService.selectBuildingNameById(deviceInstallEntity.getBuildingId());
deviceInstallEntity.setBuildingName(buildingName);
if ("电表".equalsIgnoreCase(deviceInstallEntity.getDeviceType())) {
// 000005500773
deviceInstallEntity.setDeviceAddr(ExchangeStringUtil.addZeroForNum(deviceInstallEntity.getDeviceAddr(), 12));
} else if ("水表".equalsIgnoreCase(deviceInstallEntity.getDeviceType())
&& deviceInstallEntity.getBrand().contains("美柯")) {
// 00000086058863
deviceInstallEntity.setDeviceAddr(ExchangeStringUtil.addZeroForNum(deviceInstallEntity.getDeviceAddr(), 14));
}
this.createParamCode(deviceInstallEntity);
return deviceInstallMapper.saveDevice(deviceInstallEntity);
}
/**
* 生成采集信息内容
*
* @param deviceInstallEntity
*/
@Override
public void createParamCode(DeviceInstallEntity deviceInstallEntity) {
DeviceCodeParamEntity deviceCodeParamEntity = new DeviceCodeParamEntity();
BeanUtils.copyProperties(deviceInstallEntity, deviceCodeParamEntity);
BeanUtils.copyProperties(deviceInstallEntity,deviceCodeParamEntity);
deviceCodeParamEntity.setBaudrate(deviceInstallEntity.getBaudRate());
deviceCodeParamEntity.setThread(deviceInstallEntity.getDataCom().toLowerCase().replace("com", ""));
deviceCodeParamEntity.setThread(deviceInstallEntity.getDataCom().toLowerCase().replace("com",""));
// 顺便生成采集信息
switch (deviceInstallEntity.getDeviceType()) {
case "压变":
case "温度变送器":
case "温控":
case "回水温控":
deviceCodeParamMapper.insertDeviceCodeParamList(Collections.singletonList(deviceCodeParamEntity));
break;
case "电表":
@ -123,7 +109,7 @@ public class DeviceInstallServiceImpl implements DeviceInstallService {
deviceCodeParamEntity.setRegisterAddr("000B"); //故障状态
deviceCodeParamEntity.setFunCode("03");
deviceCodeParamMapper.insertDeviceCodeParamList(Collections.singletonList(deviceCodeParamEntity));
break;
break;
case "美的2":
// 插入device_code_param表
deviceCodeParamEntity.setRegisterAddr("0064"); //实际水温
@ -166,27 +152,6 @@ public class DeviceInstallServiceImpl implements DeviceInstallService {
deviceCodeParamEntity.setFunCode("03");
deviceCodeParamMapper.insertDeviceCodeParamList(Collections.singletonList(deviceCodeParamEntity));
break;
case "海尔":
// 插入device_code_param表
deviceCodeParamEntity.setRegisterAddr(ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.IntToHex(20026), 4)); //实际水温
deviceCodeParamEntity.setFunCode("03");
deviceCodeParamMapper.insertDeviceCodeParamList(Collections.singletonList(deviceCodeParamEntity));
// 插入device_code_param1表
deviceCodeParamEntity.setRegisterAddr(ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.IntToHex(20001), 4)); //运行状态
deviceCodeParamEntity.setFunCode("03");
deviceCodeParamMapper.insertDeviceCodeParamList2(Collections.singletonList(deviceCodeParamEntity));
// 插入device_code_param2表
deviceCodeParamEntity.setRegisterAddr(ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.IntToHex(20003), 4)); //设定温度
deviceCodeParamEntity.setFunCode("03");
deviceCodeParamMapper.insertDeviceCodeParamList(Collections.singletonList(deviceCodeParamEntity));
// 插入device_code_param2表
deviceCodeParamEntity.setRegisterAddr(ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.IntToHex(20041), 4)); //故障状态
deviceCodeParamEntity.setFunCode("03");
deviceCodeParamMapper.insertDeviceCodeParamList(Collections.singletonList(deviceCodeParamEntity));
break;
default:
break;
}
@ -205,12 +170,12 @@ public class DeviceInstallServiceImpl implements DeviceInstallService {
@Override
public void updateLastValue(Long id, String lastValue, Date lastDate) {
deviceInstallMapper.updateLastValue(id, lastValue, lastDate);
deviceInstallMapper.updateLastValue(id,lastValue,lastDate);
}
@Override
public List<DeviceInstallEntity> getAllDevice(int page, int limit) {
return deviceInstallMapper.getAllDevice(page, limit);
return deviceInstallMapper.getAllDevice(page,limit);
}
@Override
@ -230,57 +195,57 @@ public class DeviceInstallServiceImpl implements DeviceInstallService {
// 查询所有启用的设备
@Override
public int getAllCount() {
public int getAllCount(){
return deviceInstallMapper.getAllCount();
}
@Override
public List<DeviceInstallEntity> queryDevice(String buildingId, String deviceType, String startDate, String endDate, String isOnline, String isUse, String isFault, int page, int limit, int level) {
return deviceInstallMapper.queryDevice(buildingId, deviceType, startDate, endDate, isOnline, isUse, isFault, page, limit, level);
public List<DeviceInstallEntity> queryDevice(String buildingId,String deviceType, String startDate, String endDate,String isOnline, String isUse,String isFault,int page, int limit) {
return deviceInstallMapper.queryDevice(buildingId,deviceType,startDate, endDate,isOnline,isUse, isFault,page, limit);
}
@Override
public int getCount(String buildingId, String deviceType, String startDate, String endDate, String isOnline, String isUse, String isFault, int page, int limit, int level) {
return deviceInstallMapper.getCount(buildingId, deviceType, startDate, endDate, isOnline, isUse, isFault, page, limit, level);
public int getCount(String buildingId,String deviceType, String startDate, String endDate,String isOnline, String isUse, String isFault, int page, int limit) {
return deviceInstallMapper.getCount(buildingId,deviceType, startDate, endDate,isOnline,isUse, isFault, page, limit);
}
//查询设备故障情况
@Override
public int getIsFaultCount(String isFault, String deviceType) {
return deviceInstallMapper.getIsFaultCount(isFault, deviceType);
public int getIsFaultCount(String isFault,String deviceType){
return deviceInstallMapper.getIsFaultCount(isFault,deviceType);
}
//查询设备在线情况
@Override
public int getIsOnlineCount(String isOnline, String deviceType) {
return deviceInstallMapper.getIsOnlineCount(isOnline, deviceType);
public int getIsOnlineCount(String isOnline,String deviceType){
return deviceInstallMapper.getIsOnlineCount(isOnline,deviceType);
}
@Override
public void updateOnline(String deviceAddr, String deviceType, String buildingId, String isOnline) {
deviceInstallMapper.updateOnline(deviceAddr, deviceType, buildingId, isOnline);
public void updateOnline(String deviceAddr, String deviceType,String buildingId,String isOnline) {
deviceInstallMapper.updateOnline(deviceAddr,deviceType,buildingId,isOnline);
}
@Override
public void updateNotOnline(String deviceAddr, String deviceType, String buildingId, String isOnline) {
deviceInstallMapper.updateNotOnline(deviceAddr, deviceType, buildingId, isOnline);
public void updateNotOnline(String deviceAddr, String deviceType,String buildingId,String isOnline) {
deviceInstallMapper.updateNotOnline(deviceAddr,deviceType,buildingId,isOnline);
}
//根据通讯地址和设备类型查询对应的设备信息
@Override
public DeviceInstallEntity selectDevice(String deviceAddr, String deviceType, String buildingId) {
return deviceInstallMapper.selectDevice(deviceAddr, deviceType, buildingId);
public DeviceInstallEntity selectDevice(String deviceAddr, String deviceType,String buildingId) {
return deviceInstallMapper.selectDevice(deviceAddr,deviceType,buildingId);
}
@Override
public int selectDeviceCount(String deviceAddr, String deviceType) {
return deviceInstallMapper.selectDeviceCount(deviceAddr, deviceType);
return deviceInstallMapper.selectDeviceCount(deviceAddr,deviceType);
}
@Override
public int deleteDevice(List<DeviceInstallEntity> records) {
for (DeviceInstallEntity record : records) {
// deviceInstallMapper.deleteDevice(record.getId().toString());
for(DeviceInstallEntity record:records) {
deviceInstallMapper.deleteDevice(record.getId().toString());
}
return 0;
}
@ -291,10 +256,6 @@ public class DeviceInstallServiceImpl implements DeviceInstallService {
DeviceInstallEntity oldEntity = deviceInstallMapper.selectDeviceById(Long.valueOf(id));
// 删除全部的device_code_param值
this.deleteParamCode(oldEntity);
if (oldEntity.getDeviceType().equals("热泵")) {
// 删除now_data表数据
nowDataMapper.deleteNowDataByDeviceAddr(oldEntity.getDeviceAddr(), oldEntity.getBuildingId());
}
return deviceInstallMapper.deleteDevice(id);
}
@ -307,31 +268,27 @@ public class DeviceInstallServiceImpl implements DeviceInstallService {
@Override
public void insertDevice_install_temp(UploadDeviceInstallEntity uploadDeviceInstallEntity) {
String deviceAddr = uploadDeviceInstallEntity.getDeviceAddr();
String deviceName = uploadDeviceInstallEntity.getDeviceName();
String deviceType = uploadDeviceInstallEntity.getDeviceType();
int baudRate = uploadDeviceInstallEntity.getBaudRate();
String dataCom = uploadDeviceInstallEntity.getDataCom();
double ratio = uploadDeviceInstallEntity.getRatio();
String buildingId = uploadDeviceInstallEntity.getBuildingId();
String rowId = uploadDeviceInstallEntity.getRowId();
String deviceName = uploadDeviceInstallEntity.getDeviceName();
String deviceType = uploadDeviceInstallEntity.getDeviceType();
int baudRate = uploadDeviceInstallEntity.getBaudRate();
String dataCom = uploadDeviceInstallEntity.getDataCom();
double ratio = uploadDeviceInstallEntity.getRatio();
String buildingId = uploadDeviceInstallEntity.getBuildingId();
String rowId = uploadDeviceInstallEntity.getRowId();
deviceInstallMapper.insertDevice_install_temp(deviceAddr, deviceName, deviceType, baudRate, dataCom, ratio, buildingId, rowId);
}
// 查询Excel导入的数据
@Override
public List<DeviceInstallTempEntity> queryExcelDevices() {
public List<DeviceInstallTempEntity> queryExcelDevices(){
return deviceInstallMapper.queryExcelDevices();
}
;
};
// 查询Excel导入的数据的记录数
@Override
public int queryExcelDevicesCount() {
public int queryExcelDevicesCount(){
return deviceInstallMapper.queryExcelDevicesCount();
}
;
};
// 在导入中的数据有重复
@Override
@ -340,13 +297,13 @@ public class DeviceInstallServiceImpl implements DeviceInstallService {
}
/**
* @throws
* @author nxr
* @title
* @description 判断导入资料数据的合法性
* @updateTime 2022-06-19
* @throws
*/
public void updateDevice_install_temp() {
public void updateDevice_install_temp(){
//判断通讯地址,在导入中的数据有重复
deviceInstallMapper.updateDevice_install_temp__multiple();
}
@ -361,7 +318,7 @@ public class DeviceInstallServiceImpl implements DeviceInstallService {
//修改设备启用状态
@Override
public void updateDeviceIsUse(String isUse, String deviceAddr) {
deviceInstallMapper.updateDeviceIsUse(isUse, deviceAddr);
deviceInstallMapper.updateDeviceIsUse(isUse,deviceAddr);
}
@Override
@ -369,20 +326,15 @@ public class DeviceInstallServiceImpl implements DeviceInstallService {
return deviceInstallMapper.selectDevices(buildingId, deviceType);
}
@Override
public List<DeviceModel> selectDevicesByOthers(String buildingId, String deviceType, String deviceName) {
return deviceInstallMapper.selectDevicesByOthers(buildingId, deviceType, deviceName);
}
@Override
public void updateDeviceFault(String isFault, String deviceAddr, String deviceType) {
deviceInstallMapper.updateDeviceFault(isFault, deviceAddr, deviceType);
deviceInstallMapper.updateDeviceFault(isFault,deviceAddr,deviceType);
}
//查询设备品牌
@Override
public String selectBrand(String buildingId, String deviceAddr) {
return deviceInstallMapper.selectBrand(buildingId, deviceAddr);
public String selectBrand(String buildingId,String deviceAddr) {
return deviceInstallMapper.selectBrand(buildingId,deviceAddr);
}
@Override
@ -411,8 +363,8 @@ public class DeviceInstallServiceImpl implements DeviceInstallService {
}
@Override
public String selectLastDate(String deviceType, String deviceAddr, String buildingId) {
return deviceInstallMapper.selectLastDate(deviceType, deviceAddr, buildingId);
public String selectLastDate(String deviceType, String deviceAddr,String buildingId) {
return deviceInstallMapper.selectLastDate(deviceType,deviceAddr,buildingId);
}
@Override
@ -435,9 +387,9 @@ public class DeviceInstallServiceImpl implements DeviceInstallService {
// 更新电表
deviceTypeStr = "电表";
}
// String dataValue = new BigDecimal(realValue).subtract(new BigDecimal(readValue)).toString();
String dataValue = new BigDecimal(realValue).subtract(new BigDecimal(readValue)).toString();
try {
deviceInstallMapper.updateDeviation(buildingId, deviceTypeStr, param, realValue);
deviceInstallMapper.updateDeviation(buildingId, deviceTypeStr, param, dataValue);
return true;
} catch (Exception e) {
throw new RuntimeException(e);
@ -465,10 +417,5 @@ public class DeviceInstallServiceImpl implements DeviceInstallService {
public void updateLastValueByOther(String addr, String strWtLevel, String deviceType, String buildingId) {
deviceInstallMapper.updateLastValueByOther(addr, strWtLevel, deviceType, buildingId);
}
@Override
public String selectSinglePumpId(String buildingId, String pumpId) {
return deviceInstallMapper.selectSinglePumpId(buildingId, pumpId);
}
}

85
user-service/src/main/java/com/mh/user/service/impl/EnergyServiceImpl.java

@ -1,12 +1,8 @@
package com.mh.user.service.impl;
import com.alibaba.druid.util.StringUtils;
import com.mh.user.entity.AreaEntity;
import com.mh.user.entity.EnergyEntity;
import com.mh.user.mapper.EnergyMapper;
import com.mh.user.model.SumModel;
import com.mh.user.service.AreaService;
import com.mh.user.service.BuildingService;
import com.mh.user.service.EnergyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -20,12 +16,6 @@ public class EnergyServiceImpl implements EnergyService {
@Autowired
EnergyMapper energyMapper;
@Autowired
private BuildingService buildingService;
@Autowired
private AreaService areaService;
@Override
public void saveEnergy(EnergyEntity energyEntity,int type) {
@ -63,58 +53,22 @@ public class EnergyServiceImpl implements EnergyService {
}
@Override
public List<EnergyEntity> queryEnergy(String buildingId, String startDate,String endDate, int page, int limit,int type, int level) {
public List<EnergyEntity> queryEnergy(String buildingId, String startDate,String endDate, int page, int limit,int type) {
List<EnergyEntity> list=new ArrayList<EnergyEntity>();
// 判断级别类型
if (level == 1) {
// 根据区域id查询区域名称
AreaEntity areaEntity = areaService.selectById(buildingId);
if (null == areaEntity) {
return list;
}
// 根据区域id获取所有楼栋 id
List<String> buildingIds = buildingService.queryBuildingIdListByAreaId(buildingId);
if(type==1) {
list=energyMapper.getAreaEnergyDay(buildingIds,startDate,endDate, page, limit, areaEntity.getAreaName());
}else if (type==2){
list=energyMapper.getAreaEnergyMonth(buildingIds,startDate,endDate, page, limit, areaEntity.getAreaName());
} else if (type==3){
list=energyMapper.getAreaEnergyYear(buildingIds,startDate,endDate, page, limit, areaEntity.getAreaName());
}
} else {
if (StringUtils.isEmpty(buildingId)) {
buildingId = "所有";
}
// 楼栋
if (type == 1) {
list = energyMapper.queryEnergyDay(buildingId, startDate, endDate, page, limit);
} else if (type == 2) {
list = energyMapper.queryEnergyMonth(buildingId, startDate, endDate, page, limit);
System.out.println(list);
} else if (type == 3) {
list = energyMapper.queryEnergyYear(buildingId, startDate, endDate, page, limit);
}
if(type==1) {
list=energyMapper.queryEnergyDay(buildingId,startDate,endDate,page,limit);
} else if (type==2){
list=energyMapper.queryEnergyMonth(buildingId,startDate,endDate,page,limit);
System.out.println(list);
} else if (type==3){
list=energyMapper.queryEnergyYear(buildingId,startDate,endDate,page,limit);
}
return list;
}
@Override
public int getEnergyCount(String buildingId, String startDate,String endDate, int page, int limit,int type, int level) {
public int getEnergyCount(String buildingId, String startDate,String endDate, int page, int limit,int type) {
int r=0; // 记录数
// 判断级别类型
if (level == 0) {
buildingId = "所有";
} else if (level == 1) {
// 根据区域id获取所有楼栋 id
List<String> buildingIds = buildingService.queryBuildingIdListByAreaId(buildingId);
if(type==1) {
r=energyMapper.getAreaEnergyDayCount(buildingIds,startDate,endDate, page, limit);
}else if (type==2){
r=energyMapper.getAreaEnergyMonthCount(buildingIds,startDate,endDate, page, limit);
} else if (type==3){
r=energyMapper.getAreaEnergyYearCount(buildingIds,startDate,endDate, page, limit);
}
}
if(type==1) {
r=energyMapper.getEnergyDayCount(buildingId,startDate,endDate, page, limit);
}else if (type==2){
@ -147,29 +101,12 @@ public class EnergyServiceImpl implements EnergyService {
}
@Override
public List<EnergyEntity> queryHourEnergy(String buildingId, String curDate, int page, int limit, int level) {
List<EnergyEntity> list=new ArrayList<EnergyEntity>();
// 判断级别类型
if (level == 0 || null == buildingId) {
buildingId = "所有";
level = 0;
}
if (level == 1) {
// 根据区域id查询区域名称
AreaEntity areaEntity = areaService.selectById(buildingId);
if (null == areaEntity) {
return list;
}
// 根据区域id获取所有楼栋 id
List<String> buildingIds = buildingService.queryBuildingIdListByAreaId(buildingId);
list=energyMapper.getAreaEnergyHour(buildingIds,curDate, page, limit, areaEntity.getAreaName());
return list;
}
public List<EnergyEntity> queryHourEnergy(String buildingId, String curDate, int page, int limit) {
return energyMapper.queryHourEnergy(buildingId,curDate,page,limit);
}
@Override
public int getHourEnergyCount(String buildingId, String curDate, int level) {
public int getHourEnergyCount(String buildingId, String curDate) {
return energyMapper.getHourEnergyCount(buildingId,curDate);
}

253
user-service/src/main/java/com/mh/user/service/impl/HistoryDataPreServiceImpl.java

@ -1,253 +0,0 @@
package com.mh.user.service.impl;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.github.benmanes.caffeine.cache.Cache;
import com.mh.algorithm.bpnn.BPModel;
import com.mh.algorithm.bpnn.BPNeuralNetworkFactory;
import com.mh.algorithm.bpnn.BPParameter;
import com.mh.algorithm.matrix.Matrix;
import com.mh.algorithm.utils.CsvInfo;
import com.mh.algorithm.utils.SerializationUtil;
import com.mh.common.utils.StringUtils;
import com.mh.user.dto.EnergyPreDTO;
import com.mh.user.dto.EnergyPreEchartDataDTO;
import com.mh.user.dto.EnergyPreTopDataDTO;
import com.mh.user.entity.HistoryDataPre;
import com.mh.user.entity.SysParamEntity;
import com.mh.user.job.GetWeatherInfoJob;
import com.mh.user.mapper.HistoryDataPreMapper;
import com.mh.user.service.HistoryDataPreService;
import com.mh.user.service.SysParamService;
import com.mh.user.utils.DateUtil;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @author LJF
* @version 1.0
* @project CHWS
* @description 预测历史数据服务实现类
* @date 2024-05-09 10:03:24
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class HistoryDataPreServiceImpl implements HistoryDataPreService {
@Resource
private HistoryDataPreMapper historyDataPreMapper;
@Resource
@Qualifier("caffeineCache")
private Cache caffeineCache;
@Resource
private SysParamService sysParamService;
@Resource
private GetWeatherInfoJob getWeatherInfoJob;
public static String[] convert(HistoryDataPre dataPre) {
// 假设HistoryDataPre有字段如field1, field2, field3等,根据需要进行转换
return new String[]{
String.valueOf(dataPre.getEnvMinTemp()),
String.valueOf(dataPre.getEnvMaxTemp()),
String.valueOf(dataPre.getPeopleNum()),
String.valueOf(dataPre.getWaterValue()),
String.valueOf(dataPre.getElectValue()),
String.valueOf(dataPre.getWaterLevel())
};
}
@Override
public void startTrainData(String buildingId) throws Exception {
List<HistoryDataPre> trainData = historyDataPreMapper.getTrainData(buildingId);
if (trainData == null || trainData.size() == 0) {
return;
}
List<String[]> historyDataPreList = new ArrayList<>();
for (HistoryDataPre dataPre : trainData) {
historyDataPreList.add(convert(dataPre));
}
// 创建训练集矩阵
CsvInfo csvInfo = new CsvInfo();
csvInfo.setCsvFileList(new ArrayList<>(historyDataPreList));
Matrix trainSet = csvInfo.toMatrix();
// 创建BPNN工厂对象
BPNeuralNetworkFactory factory = new BPNeuralNetworkFactory();
// 创建BP参数对象
BPParameter bpParameter = new BPParameter();
bpParameter.setInputLayerNeuronCount(3);
bpParameter.setHiddenLayerNeuronCount(3);
bpParameter.setOutputLayerNeuronCount(3);
bpParameter.setPrecision(0.01);
bpParameter.setMaxTimes(50000);
// 训练BP神经网络
BPModel bpModel = factory.trainBP(bpParameter, trainSet);
// 将BPModel序列化到本地
SerializationUtil.serialize(bpModel, buildingId + "_pre_data");
}
@Override
public void startPredictData(String buildingId, String curDate) throws Exception {
// 判断是否存在天气温度数据以及现在的用水量用电量等
// int isPre = historyDataPreMapper.selectIsPre(buildingId, curDate);
// if (isPre > 0) {
// return;
// }
// 获取当前天气数据
SysParamEntity sysParam = sysParamService.selectSysParam();
Object weather = caffeineCache.getIfPresent(sysParam.getProArea());
if (weather == null) {
getWeatherInfoJob.getWeatherInfo();
weather = caffeineCache.getIfPresent(sysParam.getProArea());
}
String weatherStr = (String) weather;
JSONObject jsonObject = JSON.parseObject(weatherStr);
if (null == jsonObject) {
return;
}
String envMinTemp = "16.50";
String envMaxTemp = "26.00";
JSONArray jsonArray = jsonObject.getJSONArray("forecasts").getJSONObject(0).getJSONArray("casts");
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (jsonObject1.getString("date").equals(curDate)) {
envMinTemp = jsonObject1.getString("nighttemp");
envMaxTemp = jsonObject1.getString("daytemp");
break;
}
}
// 获取当前用水量和用电量以及实际平均水位
HistoryDataPre curHistoryData = historyDataPreMapper.selectCurData(buildingId, curDate);
// 插入数据
curHistoryData.setEnvMaxTemp(new BigDecimal(envMaxTemp));
curHistoryData.setEnvMinTemp(new BigDecimal(envMinTemp));
HistoryDataPre historyDataPre = historyDataPreMapper.selectOneData(buildingId, curDate);
if (historyDataPre == null) {
historyDataPreMapper.insertData(curHistoryData);
}
// 开始预测
HistoryDataPre historyDataPre1 = historyDataPreMapper.selectOneData(buildingId, curDate);
String[] preData = new String[]{
historyDataPre1.getEnvMinTemp().toString(),
historyDataPre1.getEnvMaxTemp().toString(),
historyDataPre1.getPeopleNum().toString()
};
CsvInfo csvInfo = new CsvInfo();
ArrayList<String[]> list = new ArrayList<>();
list.add(preData);
csvInfo.setCsvFileList(list);
Matrix data = csvInfo.toMatrix();
// 将BPModel反序列化
BPModel bpModel1 = (BPModel) SerializationUtil.deSerialization(buildingId + "_pre_data");
// 创建工厂
BPNeuralNetworkFactory factory = new BPNeuralNetworkFactory();
Matrix result = factory.computeBP(bpModel1, data);
// 得出预测数据
HistoryDataPre preHistoryData = new HistoryDataPre();
preHistoryData.setId(historyDataPre1.getId());
preHistoryData.setBuildingId(buildingId);
for (int i = 0; i < result.getMatrixRowCount(); i++) {
String[] record = new String[result.getMatrixColCount()];
for (int j = 0; j < result.getMatrixColCount(); j++) {
record[j] = String.valueOf(result.getValOfIdx(i, j));
}
// 拼接预测值
preHistoryData.setWaterValuePre(evaluateAndReturnBigDecimal(record[0]));
preHistoryData.setElectValuePre(evaluateAndReturnBigDecimal(record[1]));
preHistoryData.setWaterLevelPre(evaluateAndReturnBigDecimal(record[2]).compareTo(BigDecimal.valueOf(100)) > 0 ? BigDecimal.valueOf(100) : evaluateAndReturnBigDecimal(record[2]));
}
preHistoryData.setWaterValue(curHistoryData.getWaterValue());
preHistoryData.setElectValue(curHistoryData.getElectValue());
preHistoryData.setWaterLevel(curHistoryData.getWaterLevel());
// 更新预测值
historyDataPreMapper.updateById(preHistoryData);
}
/**
* 判断输入的字符串转换的BigDecimal是否小于或等于0返回BigDecimal.ZERO
* 如果小于或等于0返回输入的BigDecimal如果大于0然后返回相应的BigDecimal值
*
* @param recordValue 记录中的值用于转换为BigDecimal进行比较
* @return 经过判断后的BigDecimal值
*/
public static BigDecimal evaluateAndReturnBigDecimal(String recordValue) {
BigDecimal value = new BigDecimal(recordValue);
if (value.compareTo(BigDecimal.ZERO) >= 0) {
return value.setScale(2, RoundingMode.HALF_UP);
} else {
return BigDecimal.ZERO;
}
}
@Override
public List<HistoryDataPre> getRecentData(String buildingId, String curDate) {
return historyDataPreMapper.getRecentData(buildingId, curDate);
}
@Override
public List<HashMap<String, Object>> getEnergyPre(String buildingId, String beginDate, String endDate, String type) {
if (StringUtils.isBlank(beginDate) || StringUtils.isBlank(endDate)) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 获取当前日期
LocalDate now = LocalDate.now();
// 向前推30天
LocalDate startDate = now.minusDays(30);
beginDate = startDate.format(formatter);
// 结束日期是当前日期
endDate = now.format(formatter);
}
if (StringUtils.isBlank(buildingId) || StringUtils.isBlank(type)) {
return null;
}
List<EnergyPreEchartDataDTO> energyPre = historyDataPreMapper.getEnergyPre(buildingId, beginDate, endDate, type);
if (energyPre.size() == 0) {
return null;
}
String[] curDate = energyPre.stream()
.map(EnergyPreEchartDataDTO::getCurDate)
.toArray(String[]::new); // 使用stream和map转换每个对象的特定字段为JSON字符串,然后转换成数组
String[] curData = energyPre.stream()
.map(EnergyPreEchartDataDTO::getCurData)
.toArray(String[]::new); // 使用stream和map转换每个对象的特定字段为JSON字符串,然后转换成数组
String[] preData = energyPre.stream()
.map(EnergyPreEchartDataDTO::getPreData)
.toArray(String[]::new); // 使用stream和map转换每个对象的特定字段为JSON字符串,然后转换成数组
String[] errorData = energyPre.stream()
.map(EnergyPreEchartDataDTO::getErrorData)
.toArray(String[]::new); // 使用stream和map转换每个对象的特定字段为JSON字符串,然后转换成数组
List<HashMap<String, Object>> resultList = new ArrayList<>();
HashMap<String, Object> resultHashMap = new HashMap<>();
resultHashMap.put("curDate", curDate);
resultHashMap.put("curData", curData);
resultHashMap.put("preData", preData);
resultHashMap.put("errorData", errorData);
resultList.add(resultHashMap);
return resultList;
}
@Override
public List<EnergyPreTopDataDTO> getTopData(String buildingId, String type) {
// 获取顶部数据(昨日,昨日预测,今日预测,昨日偏差值)
return historyDataPreMapper.getTopData(buildingId, type);
}
}

47
user-service/src/main/java/com/mh/user/service/impl/KnowledgeDataServiceImpl.java

@ -1,47 +0,0 @@
package com.mh.user.service.impl;
import com.github.pagehelper.PageHelper;
import com.mh.common.page.ColumnFilter;
import com.mh.common.page.MybatisPageHelper;
import com.mh.common.page.PageRequest;
import com.mh.common.page.PageResult;
import com.mh.user.entity.KnowledgeDataEntity;
import com.mh.user.mapper.KnowledgeDataMapper;
import com.mh.user.service.KnowledgeDataService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author LJF
* @version 1.0
* @project CHWS
* @description 知识库服务实现类
* @date 2024-06-26 14:33:20
*/
@Service
public class KnowledgeDataServiceImpl implements KnowledgeDataService {
@Resource
private KnowledgeDataMapper knowledgeDataMapper;
@Override
public void insertKnowledgeData(KnowledgeDataEntity knowledgeData) {
knowledgeDataMapper.insertKnowledgeData(knowledgeData);
}
@Override
public PageResult queryKnowledgeData(PageRequest pageRequest) {
return MybatisPageHelper.findPage(pageRequest, knowledgeDataMapper);
}
@Override
public void updateData(KnowledgeDataEntity knowledgeData) {
knowledgeDataMapper.updateData(knowledgeData);
}
@Override
public KnowledgeDataEntity getById(Long id) {
return knowledgeDataMapper.getById(id);
}
}

144
user-service/src/main/java/com/mh/user/service/impl/NowDataServiceImpl.java

@ -1,6 +1,5 @@
package com.mh.user.service.impl;
import com.mh.common.utils.StringUtils;
import com.mh.user.entity.*;
import com.mh.user.mapper.DeviceFloorMapper;
import com.mh.user.mapper.DeviceInstallMapper;
@ -18,10 +17,8 @@ import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
@Slf4j
@ -145,25 +142,18 @@ public class NowDataServiceImpl implements NowDataService {
strDate=strDate.substring(0,13)+":00:00";
try{
switch (dataType) {
case "tempSet": //温度设定
data.setTempSet(strData);
break;
case "waterTemp": //水箱水温
data.setWaterTemp(strData);
break;
case "runState": //运行状态
data.setRunState(strData);
break;
case "isFault": //是否故障
data.setIsFault(strData);
break;
case "levelSet": //水位设定
data.setLevelSet(strData);
break;
case "waterLevel": //实际水位
data.setWaterLevel(strData);
break;
if (dataType.equals("tempSet")){ //温度设定
data.setTempSet(strData);
}else if (dataType.equals("waterTemp")){ //水箱水温
data.setWaterTemp(strData);
}else if (dataType.equals("runState")){ //运行状态
data.setRunState(strData);
}else if (dataType.equals("isFault")){ //是否故障
data.setIsFault(strData);
}else if (dataType.equals("levelSet")){ //水位设定
data.setLevelSet(strData);
}else if (dataType.equals("waterLevel")){//实际水位
data.setWaterLevel(strData);
}
//从安装表获取设备信息
DeviceInstallEntity deviceInstallEntity=deviceInstallMapper.selectDevice(deviceAddr,deviceType,buildingId);
@ -198,15 +188,15 @@ public class NowDataServiceImpl implements NowDataService {
nowDataMapper.saveNowData(data);
}else {
if (deviceType.equals("压变")) {
String seat=deviceInstallService.selectSeat(deviceType,deviceAddr,buildingId);
String seat=deviceInstallService.selectSeat("压变",deviceAddr,buildingId);
log.info("-------楼栋:"+buildingName+",类型:"+deviceType+",地址:"+deviceAddr+",区位:"+seat+",数值:"+strData+"------");
if (!StringUtils.isBlank(seat)){
if (seat!=null){
nowDataMapper.nowDataWaterLevel(strData,seat,buildingId);
}else{
nowDataMapper.updateNowData2(data);
}
}else if (deviceType.equals("水位开关")){
String seat=deviceInstallService.selectSeat(deviceType,deviceAddr,buildingId);
String seat=deviceInstallService.selectSeat("水位开关",deviceAddr,buildingId);
log.info("-------楼栋:"+buildingName+",类型:"+deviceType+",地址:"+deviceAddr+",区位:"+seat+",数值:"+strData+"------");
if (seat!=null){
nowDataMapper.nowDataLevelSet(strData,seat,buildingId);
@ -223,17 +213,17 @@ public class NowDataServiceImpl implements NowDataService {
nowDataMapper.saveHistoryData(data);
}else {
if (deviceType.equals("压变")) {
String seat=deviceInstallService.selectSeat(deviceType,deviceAddr,buildingId);
if (!StringUtils.isBlank(seat)){
nowDataMapper.historyDataWaterLevel(strData,seat,buildingId,strDate);
String seat=deviceInstallService.selectSeat("压变",deviceAddr,buildingId);
if (seat!=null){
nowDataMapper.historyDataWaterLevel(strData,seat,buildingId,"");
log.info("------楼栋:"+buildingName+",历史记录压变区位:"+seat+"------");
}else{
nowDataMapper.updateHistoryData2(data);
}
}else if (deviceType.equals("水位开关")){
String seat=deviceInstallService.selectSeat(deviceType,deviceAddr,buildingId);
if (!StringUtils.isBlank(seat)){
nowDataMapper.historyDataLevelSet(strData,seat,buildingId,strDate);
String seat=deviceInstallService.selectSeat("水位开关",deviceAddr,buildingId);
if (seat!=null){
nowDataMapper.historyDataLevelSet(strData,seat,buildingId,"");
log.info("------楼栋:"+buildingName+",历史记录水位开关区位:"+seat+"------");
}else{
nowDataMapper.updateHistoryData2(data);
@ -256,19 +246,14 @@ public class NowDataServiceImpl implements NowDataService {
strDate=strDate.substring(0,13)+":00:00";
NowDataEntity data=new NowDataEntity();
try{
switch (dataType) {
case "tempSet": //温度设定
data.setTempSet(strData);
break;
case "waterTemp": //水箱水温
data.setWaterTemp(strData);
break;
case "runState": //运行状态
data.setRunState(strData);
break;
case "isFault": //是否故障
data.setIsFault(strData);
break;
if (dataType.equals("tempSet")){ //温度设定
data.setTempSet(strData);
}else if (dataType.equals("waterTemp")){ //水箱水温
data.setWaterTemp(strData);
}else if (dataType.equals("runState")){ //运行状态
data.setRunState(strData);
}else if (dataType.equals("isFault")){ //是否故障
data.setIsFault(strData);
}
String buildingName=buildingService.queryBuildingName(buildingId);
//判断实时表是否有记录
@ -312,19 +297,14 @@ public class NowDataServiceImpl implements NowDataService {
}else {
NowDataEntity data2=nowDataMapper.selectHistoryData(strDate,buildingId,pumpId);
if (data2!=null){
switch (dataType) {
case "tempSet": //温度设定
data2.setTempSet(strData);
break;
case "waterTemp": //水箱水温
data2.setWaterTemp(strData);
break;
case "runState": //运行状态
data2.setRunState(strData);
break;
case "isFault": //是否故障
data2.setIsFault(strData);
break;
if (dataType.equals("tempSet")){ //温度设定
data2.setTempSet(strData);
}else if (dataType.equals("waterTemp")){ //水箱水温
data2.setWaterTemp(strData);
}else if (dataType.equals("runState")){ //运行状态
data2.setRunState(strData);
}else if (dataType.equals("isFault")){ //是否故障
data2.setIsFault(strData);
}
nowDataMapper.updateHistoryData(data2);
}
@ -402,11 +382,6 @@ public class NowDataServiceImpl implements NowDataService {
return nowDataMapper.selectAve(buildingId, null);
}
@Override
public String selectMaxTemp(String buildingId) {
return nowDataMapper.selectMaxTemp(buildingId, null);
}
@Override
public String selectSingleTemp(String pumpId,String buildingId) {
return nowDataMapper.selectSingleTemp(pumpId,buildingId);
@ -457,20 +432,12 @@ public class NowDataServiceImpl implements NowDataService {
//查询所有楼栋每栋楼的平均温度
@Override
public List<WaterTempEntity> queryWaterTemp2(String curDate,int page,int limit, int level, String buildingID) {
List<WaterTempEntity> waterTempEntityList = nowDataMapper.queryWaterTemp2(curDate, page, limit);
// 根据level层级查询
if (level == 1) {
// 根据区域id获取对应的楼栋id
List<String> buildingIdList = buildingService.queryBuildingIdListByAreaId(buildingID);
// waterTempEntityList过滤掉非该区域的楼栋
waterTempEntityList.removeIf(waterTempEntity -> !buildingIdList.contains(waterTempEntity.getBuildingID()));
}
return waterTempEntityList;
public List<WaterTempEntity> queryWaterTemp2(String curDate,int page,int limit) {
return nowDataMapper.queryWaterTemp2(curDate,page,limit);
}
//查询所有楼栋每栋楼的平均温度记录数
@Override
public int queryWaterTempCount2(String curDate, int level, String buildingID) {
public int queryWaterTempCount2(String curDate) {
return nowDataMapper.queryWaterTempCount2(curDate);
}
@ -491,15 +458,8 @@ public class NowDataServiceImpl implements NowDataService {
}
@Override
public List<WaterLevelEntity> queryBuildWaterLevel(String curDate, int page, int limit, int level, String buildingID) {
List<WaterLevelEntity> waterLevelEntities = nowDataMapper.queryBuildWaterLevel(curDate, page, limit);
if (level == 1) {
// 根据区域id获取对应的楼栋id
List<String> buildingIdList = buildingService.queryBuildingIdListByAreaId(buildingID);
// waterLevelEntities过滤掉非该区域的楼栋
waterLevelEntities.removeIf(waterLevelEntity -> !buildingIdList.contains(waterLevelEntity.getBuildingID()));
}
return waterLevelEntities;
public List<WaterLevelEntity> queryBuildWaterLevel(String curDate, int page, int limit) {
return nowDataMapper.queryBuildWaterLevel(curDate, page, limit);
}
@Override
@ -567,24 +527,4 @@ public class NowDataServiceImpl implements NowDataService {
public String selectMinPumpId(String buildingId) {
return nowDataMapper.selectMinPumpId(buildingId);
}
@Override
public void updateNowDataByPumpName(String pumpName, String buildingId, String useWater, String backWater, String upWater) {
nowDataMapper.updateNowDataByPumpName(pumpName, buildingId, useWater, backWater, upWater);
}
@Override
public Map<String, Object> selectTopOneState(String buildingId) {
return nowDataMapper.selectTopOneState(buildingId);
}
@Override
public void updateNowPublicData(NowPublicDataEntity publicData) {
nowPublicDataMapper.updateNowPublicData(publicData);
}
@Override
public void updatePumpName(String oldPumpId, String oldPumpName, String oldBuildingId, String pumpId, String pumpName, String buildingId, String buildingName) {
nowDataMapper.updatePumpName(oldPumpId, oldPumpName, oldBuildingId, pumpId, pumpName, buildingId, buildingName);
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save