Commit 2edfee4d617bdae5094d62d076b03d01b58a25f6

Authored by 胡翰林
1 parent e73f2f60

亚芯微设备数据同步到iot

  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 YxwDevicePullService {
  45 +
  46 + @Value("${yxw.iot.organizeId:}")
  47 + private String iotOrganizeId;
  48 + @Value("${yxw.iot.profileId}")
  49 + private String iotProfileId;
  50 + @Value("${yxw.iot.deviceProfileId}")
  51 + private String iotDeviceProfileId;
  52 + @Value("${yxw.iot.userName:}")
  53 + private String iotUserName;
  54 + @Value("${yxw.iot.password:}")
  55 + private String iotPassword;
  56 + @Value("${yxw.iot.tokenUrl}")
  57 + private String iotTokenUrl;
  58 + @Value("${yxw.iot.infoUrl}")
  59 + private String iotDeviceInfoUrl;
  60 + @Value("${yxw.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 + @Resource
  75 + private RedisTemplate<String, String> redisTemplate;
  76 +
  77 + final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  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 + boolean highSpeed = deviceName.contains("高速");
  114 + if (highSpeed) {
  115 + qxDeviceInfo.setDescription("高速机");
  116 + } else {
  117 + qxDeviceInfo.setDescription("中速机");
  118 + }
  119 +
  120 + DeviceToken deviceToken = new DeviceToken();
  121 + deviceToken.setCredentialsType("ACCESS_TOKEN");
  122 + deviceToken.setCredentialsId(dtuSn);
  123 + deviceToken.setCredentialsValue(dtuSn);
  124 + qxDeviceInfo.setDeviceToken(deviceToken);
  125 + qxDeviceInfos.add(qxDeviceInfo);
  126 + //有序列号直接获取灯信息
  127 + if (StringUtils.isNotBlank(dtuSn)) {
  128 + String deviceInfoDetails = getDeviceInfoDetail(dtuSn);
  129 + if (StringUtils.isBlank(deviceInfoDetails)) {
  130 + continue;
  131 + }
  132 +
  133 + Map<String, Object> deviceInfoDetailMap = JSON.parseObject(deviceInfoDetails, new TypeReference<>() {
  134 + });
  135 +
  136 + JSONArray deviceInfoDetailList = (JSONArray) deviceInfoDetailMap.get("data");
  137 + if (CollectionUtils.isEmpty(deviceInfoDetailList)) {
  138 + continue;
  139 + }
  140 +
  141 + JSONObject deviceInfoDetailJson = (JSONObject) deviceInfoDetailList.get(0);
  142 + //灯详情数据
  143 + //序列号
  144 + String dtuSnDetail = deviceInfoDetailJson.getString("dtuSn");
  145 + //开始时间
  146 + String startTime = deviceInfoDetailJson.getString("startTime");
  147 + QxDeviceInfoDetail qxDeviceInfoDetail = new QxDeviceInfoDetail();
  148 + qxDeviceInfoDetail.setAlarm(false);
  149 + //灯状态(0:灭灯,1:红,2:黄,3:绿,4:蓝)
  150 + Integer lampState = deviceInfoDetailJson.getInteger("lampState");
  151 + switch (lampState) {
  152 + case 0:
  153 + qxDeviceInfoDetail.setStatus("OFF");
  154 + String totalCapacity = getTotalCapacity("total_capacity_" + dtuSn, 0D);
  155 + qxDeviceInfoDetail.setCumulativeOutput(Double.valueOf(totalCapacity));
  156 + break;
  157 + case 1:
  158 + qxDeviceInfoDetail.setStatus("ERROR");
  159 + qxDeviceInfoDetail.setAlarm(true);
  160 + totalCapacity = getTotalCapacity("total_capacity_" + dtuSn, 0D);
  161 + qxDeviceInfoDetail.setCumulativeOutput(Double.valueOf(totalCapacity));
  162 + break;
  163 + case 2:
  164 + qxDeviceInfoDetail.setStatus("STAND");
  165 + totalCapacity = getTotalCapacity("total_capacity_" + dtuSn, 0D);
  166 + qxDeviceInfoDetail.setCumulativeOutput(Double.valueOf(totalCapacity));
  167 + break;
  168 + case 3:
  169 + qxDeviceInfoDetail.setStatus("RUN");
  170 + //先从缓存里面拿token信息
  171 + totalCapacity = getTotalCapacity("total_capacity_" + dtuSn, highSpeed ? 120D : 90D);
  172 + qxDeviceInfoDetail.setCumulativeOutput(Double.valueOf(totalCapacity));
  173 + qxDeviceInfoDetail.setCapacity(highSpeed ? 120D : 90D);
  174 + break;
  175 + default:
  176 + continue;
  177 + }
  178 +
  179 + if (StringUtils.isNotBlank(startTime)) {
  180 + try {
  181 + qxDeviceInfoDetail.setStartTime(dateFormat.parse(startTime));
  182 + } catch (Exception e) {
  183 + log.error("时间格式出错");
  184 + qxDeviceInfoDetail.setStartTime(new Date());
  185 + }
  186 + } else {
  187 + qxDeviceInfoDetail.setStartTime(new Date());
  188 + }
  189 +
  190 + qxDeviceInfoDetail.setDtuSn(dtuSn);
  191 + qxDeviceInfoDetailMap.put(dtuSn, qxDeviceInfoDetail);
  192 + qxAddDeviceInfoDetails.add(qxDeviceInfoDetail);
  193 + }
  194 + }
  195 +
  196 + //将数据同步到IOT平台
  197 + Map<String, String> qxParam = new HashMap<>(2);
  198 + qxParam.put("username", iotUserName);
  199 + qxParam.put("password", iotPassword);
  200 +
  201 + HttpPost qxHttpPost = new HttpPost(iotTokenUrl);
  202 + String qxResult = sendPost(qxHttpPost, JSON.toJSONString(qxParam));
  203 + if (StringUtils.isBlank(qxResult)) {
  204 + return;
  205 + }
  206 + Map<String, Object> qxRes = JSON.parseObject(qxResult, new TypeReference<Map<String, Object>>() {
  207 + });
  208 +
  209 + String qxAccessToken = (String) qxRes.get("token");
  210 + if (StringUtils.isBlank(qxAccessToken)) {
  211 + return;
  212 + }
  213 +
  214 + BasicHeader qxAuthorization = new BasicHeader("X-Authorization", "Bearer " + qxAccessToken);
  215 + if (!CollectionUtils.isEmpty(qxDeviceInfos)) {
  216 + HttpPost qxDeviceInfoPost = new HttpPost(iotDeviceInfoUrl);
  217 + qxDeviceInfoPost.addHeader(qxAuthorization);
  218 + for (QxDeviceInfo qxDeviceInfo : qxDeviceInfos) {
  219 + // todo
  220 + String syncDeviceInfo = sendPost(qxDeviceInfoPost, JSON.toJSONString(qxDeviceInfo));
  221 + //log.info("同步设备信息 syncDeviceInfo:{}", syncDeviceInfo);
  222 + }
  223 + }
  224 +
  225 + if (!CollectionUtils.isEmpty(qxAddDeviceInfoDetails)) {
  226 + for (QxDeviceInfoDetail qxDeviceInfoDetail : qxAddDeviceInfoDetails) {
  227 + String qxDeviceInfoDetailUrlStr = iotDeviceDetailUrl + qxDeviceInfoDetail.getDtuSn() + "/telemetry";
  228 + HttpPost qxDeviceInfoDetailPost = new HttpPost(qxDeviceInfoDetailUrlStr);
  229 + qxDeviceInfoDetailPost.addHeader(qxAuthorization);
  230 + String syncDeviceInfoDetail = sendPost(qxDeviceInfoDetailPost, JSON.toJSONString(qxDeviceInfoDetail));
  231 +// log.info("同步设备运行数据 syncDeviceInfoDetail:{}", syncDeviceInfoDetail);
  232 + }
  233 + }
  234 + }
  235 +
  236 + private String getTotalCapacity(String key, Double production) {
  237 + String totalCapacity = redisTemplate.opsForValue().get(key);
  238 + Double totalCapacityD = 0D;
  239 + if (StringUtils.isEmpty(totalCapacity)) {
  240 + totalCapacityD = production;
  241 + } else {
  242 + totalCapacityD = Double.parseDouble(totalCapacity) + production;
  243 + }
  244 +
  245 + redisTemplate.opsForValue().set(key, String.valueOf(totalCapacityD));
  246 + return String.valueOf(totalCapacityD);
  247 + }
  248 +
  249 + public String getDeviceInfoDetail(String dtuSn) {
  250 + String accessToken = getAccessToken();
  251 + Map<String, String> dtuSnOb = new HashMap<>(1);
  252 + dtuSnOb.put("dtuSn", dtuSn);
  253 + Map<String, String> headerMap = new HashMap<>(1);
  254 + headerMap.put("Authorization", "Bearer " + accessToken);
  255 + String deviceInfoDetail = sendRequestGet(deviceDetailUrl, dtuSnOb, headerMap);
  256 + if (StringUtils.isBlank(deviceInfoDetail)) {
  257 + return null;
  258 + }
  259 +
  260 + Map<String, Object> deviceInfoDetailMap = JSON.parseObject(deviceInfoDetail,
  261 + new TypeReference<>() {
  262 + });
  263 + Integer deviceInfoDetailCode = (Integer) deviceInfoDetailMap.get("code");
  264 + if (deviceInfoDetailCode != 200) {
  265 + return null;
  266 + }
  267 +
  268 + JSONArray deviceInfoDetailList = (JSONArray) deviceInfoDetailMap.get("data");
  269 + if (CollectionUtils.isEmpty(deviceInfoDetailList)) {
  270 + return null;
  271 + }
  272 +
  273 + JSONObject deviceInfoDetailJson = (JSONObject) deviceInfoDetailList.get(0);
  274 + //灯详情数据
  275 + //灯状态(0:灭灯,1:红,2:黄,3:绿,4:蓝)
  276 + Integer lampState = deviceInfoDetailJson.getInteger("lampState");
  277 + if (lampState == null) {
  278 + return null;
  279 + }
  280 +
  281 + return deviceInfoDetail;
  282 + }
  283 +
  284 + public String getDeviceInfo() {
  285 + String accessToken = getAccessToken();
  286 + // 初始化headerMap并设置Authorization
  287 + Map<String, String> headerMap = new HashMap<>(1);
  288 + headerMap.put("Authorization", "Bearer " + accessToken);
  289 +
  290 + Map<String, String> paramsMap = new HashMap<>();
  291 + paramsMap.put("groupName", "安徽亚芯微电子有限公司");
  292 +
  293 + // 第一次请求设备信息
  294 + String deviceResult = sendRequestGet(deviceInfoUrl, paramsMap, headerMap);
  295 +
  296 + // 检查设备信息是否为空
  297 + if (StringUtils.isBlank(deviceResult)) {
  298 + return null;
  299 + }
  300 +
  301 + // 解析设备信息
  302 + Map<String, Object> deviceInfos = JSON.parseObject(deviceResult, new TypeReference<>() {
  303 + });
  304 + Integer deviceInfoCode = (Integer) deviceInfos.get("code");
  305 +
  306 + // 如果code不为200,可能是accessToken失效,重新获取token并重试
  307 + if (deviceInfoCode != 200) {
  308 + accessToken = getAccessToken();
  309 + if (StringUtils.isEmpty(accessToken)) {
  310 + return null;
  311 + }
  312 +
  313 + // 更新headerMap中的Authorization
  314 + headerMap.put("Authorization", "Bearer " + accessToken);
  315 +
  316 + // 第二次请求设备信息
  317 + deviceResult = sendRequestGet(deviceInfoUrl, paramsMap, headerMap);
  318 + if (StringUtils.isBlank(deviceResult)) {
  319 + return null;
  320 + }
  321 +
  322 + // 重新解析设备信息
  323 + deviceInfos = JSON.parseObject(deviceResult, new TypeReference<>() {
  324 + });
  325 + deviceInfoCode = (Integer) deviceInfos.get("code");
  326 +
  327 + // 如果第二次请求仍然失败,返回错误信息
  328 + if (deviceInfoCode != 200) {
  329 + return null;
  330 + }
  331 + }
  332 +
  333 + // 返回成功的设备信息
  334 + return deviceResult;
  335 + }
  336 +
  337 + private String getAccessToken() {
  338 + String accessToken = "";
  339 + String redisKey = "device_token";
  340 + if (StringUtils.isNotBlank(redisTemplate.opsForValue().get(redisKey)) && redisTemplate.getExpire(redisKey) > 0) {
  341 + return redisTemplate.opsForValue().get(redisKey);
  342 + }
  343 +
  344 + Map<String, String> param = new HashMap<>(2);
  345 + param.put("username", deviceUserName);
  346 + param.put("password", devicePassword);
  347 + HttpPost httpPost = new HttpPost(deviceTokenUrl);
  348 + String result = sendPost(httpPost, JSON.toJSONString(param));
  349 + if (StringUtils.isBlank(result)) {
  350 + return accessToken;
  351 + }
  352 +
  353 + Map<String, Object> res = JSON.parseObject(result, new TypeReference<>() {
  354 + });
  355 +
  356 + Integer code = (Integer) res.get("code");
  357 + if (code == 200) {
  358 + JSONObject data = (JSONObject) res.get("data");
  359 + accessToken = (String) data.get("token");
  360 + redisTemplate.opsForValue().set(redisKey, accessToken, 3600, TimeUnit.SECONDS); // 一小时过期
  361 + }
  362 +
  363 + return accessToken;
  364 + }
  365 +
  366 + public static String sendRequestGet(String url, Map<String, String> params, Map<String, String> header) {
  367 + //实例化httpclient
  368 + CloseableHttpClient httpclient = HttpClients.createDefault();
  369 + url = builderUrl(url, params);
  370 + //请求结果
  371 + String content = "";
  372 + //实例化get方法
  373 + HttpGet httpget = new HttpGet(url);
  374 + if (!CollectionUtils.isEmpty(header)) {
  375 + for (Map.Entry<String, String> entry : header.entrySet()) {
  376 + httpget.setHeader(entry.getKey(), entry.getValue());
  377 + }
  378 + }
  379 +
  380 + try (CloseableHttpResponse response = httpclient.execute(httpget)) {
  381 +
  382 + //执行get方法
  383 + if (response.getStatusLine().getStatusCode() == 200) {
  384 + content = EntityUtils.toString(response.getEntity(), "UTF-8");
  385 + }
  386 + } catch (IOException e) {
  387 + log.error("sendRequest---GET Error!", e);
  388 + }
  389 + return content;
  390 + }
  391 +
  392 + private static String builderUrl(String url, Map<String, String> params) {
  393 + UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url);
  394 + if (!CollectionUtils.isEmpty(params)) {
  395 + MultiValueMap<String, String> paramsValue = new LinkedMultiValueMap<>();
  396 + for (Map.Entry<String, String> entry : params.entrySet()) {
  397 + paramsValue.add(entry.getKey(), entry.getValue());
  398 + }
  399 +
  400 + uriBuilder = uriBuilder.queryParams(paramsValue);
  401 + }
  402 +
  403 + return uriBuilder.toUriString();
  404 + }
  405 +
  406 + private String sendPost(HttpPost httpPost, String jsonData) {
  407 + CloseableHttpClient httpClient = HttpClients.createDefault();
  408 + StringEntity entity = new StringEntity(jsonData, ContentType.create("application/json", Consts.UTF_8));
  409 + httpPost.setEntity(entity);
  410 + String result = null;
  411 + try {
  412 + CloseableHttpResponse execute = httpClient.execute(httpPost);
  413 + HttpEntity res = execute.getEntity();
  414 + InputStream is = res.getContent();
  415 + int len;
  416 + byte[] buf = new byte[128];
  417 + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  418 + while ((len = is.read(buf)) != -1) {
  419 + byteArrayOutputStream.write(buf, 0, len);
  420 + }
  421 + result = byteArrayOutputStream.toString();
  422 + } catch (IOException e) {
  423 + e.printStackTrace();
  424 + }
  425 + return result;
  426 + }
  427 +}
