2021与蓝度共同重构项目,服务端
zhanzhiqin
2022-04-26 407ea8abef30f30608a0cd933f7f6c35e97095be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
package com.sandu.ximon.admin.service;
 
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.sandu.common.domain.CommonPage;
import com.sandu.common.execption.BusinessException;
import com.sandu.common.redis.RedisService;
import com.sandu.common.service.impl.BaseServiceImpl;
import com.sandu.common.util.SpringContextHolder;
import com.sandu.ximon.admin.dto.LightTaskDto;
import com.sandu.ximon.admin.manager.iot.frame.A5Frame;
import com.sandu.ximon.admin.manager.iot.frame.inner.report.A5LightHeartbeatReportInnerFrame;
import com.sandu.ximon.admin.manager.iot.frame.inner.request.A5LightBrightnessReqInnerFrame;
import com.sandu.ximon.admin.manager.iot.frame.inner.response.A5LightBrightnessRespInnerFrame;
import com.sandu.ximon.admin.manager.iot.rrpc.dto.WrapResponseCommonFrame;
import com.sandu.ximon.admin.manager.iot.rrpc.enums.A5OrderEnum;
import com.sandu.ximon.admin.manager.iot.rrpc.mainboard.MainBoardInvokeSyncService;
import com.sandu.ximon.admin.param.LightControlParam;
import com.sandu.ximon.admin.param.LightRemarkParam;
import com.sandu.ximon.admin.redis.LightKey;
import com.sandu.ximon.admin.security.SecurityUtils;
import com.sandu.ximon.admin.vo.ControlLightCommandVO;
import com.sandu.ximon.dao.bo.LightBo;
import com.sandu.ximon.dao.domain.Light;
import com.sandu.ximon.dao.domain.LightReportData;
import com.sandu.ximon.dao.domain.Pole;
import com.sandu.ximon.dao.domain.PoleBinding;
import com.sandu.ximon.dao.enums.DeviceRespStatusEnums;
import com.sandu.ximon.dao.mapper.LightMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
 
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
/**
 * @author chenjiantian
 * @date 2021/12/13 16:00
 * 灯设备service
 */
@Service
@Slf4j
@AllArgsConstructor
public class LightService extends BaseServiceImpl<LightMapper, Light> {
 
    private final RedisService redisService;
    private final LightReportDataService lightReportDataService;
    private final PoleBindingService bindingService;
    private final PoleService poleService;
 
    /**
     * 录入当前设备码的路灯数据
     *
     * @param deviceName           mac
     * @param heartBeatDataPackage 心跳数据
     */
    public void saveLight(String deviceName, A5LightHeartbeatReportInnerFrame.HeartBeatDataPackage heartBeatDataPackage) {
        Boolean hasKey = redisService.hasKey(LightKey.REPORT_MAC.key(deviceName));
        if (!hasKey) {
            int count = count(Wrappers.lambdaQuery(Light.class).eq(Light::getDeviceCode, deviceName));
            log.info("redis查不到路灯数据{}={}", count, deviceName);
            // 当前路灯表没有录入设备吗
            if (count == 0) {
                Light light = new Light();
                light.setDeviceCode(deviceName);
                light.setLightPercent(heartBeatDataPackage.getLightPercent());
                light.setLight2Percent(heartBeatDataPackage.getLight2Percent());
                save(light);
            }
            redisService.set(LightKey.REPORT_MAC.key(deviceName), 1, LightKey.REPORT_MAC.expireSeconds());
            log.info("新增路灯");
        } else {
            Light light = new Light();
            light.setLightPercent(heartBeatDataPackage.getLightPercent());
            light.setLight2Percent(heartBeatDataPackage.getLight2Percent());
            update(light, Wrappers.lambdaUpdate(Light.class).eq(Light::getDeviceCode, deviceName));
            log.info("更新路灯亮度");
        }
    }
 
