Commit e0279c66cb587741069cd2b36abc2c3fb5c734a6

Authored by 杨鸣坤
1 parent 2edfee4d

尚云幕墙三色灯设备同步

  1 +package com.iot.scheduler.service.wuwei;
  2 +
  3 +import com.alibaba.fastjson.JSON;
  4 +import com.alibaba.fastjson.JSONArray;
  5 +import com.alibaba.fastjson.JSONObject;
  6 +import com.alibaba.fastjson.TypeReference;
  7 +import com.iot.scheduler.model.DeviceToken;
  8 +import com.iot.scheduler.model.QxDeviceInfo;
  9 +import com.iot.scheduler.model.QxDeviceInfoDetail;
  10 +import jakarta.annotation.Resource;
  11 +import lombok.extern.slf4j.Slf4j;
  12 +import org.apache.commons.lang3.StringUtils;
  13 +import org.apache.http.Consts;
  14 +import org.apache.http.HttpEntity;
  15 +import org.apache.http.client.methods.CloseableHttpResponse;
  16 +import org.apache.http.client.methods.HttpGet;
  17 +import org.apache.http.client.methods.HttpPost;
  18 +import org.apache.http.entity.ContentType;
  19 +import org.apache.http.entity.StringEntity;
  20 +import org.apache.http.impl.client.CloseableHttpClient;
  21 +import org.apache.http.impl.client.HttpClients;
  22 +import org.apache.http.message.BasicHeader;
  23 +import org.apache.http.util.EntityUtils;
  24 +import org.springframework.beans.factory.annotation.Value;
  25 +import org.springframework.data.redis.core.RedisTemplate;
  26 +import org.springframework.stereotype.Service;
  27 +import org.springframework.util.CollectionUtils;
  28 +import org.springframework.util.LinkedMultiValueMap;
  29 +import org.springframework.util.MultiValueMap;
  30 +import org.springframework.web.util.UriComponentsBuilder;
  31 +
  32 +import java.io.ByteArrayOutputStream;
  33 +import java.io.IOException;
  34 +import java.io.InputStream;
  35 +import java.text.SimpleDateFormat;
  36 +import java.util.*;
  37 +import java.util.concurrent.TimeUnit;
  38 +
  39 +
  40 +/**
  41 + * 尚云幕墙三色灯--->IOT平台
  42 + */
  43 +@Slf4j
  44 +@Service
  45 +public class SyDevicePullService {
  46 +
  47 + @Value("${sy.iot.organizeId:}")
  48 + private String iotOrganizeId;
  49 + @Value("${sy.iot.profileId}")
  50 + private String iotProfileId;
  51 + @Value("${sy.iot.deviceProfileId}")
  52 + private String iotDeviceProfileId;
  53 + @Value("${sy.iot.userName:}")
  54 + private String iotUserName;
  55 + @Value("${sy.iot.password:}")
  56 + private String iotPassword;
  57 + @Value("${sy.iot.tokenUrl}")
  58 + private String iotTokenUrl;
  59 + @Value("${sy.iot.infoUrl}")
  60 + private String iotDeviceInfoUrl;
  61 + @Value("${sy.iot.detailUrl}")
  62 + private String iotDeviceDetailUrl;
  63 +
  64 +
  65 + @Value("${device.token.url}")
  66 + private String deviceTokenUrl;
  67 + @Value("${device.token.userName}")
  68 + private String deviceUserName;
  69 + @Value("${device.token.password}")
  70 + private String devicePassword;
  71 + @Value("${device.info.url}")
  72 + private String deviceInfoUrl;
  73 + @Value("${device.detail.url}")
  74 + private String deviceDetailUrl;
  75 +
  76 + @Resource
  77 + private RedisTemplate<String, String> redisTemplate;
  78 +
  79 + final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  80 +
  81 + public void pullDeviceAndPushToIot() {
  82 + String deviceResult = getDeviceInfo();
  83 + Map<String, Object> deviceInfos = JSON.parseObject(deviceResult, new TypeReference<>() {
  84 + });
  85 +
  86 + JSONArray deviceInfoList = (JSONArray) deviceInfos.get("data");
  87 + List<QxDeviceInfo> qxDeviceInfos = new ArrayList<>();
  88 + List<QxDeviceInfoDetail> qxAddDeviceInfoDetails = new ArrayList<>();
  89 + Map<String, QxDeviceInfoDetail> qxDeviceInfoDetailMap = new HashMap<>();
  90 + for (Object o : deviceInfoList) {
  91 + JSONObject deviceInfoJson = (JSONObject) o;
  92 + QxDeviceInfo qxDeviceInfo = new QxDeviceInfo();
  93 + qxDeviceInfo.setDeviceType("DIRECT_CONNECTION");
  94 + qxDeviceInfo.setTransportType("DEFAULT");
  95 + qxDeviceInfo.setOrganizationId(iotOrganizeId);
  96 + qxDeviceInfo.setDeviceProfileId(iotDeviceProfileId);
  97 + qxDeviceInfo.setProfileId(iotProfileId);
  98 +// //项目状态(1:在线,2:离线,3:报警)
  99 +// Integer projectState = deviceInfoJson.getInteger("projectState");
  100 +// if (projectState != null) {
  101 +// qxDeviceInfo.setDescription(String.valueOf(projectState));
  102 +// }
  103 +
  104 + //项目类型
  105 + qxDeviceInfo.setLabel("生产设备");
  106 + //设备名称
  107 + String deviceName = deviceInfoJson.getString("deviceName");
  108 +
  109 + qxDeviceInfo.setName(deviceName);
  110 + qxDeviceInfo.setBrand(deviceName);
  111 + //序列号
  112 + String dtuSn = deviceInfoJson.getString("dtuSn");
  113 + qxDeviceInfo.setSn(dtuSn);
  114 + DeviceToken deviceToken = new DeviceToken();
  115 + deviceToken.setCredentialsType("ACCESS_TOKEN");
  116 + deviceToken.setCredentialsId(dtuSn);
  117 + deviceToken.setCredentialsValue(dtuSn);
  118 + qxDeviceInfo.setDeviceToken(deviceToken);
  119 + qxDeviceInfos.add(qxDeviceInfo);
  120 + //有序列号直接获取灯信息
  121 + if (StringUtils.isNotBlank(dtuSn)) {
  122 + String deviceInfoDetails = getDeviceInfoDetail(dtuSn);
  123 + if (StringUtils.isBlank(deviceInfoDetails)) {
  124 + continue;
  125 + }
  126 +
  127 + Map<String, Object> deviceInfoDetailMap = JSON.parseObject(deviceInfoDetails, new TypeReference<>() {
  128 + });
  129 +
  130 + JSONArray deviceInfoDetailList = (JSONArray) deviceInfoDetailMap.get("data");
  131 + if (CollectionUtils.isEmpty(deviceInfoDetailList)) {
  132 + continue;
  133 + }
  134 +
  135 + JSONObject deviceInfoDetailJson = (JSONObject) deviceInfoDetailList.get(0);
  136 + //灯详情数据
  137 + //序列号
  138 + String dtuSnDetail = deviceInfoDetailJson.getString("dtuSn");
  139 + //开始时间
  140 + String startTime = deviceInfoDetailJson.getString("startTime");
  141 + QxDeviceInfoDetail qxDeviceInfoDetail = new QxDeviceInfoDetail();
  142 + qxDeviceInfoDetail.setAlarm(false);
  143 + //灯状态(0:灭灯,1:红,2:黄,3:绿,4:蓝)
  144 + Integer lampState = deviceInfoDetailJson.getInteger("lampState");
  145 + switch (lampState) {
  146 + case 0:
  147 + qxDeviceInfoDetail.setStatus("OFF");
  148 + break;
  149 + case 1:
  150 + qxDeviceInfoDetail.setStatus("ERROR");
  151 + qxDeviceInfoDetail.setAlarm(true);
  152 + break;
  153 + case 2:
  154 + qxDeviceInfoDetail.setStatus("STAND");
  155 + break;
  156 + case 3:
  157 + qxDeviceInfoDetail.setStatus("RUN");
  158 + break;
  159 + default:
  160 + continue;
  161 + }
  162 +
  163 + if (StringUtils.isNotBlank(startTime)) {
  164 + try {
  165 + qxDeviceInfoDetail.setStartTime(dateFormat.parse(startTime));
  166 + } catch (Exception e) {
  167 + log.error("时间格式出错");
  168 + qxDeviceInfoDetail.setStartTime(new Date());
  169 + }
  170 + } else {
  171 + qxDeviceInfoDetail.setStartTime(new Date());
  172 + }
  173 +
  174 + qxDeviceInfoDetail.setDtuSn(dtuSn);
  175 + qxDeviceInfoDetailMap.put(dtuSn, qxDeviceInfoDetail);
  176 + qxAddDeviceInfoDetails.add(qxDeviceInfoDetail);
  177 + }
  178 + }
  179 +
  180 + //将数据同步到IOT平台
  181 + Map<String, String> qxParam = new HashMap<>(2);
  182 + qxParam.put("username", iotUserName);
  183 + qxParam.put("password", iotPassword);
  184 +
  185 + HttpPost qxHttpPost = new HttpPost(iotTokenUrl);
  186 + String qxResult = sendPost(qxHttpPost, JSON.toJSONString(qxParam));
  187 + if (StringUtils.isBlank(qxResult)) {
  188 + return;
  189 + }
  190 + Map<String, Object> qxRes = JSON.parseObject(qxResult, new TypeReference<Map<String, Object>>() {
  191 + });
  192 +
  193 + String qxAccessToken = (String) qxRes.get("token");
  194 + if (StringUtils.isBlank(qxAccessToken)) {
  195 + return;
  196 + }
  197 +
  198 + BasicHeader qxAuthorization = new BasicHeader("X-Authorization", "Bearer " + qxAccessToken);
  199 + if (!CollectionUtils.isEmpty(qxDeviceInfos)) {
  200 + HttpPost qxDeviceInfoPost = new HttpPost(iotDeviceInfoUrl);
  201 + qxDeviceInfoPost.addHeader(qxAuthorization);
  202 + for (QxDeviceInfo qxDeviceInfo : qxDeviceInfos) {
  203 + // todo
  204 + String syncDeviceInfo = sendPost(qxDeviceInfoPost, JSON.toJSONString(qxDeviceInfo));
  205 + //log.info("同步设备信息 syncDeviceInfo:{}", syncDeviceInfo);
  206 + }
  207 + }
  208 +
  209 + if (!CollectionUtils.isEmpty(qxAddDeviceInfoDetails)) {
  210 + for (QxDeviceInfoDetail qxDeviceInfoDetail : qxAddDeviceInfoDetails) {
  211 + String qxDeviceInfoDetailUrlStr = iotDeviceDetailUrl + qxDeviceInfoDetail.getDtuSn() + "/telemetry";
  212 + HttpPost qxDeviceInfoDetailPost = new HttpPost(qxDeviceInfoDetailUrlStr);
  213 + qxDeviceInfoDetailPost.addHeader(qxAuthorization);
  214 + String syncDeviceInfoDetail = sendPost(qxDeviceInfoDetailPost, JSON.toJSONString(qxDeviceInfoDetail));
  215 + }
  216 + }
  217 + }
  218 +
  219 + public String getDeviceInfoDetail(String dtuSn) {
  220 + String accessToken = getAccessToken();
  221 + Map<String, String> dtuSnOb = new HashMap<>(1);
  222 + dtuSnOb.put("dtuSn", dtuSn);
  223 + Map<String, String> headerMap = new HashMap<>(1);
  224 + headerMap.put("Authorization", "Bearer " + accessToken);
  225 + String deviceInfoDetail = sendRequestGet(deviceDetailUrl, dtuSnOb, headerMap);
  226 + if (StringUtils.isBlank(deviceInfoDetail)) {
  227 + return null;
  228 + }
  229 +
  230 + Map<String, Object> deviceInfoDetailMap = JSON.parseObject(deviceInfoDetail,
  231 + new TypeReference<>() {
  232 + });
  233 + Integer deviceInfoDetailCode = (Integer) deviceInfoDetailMap.get("code");
  234 + if (deviceInfoDetailCode != 200) {
  235 + return null;
  236 + }
  237 +
  238 + JSONArray deviceInfoDetailList = (JSONArray) deviceInfoDetailMap.get("data");
  239 + if (CollectionUtils.isEmpty(deviceInfoDetailList)) {
  240 + return null;
  241 + }
  242 +
  243 + JSONObject deviceInfoDetailJson = (JSONObject) deviceInfoDetailList.get(0);
  244 + //灯详情数据
  245 + //灯状态(0:灭灯,1:红,2:黄,3:绿,4:蓝)
  246 + Integer lampState = deviceInfoDetailJson.getInteger("lampState");
  247 + if (lampState == null) {
  248 + return null;
  249 + }
  250 +
  251 + return deviceInfoDetail;
  252 + }
  253 +
  254 +
  255 + public String getDeviceInfo() {
  256 + String accessToken = getAccessToken();
  257 + // 初始化headerMap并设置Authorization
  258 + Map<String, String> headerMap = new HashMap<>(1);
  259 + headerMap.put("Authorization", "Bearer " + accessToken);
  260 +
  261 + Map<String, String> paramsMap = new HashMap<>();
  262 + paramsMap.put("groupName", "尚云幕墙");
  263 +
  264 + // 第一次请求设备信息
  265 + String deviceResult = sendRequestGet(deviceInfoUrl, paramsMap, headerMap);
  266 +
  267 + // 检查设备信息是否为空
  268 + if (StringUtils.isBlank(deviceResult)) {
  269 + return null;
  270 + }
  271 +
  272 + // 解析设备信息
  273 + Map<String, Object> deviceInfos = JSON.parseObject(deviceResult, new TypeReference<>() {
  274 + });
  275 + Integer deviceInfoCode = (Integer) deviceInfos.get("code");
  276 +
  277 + // 如果code不为200,可能是accessToken失效,重新获取token并重试
  278 + if (deviceInfoCode != 200) {
  279 + accessToken = getAccessToken();
  280 + if (StringUtils.isEmpty(accessToken)) {
  281 + return null;
  282 + }
  283 +
  284 + // 更新headerMap中的Authorization
  285 + headerMap.put("Authorization", "Bearer " + accessToken);
  286 +
  287 + // 第二次请求设备信息
  288 + deviceResult = sendRequestGet(deviceInfoUrl, paramsMap, headerMap);
  289 + if (StringUtils.isBlank(deviceResult)) {
  290 + return null;
  291 + }
  292 +
  293 + // 重新解析设备信息
  294 + deviceInfos = JSON.parseObject(deviceResult, new TypeReference<>() {
  295 + });
  296 + deviceInfoCode = (Integer) deviceInfos.get("code");
  297 +
  298 + // 如果第二次请求仍然失败,返回错误信息
  299 + if (deviceInfoCode != 200) {
  300 + return null;
  301 + }
  302 + }
  303 +
  304 + // 返回成功的设备信息
  305 + return deviceResult;
  306 + }
  307 +
  308 + private String getAccessToken() {
  309 + String accessToken = "";
  310 + String redisKey = "device_token";
  311 + if (StringUtils.isNotBlank(redisTemplate.opsForValue().get(redisKey)) && redisTemplate.getExpire(redisKey) > 0) {
  312 + return redisTemplate.opsForValue().get(redisKey);
  313 + }
  314 +
  315 + Map<String, String> param = new HashMap<>(2);
  316 + param.put("username", deviceUserName);
  317 + param.put("password", devicePassword);
  318 + HttpPost httpPost = new HttpPost(deviceTokenUrl);
  319 + String result = sendPost(httpPost, JSON.toJSONString(param));
  320 + if (StringUtils.isBlank(result)) {
  321 + return accessToken;
  322 + }
  323 +
  324 + Map<String, Object> res = JSON.parseObject(result, new TypeReference<>() {
  325 + });
  326 +
  327 + Integer code = (Integer) res.get("code");
  328 + if (code == 200) {
  329 + JSONObject data = (JSONObject) res.get("data");
  330 + accessToken = (String) data.get("token");
  331 + redisTemplate.opsForValue().set(redisKey, accessToken, 3600, TimeUnit.SECONDS); // 一小时过期
  332 + }
  333 +
  334 + return accessToken;
  335 + }
  336 +
  337 + public static String sendRequestGet(String url, Map<String, String> params, Map<String, String> header) {
  338 + //实例化httpclient
  339 + CloseableHttpClient httpclient = HttpClients.createDefault();
  340 + url = builderUrl(url, params);
  341 + //请求结果
  342 + String content = "";
  343 + //实例化get方法
  344 + HttpGet httpget = new HttpGet(url);
  345 + if (!CollectionUtils.isEmpty(header)) {
  346 + for (Map.Entry<String, String> entry : header.entrySet()) {
  347 + httpget.setHeader(entry.getKey(), entry.getValue());
  348 + }
  349 + }
  350 +
  351 + try (CloseableHttpResponse response = httpclient.execute(httpget)) {
  352 +
  353 + //执行get方法
  354 + if (response.getStatusLine().getStatusCode() == 200) {
  355 + content = EntityUtils.toString(response.getEntity(), "UTF-8");
  356 + }
  357 + } catch (IOException e) {
  358 + log.error("sendRequest---GET Error!", e);
  359 + }
  360 + return content;
  361 + }
  362 +
  363 + private static String builderUrl(String url, Map<String, String> params) {
  364 + UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url);
  365 + if (!CollectionUtils.isEmpty(params)) {
  366 + MultiValueMap<String, String> paramsValue = new LinkedMultiValueMap<>();
  367 + for (Map.Entry<String, String> entry : params.entrySet()) {
  368 + paramsValue.add(entry.getKey(), entry.getValue());
  369 + }
  370 +
  371 + uriBuilder = uriBuilder.queryParams(paramsValue);
  372 + }
  373 +
  374 + return uriBuilder.toUriString();
  375 + }
  376 +
  377 + private String sendPost(HttpPost httpPost, String jsonData) {
  378 + CloseableHttpClient httpClient = HttpClients.createDefault();
  379 + StringEntity entity = new StringEntity(jsonData, ContentType.create("application/json", Consts.UTF_8));
  380 + httpPost.setEntity(entity);
  381 + String result = null;
  382 + try {
  383 + CloseableHttpResponse execute = httpClient.execute(httpPost);
  384 + HttpEntity res = execute.getEntity();
  385 + InputStream is = res.getContent();
  386 + int len;
  387 + byte[] buf = new byte[128];
  388 + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  389 + while ((len = is.read(buf)) != -1) {
  390 + byteArrayOutputStream.write(buf, 0, len);
  391 + }
  392 + result = byteArrayOutputStream.toString();
  393 + } catch (IOException e) {
  394 + e.printStackTrace();
  395 + }
  396 + return result;
  397 + }
  398 +}