... ...
  1 +package com.iot.scheduler.zone;
  2 +
  3 +import com.iot.scheduler.service.YxwDevicePullService;
  4 +import com.iot.scheduler.task.AbstractZoneScheduler;
  5 +import jakarta.annotation.Resource;
  6 +import lombok.extern.slf4j.Slf4j;
  7 +import org.springframework.scheduling.annotation.Scheduled;
  8 +import org.springframework.stereotype.Component;
  9 +
  10 +@Slf4j
  11 +@Component
  12 +public class NanQiaoZoneScheduler extends AbstractZoneScheduler {
  13 + @Override
  14 + protected String getZoneName() {
  15 + return "chouzhounanqiao (滁州南谯区)";
  16 + }
  17 +
  18 + @Resource
  19 + private YxwDevicePullService yxwDevicePullService;
  20 +
  21 + @Scheduled(cron = "${scheduler.nanqiao.pull:0 0/10 * * * ?}")
  22 + public void pullDevicesFromThirdParty() {
  23 + String taskName = "Pull Devices (3rd Party -> IoT)";
  24 + logStart(taskName);
  25 + try {
  26 + // TODO: Implement actual logic
  27 + log.info("[{}] Simulating pulling devices...", getZoneName());
  28 + yxwDevicePullService.pullDeviceAndPushToIot();
  29 + Thread.sleep(1000);
  30 + } catch (Exception e) {
  31 + logError(taskName, e);
  32 + } finally {
  33 + logEnd(taskName);
  34 + }
  35 + }
  36 +}
