fengxiang
2018-07-04 288d18ea9f93236f179cbd333dc21bebda7c023a
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
package com.moral.service.impl;
 
import java.util.*;
import java.util.stream.Collectors;
 
import javax.annotation.Resource;
 
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.Page;
import com.moral.common.bean.Constants;
import com.moral.common.bean.PageBean;
import com.moral.common.bean.PageResult;
import com.moral.common.exception.BusinessException;
import com.moral.common.util.ExampleUtil;
import com.moral.common.util.RedisUtils;
import com.moral.entity.DeviceVersion;
import com.moral.mapper.DeviceVersionMapper;
import com.moral.mapper.MonitorPointMapper;
import com.moral.mapper.OrganizationMapper;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
 
import com.github.pagehelper.PageHelper;
import com.moral.common.util.ValidateUtil;
import com.moral.entity.Device;
import com.moral.mapper.DeviceMapper;
import com.moral.service.AccountService;
import com.moral.service.DeviceService;
import tk.mybatis.mapper.entity.Example;
 
@Service
public class DeviceServiceImpl implements DeviceService {
    private static Logger log = Logger.getLogger(DeviceServiceImpl.class);
    //-----------------------redis key前缀-开始---------------------------------
    private static String AlARM = "alarm";//警报阀值储存key前缀
    private static String ADJUST="adjust";//校准值存储key前缀
    private static String DEVICE = "device";//设备信息数据key前缀
    private static String STATE = "state";//设备实时状态key前缀
    private static String DATA = "data";//设备实时数据key前缀
    //-----------------------redis key前缀-结束---------------------------------
    private String keysConnect(String... keys) {
        StringBuilder key = new StringBuilder(keys[0]);
        for(int i=1;i<keys.length;i++) {
            key.append("_");
            key.append(keys[i]);
        }
        return key.toString().toLowerCase();
    }
    @Resource
    private DeviceMapper deviceMapper;
    @Resource
    private MonitorPointMapper monitorPointMapper;
    @Resource
    private AccountService accountService;
    private Class ENTITY_CLASS = Device.class;
    @Resource
    OrganizationMapper orgMapper;
    @Resource
    DeviceVersionMapper deviceVersionMapper;
    @Resource
    RedisUtils redisUtils;
    @Override
    public Map<String, Object> getDeviceStatesByAccount(Map<String, Object> parameters) {
        ValidateUtil.notNull(parameters.get("accountId"), "param.is.null");
        Map<String, Object> result = new HashMap<String, Object>();
        accountService.setOrgIdsByAccount(parameters);
        List<Map<String, Object>> list = deviceMapper.getDeviceStatesByAccount(parameters);
        Long all = 0L, normal = 0L, abnormal = 0L, stop = 0L;
        for (Map<String, Object> map : list) {
            Long count = (Long) map.get("count");
            all += count;
            switch (Integer.valueOf((String) map.get("state"))) {
            case 0:
                normal = count;
                break;
            case 4:
                stop = count;
                break;
            default:
                abnormal += count;
            }
        }
        result.put("all", all);
        result.put("normal", normal);
        result.put("abnormal", abnormal);
        result.put("stop", stop);
        return result;
    }
    
    @Override
    @Transactional
    public void saveOrUpdateDevice(Device device) {
        ValidateUtil.notNull(device, "param.is.null");
        ValidateUtil.notEmpty(device.getMac(), "param.is.null");
        Device queryDevice = new Device();
        queryDevice.setMac(device.getMac());
        queryDevice = deviceMapper.selectOne(queryDevice);
        Date operateDate = new Date();
        device.setInstallTime(operateDate);
        if (ObjectUtils.isEmpty(queryDevice)) {
            device.setCreateTime(operateDate);
            device.setState("4");
            device.setIsDelete(Constants.IS_DELETE_FALSE);
            deviceMapper.insertSelective(device);
        }else {
            device.setId(queryDevice.getId());
            deviceMapper.updateByPrimaryKeySelective(device);
        }
        //刷新redis里的信息
        refreshDeviceInRedis(device.getMac());
    }
 