    /**
     * 获取路灯列表
     *
     * @return 返回组合数据dto
     */
    public List<LightBo> listLight(int pageNo, int pageSize, String keyword) {
        Long clientId = SecurityUtils.getClientId();
 
        PageHelper.startPage(pageNo, pageSize);
 
        List<LightBo> listLight = baseMapper.listLight(clientId, keyword);
 
        // 获取最近的上报时间
        List<String> deviceCodeList = listLight.stream().map(Light::getDeviceCode).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(deviceCodeList)) {
            List<LightReportData> reportDataList = lightReportDataService.getNewestReportByDeviceCode(deviceCodeList);
            for (LightBo lightBo : listLight) {
                deviceCodeList.forEach(code -> {
                            PoleBinding bind = bindingService.getPoleIdByMac(code);
                            if (bind != null && lightBo.getDeviceCode().equals(bind.getDeviceCode())) {
                                Long poleId = bind.getPoleId();
                                Pole pole = poleService.getById(poleId);
                                lightBo.setPoleId(pole.getId());
                                lightBo.setPoleCode(pole.getDeviceCode());
                                lightBo.setPoleName(pole.getPoleName());
                            }
                        }
                );
                for (LightReportData lightReportData : reportDataList) {
                    if (StrUtil.equals(lightBo.getDeviceCode(), lightReportData.getDeviceCode())) {
                        lightBo.setReportTime(lightReportData.getCreateTime());
                        break;
                    }
                }
            }
        }
 
