Commit 50bfa2df7b87feef4e77966e1aab254549ed3a46

Authored by 杨鸣坤
1 parent 692d58d5

feat: 添加建能电气设备数据同步功能

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