    @Override
    public List<Device> getInstallDevicesByOperateUser(Integer uid, Integer pageIndex, Integer pageSize) {
        ValidateUtil.notNull(uid, "param.is.null");
        Device device = new Device();
        device.setOperateUserId(uid);
        PageHelper.startPage(pageIndex, pageSize,false);
        List<Device> devices = deviceMapper.select(device);
        return devices;
    }
 
    /**
     *
     * @param mac
     * @param fromCache
     * @return 包含组织数组
     */
    @Override
    public  Device getDeviceByMac (String mac ,boolean fromCache){
        if(fromCache){
            Device device = getDeviceFromRedis(mac);
            if(device==null) {
                device = deviceMapper.selectWithOrgIdsByMac(mac);
                if(device!=null){
                    setDeviceToRedis(mac,device);
                }
            }
            return  device;
        }else {
            return  deviceMapper.selectWithOrgIdsByMac(mac);
        }
 
    }
 
    /**
     * 默认会从缓存取
     * @param mac
     * @return
     */
    @Override
    public Device getDeviceByMac(String mac) {
 
        return getDeviceByMac(mac,true);
    }
    /*
     * 获取报警阀值在redis里的key
     */
    private String getDeviceKey(String mac) {
        return keysConnect(DEVICE,mac);
    }
    /*
     * 将校正值存入redis方法组 开始
     */
    private void setDeviceToRedis(String mac,Device device){
        String key = getDeviceKey(mac);
        Device simpleDevice = new Device();
        simpleDevice.setId(device.getId());// id
        simpleDevice.setName(device.getName());// name
        simpleDevice.setAddress(device.getAddress());// address
        simpleDevice.setDeviceVersionId(device.getDeviceVersionId());// version
        simpleDevice.setMac(device.getMac()); // mac
        simpleDevice.setMonitorPointId(device.getMonitorPointId());// 监控地id
        simpleDevice.setOrganizationIds(device.getOrganizationIds());// 组织数组
        simpleDevice.setDeviceVersion(device.getDeviceVersion());
        redisUtils.set(key,simpleDevice);
    }
    private Device getDeviceFromRedis(String mac) {
        String key = getDeviceKey(mac);
        return redisUtils.get(key,Device.class);
    }
 
    /**
     *
     * @param params
     * map里 包括 组织id和4个坐标点
     * @return 返回未删除结果集
     */
    @Override
    public List<Device> query(Map<String, Object> params) {
        Object orgIdObj = params.get("orgId");
        List<Device> deviceList = null;
        if(orgIdObj != null) {
            Integer orgId = Integer.parseInt(orgIdObj.toString());
            List<Integer> orgIds = orgMapper.selectLowerOrgIds(orgId);
            params.put("orgIds", orgIds);
            deviceList = deviceMapper.selectByMap(params);
            loadDeviceState(deviceList);
        }
        return deviceList;
    }
    /**
     *  根据组织id和设备名称 分页查询设备
     * @param orgId
     * @param deviceName
     * @param pageSize
     * @param pageNo
     * @return 返回未删除结果
     */
    @Override
    public PageResult query(Integer orgId, String deviceName, Integer pageSize, Integer pageNo) {
        List<Integer> orgIds = orgMapper.selectLowerOrgIds(orgId);
        if(!ObjectUtils.isEmpty(pageSize)&&!ObjectUtils.isEmpty(pageNo)){
            PageHelper.startPage(pageNo,pageSize);
        }
        String state = null;
        switch (deviceName){
            case "正常":
                state = "0";
                deviceName = null;break;
                case "轻度":
                state = "1";
                deviceName = null;break;
            case "中度":
                state = "2";
                deviceName = null;break;
            case "重度":
                state = "3";
                deviceName = null;break;
            case "维保":
                state = "4";
                deviceName = null;break;
        }
        List<Device> list = deviceMapper.selectByOrgIdAndDevName(orgId,orgIds,state,deviceName);
        //从redis里取状态
        loadDeviceState(list);
        if(list instanceof Page){
            return new PageResult(((Page) list).getTotal(),list);
        }
        return new PageResult(null,list);
    }
 
