SmartSceneServiceImpl.java
16.3 KB
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
package com.glsx.smart.service.impl;
import cn.com.glsx.didicb.app.enums.MessageTypeEnum;
import cn.com.glsx.didicb.app.model.CarAssistantInfo;
import cn.com.glsx.didicb.app.remote.CarAssistantInfoRemote;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsx.smart.dao.entity.SmartDeviceStatus;
import com.glsx.smart.dao.entity.SmartScene;
import com.glsx.smart.dao.entity.SmartSceneData;
import com.glsx.smart.dao.mapper.SmartDeviceStatusMapper;
import com.glsx.smart.dao.mapper.SmartSceneDataMapper;
import com.glsx.smart.dao.mapper.SmartSceneMapper;
import com.glsx.smart.exception.BusinessException;
import com.glsx.smart.exception.ResultEnum;
import com.glsx.smart.pojo.ExecuteTaskVo;
import com.glsx.smart.pojo.OrderResponse;
import com.glsx.smart.pojo.ResponseVo;
import com.glsx.smart.redis.RedisService;
import com.glsx.smart.service.BaseService;
import com.glsx.smart.service.SmartSceneService;
import com.glsx.smart.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* <p>Description:
* <p>Project: chejia-smart
*
* @author wbh
* @date 2021-03-15
*/
@Slf4j
@Service
public class SmartSceneServiceImpl extends BaseService implements SmartSceneService {
@Resource
private SmartSceneMapper sceneMapper;
@Resource
private SmartSceneDataMapper sceneDataMapper;
@Value("${orderIssueurl}")
private String orderIssueurl;
@Value("${instructionInfIssue}")
private String instructionInfIssue;
@Value("${infoUrl}")
private String infoUrl;
@Value("${infotimeout}")
private int infotimeout;
@DubboReference
private CarAssistantInfoRemote carAssistantInfoRemote;
@Resource
private SmartDeviceStatusMapper smartDeviceStatusMapper;
@Resource
private RedisService redisService;
@Override
public List<SmartScene> getList(SmartScene record) {
return sceneMapper.getList(record);
}
@Override
public int deleteByPrimaryKey(Long id) {
return sceneMapper.deleteByPrimaryKey(id);
}
@Override
public int insertOrUpdate(SmartScene scene) {
if (scene.getId() == null) {
return sceneMapper.insertSelective(scene);
} else {
SmartScene record = sceneMapper.selectByPrimaryKey(scene.getId());
if (record != null) {
return sceneMapper.updateByPrimaryKeySelective(scene);
} else {
throw new BusinessException(ResultEnum.ID_NOT_FOUND);
}
}
}
@Override
public int insertSelective(SmartScene scene) {
return sceneMapper.insertSelective(scene);
}
@Override
@Transactional
public int insert(SmartScene record) {
int i = sceneMapper.insertSelective(record);
Long id = record.getId();
log.info("保存用户场景数据生成id:{}", record.getId());
if (i > 0) {
List<SmartSceneData> list = record.getDataList();
if (!list.isEmpty()) {
for (SmartSceneData data : list) {
data.setSceneId(id);
}
sceneDataMapper.batchInsert(list);
}
}
return i;
}
@Override
@Transactional
public int update(SmartScene record) {
Long id = record.getId();
int i = sceneMapper.updateByPrimaryKeySelective(record);
if (i > 0) {
sceneDataMapper.deleteBySceneId(id);
List<SmartSceneData> list = record.getDataList();
if (!list.isEmpty()) {
for (SmartSceneData data : list) {
data.setSceneId(id);
}
sceneDataMapper.batchInsert(list);
}
}
return i;
}
@Override
public SmartScene getById(Long id) {
return sceneMapper.getById(id);
}
@Override
public int updateByPrimaryKeySelective(SmartScene record) {
return sceneMapper.updateByPrimaryKeySelective(record);
}
private Object revertType(String valueType, String object) {
Object orderValue = null;
switch (valueType) {
case "1":
orderValue = object;
break;
case "2":
orderValue = Integer.parseInt(object);
break;
case "3":
orderValue = Boolean.valueOf(object);
break;
default:
orderValue = object;
break;
}
return orderValue;
}
/**
* 下发场景
*
* @param scene 场景
* @return
*/
@Override
public List<OrderResponse> issueOrder(SmartScene scene) {
List<OrderResponse> orderResponseList = new ArrayList<>();
List<SmartSceneData> smartTemplateParamList = sceneDataMapper.getBySceneId(scene.getId());
if (CollectionUtils.isEmpty(smartTemplateParamList)) {
log.info("未查到该场景id的条件{}", scene.getId());
return orderResponseList;
}
// 下发指令
List<SmartSceneData> orders = smartTemplateParamList.stream().filter(index -> index.getParamKey().equals("scene_content_device")).collect(Collectors.toList());
if (CollectionUtils.isEmpty(orders)) {
log.info("未查到该场景id的指令{}", scene.getId());
} else {
try {
for (int i = 0; i < orders.size(); i++) {
OrderResponse orderResponse = new OrderResponse();
Map<String, List<Map<String, Object>>> ordermaps = new HashMap<>();
SmartSceneData index = orders.get(i);
List<Map<String, Object>> maps = new ArrayList<>();
Map<String, Object> ordermap = new HashMap<>();
String paramValue = index.getParamValue();
if (StringUtils.isEmpty(paramValue)) {
log.info("参数异常{}", index.getParamKey());
continue;
}
ExecuteTaskVo executeTaskVo = JSONObject.parseObject(paramValue, ExecuteTaskVo.class);
if (StringUtils.isEmpty(executeTaskVo.getSelect())) {
log.info("参数异常{}", index.getParamKey());
continue;
}
// 根据遥控器id下发普通指令还是红外遥控指令
String remoteId = executeTaskVo.getRemoteId();
String devideId = executeTaskVo.getSelect();
JSONObject jsonObject = null;
if (StringUtils.isBlank(remoteId)) {
// 如果设备状态已经是设置的,不重复下发
String order_value = executeTaskVo.getOrderVal() == null ? executeTaskVo.getValue() : executeTaskVo.getOrderVal();
SmartDeviceStatus smartDevideStatus = smartDeviceStatusMapper.findDevStatusByIdAndCode(devideId, executeTaskVo.getOrder());
if (smartDevideStatus != null && smartDevideStatus.getDeviceOrderValue().equals(order_value)) {
log.info("该设备已经设置成当前需要的状态,设备id{}", devideId);
continue;
}
String valueType = executeTaskVo.getValType();
ordermap.put("code", executeTaskVo.getOrder());
ordermap.put("value", revertType(valueType, order_value));
maps.add(ordermap);
ordermaps.put("commands", maps);
log.info("发送的指令{}", JSON.toJSONString(maps));
// 下发普通指令
jsonObject = HttpUtil.sendPost(orderIssueurl.replace("{device_id}", devideId), JSONObject.toJSONString(ordermaps), new HashMap<>());
} else {
ordermap.put("key", executeTaskVo.getOrderVal());
// 下发红外遥控指令
jsonObject = HttpUtil.sendPost(instructionInfIssue.replace("{remote_id}", remoteId).replace("{infrared_id}", devideId), JSONObject.toJSONString(ordermap), new HashMap<>());
}
if (jsonObject != null) {
ResponseVo responseVo = JSONObject.toJavaObject(jsonObject, ResponseVo.class);
if (responseVo.getCode().equals("200")) {
log.info("设备{}下发成功", devideId);
orderResponse.setMessage("下发成功");
orderResponse.setResult(true);
} else {
log.info("设备{}下发失败,错误信息为{}", devideId, responseVo.getMessage());
orderResponse.setResult(false);
orderResponse.setMessage(responseVo.getMessage());
orderResponse.setCode(Integer.parseInt(responseVo.getCode()));
}
orderResponse.setDeviceName(executeTaskVo.getDeviceName());
orderResponseList.add(orderResponse);
}
}
} catch (Exception e) {
e.printStackTrace();
log.info("下发异常,{}", e);
}
}
// 下发推送通知(Android设备和ios设备)
issueNotice(scene, orderResponseList);
// 下发系统消息
List<SmartSceneData> scene_content_system = smartTemplateParamList.stream().filter(index -> index.getParamKey().equals("scene_content_system")).collect(Collectors.toList());
scene_content_system.forEach(index -> {
String paramValue = index.getParamValue();
ExecuteTaskVo executeTaskVo = JSONObject.parseObject(paramValue, ExecuteTaskVo.class);
issueSystemNotice(scene, executeTaskVo.getMsg());
});
return orderResponseList;
}
/**
* 下发系统通知
*
* @param scene 场景
* @param msg 信息
*/
private void issueSystemNotice(SmartScene scene, String msg) {
String title = "收到一条智能消息";
Map<String, Object> map = sceneMapper.getBySourceAndUserId(scene.getId());
String user_id = map.get("user_id") + "";
Map<String, String> paramMap = new HashMap<>();
paramMap.put("alias", user_id);
paramMap.put("deviceType", map.get("source") + "");
paramMap.put("title", title);
paramMap.put("body", msg);
paramMap.put("msgBody", msg);
saveMegInfo(user_id, title, msg);
try {
JSONObject jsonObject = HttpUtil.sendPost(infoUrl, JSONObject.toJSONString(paramMap), new HashMap<>());
if (jsonObject != null) {
String code = jsonObject.get("code") + "";
if (("200").equals(code)) {
log.info("场景{}系统消息下发通知成功", scene.getId());
} else {
log.info("场景{}系统消息下发通知失败", jsonObject.get("message"));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 保存消息通知
*
* @param user_id 用户id
* @param title 标题
* @param msg 消息
*/
private void saveMegInfo(String user_id, String title, String msg) {
CarAssistantInfo carAssistantInfo = new CarAssistantInfo();
carAssistantInfo.setUserId(Integer.parseInt(user_id));
carAssistantInfo.setCreateBy(Integer.parseInt(user_id));
carAssistantInfo.setContent(msg);
carAssistantInfo.setTitle(title);
carAssistantInfo.setMessageType(MessageTypeEnum.SYSTEM_MESSAGE.getValue());
carAssistantInfoRemote.insert(carAssistantInfo);
}
/**
* 推送通知
*
* @param scene 场景
* @param orderResponseList 下发场景返回的消息
*/
private void issueNotice(SmartScene scene, List<OrderResponse> orderResponseList) {
if (CollectionUtils.isNotEmpty(orderResponseList)) {
String content = "";
String title = "收到一条智能消息";
Map<String, Object> map = sceneMapper.getBySourceAndUserId(scene.getId());
String user_id = map.get("user_id") + "";
String scene_name = map.get("scene_name") + "";
Map<String, String> paramMap = new HashMap<>();
paramMap.put("alias", user_id);
paramMap.put("deviceType", map.get("source") + "");
paramMap.put("title", title);
List<OrderResponse> collect = orderResponseList.stream().filter(index -> !index.isResult()).collect(Collectors.toList());
if (CollectionUtils.isEmpty(collect)) {
content = MessageFormat.format("您配置的{0}场景已执行,点击可查看详情。", scene_name);
} else {
boolean flag = repeatNotification(scene.getId());
if (flag) {
log.info("场景下发不成功,不允许持续发消息,场景id{}", scene.getId());
return;
}
content = MessageFormat.format("您配置的{0}场景未顺利执行,点击可查看详情。", scene_name);
}
paramMap.put("body", content);
String context = buildBody(user_id, title, collect, scene.getId(), scene_name);
paramMap.put("msgBody", context);
saveMegInfo(user_id, title, context);
try {
JSONObject jsonObject = HttpUtil.sendPost(infoUrl, JSONObject.toJSONString(paramMap), new HashMap<>());
if (jsonObject != null) {
String code = jsonObject.get("code") + "";
if (("200").equals(code)) {
log.info("场景{}下发通知成功", scene.getId());
} else {
log.info("场景{}下发通知失败", jsonObject.get("message"));
}
}
} catch (IOException e) {
e.printStackTrace();
log.info("下发通知异常{}",e);
}
}
}
private boolean repeatNotification(Long id) {
String key = "senceId_" + id;
Object o = redisService.get(key);
log.info("{}从redis查询出来的数据为{}", key, o);
if (o == null) {
redisService.setOutTime(key, key, infotimeout, TimeUnit.MINUTES);
return false;
} else {
return true;
}
}
/**
* 消息推送到app端
*
* @param user_id 用户id
* @param title 标题
* @param orderResponseList 内容
* @param id 场景id
* @param scene_name
*/
private String buildBody(String user_id, String title, List<OrderResponse> orderResponseList, Long id, String scene_name) {
String context = "";
if (CollectionUtils.isEmpty(orderResponseList)) {
context = MessageFormat.format("您配置的{0}场景已在{1} 成功执行", scene_name, new Date());
} else {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < orderResponseList.size(); i++) {
OrderResponse orderResponse = orderResponseList.get(i);
String deviceName = orderResponse.getDeviceName();
String message = orderResponse.getMessage();
sb.append(deviceName).append(message).append(",");
}
context = MessageFormat.format("您配置的{0}场景已在{1}触发执行,但因以下设备{2}未能执行成功,请关注以上设备状态", scene_name, new Date(), sb.toString().substring(0, sb.toString().length() - 1));
}
return context;
}
}