1 package com.iot.scheduler.zone; 1 package com.iot.scheduler.zone;
2 2
3 import com.iot.scheduler.service.wuwei.JmDevicePullService; 3 import com.iot.scheduler.service.wuwei.JmDevicePullService;
  4 +import com.iot.scheduler.service.wuwei.SyDevicePullService;
4 import com.iot.scheduler.service.wuwei.WWDeviceReportService; 5 import com.iot.scheduler.service.wuwei.WWDeviceReportService;
5 import com.iot.scheduler.task.AbstractZoneScheduler; 6 import com.iot.scheduler.task.AbstractZoneScheduler;
6 import jakarta.annotation.Resource; 7 import jakarta.annotation.Resource;
@@ -19,6 +20,8 @@ public class WuweiZoneScheduler extends AbstractZoneScheduler { @@ -19,6 +20,8 @@ public class WuweiZoneScheduler extends AbstractZoneScheduler {
19 private JmDevicePullService jmDevicePullService; 20 private JmDevicePullService jmDevicePullService;
20 @Resource 21 @Resource
21 private WWDeviceReportService wwDeviceReportService; 22 private WWDeviceReportService wwDeviceReportService;
  23 + @Resource
  24 + private SyDevicePullService syDevicePullService;
22 25
23 @Override 26 @Override
24 protected String getZoneName() { 27 protected String getZoneName() {
@@ -34,6 +37,7 @@ public class WuweiZoneScheduler extends AbstractZoneScheduler { @@ -34,6 +37,7 @@ public class WuweiZoneScheduler extends AbstractZoneScheduler {
34 log.info("[{}] Simulating pulling devices...", getZoneName()); 37 log.info("[{}] Simulating pulling devices...", getZoneName());
35 jmDevicePullService.pullDeviceAndPushToIot(); 38 jmDevicePullService.pullDeviceAndPushToIot();
36 jmDevicePullService.pullCreateDeviceInfo(); 39 jmDevicePullService.pullCreateDeviceInfo();
  40 + syDevicePullService.pullDeviceAndPushToIot();;
37 Thread.sleep(1000); 41 Thread.sleep(1000);
38 } catch (Exception e) { 42 } catch (Exception e) {
39 logError(taskName, e); 43 logError(taskName, e);
@@ -247,6 +247,18 @@ yxw: @@ -247,6 +247,18 @@ yxw:
247 tokenUrl: "https://iot.hzzlyun.com/api/auth/login" 247 tokenUrl: "https://iot.hzzlyun.com/api/auth/login"
248 infoUrl: "https://iot.hzzlyun.com/api/yt/device" 248 infoUrl: "https://iot.hzzlyun.com/api/yt/device"
249 detailUrl: "https://iot.hzzlyun.com/api/v1/" 249 detailUrl: "https://iot.hzzlyun.com/api/v1/"
  250 +
  251 +sy:
  252 + iot:
  253 + organizeId: "8340c4df-9d44-4490-a474-9028748ece86"
  254 + profileId: "e717b260-025d-11f1-9cb8-e3376d1e7978"
  255 + deviceProfileId: "e717b260-025d-11f1-9cb8-e3376d1e7978"
  256 + userName: "wwyq"
  257 + password: "Wwyq@123.com"
  258 + tokenUrl: "https://iot.hzzlyun.com/api/auth/login"
  259 + infoUrl: "https://iot.hzzlyun.com/api/yt/device"
  260 + detailUrl: "https://iot.hzzlyun.com/api/v1/"
  261 +
250 device: 262 device:
251 token: 263 token:
252 url: "https://iotgc.cniot.vip/auth/token" 264 url: "https://iotgc.cniot.vip/auth/token"