    /**
     * 根据组织id和监控点id 分页查询设备
     * @param orgId
     * @param mpId
     * @param pageSize
     * @param pageNo
     * @return 返回未删除结果
     */
    @Override
    public PageResult query(Integer orgId, Integer mpId, Integer pageSize, Integer pageNo) {
        List<Integer> orgIds = orgMapper.selectLowerOrgIds(orgId);
        if(!ObjectUtils.isEmpty(pageSize)&&!ObjectUtils.isEmpty(pageNo)){
            PageHelper.startPage(pageNo,pageSize);
        }
        List<Device> list = deviceMapper.selectByOrgIdAndMpId(orgId,orgIds,mpId);
        //从redis里取状态
        loadDeviceState(list);
        if(list instanceof Page){
            return new PageResult(((Page) list).getTotal(),list);
        }
        return new PageResult(null,list);
    }
    private void loadDeviceState(List<Device> list){
        //从redis里取状态
        list.stream().map( device -> {
            String mac = device.getMac();
            if(!StringUtils.isBlank(mac)){
                String state = getSateFromRedis(device.getMonitorPointId(),mac.toLowerCase());
                device.setState(state);
            }else{
                device.setState(Constants.DEVICE_STATE_OFFLINE);
            }
            return device;
        }).count();
    }
    private String getSateFromRedis(Integer mpId,String mac){
 
        Map<String,String> stateMap  = getStateMapFromRedis(mpId,mac);
        String state = null;
        if(stateMap != null){
            state  = stateMap.get("state");
        }
        state = state == null ?Constants.DEVICE_STATE_OFFLINE:state;
        return  state;
    }
    public Map<String,String> getStateMapFromRedis(Integer mpId,String mac){
        StringBuilder key = new StringBuilder();
        //拼凑key
        key.append("state_").append(mpId).append("_").append(mac);
        return   redisUtils.get(key.toString(),new TypeReference<Map<String,String>>(){});
    }
    private Device getDeviceWithOrgIdsByMac(String mac) {
        String key = "device_"+mac;
        Device device = redisUtils.get(key,Device.class);
        if(device==null) {
            device = deviceMapper.selectWithOrgIdsByMac(mac);
            if(device!=null){
                redisUtils.set(key,device);
            }
        }
        return device;
    }
 
    /**
     * 要在数据库更改后刷新
     * 刷新 redis 设备的信息
     * @param mac
     */
    private void refreshDeviceInRedis(String mac){
         if(!StringUtils.isBlank(mac)){
              Device device = deviceMapper.selectWithOrgIdsByMac(mac);
             setDeviceToRedis(mac,device);
         }else
         {
             log.warn("param mac is null in method [refreshDeviceInRedis]");
         }
    }
    @Override
    public int countByExample(PageBean pageBean){
        Example example = ExampleUtil.generateExample(ENTITY_CLASS,pageBean);
        addDeletesToExample(example);
        return deviceMapper.selectCountByExample(example);
    }
 
    /**
     * 增加删除条件过滤
     * @param example
     */
    private void addDeletesToExample(Example example){
        List<Example.Criteria> criteriaList = example.getOredCriteria();
        if(criteriaList!=null&&criteriaList.size()>0){
            for(Example.Criteria cri : criteriaList){
                cri.andNotEqualTo("isDelete", Constants.IS_DELETE_TRUE);
            }
        }else {
            example.or().andNotEqualTo("isDelete",Constants.IS_DELETE_TRUE);
        }
    }
    @Override
    public PageBean queryByPageBean(PageBean pageBean) {
        Example example = ExampleUtil.generateExample(ENTITY_CLASS,pageBean);
        addDeletesToExample(example);
        if(pageBean.getPageSize()>0){
            PageHelper.startPage(pageBean.getPageIndex(),pageBean.getPageSize());
        }
        List<Device> deviceList = deviceMapper.selectWithRelationData(example);
        return new PageBean(deviceList);
    }
 