        return listLight;
    }
 
    /**
     * 获取单个路灯信息
     *
     * @param deviceCode 设备码
     * @return
     */
    public Light getLight(String deviceCode) {
        Light one = getOne(Wrappers.<Light>lambdaQuery().eq(Light::getDeviceCode, deviceCode));
        Object o = redisService.get(LightKey.REPORT_MAC.key(deviceCode));
        if (o != null) {
            one.setOnlineStatus(1);
        } else {
            one.setOnlineStatus(0);
        }
        return one;
    }
 
    public boolean addRemark(LightRemarkParam param) {
        Light light = getById(param.getLightId());
        if (light == null) {
            throw new BusinessException("找不到路灯");
        }
        Light update = new Light();
        update.setLightId(param.getLightId());
        update.setRemark(param.getRemark());
        return updateById(update);
    }
 
    /**
     * 单灯亮度控制
     *
     * @return com.sandu.ximon.dao.enums.DeviceRespStatusEnums
     */
    public List<Map<String, Object>> controlBrightness(List<LightControlParam> paramList) {
        if (CollectionUtil.isEmpty(paramList)) {
            throw new BusinessException("参数不能为空");
        }
 
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (LightControlParam param : paramList) {
            A5LightBrightnessReqInnerFrame lightControlFrame = new A5LightBrightnessReqInnerFrame(param.getBrightness());
            A5Frame a5Frame = new A5Frame(A5OrderEnum.REQUEST_LIGHT_DATA.getCode(), lightControlFrame);
            Map<String, Object> map = new HashMap<>();
            try {
                map.put("deviceCode", param.getDeviceCode());
                WrapResponseCommonFrame<A5LightBrightnessRespInnerFrame> frame = MainBoardInvokeSyncService.getInstance()
                        .sendRRPC(param.getDeviceCode(), a5Frame, A5LightBrightnessRespInnerFrame.class);
                if (frame == null) {
                    map.put("status", DeviceRespStatusEnums.OTHER_ERROR.getCode());
                    resultList.add(map);
                    continue;
                }
                String responseStatus = frame.getResponseInnerFrame().getResponseStatus();
                int status = HexUtil.hexToInt(responseStatus);
                map.put("status", status);
                resultList.add(map);
 
                // 更新亮度成功,修改到数据库
                if (DeviceRespStatusEnums.SUCCESS.getCode().equals(status)) {
                    Light light = new Light();
                    light.setLightPercent(param.getBrightness());
                    update(light, Wrappers.lambdaUpdate(Light.class).eq(Light::getDeviceCode, param.getDeviceCode()));
                }
            } catch (BusinessException e) {
                map.put("status", DeviceRespStatusEnums.OTHER_ERROR.getCode());
                resultList.add(map);
            }
        }
 
        return resultList;
    }
 
    /**
     * 单灯节能率
     *
     * @return
     */
    public Map controlEnergySaving() {
        Long clientId = SecurityUtils.getClientId();
//        List<LightBo> listLight = baseMapper.listLight(clientId, null);
//        List<String> deviceCodeList = listLight.stream().map(LightBo::getDeviceCode).collect(Collectors.toList());
 
        //获取到正在执行的任务列表
        List<LightTaskDto> lightTaskDtos = SpringContextHolder.getBean(LightTaskService.class).listTask();
        LocalDateTime now = LocalDateTime.now();
 
        List<LightTaskDto> list1 = new ArrayList<>();
        List<LightTaskDto> list2 = new ArrayList<>();
        List<LightTaskDto> list3 = new ArrayList<>();
        List<LightTaskDto> list4 = new ArrayList<>();
        List<LightTaskDto> list5 = new ArrayList<>();
        List<LightTaskDto> list6 = new ArrayList<>();
        List<LightTaskDto> list7 = new ArrayList<>();
 
        for (LightTaskDto lightTaskDto : lightTaskDtos) {
            List<Integer> weekList = lightTaskDto.getWeekList();
            System.out.println(weekList + "===========================");
            for (Integer one : weekList) {
                switch (one) {
                    case 1:
                        list1.add(lightTaskDto);
                        break;
                    case 2:
                        list2.add(lightTaskDto);
                        break;
                    case 4:
                        list3.add(lightTaskDto);
                        break;
                    case 8:
                        list4.add(lightTaskDto);
                        break;
                    case 16:
                        list5.add(lightTaskDto);
                        break;
                    case 32:
                        list6.add(lightTaskDto);
                        break;
                    case 64:
                        list7.add(lightTaskDto);
                        break;
                    default:
                }
            }
        }
 
        Integer week = now.getDayOfWeek().getValue();
 
        Map map = new HashMap();
 
 
        for (int i = 1; i < 8; i++) {
            week--;
            if (week < 1) {
                week = 7;
            }
            map.put(i, "周" + week);
//            map.put(i, getlist(week));
        }
 
 
        return map;
    }
 
 
    public BigDecimal getlist(Integer week) {
 
        Long clientId = SecurityUtils.getClientId();
//        List<LightBo> listLight = baseMapper.listLight(clientId, null);
//        List<String> deviceCodeList = listLight.stream().map(LightBo::getDeviceCode).collect(Collectors.toList());
 
        //获取到正在执行的任务列表
        List<LightTaskDto> lightTaskDtos = SpringContextHolder.getBean(LightTaskService.class).listTask();
        LocalDateTime now = LocalDateTime.now();
 
        List<LightTaskDto> list1 = new ArrayList<>();
        List<LightTaskDto> list2 = new ArrayList<>();
        List<LightTaskDto> list3 = new ArrayList<>();
        List<LightTaskDto> list4 = new ArrayList<>();
        List<LightTaskDto> list5 = new ArrayList<>();
        List<LightTaskDto> list6 = new ArrayList<>();
        List<LightTaskDto> list7 = new ArrayList<>();
 
        for (LightTaskDto lightTaskDto : lightTaskDtos) {
            List<Integer> weekList = lightTaskDto.getWeekList();
            System.out.println(weekList + "===========================");
            for (Integer one : weekList) {
                switch (one) {
                    case 1:
                        list1.add(lightTaskDto);
                        break;
                    case 2:
                        list2.add(lightTaskDto);
                        break;
                    case 4:
                        list3.add(lightTaskDto);
                        break;
                    case 8:
                        list4.add(lightTaskDto);
                        break;
                    case 16:
                        list5.add(lightTaskDto);
                        break;
                    case 32:
                        list6.add(lightTaskDto);
                        break;
                    case 64:
                        list7.add(lightTaskDto);
                        break;
                    default:
                }
            }
        }
        if (week == 1) {
            return jisuan(list1);
        } else if (week == 2) {
            return jisuan(list2);
 
        } else if (week == 3) {
            return jisuan(list3);
        } else if (week == 4) {
            return jisuan(list4);
        } else if (week == 5) {
            return jisuan(list5);
 
        } else if (week == 6) {
            return jisuan(list6);
        } else if (week == 7) {
            return jisuan(list7);
        }
 
        return null;
    }
 
    /**
     * 一天的节能率
     *
     * @param list
     * @return
     */
    public BigDecimal jisuan(List<LightTaskDto> list) {
        final BigDecimal[] bigDecimalResult = {new BigDecimal(0.00)};
        /**
         * 节能率计算开始
         */
        list.forEach(Task -> {
//            List<BigDecimal> saving = new ArrayList<>();
            ControlLightCommandVO startTime = parseSwitchLightCommand(Task.getOpenOrder());
            ControlLightCommandVO endTime = parseSwitchLightCommand(Task.getCloseOrder());
            //存放节能率
            //获取到单灯任务的节能率
            if (Task.getControlOrder() != null) {//有控等指令 拆分计算
                List<ControlLightCommandVO> controlLightCommandVOS = parseControlLightCommand(Task.getControlOrder());
 
 
                for (int i = 0; i < controlLightCommandVOS.size(); i++) {
                    BigDecimal bigDecimal = calculateEnergySaving(startTime, controlLightCommandVOS.get(i));
                    if (controlLightCommandVOS.size() == (i + 1)) {
                        BigDecimal bigDecimal1 = calculateEnergySaving(controlLightCommandVOS.get(i), endTime);
                        System.out.println(bigDecimal1 + "===========================");
//                        saving.add(bigDecimal1);
                        bigDecimalResult[0] = bigDecimalResult[0].add(bigDecimal1);
                        break;
                    }
                    startTime = controlLightCommandVOS.get(i);
//                    saving.add(bigDecimal);
                    bigDecimalResult[0] = bigDecimalResult[0].add(bigDecimal);
                }
            } else {//无控灯指令 直接计算
                BigDecimal bigDecimal = calculateEnergySaving(startTime, endTime);
//                saving.add(bigDecimal);
                bigDecimalResult[0] = bigDecimalResult[0].add(bigDecimal);
            }
        });
        return bigDecimalResult[0];
 
        /**
         * 节能率计算结束
         */
    }
 
    /**
     * 解析开关灯指令
     */
    public ControlLightCommandVO parseSwitchLightCommand(String command) {
        char[] chars = command.toCharArray();
        ControlLightCommandVO vo = new ControlLightCommandVO();
        if (chars.length == 7) {
            int hour = Integer.valueOf(command.substring(0, 2));
            int min = Integer.valueOf(command.substring(2, 4));
            int brightness = Integer.valueOf(command.substring(4, 7));
            vo.setHour(hour);
            vo.setMin(min);
            vo.setBrightness(brightness);
        }
        return vo;
    }
 
    /**
     * 解析控灯指令
     */
    public List<ControlLightCommandVO> parseControlLightCommand(String command) {
        char[] chars = command.toCharArray();
        int i = chars.length / 7;
 
        List<ControlLightCommandVO> list = new ArrayList<>();
 
        for (int j = 0; j < i; j++) {
            int hour = Integer.valueOf(command.substring(0 + (j * 7), 2 + (j * 7)));
            int min = Integer.valueOf(command.substring(2 + (j * 7), 4 + (j * 7)));
            int brightness = Integer.valueOf(command.substring(4 + (j * 7), 7 + (j * 7)));
            ControlLightCommandVO vo = new ControlLightCommandVO();
            vo.setHour(hour);
            vo.setMin(min);
            vo.setBrightness(brightness);
            list.add(vo);
        }
        return list;
    }
 
    //计算节能率
    public BigDecimal calculateEnergySaving(ControlLightCommandVO v1, ControlLightCommandVO v2) {
 
        BigDecimal hour = BigDecimal.valueOf((v2.getHour() - v1.getHour()));
        BigDecimal min = BigDecimal.valueOf((v2.getMin() - v1.getMin()) / 60);
        BigDecimal totalTime = (hour.add(min));
 
        BigDecimal energySaving = BigDecimal.valueOf((100 - v1.getBrightness())).divide(BigDecimal.valueOf(100)).multiply(totalTime).divide(BigDecimal.valueOf(24), 2);
        System.out.println(energySaving);
        return energySaving;
    }
 