... ...
... ... @@ -40,6 +40,9 @@ scheduler:
40 40 jmdq:
41 41 pull: "0 0/20 * * * ?"
42 42 push: "0 0/2 * * * ?"
  43 + nanqiao:
  44 + pull: "0 0/1 * * * ?"
  45 + push: "0 0/1 * * * ?"
43 46
44 47 hn:
45 48 third:
... ... @@ -234,7 +237,16 @@ jmdq:
234 237 tokenUrl: "https://iot.hzzlyun.com/api/auth/login"
235 238 infoUrl: "https://iot.hzzlyun.com/api/yt/device"
236 239 detailUrl: "https://iot.hzzlyun.com/api/v1/"
237   -
  240 +yxw:
  241 + iot:
  242 + organizeId: "a5d98b44-6e1c-4ed6-a4fa-269e4a89f58b"
  243 + profileId: "829f4a10-1481-11f1-9cb8-e3376d1e7978"
  244 + deviceProfileId: "829f4a10-1481-11f1-9cb8-e3376d1e7978"
  245 + userName: "yxw"
  246 + password: "Yxw@123.com"
  247 + tokenUrl: "https://iot.hzzlyun.com/api/auth/login"
  248 + infoUrl: "https://iot.hzzlyun.com/api/yt/device"
  249 + detailUrl: "https://iot.hzzlyun.com/api/v1/"
238 250 device:
239 251 token:
240 252 url: "https://iotgc.cniot.vip/auth/token"
... ...