    @Override
    public void deleteByIds(Integer[] ids) {
        Device device = new Device();
        device.setIsDelete(Constants.IS_DELETE_TRUE);
        if(ids!=null&&ids.length>0){
            Example example = new Example(ENTITY_CLASS);
            example.or().andIn("id", Arrays.asList(ids));
            if(ids.length==1){
                device.setId(ids[0]);
                deviceMapper.updateByPrimaryKeySelective(device);
            }else{
                deviceMapper.updateByExampleSelective(device,example);
            }
            List<Device> deviceList = deviceMapper.selectByExample(example);
            List<String> adjustAndDeviceKeys = deviceList.stream().collect(
                    ArrayList<String>::new,
                    (list,dev) -> {
                        if(!StringUtils.isBlank(dev.getMac())){
                            list.add("device_"+dev.getMac());
                            list.add("adjust_"+dev.getMac());
                        }
                    },
                    (oList,nList)-> {
                        oList.addAll(nList);
                    }
            );
            redisUtils.remove(adjustAndDeviceKeys.toArray(new String [adjustAndDeviceKeys.size()]));
        }
    }
 
    @Override
    @Transactional
    public void addOrModify(Device device){
        try{
            //mac 转小写
            if(!StringUtils.isBlank(device.getMac())){
                device.setMac(device.getMac().toLowerCase());
            }
            if(device.getId()!=null){
                deviceMapper.updateByPrimaryKeySelective(device);
            }else{
                Device deviceQuery = new Device();
                deviceQuery.setMac(device.getMac());
                Device deviceResult = deviceMapper.selectOne(deviceQuery);
                if(deviceResult !=null){
                    device.setId(deviceResult.getId());
                    deviceMapper.updateByPrimaryKeySelective(device);
                }else {
                    device.setState(Constants.DEVICE_STATE_OFFLINE);
                    device.setIsDelete(Constants.IS_DELETE_FALSE);
                    deviceMapper.insertSelective(device);
                }
            }
            //刷新redis里设备信息
            refreshDeviceInRedis(device.getMac());
        }
        catch (Exception ex){
            throw  ex;
        }
    }
    @Override
    public List<Map> countByTimes(Date start,Date end,String format){
        if(start==null||end==null||StringUtils.isBlank(format)){
            log.error("some  params is null");
            throw new BusinessException("some  params is null");
        }
        return  deviceMapper.countByTimes(start, end, format);
    }
    @Override
    public List<Device> getDevicesByMonitorPointId(Integer monitorPointId) {
        Device device = new Device();
        device.setMonitorPointId(monitorPointId);
        device.setIsDelete(Constants.IS_DELETE_FALSE);
        return deviceMapper.select(device);
    }
 
    /**
     *  返回map{mac:,state:}
     * @param macList
     * @return
     */
    @Override
    public List<Map<String,String>> queryDevicesState(List<String> macList,Boolean withData) {
        List<Map<String,String>> list = macList.stream().map(mac->{
            Map<String,String> resultMap = new HashMap<>();
            if(!StringUtils.isBlank(mac)){
                mac = mac.toLowerCase();
                Device device = getDeviceWithOrgIdsByMac(mac);
                Map<String,String> stateMap = getStateMapFromRedis(device.getMonitorPointId(),mac);
                if(!MapUtils.isEmpty(stateMap)){
                    resultMap.putAll(stateMap);
                }else{
                    resultMap.put("state",Constants.DEVICE_STATE_OFFLINE);
                    resultMap.put("mac",mac);
                }
                //添加data
                if(BooleanUtils.isTrue(withData)){
                    String dataKey = "data_"+mac;
                    Map<String,String> dataMap = redisUtils.get(dataKey,new TypeReference<Map<String,String>>(){});
                    if(!MapUtils.isEmpty(dataMap)){
                        resultMap.putAll(dataMap);
                    }
                }
            }
            return  resultMap;
        }).collect(Collectors.toList());
        return list;
    }
 
    @Override
    public Device queryById(Integer id) {
        return deviceMapper.selectByPrimaryKey(id);
    }
 
    @Override
    public List<Device> getDevicesByProfessionId(Map<String, Object> parameters) {
        
        return deviceMapper.getDevicesByProfession(parameters);
    }
 
}