Browse Source

新增更新设备下发日志结果信息。优化同步设备下发日志保存功能。

master
bgy 1 week ago
parent
commit
bd6fd4e7a7
10 changed files with 222 additions and 35 deletions
  1. +1
    -1
      src/main/java/com/topsail/influxdb/controller/DeviceDataController.java
  2. +5
    -5
      src/main/java/com/topsail/influxdb/controller/DeviceLogController.java
  3. +1
    -0
      src/main/java/com/topsail/influxdb/entity/DeviceLogData.java
  4. +2
    -0
      src/main/java/com/topsail/influxdb/entity/DeviceLogInfluxData.java
  5. +59
    -0
      src/main/java/com/topsail/influxdb/entity/SupplierVO.java
  6. +3
    -0
      src/main/java/com/topsail/influxdb/mapper/DeviceInfoMapper.java
  7. +12
    -7
      src/main/java/com/topsail/influxdb/mapper/DeviceInfoMapper.xml
  8. +27
    -2
      src/main/java/com/topsail/influxdb/rabbitmq/AmqpListener.java
  9. +8
    -1
      src/main/java/com/topsail/influxdb/service/DeviceDataService.java
  10. +104
    -19
      src/main/java/com/topsail/influxdb/service/DeviceLogService.java

+ 1
- 1
src/main/java/com/topsail/influxdb/controller/DeviceDataController.java View File