//    //计算节能率
//    public void calculateEnergySaving(ControlLightCommandVO v1,ControlLightCommandVO v2){
//      int hour = v2.getHour()- v1.getHour();
//      int min = (v2.getMin()- v1.getMin());
//      int brightness = v2.getBrightness()- v1.getBrightness();
//      int totalTime=(hour*60+min)*60;
//      Double energySaving = (1-(v1.getBrightness()/100.0))*totalTime/(36*24);
//    }
 
 
    /**
     * 用户拥有的路灯
     *
     * @return
     */
    public List<Light> listLight() {
        List<LightBo> listLight;
        if (SecurityUtils.getClientId() != null) {
            listLight = baseMapper.listLight(SecurityUtils.getUserId(), null);
        } else {
            listLight = baseMapper.listLight(null, null);
        }
        List<Light> lightList = new ArrayList<>();
        for (LightBo bean : listLight) {
            Light light = getLight(bean.getDeviceCode());
            lightList.add(light);
        }
        return lightList;
    }
 
    /**
     * 获取用户所有的设备码
     */
    public CommonPage<String> listDeviceCode(int pageNo, int pageSize,String keyword, String deviceCode) {
        List<String> list;
        if (SecurityUtils.getClientId() != null) {
            PageHelper.startPage(pageNo, pageSize);
            list = baseMapper.listCode(SecurityUtils.getUserId(),keyword,deviceCode);
        } else {
 
            PageHelper.startPage(pageNo, pageSize);
            list = baseMapper.listCode(null,keyword,deviceCode);
        }
 
        return CommonPage.restPage(list);
    }
 
    public boolean setPower(List<Long> ids, Integer power1, Integer power2) {
        List<Light> lights = listByIds(ids);
        lights.forEach(light -> {
                    light.setPower1(power1);
                    light.setPower2(power2);
                }
        );
        return updateBatchById(lights);
    }
}