文旅相关逻辑集成

This commit is contained in:
2025-01-03 18:48:11 +08:00
parent 6dcc2800ae
commit 9037a8cbab
125 changed files with 2917 additions and 1616 deletions
@@ -0,0 +1,53 @@
package com.central.common.iot;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* iot 自动配置
*
* @author wangpeijie
* @date 2024/11/19
*/
@Configuration
class IoTConfiguration {
/**
* iot v1版本配置
*
* @return
*/
@Bean("iotProperties")
@ConditionalOnProperty(name = "jetlinks.version", havingValue = "1.0")
@ConfigurationProperties(prefix = "jetlinks.server.v1")
public IoTProperties iotPropertiesV1() {
return new IoTProperties();
}
/**
* iot v2版本配置
*
* @return
*/
@Bean("iotProperties")
@ConditionalOnProperty(name = "jetlinks.version", havingValue = "2.0")
@ConfigurationProperties(prefix = "jetlinks.server.v2")
public IoTProperties iotPropertiesV2() {
return new IoTProperties();
}
/**
* iot 模板
*
* @param iotProperties
* @return
*/
@Bean
public IoTTemplate iotTemplate(@Qualifier("iotProperties") IoTProperties iotProperties) {
return new IoTTemplate(iotProperties);
}
}
@@ -0,0 +1,14 @@
package com.central.common.iot;
/**
* iot 异常
*
* @author wangpeijie
* @date 2024/11/28
*/
public class IoTException extends RuntimeException {
public IoTException(String message) {
super(message);
}
}
@@ -0,0 +1,181 @@
package com.central.common.iot;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
/**
* iot 配置
*
* @author wangpeijie
* @date 2024/11/19
*/
@Setter
public class IoTProperties {
@Value("${jetlinks.version}")
private String version;
@Value("${jetlinks.clientId}")
private String clientId;
@Value("${jetlinks.secureKey}")
private String secureKey;
@Value("${jetlinks.dockProductIds:}")
private String dockProductIds;
@Value("${jetlinks.droneProductIds:}")
private String droneProductIds;
private String deviceInfoQueryUrl = "/device-instance/_query";
private String url;
private String ws;
private String mqtt;
/**
* 获取iot平台token
*/
private String queryToken;
/**
* hushi->iot执行任务指令
*/
private String execMissionUrl;
/**
* mgnt -> iot 添加设备
*/
private String saveDeviceUrl;
/**
* mgnt -> iot 激活设备
*/
private String activeDeviceUrl;
/**
* hushi查询产品
*/
private String productQueryUrl;
/**
* hushi查询固件历史
*/
private String upgradeHistoryUrl;
/**
* 查询固件
*/
private String firmwareQueryUrl;
/**
* 固件升级任务
*/
private String firmwareUpgradeTaskStartUrl;
/**
* 查询设备日志
*/
private String deviceLogUrl;
/**
* 查询设备所有属性
*/
private String propertiesQueryUrl;
/**
* 查询设备所有属性
*/
private String propertyQueryUrl;
/**
* 查询单个设备最新的全部属性
*/
private String propertyLatest;
public String getDockProductIds() {
return dockProductIds;
}
public String getDroneProductIds() {
return droneProductIds;
}
public String getVersion() {
return this.version;
}
public String getClientId() {
return this.clientId;
}
public String getSecureKey() {
return this.secureKey;
}
public String getUrl() {
return this.url;
}
public String getWsUrl() {
return this.ws;
}
public String getMqttUrl() {
return this.mqtt;
}
public String getQueryTokenUrl() {
return this.url + this.queryToken;
}
public String getExecMissionUrl() {
return this.url + this.execMissionUrl;
}
public String getSaveDeviceUrl() {
return this.url + this.saveDeviceUrl;
}
public String getActiveDeviceUrl() {
return this.url + this.activeDeviceUrl;
}
public String getProductQueryUrl() {
return this.url + this.productQueryUrl;
}
public String getUpgradeHistoryUrl() {
return this.url + this.upgradeHistoryUrl;
}
public String getFirmwareQueryUrl() {
return this.url + this.firmwareQueryUrl;
}
public String getFirmwareUpgradeTaskStartUrl() {
return this.url + this.firmwareUpgradeTaskStartUrl;
}
public String getDeviceLogUrl() {
return this.url + this.deviceLogUrl;
}
public String getPropertiesQueryUrl() {
return this.url + this.propertiesQueryUrl;
}
public String getPropertyQueryUrl() {
return this.url + this.propertyQueryUrl;
}
public String getPropertyLatestUrl() {
return this.url + this.propertyLatest;
}
public String getDeviceInfoQueryUrl() {
return this.url + this.deviceInfoQueryUrl;
}
}
@@ -0,0 +1,154 @@
package com.central.common.iot;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
/**
* IoT Template
*
* @author wangpeijie
* @date 2024/11/20
*/
@Slf4j
@RequiredArgsConstructor
public class IoTTemplate {
private final IoTProperties iotProperties;
/**
* 查询token
*
* @return
*/
public String queryToken() {
String queryTokenUrl = iotProperties.getQueryTokenUrl();
Map<String, Object> param = new HashMap<>(2);
param.put("expires", 7200 * 24);
return this.execute(queryTokenUrl, param);
}
/**
* 返回报文结构
* {
* "total": 865,
* "data": [
* {
* "formatValue": "DNS1MINIPT23160061",
* "propertyName": "设备ID",
* "createTime": 1735095082942,
* "property": "deviceId",
* "id": "eZP7ud--Szm9VElG6y3BvT76MNySv3ZC",
* "type": "string",
* "deviceId": "DNS1MINIPT23160061",
* "value": "DNS1MINIPT23160061",
* "originValue": "DNS1MINIPT23160061",
* "timestamp": 1735095082940
* }
* ],
* "pageIndex": 0,
* "pageSize": 1
* }
* 单个属性查询
*
* @param deviceSn 设备SN
* @param property 属性
* @return
*/
public String queryProperty(String deviceSn, String property) {
String url = iotProperties.getPropertyQueryUrl();
url = url.replace("{deviceId}", deviceSn).replace("{property}", property);
Map<String, Object> params = new HashMap<>(5);
params.put("pageSize", 1);
params.put("pageIndex", 0);
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> termParam = new HashMap<>(5);
termParam.put("column", "property");
termParam.put("value", property);
list.add(termParam);
params.put("terms", list);
return this.execute(url, params);
}
/**
* 单个属性值查询
*
* @param deviceSn 设备SN
* @param property 属性
* @return
*/
public String queryPropertyValue(String deviceSn, String property) {
String result = this.queryProperty(deviceSn, property);
JSONObject resultObject = JSON.parseObject(result);
JSONArray dataArray = resultObject.getJSONArray("data");
if (dataArray != null && !dataArray.isEmpty()) {
JSONObject jsonObject = dataArray.getJSONObject(0);
return jsonObject.getString("value");
}
return null;
}
/**
* iot 核心请求方法,JSON报文体
*
* @param url 请求地址
* @param param 报文参数
* @return
*/
public String execute(String url, Map<String, Object> param) {
String body = JSON.toJSONString(param);
return this.execute(url, body);
}
/**
* iot 核心请求方法,字符串报文体
*
* @param url 请求地址
* @param body 报文体
* @return
*/
public String execute(String url, String body) {
//时间戳
String xTimestamp = String.valueOf(System.currentTimeMillis());
//param+X-Timestamp+SecureKey通过MD5加密
MessageDigest digest = DigestUtil.digester(DigestAlgorithm.MD5).getDigest();
digest.update(body.getBytes());
digest.update(xTimestamp.getBytes());
digest.update(iotProperties.getSecureKey().getBytes());
Map<String, String> headers = new HashMap<>(5);
headers.put("X-Sign", HexUtil.encodeHexStr(digest.digest()));
headers.put("X-Client-Id", iotProperties.getClientId());
headers.put("X-Timestamp", xTimestamp);
HttpRequest httpRequest = HttpUtil.createPost(url);
httpRequest.addHeaders(headers);
httpRequest.body(body);
String result = null;
try (HttpResponse httpResponse = httpRequest.execute()) {
result = new String(httpResponse.bodyBytes(), StandardCharsets.UTF_8);
log.info("IoTTemplate请求地址:{},请求头:{}, 请求参数:{},响应结果:{}", url, headers, body, result);
} catch (Exception e) {
log.error("IoTTemplate请求地址:{},请求头:{}, 请求参数:{}", url, headers, body, e);
}
JSONObject jsonObject = JSON.parseObject(result);
if (jsonObject != null && Objects.equals(jsonObject.getInteger("status"), 200)) {
return jsonObject.getString("result");
}
throw new IoTException(StringUtils.defaultIfBlank(jsonObject.getString("message"), "IoTTemplate请求异常"));
}
}
@@ -0,0 +1,248 @@
package com.central.common.iot;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* iot websocket 客户端
*
* @author wangpeijie
* @date 2024/11/20
*/
@Slf4j
public class IoTWebSocketClient implements BeanNameAware, InitializingBean, DisposableBean {
private String beanName;
/**
* 尝试重连标识
*/
private final AtomicBoolean tryReconnect = new AtomicBoolean(false);
/**
* 需要ping标识
*/
private final AtomicBoolean needPing = new AtomicBoolean(true);
/**
* 连接结束标识
*/
private final AtomicBoolean end = new AtomicBoolean(false);
/**
* 重连次数
*/
private AtomicInteger reConnectTimes = new AtomicInteger(0);
/**
* iot 消息处理器
*/
private final IoTWebSocketHandler iotWebSocketHandler;
private WebSocketClient webSocketClient;
@Autowired
private IoTProperties iotProperties;
@Autowired
private IoTTemplate iotTemplate;
public IoTWebSocketClient(IoTWebSocketHandler iotWebSocketHandler) {
this.iotWebSocketHandler = iotWebSocketHandler;
}
/**
* 设置bean名称
*
* @param beanName
*/
@Override
public void setBeanName(String beanName) {
this.beanName = beanName;
}
/**
* 初始化
*
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
connect();
circlePing();
}
/**
* 连接
*/
private void connect() throws Exception {
String token = null;
for (int i = 0; i < 3; i++) {
token = iotTemplate.queryToken();
if (StrUtil.isNotBlank(token)) {
break;
}
}
if (StringUtils.isBlank(token)) {
log.warn("iot token 获取失败...");
return;
}
String url = iotProperties.getWsUrl() + token;
webSocketClient = new WebSocketClient(new URI(url)) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
log.info("[{}]IoTWebSocketClient [onOpen]连接成功{}", beanName, getRemoteSocketAddress());
tryReconnect.set(false);
}
@Override
public void onMessage(String message) {
if (StringUtils.isEmpty(message)) {
return;
}
if (message.contains("{\"type\":\"pong\"}")) {
return;
}
if (log.isDebugEnabled()) {
log.debug("[{}]IoTWebSocketClient [onMessage]接收到消息{}", beanName, message);
}
JSONObject jsonObject = JSON.parseObject(message);
if (jsonObject == null || StringUtils.isBlank(jsonObject.getString("topic"))) {
return;
}
JSONObject payload = jsonObject.getJSONObject("payload");
try {
iotWebSocketHandler.onMessage(payload);
} catch (Exception e) {
log.error("[{}]IoTWebSocketClient [onMessage]处理消息异常", beanName, e);
}
}
@Override
public void onClose(int code, String reason, boolean remote) {
log.info("[{}]IoTWebSocketClient [onClose]关闭,code={},reason={},remote={}", beanName, code, reason, remote);
if (StrUtil.hasBlank(reason) || reason.contains("https")) {
if (end.get()) {
return;
}
try {
IoTWebSocketClient.this.reconnect();
} catch (Exception e) {
log.error("[{}]IoTWebSocketClient [onClose]重连失败", beanName, e);
}
}
}
@Override
public void onError(Exception e) {
log.info("[{}]IoTWebSocketClient [onError]异常", beanName, e);
try {
IoTWebSocketClient.this.reconnect();
} catch (Exception exception) {
log.info("[{}]IoTWebSocketClient [onError]重连失败", beanName, exception);
}
}
};
webSocketClient.connectBlocking(10, TimeUnit.SECONDS);
iotWebSocketHandler.onConnect(this);
}
/**
* 重连
*/
private void reconnect() throws Exception {
ThreadUtil.sleep(10, TimeUnit.SECONDS);
int cul = reConnectTimes.incrementAndGet();
if (end.get()) {
log.info("已确认关闭连接");
return;
}
log.warn("[{}]第[{}]次断开重连", beanName, cul);
if (tryReconnect.get()) {
log.error("[{}]第[{}]次断开重连结果 -> 连接正在重连,本次重连请求放弃", beanName, cul);
return;
}
try {
tryReconnect.set(true);
if (webSocketClient.isOpen()) {
log.warn("[{}]第[{}]次断开重连,关闭旧连接", beanName, cul);
webSocketClient.closeConnection(2, "reconnect stop");
}
webSocketClient = null;
connect();
reConnectTimes = new AtomicInteger(0);
} catch (Exception e) {
log.error("[{}]第[{}]次断开重连结果 -> 连接正在重连", beanName, cul, e);
reconnect();
} finally {
tryReconnect.set(false);
}
}
/**
* 心跳
*/
public void circlePing() {
new Thread(
() -> {
while (needPing.get()) {
if (webSocketClient.isOpen()) {
String ping = "{\"type\":\"ping\"}";
webSocketClient.send(ping);
}
ThreadUtil.sleep(5, TimeUnit.SECONDS);
}
log.warn("[{}]Ping循环关闭", beanName);
})
.start();
}
/**
* 销毁
*/
@Override
public void destroy() throws Exception {
needPing.set(false);
end.set(true);
if (webSocketClient != null) {
try {
webSocketClient.closeConnection(3, "real stop");
} catch (Exception e) {
log.error("[{}]IoTWebSocketClient 关闭失败", beanName, e);
}
try {
webSocketClient.close();
} catch (Exception e) {
log.error("[{}]IoTWebSocketClient 关闭失败", beanName, e);
}
reConnectTimes = new AtomicInteger(0);
webSocketClient = null;
}
}
/**
* 发送消息
*
* @param message
*/
public void send(String message) {
if (webSocketClient.isOpen()) {
webSocketClient.send(message);
}
}
}
@@ -0,0 +1,29 @@
package com.central.common.iot;
import com.alibaba.fastjson.JSONObject;
/**
* IoT WebSocket 处理器
*
* @author wangpeijie
* @date 2024/11/20
*/
public interface IoTWebSocketHandler {
/**
* 连接成功
*
* @param webSocketClient
*/
default void onConnect(IoTWebSocketClient webSocketClient) {
}
/**
* 处理消息
*
* @param message
*/
void onMessage(JSONObject message);
}
@@ -0,0 +1,2 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.central.common.iot.IoTConfiguration