@ -41,7 +41,7 @@ public class DeviceDataController {
/** /**
* 删除所有的设备历史数据 * 删除所有的设备历史数据
*/ */
@RequestMapping(value = "/shengDiLandelete", method = RequestMethod.GET)
@RequestMapping(value = "/shengDiLanDelete", method = RequestMethod.GET)
public Result<List<DeviceHistoryData>> deleteDeviceData() throws ParseException, BindException { public Result<List<DeviceHistoryData>> deleteDeviceData() throws ParseException, BindException {
List<DeviceHistoryData> list = new ArrayList<>(); List<DeviceHistoryData> list = new ArrayList<>();
// deviceDataService.deleteDeviceData(); // deviceDataService.deleteDeviceData();


+ 5
- 5
src/main/java/com/topsail/influxdb/controller/DeviceLogController.java View File

@ -38,17 +38,17 @@ public class DeviceLogController {
* @return * @return
*/ */
@GetMapping(value = "/getShengDiLanDeviceLog") @GetMapping(value = "/getShengDiLanDeviceLog")
public Result getPageDeviceLog(Integer pageNode, Integer pageSize, String startTime, String endTime, String result, String imei, String supplierId, String companyId, String operator, Integer houseId, String bindingInfo) throws ParseException, BindException {
JSONObject jsonObject = deviceLogService.getPageDeviceLog(pageNode, pageSize, startTime, endTime, result, imei, supplierId, companyId, operator, houseId, bindingInfo);
public Result getPageDeviceLog(Integer pageNode, Integer pageSize, String startTime, String endTime, String result, String statusIssue, String imei, String supplierId, String companyId, String operator, Integer houseId, String bindingInfo) throws ParseException, BindException {
JSONObject jsonObject = deviceLogService.getPageDeviceLog(pageNode, pageSize, startTime, endTime, result, statusIssue, imei, supplierId, companyId, operator, houseId, bindingInfo);
return Result.success(jsonObject); return Result.success(jsonObject);
} }
/** /**
* 删除所有的设备下发日志 * 删除所有的设备下发日志
*/ */
@RequestMapping(value = "/shengDiLandelete", method = RequestMethod.GET)
public Result delete() throws ParseException, BindException {
// deviceLogService.deleteDeviceLog();
@RequestMapping(value = "/shengDiLanDelete", method = RequestMethod.GET)
public Result delete(@RequestParam (name = "id",required = false) Integer id) throws ParseException, BindException {
deviceLogService.deleteDeviceLog(id);
return Result.success(new CodeMsg(0, "success")); return Result.success(new CodeMsg(0, "success"));
} }
} }

+ 1
- 0
src/main/java/com/topsail/influxdb/entity/DeviceLogData.java View File

@ -20,6 +20,7 @@ public class DeviceLogData {
private Integer companyId; private Integer companyId;
private Integer id; private Integer id;
private Integer supplierId; private Integer supplierId;
private String supplierName;
private String imei; // 设备imei号 private String imei; // 设备imei号
private String operation; // 操作 private String operation; // 操作
private String params; // 参数 private String params; // 参数


+ 2
- 0
src/main/java/com/topsail/influxdb/entity/DeviceLogInfluxData.java View File

@ -7,6 +7,8 @@ import java.time.Instant;
@Measurement(name = "devicelog") @Measurement(name = "devicelog")
public class DeviceLogInfluxData { public class DeviceLogInfluxData {
@Column(tag = true)
public Integer id;
@Column(tag = true) @Column(tag = true)
public String imei; public String imei;
@Column(tag = true) @Column(tag = true)


+ 59
- 0
src/main/java/com/topsail/influxdb/entity/SupplierVO.java View File

@ -0,0 +1,59 @@
package com.topsail.influxdb.entity;
import lombok.Data;
import java.io.Serializable;
/**
*
* 供应商表实体
*
* @version
*
<pre>
* Author Version Date Changes
* wg 1.0 2020年08月26日 Created
*
* </pre>
* @since 1.
*/
@Data
public class SupplierVO implements Serializable {
private static final long serialVersionUID = 5342511411663841L;
/**
* 所属公司
*/
private Integer companyId;
/**
*ID
*/
private Integer id;
/**
*供应商名字
*/
private String supplierName;
/**
*供应商负责人名字
*/
private String supplierPrincipalName;
/**
*供应商负责人电话
*/
private String supplierPrincipalPhone;
/**
*供应商负责人邮箱
*/
private String supplierPrincipalEmail;
/**
*供应商密钥
*/
private String supplierSecret;
/**
*下发命令url
*/
private String issueUrl;
}

+ 3
- 0
src/main/java/com/topsail/influxdb/mapper/DeviceInfoMapper.java View File

@ -2,6 +2,7 @@ package com.topsail.influxdb.mapper;
import com.topsail.influxdb.entity.DeviceBelongInfo; import com.topsail.influxdb.entity.DeviceBelongInfo;
import com.topsail.influxdb.entity.DeviceLogData; import com.topsail.influxdb.entity.DeviceLogData;
import com.topsail.influxdb.entity.SupplierVO;
import com.topsail.influxdb.entity.SyncDataFlag; import com.topsail.influxdb.entity.SyncDataFlag;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
@ -42,4 +43,6 @@ public interface DeviceInfoMapper {
void updateSyncDeviceDataFlagInfo(@Param("id") Integer id, @Param("flag") Integer flag); void updateSyncDeviceDataFlagInfo(@Param("id") Integer id, @Param("flag") Integer flag);
void updateSyncDeviceLogFlagInfo(@Param("id") Integer id, @Param("flag") Integer flag); void updateSyncDeviceLogFlagInfo(@Param("id") Integer id, @Param("flag") Integer flag);
List<SupplierVO> getSupplierList();
} }

+ 12
- 7
src/main/java/com/topsail/influxdb/mapper/DeviceInfoMapper.xml View File

@ -84,13 +84,13 @@
<update id="updateSyncDeviceDataFlagInfo"> <update id="updateSyncDeviceDataFlagInfo">
UPDATE shengdilan_sync_data_flag UPDATE shengdilan_sync_data_flag
SET sync_device_data = #{flag}, SET sync_device_data = #{flag},
update_time = NOW()
update_time = NOW()
WHERE id = #{id} WHERE id = #{id}
</update> </update>
<update id="updateSyncDeviceLogFlagInfo"> <update id="updateSyncDeviceLogFlagInfo">
UPDATE shengdilan_sync_data_flag UPDATE shengdilan_sync_data_flag
SET sync_device_log = #{flag}, SET sync_device_log = #{flag},
update_time = NOW()
update_time = NOW()
WHERE id = #{id} WHERE id = #{id}
</update> </update>
<select id="queryDeviceBelongInfo" resultType="com.topsail.influxdb.entity.DeviceBelongInfo"> <select id="queryDeviceBelongInfo" resultType="com.topsail.influxdb.entity.DeviceBelongInfo">
@ -129,19 +129,24 @@
</select> </select>
<select id="queryDeviceLogData" resultType="com.topsail.influxdb.entity.DeviceLogData"> <select id="queryDeviceLogData" resultType="com.topsail.influxdb.entity.DeviceLogData">
SELECT id, SELECT id,
company_id,
supplier_id,
company_id companyId,
supplier_id supplierId,
imei, imei,
operation, operation,
params, params,
operator, operator,
createtime, createtime,
result, result,
status_issue,
target_value,
feedback_value
status_issue statusIssue,
target_value targetValue,
feedback_value feedbackValue
FROM device_log FROM device_log
WHERE imei = #{imei} WHERE imei = #{imei}
AND company_id = #{companyId} AND company_id = #{companyId}
</select> </select>
<select id="getSupplierList" resultType="com.topsail.influxdb.entity.SupplierVO">
SELECT s.id,
s.supplier_name supplierName
FROM supplier s
</select>
</mapper> </mapper>

+ 27
- 2
src/main/java/com/topsail/influxdb/rabbitmq/AmqpListener.java View File

@ -37,7 +37,7 @@ public class AmqpListener {
* @throws Exception * @throws Exception
*/ */
// @RabbitListener(queues = "shengdilandevicedata2")
@RabbitListener(queues = "shengdilandevicedataall")
public void deviceDataMqListener(@Payload String message, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws Exception { public void deviceDataMqListener(@Payload String message, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws Exception {
if (StringUtils.isEmpty(message)) { if (StringUtils.isEmpty(message)) {
channel.basicAck(deliveryTag, false); channel.basicAck(deliveryTag, false);
@ -63,7 +63,7 @@ public class AmqpListener {
* @throws Exception * @throws Exception
*/ */
// @RabbitListener(queues = "shengdilandevicelog")
// @RabbitListener(queues = "shengdilandevicelogall")
public void deviceLogMqListener(@Payload String message, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws Exception { public void deviceLogMqListener(@Payload String message, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws Exception {
if (StringUtils.isEmpty(message)) { if (StringUtils.isEmpty(message)) {
channel.basicAck(deliveryTag, false); channel.basicAck(deliveryTag, false);
@ -79,4 +79,29 @@ public class AmqpListener {
LOG.info("saveDeviceLogToInfluxdb Error:(" + e + ")-" + message); LOG.info("saveDeviceLogToInfluxdb Error:(" + e + ")-" + message);
} }
} }
/**
* 更新设备下发命令日志
*
* @param message
* @param deliveryTag
* @param channel
* @throws Exception
*/
// @RabbitListener(queues = "shengdilandevicelogupdate")
public void updateDeviceLogMqListener(@Payload String message, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws Exception {
if (StringUtils.isEmpty(message)) {
channel.basicAck(deliveryTag, false);
return;
}
try {
DeviceLogData deviceLogData = JSON.parseObject(message, DeviceLogData.class);
deviceLogService.updateDeviceLogMqListener(deviceLogData);
LOG.info("saveDeviceLogToInfluxdb OK:" + deviceLogData.getImei());
channel.basicAck(deliveryTag, false);
} catch (Exception e) {
channel.basicNack(deliveryTag, false, true);
LOG.info("saveDeviceLogToInfluxdb Error:(" + e + ")-" + message);
}
}
} }

+ 8
- 1
src/main/java/com/topsail/influxdb/service/DeviceDataService.java View File

@ -325,8 +325,14 @@ public class DeviceDataService {
//1.查询所有的设备编号 //1.查询所有的设备编号
List<SyncDataFlag> syncDataFlags = deviceInfoMapper.querySyncDeviceDataFlagInfo(imei); List<SyncDataFlag> syncDataFlags = deviceInfoMapper.querySyncDeviceDataFlagInfo(imei);
//2.根据设备编号查询历史Influxdb所有的设备数据 //2.根据设备编号查询历史Influxdb所有的设备数据
Boolean flag = true;
if (syncDataFlags != null && syncDataFlags.size() > 0) { if (syncDataFlags != null && syncDataFlags.size() > 0) {
for (SyncDataFlag syncDataFlag : syncDataFlags) {
for (int i = 0; i < syncDataFlags.size(); i++) {
if (!flag) {
syncDataFlags = deviceInfoMapper.querySyncDeviceDataFlagInfo(null);
}
int index = new Random().nextInt(syncDataFlags.size());
SyncDataFlag syncDataFlag = syncDataFlags.get(index);
Boolean syncDeviceData = false; Boolean syncDeviceData = false;
List<DeviceDataInfluxData> influxdbDataList = getOldInfluxdbData(syncDataFlag.getImei().toLowerCase(Locale.ROOT)); List<DeviceDataInfluxData> influxdbDataList = getOldInfluxdbData(syncDataFlag.getImei().toLowerCase(Locale.ROOT));
if (influxdbDataList != null && influxdbDataList.size() > 0) { if (influxdbDataList != null && influxdbDataList.size() > 0) {
@ -354,6 +360,7 @@ public class DeviceDataService {
//4.更新同步设备数据状态 //4.更新同步设备数据状态
deviceInfoMapper.updateSyncDeviceDataFlagInfo(syncDataFlag.getId(), 1); deviceInfoMapper.updateSyncDeviceDataFlagInfo(syncDataFlag.getId(), 1);
} }
flag = false;
} }
} }
} }


+ 104
- 19
src/main/java/com/topsail/influxdb/service/DeviceLogService.java View File

@ -9,19 +9,18 @@ import com.influxdb.client.WriteApi;
import com.influxdb.client.domain.WritePrecision; import com.influxdb.client.domain.WritePrecision;
import com.influxdb.query.FluxRecord; import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable; import com.influxdb.query.FluxTable;
import com.topsail.influxdb.entity.DeviceBelongInfo;
import com.topsail.influxdb.entity.DeviceLogData;
import com.topsail.influxdb.entity.DeviceLogInfluxData;
import com.topsail.influxdb.entity.SyncDataFlag;
import com.topsail.influxdb.entity.*;
import com.topsail.influxdb.mapper.DeviceInfoMapper; import com.topsail.influxdb.mapper.DeviceInfoMapper;
import com.topsail.influxdb.rabbitmq.service.AmqpService; import com.topsail.influxdb.rabbitmq.service.AmqpService;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
@ -33,6 +32,27 @@ import java.util.*;
@Service @Service
public class DeviceLogService { public class DeviceLogService {
public static final Logger LOG = LoggerFactory.getLogger(DeviceLogService.class); public static final Logger LOG = LoggerFactory.getLogger(DeviceLogService.class);
private static volatile Map<Integer, String> supplierInfoMap = new HashMap<>();
// 初始化时加载圣地蓝项目信息例如在构造函数或@PostConstruct方法中
@PostConstruct
public void initShendianlanProjects() {
if (supplierInfoMap.isEmpty()) {
synchronized (DeviceLogService.class) {
if (supplierInfoMap.isEmpty()) {
List<SupplierVO> supplierList = deviceInfoMapper.getSupplierList();
if (supplierList != null && !supplierList.isEmpty()) {
//查询出属于圣地蓝项目的IMEI号
for (SupplierVO supplierVO : supplierList) {
Integer id = supplierVO.getId();
String name = supplierVO.getSupplierName();
supplierInfoMap.put(id, name);
}
}
}
}
}
}
// InfluxDB基础配置 // InfluxDB基础配置
private static final String LOG_BUCKET_NAME = "devicelog"; private static final String LOG_BUCKET_NAME = "devicelog";
@ -61,10 +81,14 @@ public class DeviceLogService {
return; return;
} }
Date createtime = deviceLogData.getCreatetime(); Date createtime = deviceLogData.getCreatetime();
if (createtime == null) {
createtime = new Date();
}
//将时间转换成Instant //将时间转换成Instant
Instant time = createtime.toInstant(); Instant time = createtime.toInstant();
InfluxDBClient client = InfluxDBClientFactory.create(url, token.toCharArray()); InfluxDBClient client = InfluxDBClientFactory.create(url, token.toCharArray());
DeviceLogInfluxData deviceLogInfluxData = new DeviceLogInfluxData(); DeviceLogInfluxData deviceLogInfluxData = new DeviceLogInfluxData();
deviceLogInfluxData.id = deviceLogData.getId();
deviceLogInfluxData.imei = deviceLogData.getImei(); deviceLogInfluxData.imei = deviceLogData.getImei();
//从内部移动处出来value有没有数值都进行插入 //从内部移动处出来value有没有数值都进行插入
deviceLogInfluxData.result = deviceLogData.getResult(); deviceLogInfluxData.result = deviceLogData.getResult();
@ -91,19 +115,26 @@ public class DeviceLogService {
/** /**
* 删除掉所有的Influxdb数据 * 删除掉所有的Influxdb数据
*/ */
public void deleteDeviceLog() {
public void deleteDeviceLog(Integer deviceLogId) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
InfluxDBClient client = InfluxDBClientFactory.create(url, token.toCharArray(), org); InfluxDBClient client = InfluxDBClientFactory.create(url, token.toCharArray(), org);
StringBuffer query = new StringBuffer();
query.append("from(bucket: \"devicelog\") ");
query.append(String.format(" |> filter(fn: (r) => r[\"_measurement\"] == \"devicelog\")"));
query.append("|> range(start: -36d)");
System.out.println("查询语句==========:" + query);
// 1. 拼接公共过滤条件片段总条数和分页查询共用
StringBuilder predicates = new StringBuilder();
// 2. 拼接固定过滤条件_measurement和_field必选
predicates.append("_measurement=devicelog");
if (deviceLogId != null) {
if (predicates.length() > 0) {
predicates.append(" and ").append("id = ").append(deviceLogId);
}
}
System.out.println(predicates.toString());
DeleteApi deleteApi = client.getDeleteApi(); DeleteApi deleteApi = client.getDeleteApi();
OffsetDateTime start = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
OffsetDateTime stop = OffsetDateTime.of(2026, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
try { try {
// Delete data with specific time range
deleteApi.delete(start, stop, "", LOG_BUCKET_NAME, org);
// // 删除指定时间范围内所有数据
OffsetDateTime start = OffsetDateTime.of(calendar.get(Calendar.YEAR) - 10, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
OffsetDateTime stop = OffsetDateTime.of(calendar.get(Calendar.YEAR) + 1, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
deleteApi.delete(start, stop, predicates.toString(), LOG_BUCKET_NAME, org);
System.out.println("Data deleted successfully"); System.out.println("Data deleted successfully");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -130,7 +161,7 @@ public class DeviceLogService {
* @param houseId 房间id * @param houseId 房间id
* @return * @return
*/ */
public JSONObject getPageDeviceLog(Integer pageNode, Integer pageSize, String startTime, String endTime, String result, String imei, String supplierId, String companyId, String operator, Integer houseId, String bindingInfo) {
public JSONObject getPageDeviceLog(Integer pageNode, Integer pageSize, String startTime, String endTime, String result, String statusIssue, String imei, String supplierId, String companyId, String operator, Integer houseId, String bindingInfo) {
JSONObject resultSet = new JSONObject(); JSONObject resultSet = new JSONObject();
InfluxDBClient client = InfluxDBClientFactory.create(url, token.toCharArray(), org); InfluxDBClient client = InfluxDBClientFactory.create(url, token.toCharArray(), org);
// 1. 拼接公共过滤条件片段总条数和分页查询共用 // 1. 拼接公共过滤条件片段总条数和分页查询共用
@ -162,6 +193,9 @@ public class DeviceLogService {
if (result != null && !result.trim().isEmpty()) { if (result != null && !result.trim().isEmpty()) {
filterFragment.append(String.format(" |> filter(fn: (r) => r[\"result\"] == \"%s\")", result.trim())); filterFragment.append(String.format(" |> filter(fn: (r) => r[\"result\"] == \"%s\")", result.trim()));
} }
if (statusIssue != null && !statusIssue.trim().isEmpty()) {
filterFragment.append(String.format(" |> filter(fn: (r) => r[\"statusIssue\"] == \"%s\")", statusIssue.trim()));
}
// 5. 动态拼接supplierId过滤条件仅当supplierId非空且非空白字符串时拼接 // 5. 动态拼接supplierId过滤条件仅当supplierId非空且非空白字符串时拼接
if (supplierId != null && !supplierId.trim().isEmpty()) { if (supplierId != null && !supplierId.trim().isEmpty()) {
filterFragment.append(String.format(" |> filter(fn: (r) => r[\"supplierId\"] == \"%s\")", supplierId.trim())); filterFragment.append(String.format(" |> filter(fn: (r) => r[\"supplierId\"] == \"%s\")", supplierId.trim()));
@ -203,8 +237,8 @@ public class DeviceLogService {
dataQuery.append(filterFragment); // 复用过滤条件 dataQuery.append(filterFragment); // 复用过滤条件
dataQuery.append(" |> sort(columns:[\"_time\"], desc:true)"); dataQuery.append(" |> sort(columns:[\"_time\"], desc:true)");
// 处理分页参数默认值 // 处理分页参数默认值
int finalPageNum = pageNode != null ? pageNode:DEFAULT_PAGE_NUM;
int finalPageSize = pageSize != null ? pageSize:DEFAULT_PAGE_SIZE;
int finalPageNum = pageNode != null ? pageNode : DEFAULT_PAGE_NUM;
int finalPageSize = pageSize != null ? pageSize : DEFAULT_PAGE_SIZE;
int offset = (finalPageNum - 1) * finalPageSize; int offset = (finalPageNum - 1) * finalPageSize;
// dataQuery.append(" |> limit(n: " + finalPageSize + ", offset: " + offset + ")"); // dataQuery.append(" |> limit(n: " + finalPageSize + ", offset: " + offset + ")");
dataQuery.append(" |> yield(name: \"data\")"); // 标记结果集为data dataQuery.append(" |> yield(name: \"data\")"); // 标记结果集为data
@ -229,6 +263,9 @@ public class DeviceLogService {
for (FluxRecord fluxRecord : records) { for (FluxRecord fluxRecord : records) {
String value = (String) fluxRecord.getValueByKey("_value"); String value = (String) fluxRecord.getValueByKey("_value");
DeviceLogData data = JSONObject.parseObject(value, DeviceLogData.class); DeviceLogData data = JSONObject.parseObject(value, DeviceLogData.class);
if (data.getSupplierId() != null) {
data.setSupplierName(supplierInfoMap.get(data.getSupplierId()));
}
rerurnList.add(data); rerurnList.add(data);
} }
} }
@ -236,7 +273,9 @@ public class DeviceLogService {
Collections.reverse(rerurnList); Collections.reverse(rerurnList);
resultSet.put("count", totalCount); resultSet.put("count", totalCount);
//对结果按照分页要求截取构造数据 //对结果按照分页要求截取构造数据
rerurnList = rerurnList.subList(offset, Math.min(offset + finalPageSize, rerurnList.size()));
if (rerurnList != null && rerurnList.size() > 0) {
rerurnList = rerurnList.subList(offset, Math.min(offset + finalPageSize, rerurnList.size()));
}
resultSet.put("list", rerurnList); resultSet.put("list", rerurnList);
return resultSet; return resultSet;
} }
@ -271,12 +310,13 @@ public class DeviceLogService {
String imei = syncDataFlag.getImei(); String imei = syncDataFlag.getImei();
List<DeviceLogData> deviceLogDataList = deviceInfoMapper.queryDeviceLogData(imei, companyId); List<DeviceLogData> deviceLogDataList = deviceInfoMapper.queryDeviceLogData(imei, companyId);
if (deviceLogDataList != null && deviceLogDataList.size() > 0) { if (deviceLogDataList != null && deviceLogDataList.size() > 0) {
DeviceBelongInfo deviceBelongInfo = deviceInfoMapper.queryDeviceBelongInfo(imei);
DeviceBelongInfo deviceBelongInfo = deviceInfoMapper.queryDeviceBelongInfo(imei);
//3. 批量插入设备命令下发日志数据到influxdb中 //3. 批量插入设备命令下发日志数据到influxdb中
for (DeviceLogData deviceLogData : deviceLogDataList) { for (DeviceLogData deviceLogData : deviceLogDataList) {
deviceLogData.setDeviceBelongInfo(deviceBelongInfo != null ? deviceBelongInfo.getDeviceBelongInfo() : null); deviceLogData.setDeviceBelongInfo(deviceBelongInfo != null ? deviceBelongInfo.getDeviceBelongInfo() : null);
deviceLogData.setHouseId(deviceBelongInfo != null ? deviceBelongInfo.getHouseId() : null); deviceLogData.setHouseId(deviceBelongInfo != null ? deviceBelongInfo.getHouseId() : null);
try { try {
deviceLogData.setCompanyId(companyId);
saveDeviceLogToInfluxdb(deviceLogData); saveDeviceLogToInfluxdb(deviceLogData);
flag = true; flag = true;
} catch (Exception e) { } catch (Exception e) {
@ -295,4 +335,49 @@ public class DeviceLogService {
} }
} }
} }
/**
* 更新设备命令下发日志数据
*/
public void updateDeviceLogMqListener(DeviceLogData deviceLogData) {
//步骤1查出ID对应的日志
InfluxDBClient client = InfluxDBClientFactory.create(url, token.toCharArray(), org);
// 1. 拼接公共过滤条件片段总条数和分页查询共用
StringBuilder filterFragment = new StringBuilder();
filterFragment.append("from(bucket: \"devicelog\") ");
filterFragment.append("|> range(start: -360d)");
// 2. 拼接固定过滤条件_measurement和_field必选
filterFragment.append(" |> filter(fn: (r) => r[\"_measurement\"] == \"devicelog\")");
filterFragment.append(" |> filter(fn: (r) => r[\"_field\"] == \"logjson\")");
// 3. 动态拼接imei过滤条件仅当imei非空且非空白字符串时拼接
filterFragment.append(String.format(" |> filter(fn: (r) => r[\"id\"] == \"%s\")", deviceLogData.getId()));
// 3. 构建分页数据查询子句yield命名为data
StringBuilder dataQuery = new StringBuilder();
dataQuery.append(filterFragment); // 复用过滤条件
dataQuery.append(" |> sort(columns:[\"_time\"], desc:true)");
dataQuery.append(" |> yield(name: \"data\")"); // 标记结果集为data
System.out.println("查询数据语句:" + dataQuery.toString());
//查询数据结果
List<FluxTable> dataResults = client.getQueryApi().query(dataQuery.toString());
for (FluxTable fluxTable : dataResults) {
List<FluxRecord> records = fluxTable.getRecords();
for (FluxRecord fluxRecord : records) {
String value = (String) fluxRecord.getValueByKey("_value");
DeviceLogData data = JSONObject.parseObject(value, DeviceLogData.class);
//构造数据
DeviceLogData newData = new DeviceLogData();
BeanUtils.copyProperties(data, newData);
newData.setId(deviceLogData.getId());
newData.setFeedbackValue(deviceLogData.getFeedbackValue());
newData.setStatusIssue(deviceLogData.getStatusIssue());
//步骤2删除该日志
//删除设备命令下发日志数据
deleteDeviceLog(deviceLogData.getId());
//步骤3更新该日志
//保存设备命令下发日志数据到influxdb中
saveDeviceLogToInfluxdb(newData);
}
}
client.close();
}
} }

Loading…
Cancel
Save