添加流量计设备实时数据相关接口以及定时任务,统计流量计设备在线数量等

This commit is contained in:
蒾酒 2024-12-30 02:54:13 +08:00
parent 3aac79e169
commit b590dfa9fa
20 changed files with 855 additions and 28 deletions

View File

@ -28,7 +28,7 @@ server:
openws: true # 控制webSocket是否开启 openws: true # 控制webSocket是否开启
websocket-port: 8083 websocket-port: 8083
websocket-path: /mqtt websocket-path: /mqtt
keep-alive: 70 # 默认的全部客户端心跳上传时间 keep-alive: 240 # 默认的全部客户端心跳上传时间
#TCP服务端口 #TCP服务端口
tcp: tcp:
enabled: true # 控制tcp端口是否开启 enabled: true # 控制tcp端口是否开启

View File

@ -27,7 +27,7 @@ public interface FastBeeConstant {
String FAST_PHONE = "phone-"; String FAST_PHONE = "phone-";
/*MQTT平台判定离线时间 keepAlive*1.5 */ /*MQTT平台判定离线时间 keepAlive*1.5 */
Long DEVICE_PING_EXPIRED = 240000L; Long DEVICE_PING_EXPIRED = 360000L;
} }
interface CLIENT{ interface CLIENT{

View File

@ -83,15 +83,22 @@ public class DeviceOtherMsgConsumer {
//收到定时报文 //收到定时报文
if(JSONUtil.parseObj(data1).get("action").equals("timeMsg")){ if(JSONUtil.parseObj(data1).get("action").equals("timeMsg")){
pumpUsageRecords.setMessageContent(JSONUtil.toJsonStr(jsonObject)); pumpUsageRecords.setMessageContent(JSONUtil.toJsonStr(jsonObject));
int i = ngWaterPumpUsageRecordsMapper.insertNgWaterPumpUsageRecords(pumpUsageRecords); // int i = ngWaterPumpUsageRecordsMapper.insertNgWaterPumpUsageRecords(pumpUsageRecords);
if(i<1){ // if(i<1){
System.err.println("--------------------------保存使用记录失败!---------------------------"); // System.err.println("--------------------------保存使用记录失败!---------------------------");
} // }
}else if(JSONUtil.parseObj(data1).get("action").equals("safeMsg")){ }else if(JSONUtil.parseObj(data1).get("action").equals("safeMsg")){
//续费在线状态 //续费在线状态
updateDeviceOnlineStatus( productId,serialNumber); updateDeviceOnlineStatus( productId,serialNumber);
//保存数据 //保存数据
pumpUsageRecords.setMessageContent(JSONUtil.toJsonStr(jsonObject)); pumpUsageRecords.setMessageContent(JSONUtil.toJsonStr(jsonObject));
// int i = ngWaterPumpUsageRecordsMapper.insertNgWaterPumpUsageRecords(pumpUsageRecords);
// if(i<1){
// System.err.println("--------------------------保存使用记录失败!---------------------------");
// }
}//开阀门关阀门
else if(JSONUtil.parseObj(data1).get("action").equals("startPump")||JSONUtil.parseObj(data1).get("action").equals("stopPump")){
int i = ngWaterPumpUsageRecordsMapper.insertNgWaterPumpUsageRecords(pumpUsageRecords); int i = ngWaterPumpUsageRecordsMapper.insertNgWaterPumpUsageRecords(pumpUsageRecords);
if(i<1){ if(i<1){
System.err.println("--------------------------保存使用记录失败!---------------------------"); System.err.println("--------------------------保存使用记录失败!---------------------------");

View File

@ -35,6 +35,7 @@ import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.quartz.SchedulerException; import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
@ -61,7 +62,7 @@ public class DeviceController extends BaseController {
private DeviceMapper deviceMapper; private DeviceMapper deviceMapper;
@Autowired @Autowired
private IDeviceDetailService deviceDetailService; private IDeviceDetailService deviceDetailService;
// @Lazy @Lazy
@Autowired @Autowired
private IMqttMessagePublish messagePublish; private IMqttMessagePublish messagePublish;

View File

@ -88,9 +88,15 @@ public class DeviceReportInfoController extends BaseController
List<DeviceReportInfo> list = deviceReportInfoService.selectDeviceReportInfoList(deviceReportInfo); List<DeviceReportInfo> list = deviceReportInfoService.selectDeviceReportInfoList(deviceReportInfo);
AtomicInteger onLineTotal= new AtomicInteger(); AtomicInteger onLineTotal= new AtomicInteger();
list.forEach(d->{ list.forEach(d->{
if(Boolean.TRUE.equals(stringRedisTemplate.hasKey("neixiang_device_online_status:" + 147 + ":" + d.getSerialNumber()))) if(d.getType()==1){
{ if(Boolean.TRUE.equals(stringRedisTemplate.hasKey("neixiang_device_online_status:" + 147 + ":" + d.getSerialNumber())))
onLineTotal.getAndIncrement(); {
onLineTotal.getAndIncrement();
}
} else if ( d.getType()==2) {
if(d.getOnLine()==1){
onLineTotal.getAndIncrement();
}
} }
}); });
Map<String,Object> resp=new HashMap<>(); Map<String,Object> resp=new HashMap<>();

View File

@ -0,0 +1,107 @@
package com.fastbee.data.controller.userRecharge;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.iot.domain.NgFlowDeviceData;
import com.fastbee.iot.service.INgFlowDeviceDataService;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.common.core.page.TableDataInfo;
/**
* 流量计设备数据Controller
*
* @author kerwincui
* @date 2024-12-30
*/
@RestController
@RequestMapping("/rechargecard/flow/data")
@Api(tags = "流量计设备数据")
public class NgFlowDeviceDataController extends BaseController
{
@Autowired
private INgFlowDeviceDataService ngFlowDeviceDataService;
/**
* 查询流量计设备数据列表
*/
// @PreAuthorize("@ss.hasPermi('rechargecard:data:list')")
@GetMapping("/list")
@ApiOperation("查询流量计设备数据列表")
public TableDataInfo list(NgFlowDeviceData ngFlowDeviceData)
{
startPage();
List<NgFlowDeviceData> list = ngFlowDeviceDataService.selectNgFlowDeviceDataList(ngFlowDeviceData);
return getDataTable(list);
}
/**
* 导出流量计设备数据列表
*/
@ApiOperation("导出流量计设备数据列表")
// @PreAuthorize("@ss.hasPermi('rechargecard:data:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, NgFlowDeviceData ngFlowDeviceData)
{
List<NgFlowDeviceData> list = ngFlowDeviceDataService.selectNgFlowDeviceDataList(ngFlowDeviceData);
ExcelUtil<NgFlowDeviceData> util = new ExcelUtil<NgFlowDeviceData>(NgFlowDeviceData.class);
util.exportExcel(response, list, "流量计设备数据数据");
}
/**
* 获取流量计设备数据详细信息
*/
// @PreAuthorize("@ss.hasPermi('rechargecard:data:query')")
@GetMapping(value = "/{id}")
@ApiOperation("获取流量计设备数据详细信息")
public AjaxResult getInfo(@PathVariable("id") Long id)
{
return success(ngFlowDeviceDataService.selectNgFlowDeviceDataById(id));
}
/**
* 新增流量计设备数据
*/
// @PreAuthorize("@ss.hasPermi('rechargecard:data:add')")
@PostMapping
@ApiOperation("新增流量计设备数据")
public AjaxResult add(@RequestBody NgFlowDeviceData ngFlowDeviceData)
{
return toAjax(ngFlowDeviceDataService.insertNgFlowDeviceData(ngFlowDeviceData));
}
/**
* 修改流量计设备数据
*/
// @PreAuthorize("@ss.hasPermi('rechargecard:data:edit')")
@PutMapping
@ApiOperation("修改流量计设备数据")
public AjaxResult edit(@RequestBody NgFlowDeviceData ngFlowDeviceData)
{
return toAjax(ngFlowDeviceDataService.updateNgFlowDeviceData(ngFlowDeviceData));
}
/**
* 删除流量计设备数据
*/
// @PreAuthorize("@ss.hasPermi('rechargecard:data:remove')")
@DeleteMapping("/{ids}")
@ApiOperation("删除流量计设备数据")
public AjaxResult remove(@PathVariable Long[] ids)
{
return toAjax(ngFlowDeviceDataService.deleteNgFlowDeviceDataByIds(ids));
}
}

View File

@ -50,8 +50,8 @@ public class NgUserRechargeRecordsController extends BaseController
startPage(); startPage();
List<NgUserRechargeRecords> list = ngUserRechargeRecordsService.selectNgUserRechargeRecordsList(ngUserRechargeRecords); List<NgUserRechargeRecords> list = ngUserRechargeRecordsService.selectNgUserRechargeRecordsList(ngUserRechargeRecords);
//按照充值时间由近到远排序 //按照充值时间由近到远排序
list.sort(Comparator.comparing(NgUserRechargeRecords::getRechargeTime).reversed()); // list.sort(Comparator.comparing(NgUserRechargeRecords::getRechargeTime).reversed());
System.err.println("充值list = " + list); // System.err.println("充值list = " + list);
return getDataTable(list); return getDataTable(list);
} }

View File

@ -12,8 +12,11 @@ import java.math.BigDecimal;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
/**
* @author mijiupro
*/
@Component("zhanLianBaseService1") @Component("zhanLianBaseService1")
public class ZhanLianBaseService { public class ZhanLianBaseService1 {
@Autowired @Autowired
private ZhanLianAuthorizationService authorizationService; private ZhanLianAuthorizationService authorizationService;
@ -28,7 +31,7 @@ public class ZhanLianBaseService {
*/ */
public JSONObject baseRequest(Map<String,Object> body){ public JSONObject baseRequest(Map<String,Object> body){
String jsonStr = JSONUtil.toJsonStr(body); String jsonStr = JSONUtil.toJsonStr(body);
String respStr = HttpUtil.post(authorizationService.getAuthEndpoint(), jsonStr); String respStr = HttpUtil.post(new ZhanLianAuthorizationService().getAuthEndpoint(), jsonStr);
JSONObject resp = JSONUtil.parseObj(respStr); JSONObject resp = JSONUtil.parseObj(respStr);
System.err.println(resp); System.err.println(resp);
if(!resp.get("code").toString().equals("200")){ if(!resp.get("code").toString().equals("200")){
@ -56,6 +59,19 @@ public class ZhanLianBaseService {
return baseRequest(body); return baseRequest(body);
} }
/**
* 请求设备统计数据
* @return 统计数据
*/
private JSONObject requestDeviceCount() {
HashMap<String, Object> body = new HashMap<>();
body.put("method","get");
body.put("path","/api/v1/product/device/statistics");
Map<String,Object> params=new HashMap<>();
body.put("params",params);
return baseRequest(body);
}
/** /**
@ -85,29 +101,29 @@ public class ZhanLianBaseService {
//属性key //属性key
String key = propertyMap.get("key").toString(); String key = propertyMap.get("key").toString();
//属性值 //属性值
Object value1 = JSONUtil.parseObj(p).get("value"); String value1 = JSONUtil.parseObj(p).getStr("value");
String value="" ; String value="" ;
if(value1!=null){ if(value1!=null){
value = value1.toString(); value = value1;
} }
//TODO 属性值历史数据是否需要 //TODO 属性值历史数据是否需要
Object list = JSONUtil.parseObj(p).get("list"); // Object list = JSONUtil.parseObj(p).get("list");
//建立属性-值映射关系 //建立属性-值映射关系
propertiesMap.put(key,value); propertiesMap.put(key,value);
}); });
//在线状态
propertiesMap.put("status",status.toString()); propertiesMap.put("status",status.toString());
//设备id
propertiesMap.put("deviceId",deviceId); propertiesMap.put("deviceId",deviceId);
//上报时间
propertiesMap.put("realTime",time); propertiesMap.put("realTime",time);
return propertiesMap; return propertiesMap;
} }
public BigDecimal toBigDecimalValue(String str) { public BigDecimal toBigDecimalValue(String str) {
if (str == null|| str.isEmpty()) { if (str == null|| str.isEmpty()) {
return null; return null;
@ -121,4 +137,9 @@ public class ZhanLianBaseService {
return Long.parseLong(str); return Long.parseLong(str);
} }
public static void main(String[] args) {
ZhanLianBaseService1 zhanLianBaseService = new ZhanLianBaseService1();
Map<String, String> deviceRealTimeData = zhanLianBaseService.getDeviceRealTimeData("3849");
System.err.println(deviceRealTimeData);
}
} }

View File

@ -2,9 +2,7 @@ package com.fastbee.data.controller.userRecharge.zhanLian;
import cn.hutool.json.JSONObject; import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.fastbee.common.core.domain.AjaxResultPro; import com.fastbee.common.core.domain.AjaxResultPro;
import com.fastbee.rechargecard.domain.NgUserRechargeRecords;
import com.fastbee.rechargecard.domain.NgWaterPumpUsageRecords; import com.fastbee.rechargecard.domain.NgWaterPumpUsageRecords;
import com.fastbee.rechargecard.mapper.NgWaterPumpUsageRecordsMapper; import com.fastbee.rechargecard.mapper.NgWaterPumpUsageRecordsMapper;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
@ -12,7 +10,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.Comparator; import java.util.Comparator;
@ -29,7 +26,7 @@ import java.util.Map;
public class ZhanLianFlowDeviceDataController { public class ZhanLianFlowDeviceDataController {
@Autowired @Autowired
private ZhanLianBaseService zhanLianBaseService; private ZhanLianBaseService1 zhanLianBaseService;
@Autowired @Autowired
private NgWaterPumpUsageRecordsMapper ngWaterPumpUsageRecordsMapper; private NgWaterPumpUsageRecordsMapper ngWaterPumpUsageRecordsMapper;

View File

@ -44,6 +44,7 @@ import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil; import io.netty.buffer.ByteBufUtil;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.annotation.Resource; import javax.annotation.Resource;
@ -61,6 +62,7 @@ public class DeviceMessageServiceImpl implements IDeviceMessageService {
@Resource @Resource
private ModbusEncoder modbusMessageEncoder; private ModbusEncoder modbusMessageEncoder;
@Resource @Resource
@Lazy
private IDeviceService deviceService; private IDeviceService deviceService;
@Resource @Resource
private TopicsUtils topicsUtils; private TopicsUtils topicsUtils;

View File

@ -28,7 +28,7 @@ public class ZhanLianBaseService {
*/ */
public JSONObject baseRequest(Map<String,Object> body){ public JSONObject baseRequest(Map<String,Object> body){
String jsonStr = JSONUtil.toJsonStr(body); String jsonStr = JSONUtil.toJsonStr(body);
String respStr = HttpUtil.post(authorizationService.getAuthEndpoint(), jsonStr); String respStr = HttpUtil.post(new ZhanLianAuthorizationService().getAuthEndpoint(), jsonStr);
JSONObject resp = JSONUtil.parseObj(respStr); JSONObject resp = JSONUtil.parseObj(respStr);
if(!resp.get("code").toString().equals("200")){ if(!resp.get("code").toString().equals("200")){
throw new ServiceException(resp.get("message").toString()); throw new ServiceException(resp.get("message").toString());
@ -91,7 +91,7 @@ public class ZhanLianBaseService {
} }
//TODO 属性值历史数据是否需要 //TODO 属性值历史数据是否需要
Object list = JSONUtil.parseObj(p).get("list"); // Object list = JSONUtil.parseObj(p).get("list");
//建立属性-值映射关系 //建立属性-值映射关系
propertiesMap.put(key,value); propertiesMap.put(key,value);

View File

@ -0,0 +1,66 @@
package com.fastbee.iot.domain;
import java.io.Serializable;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.fastbee.common.annotation.Excel;
import com.fastbee.common.core.domain.BaseEntity;
/**
* 流量计设备数据对象 ng_flow_device_data
*
* @author kerwincui
* @date 2024-12-30
*/
@ApiModel(value = "NgFlowDeviceData",description = "流量计设备数据 ng_flow_device_data")
@Data
public class NgFlowDeviceData implements Serializable {
private static final long serialVersionUID = 1L;
/** $column.columnComment */
private Long id;
/** shun'shi */
@Excel(name = "shun'shi")
@ApiModelProperty("shun'shi")
private String inFlow;
/** 累计流量 */
@Excel(name = "累计流量")
@ApiModelProperty("累计流量")
private String sumFlow;
/** 设备编码 */
@Excel(name = "设备编码")
@ApiModelProperty("设备编码")
private String deviceNumber;
/** 实时时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "实时时间", width = 30, dateFormat = "yyyy-MM-dd")
@ApiModelProperty("实时时间")
private Date realTime;
/** 设备状态 0未启用1离线2在线 */
@Excel(name = "设备状态 0未启用1离线2在线")
@ApiModelProperty("设备状态 0未启用1离线2在线")
private Long status;
/** 保存时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "保存时间", width = 30, dateFormat = "yyyy-MM-dd")
@ApiModelProperty("保存时间")
private Date saveTime;
/** ji'gou */
@Excel(name = "ji'gou")
@ApiModelProperty("ji'gou")
private Long deptId;
}

View File

@ -0,0 +1,65 @@
package com.fastbee.iot.mapper;
import java.util.List;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fastbee.iot.domain.NgFlowDeviceData;
import org.apache.ibatis.annotations.Mapper;
/**
* 流量计设备数据Mapper接口
*
* @author kerwincui
* @date 2024-12-30
*/
@Mapper
public interface NgFlowDeviceDataMapper extends BaseMapper<NgFlowDeviceData>
{
/**
* 查询流量计设备数据
*
* @param id 流量计设备数据主键
* @return 流量计设备数据
*/
public NgFlowDeviceData selectNgFlowDeviceDataById(Long id);
/**
* 查询流量计设备数据列表
*
* @param ngFlowDeviceData 流量计设备数据
* @return 流量计设备数据集合
*/
public List<NgFlowDeviceData> selectNgFlowDeviceDataList(NgFlowDeviceData ngFlowDeviceData);
/**
* 新增流量计设备数据
*
* @param ngFlowDeviceData 流量计设备数据
* @return 结果
*/
public int insertNgFlowDeviceData(NgFlowDeviceData ngFlowDeviceData);
/**
* 修改流量计设备数据
*
* @param ngFlowDeviceData 流量计设备数据
* @return 结果
*/
public int updateNgFlowDeviceData(NgFlowDeviceData ngFlowDeviceData);
/**
* 删除流量计设备数据
*
* @param id 流量计设备数据主键
* @return 结果
*/
public int deleteNgFlowDeviceDataById(Long id);
/**
* 批量删除流量计设备数据
*
* @param ids 需要删除的数据主键集合
* @return 结果
*/
public int deleteNgFlowDeviceDataByIds(Long[] ids);
}

View File

@ -0,0 +1,63 @@
package com.fastbee.iot.service;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.IService;
import com.fastbee.iot.domain.NgFlowDeviceData;
/**
* 流量计设备数据Service接口
*
* @author kerwincui
* @date 2024-12-30
*/
public interface INgFlowDeviceDataService extends IService<NgFlowDeviceData>
{
/**
* 查询流量计设备数据
*
* @param id 流量计设备数据主键
* @return 流量计设备数据
*/
public NgFlowDeviceData selectNgFlowDeviceDataById(Long id);
/**
* 查询流量计设备数据列表
*
* @param ngFlowDeviceData 流量计设备数据
* @return 流量计设备数据集合
*/
public List<NgFlowDeviceData> selectNgFlowDeviceDataList(NgFlowDeviceData ngFlowDeviceData);
/**
* 新增流量计设备数据
*
* @param ngFlowDeviceData 流量计设备数据
* @return 结果
*/
public int insertNgFlowDeviceData(NgFlowDeviceData ngFlowDeviceData);
/**
* 修改流量计设备数据
*
* @param ngFlowDeviceData 流量计设备数据
* @return 结果
*/
public int updateNgFlowDeviceData(NgFlowDeviceData ngFlowDeviceData);
/**
* 批量删除流量计设备数据
*
* @param ids 需要删除的流量计设备数据主键集合
* @return 结果
*/
public int deleteNgFlowDeviceDataByIds(Long[] ids);
/**
* 删除流量计设备数据信息
*
* @param id 流量计设备数据主键
* @return 结果
*/
public int deleteNgFlowDeviceDataById(Long id);
}

View File

@ -0,0 +1,97 @@
package com.fastbee.iot.service.impl;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fastbee.deviceData.domain.DeviceRealtimedataMeteorology;
import com.fastbee.deviceData.mapper.DeviceRealtimedataMeteorologyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fastbee.iot.mapper.NgFlowDeviceDataMapper;
import com.fastbee.iot.domain.NgFlowDeviceData;
import com.fastbee.iot.service.INgFlowDeviceDataService;
/**
* 流量计设备数据Service业务层处理
*
* @author kerwincui
* @date 2024-12-30
*/
@Service
public class NgFlowDeviceDataServiceImpl extends ServiceImpl<NgFlowDeviceDataMapper, NgFlowDeviceData> implements INgFlowDeviceDataService
{
@Autowired
private NgFlowDeviceDataMapper ngFlowDeviceDataMapper;
/**
* 查询流量计设备数据
*
* @param id 流量计设备数据主键
* @return 流量计设备数据
*/
@Override
public NgFlowDeviceData selectNgFlowDeviceDataById(Long id)
{
return ngFlowDeviceDataMapper.selectNgFlowDeviceDataById(id);
}
/**
* 查询流量计设备数据列表
*
* @param ngFlowDeviceData 流量计设备数据
* @return 流量计设备数据
*/
@Override
public List<NgFlowDeviceData> selectNgFlowDeviceDataList(NgFlowDeviceData ngFlowDeviceData)
{
return ngFlowDeviceDataMapper.selectNgFlowDeviceDataList(ngFlowDeviceData);
}
/**
* 新增流量计设备数据
*
* @param ngFlowDeviceData 流量计设备数据
* @return 结果
*/
@Override
public int insertNgFlowDeviceData(NgFlowDeviceData ngFlowDeviceData)
{
return ngFlowDeviceDataMapper.insertNgFlowDeviceData(ngFlowDeviceData);
}
/**
* 修改流量计设备数据
*
* @param ngFlowDeviceData 流量计设备数据
* @return 结果
*/
@Override
public int updateNgFlowDeviceData(NgFlowDeviceData ngFlowDeviceData)
{
return ngFlowDeviceDataMapper.updateNgFlowDeviceData(ngFlowDeviceData);
}
/**
* 批量删除流量计设备数据
*
* @param ids 需要删除的流量计设备数据主键
* @return 结果
*/
@Override
public int deleteNgFlowDeviceDataByIds(Long[] ids)
{
return ngFlowDeviceDataMapper.deleteNgFlowDeviceDataByIds(ids);
}
/**
* 删除流量计设备数据信息
*
* @param id 流量计设备数据主键
* @return 结果
*/
@Override
public int deleteNgFlowDeviceDataById(Long id)
{
return ngFlowDeviceDataMapper.deleteNgFlowDeviceDataById(id);
}
}

View File

@ -0,0 +1,293 @@
package com.fastbee.iot.timer;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.fastbee.common.exception.ServiceException;
import com.fastbee.common.utils.DateUtils;
import com.fastbee.deviceData.api.devlink.service.ZhanLianBaseService;
import com.fastbee.deviceData.api.devlink.service.ZhanLianConfig;
import com.fastbee.iot.domain.DeviceReportInfo;;
import com.fastbee.iot.domain.NgFlowDeviceData;
import com.fastbee.iot.mapper.DeviceReportInfoMapper;
import com.fastbee.iot.mapper.NgFlowDeviceDataMapper;
import com.fastbee.iot.service.INgFlowDeviceDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* @author mijiupro
*/
@Component("waterConservancyFlowDeviceDateTask")
@Slf4j
public class NGFlowDeviceDateTask {
//
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private DeviceReportInfoMapper deviceReportInfoMapper;
@Autowired
private NgFlowDeviceDataMapper ngFlowDeviceDataMapper;
@Autowired
private INgFlowDeviceDataService ngFlowDeviceDataService;
// @Autowired
// private ThreadPoolTaskExecutor taskExecutor;
private String ak = "nanyang";
private String sk = "VMSMSV4D";
private String authId = "25";
private String endpoint = "https://plat.developlink.cloud/prod-api/iot/data/forward";
public String getAuthEndpoint(){
return endpoint + getDefaultAuth();
}
/**
* 鉴权参数生成
*/
public String getDefaultAuth(){
String sign;
long time = System.currentTimeMillis();
String message = "ak=" + ak + "&authId=" + authId + "&time=" + time;
try {
SecretKeySpec keySpec = new SecretKeySpec(
sk.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(keySpec);
byte[] rawHmac = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
sign = DatatypeConverter.printHexBinary(rawHmac).toLowerCase();
// System.err.println("result:"+sign);
} catch (Exception e) {
throw new RuntimeException("签名生成失败! : " + e.getMessage(), e);
}
return "?ak="+ak+"&time="+time+"&sign="+sign+"&authId="+authId;
}
public String getAuth(ZhanLianConfig zhanLianConfig){
String ak = zhanLianConfig.getAk();
String sk = zhanLianConfig.getSk();
String authId = zhanLianConfig.getAuthId();
String sign;
long time = System.currentTimeMillis();
String message = "ak=" + ak + "&authId=" + authId + "&time=" + time;
try {
SecretKeySpec keySpec = new SecretKeySpec(
sk.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(keySpec);
byte[] rawHmac = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
sign = DatatypeConverter.printHexBinary(rawHmac).toLowerCase();
} catch (Exception e) {
throw new RuntimeException("签名生成失败! : " + e.getMessage(), e);
}
return "?ak="+ak+"&time="+time+"&sign="+sign+"&authId="+authId;
}
/**
* 基本请求
* @param body 请求负载
* @return 请求结果 data
*/
public JSONObject baseRequest(Map<String,Object> body){
String jsonStr = JSONUtil.toJsonStr(body);
String respStr = HttpUtil.post(getAuthEndpoint(), jsonStr);
JSONObject resp = JSONUtil.parseObj(respStr);
// System.err.println(resp);
if(!resp.get("code").toString().equals("200")){
throw new ServiceException(resp.get("message").toString());
}
return resp.getJSONObject("data");
}
/**
* 请求设备实时数据
* @param deviceId 设备id
* @return 实时数据
*/
private JSONObject requestDeviceData(String deviceId) {
//构建请求体
HashMap<String, Object> body = new HashMap<>();
body.put("method","get");
body.put("path","api/v1/product/device/run_status");
Map<String,Object> params=new HashMap<>();
params.put("id", deviceId);
body.put("params",params);
return baseRequest(body);
}
/**
* 请求设备统计数据
* @return 统计数据
*/
private JSONObject requestDeviceCount() {
HashMap<String, Object> body = new HashMap<>();
body.put("method","get");
body.put("path","/api/v1/product/device/statistics");
Map<String,Object> params=new HashMap<>();
body.put("params",params);
return baseRequest(body);
}
/**
* 根据设备id请求数据并解析设备实时数据为易于存储的map键值对
* @param deviceId 设备id
* @return 实时数据
*/
public Map<String,String> getDeviceRealTimeData(String deviceId){
//解析返回数据
JSONObject data = requestDeviceData(deviceId);
//获取设备状态
JSONObject jsonObjectData = JSONUtil.parseObj(data);
Object status = jsonObjectData.get("status");
//获取设备属性以及实时数据值
Object properties = jsonObjectData.get("properties");
//获取数据上报时间
String time = jsonObjectData.get("lastOnlineTime").toString();
JSONArray propertiesArray = JSONUtil.parseArray(properties);
//获取设备各项属性实时数据
//设备属性与值建立map
Map<String, String> propertiesMap = new HashMap<>();
propertiesArray.forEach(p -> {
Object property = JSONUtil.parseObj(p).get("property");
JSONObject propertyMap = JSONUtil.parseObj(property);
//属性名称
String name = propertyMap.get("name").toString();
//属性key
String key = propertyMap.get("key").toString();
//属性值
String value1 = JSONUtil.parseObj(p).getStr("value");
String value="" ;
if(value1!=null){
value = value1;
}
//TODO 属性值历史数据是否需要
// Object list = JSONUtil.parseObj(p).get("list");
//建立属性-值映射关系
propertiesMap.put(key,value);
});
//在线状态
propertiesMap.put("status",status.toString());
//设备id
propertiesMap.put("deviceId",deviceId);
//上报时间
propertiesMap.put("realTime",time);
return propertiesMap;
}
/**
* 获取流量计设备实时数据
*/
public void getFlowDeviceData() {
//查询全部流量计设备列表
List<DeviceReportInfo> list = new LambdaQueryChainWrapper<>(deviceReportInfoMapper)
.select(DeviceReportInfo::getSerialNumber,DeviceReportInfo::getDeviceId)
.eq(DeviceReportInfo::getType,2)
.list();
//实时数据集合
List<NgFlowDeviceData> ngFlowDeviceDataList = new ArrayList<>();
//循环获取设备实时数据
list.forEach(d->{
try {
Map<String, String> deviceRealTimeData = getDeviceRealTimeData(d.getSerialNumber());
//存储设备实时数据
NgFlowDeviceData ngFlowDeviceData = new NgFlowDeviceData();
//拼接累计流量整数部分加小数部分
String l = deviceRealTimeData.get("sumFlow_l");
String f = deviceRealTimeData.get("sumFlow_F");
ngFlowDeviceData.setSumFlow(l+f);
//瞬时流量
ngFlowDeviceData.setInFlow(deviceRealTimeData.get("inFlow"));
//实时时间
ngFlowDeviceData.setRealTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(deviceRealTimeData.get("realTime")));
//保存时间
ngFlowDeviceData.setSaveTime(DateUtils.getNowDate());
//设备状态
String status = deviceRealTimeData.get("status");
ngFlowDeviceData.setStatus(Long.valueOf(status));
//维护设备在线状态
//设备离线
if(status.equals("1")){
new LambdaUpdateChainWrapper<>(deviceReportInfoMapper)
.set(DeviceReportInfo::getOnLine,0)
.eq(DeviceReportInfo::getSerialNumber,d.getSerialNumber())
.update();
}
//设备上线
else if (status.equals("2")) {
new LambdaUpdateChainWrapper<>(deviceReportInfoMapper)
.set(DeviceReportInfo::getOnLine,1)
.eq(DeviceReportInfo::getSerialNumber,d.getSerialNumber())
.update();
}
//设备编码
ngFlowDeviceData.setDeviceNumber(d.getSerialNumber());
//机构id
ngFlowDeviceData.setDeptId(d.getDeptId());
//设备在线才保存设备数据
if(status.equals("2")){
ngFlowDeviceDataList.add(ngFlowDeviceData);
}
}catch (Exception e){
log.error("流量计设备数据同步异常");
}
});
//批量插入数据
boolean saveBatch = ngFlowDeviceDataService.saveBatch(ngFlowDeviceDataList);
}
public static void main(String[] args) {
NGFlowDeviceDateTask ngFlowDeviceDateTask = new NGFlowDeviceDateTask();
Map<String, String> deviceRealTimeData =ngFlowDeviceDateTask.getDeviceRealTimeData("3855");
System.err.println(deviceRealTimeData);
}
}

View File

@ -74,6 +74,8 @@
<if test="areaCode != null and areaCode != ''"> and area_code = #{areaCode}</if> <if test="areaCode != null and areaCode != ''"> and area_code = #{areaCode}</if>
<if test="deptId != null "> and dept_id = #{deptId}</if> <if test="deptId != null "> and dept_id = #{deptId}</if>
</where> </where>
<!-- 添加排序 -->
order by powers_time desc
</select> </select>
<select id="selectDeviceReportInfoById" parameterType="Long" resultMap="DeviceReportInfoResult"> <select id="selectDeviceReportInfoById" parameterType="Long" resultMap="DeviceReportInfoResult">

View File

@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fastbee.iot.mapper.NgFlowDeviceDataMapper">
<resultMap type="NgFlowDeviceData" id="NgFlowDeviceDataResult">
<result property="id" column="id" />
<result property="inFlow" column="in_flow" />
<result property="sumFlow" column="sum_flow" />
<result property="deviceNumber" column="device_number" />
<result property="realTime" column="real_time" />
<result property="status" column="status" />
<result property="saveTime" column="save_time" />
<result property="deptId" column="dept_id" />
</resultMap>
<sql id="selectNgFlowDeviceDataVo">
select id, in_flow, sum_flow, device_number, real_time, status, save_time, dept_id from ng_flow_device_data
</sql>
<select id="selectNgFlowDeviceDataList" parameterType="NgFlowDeviceData" resultMap="NgFlowDeviceDataResult">
<include refid="selectNgFlowDeviceDataVo"/>
<where>
<if test="inFlow != null "> and in_flow = #{inFlow}</if>
<if test="sumFlow != null and sumFlow != ''"> and sum_flow = #{sumFlow}</if>
<if test="deviceNumber != null and deviceNumber != ''"> and device_number = #{deviceNumber}</if>
<if test="realTime != null "> and real_time = #{realTime}</if>
<if test="status != null "> and status = #{status}</if>
<if test="saveTime != null "> and save_time = #{saveTime}</if>
<if test="deptId != null "> and dept_id = #{deptId}</if>
</where>
</select>
<select id="selectNgFlowDeviceDataById" parameterType="Long" resultMap="NgFlowDeviceDataResult">
<include refid="selectNgFlowDeviceDataVo"/>
where id = #{id}
</select>
<insert id="insertNgFlowDeviceData" parameterType="NgFlowDeviceData" useGeneratedKeys="true" keyProperty="id">
insert into ng_flow_device_data
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="inFlow != null">in_flow,</if>
<if test="sumFlow != null">sum_flow,</if>
<if test="deviceNumber != null">device_number,</if>
<if test="realTime != null">real_time,</if>
<if test="status != null">status,</if>
<if test="saveTime != null">save_time,</if>
<if test="deptId != null">dept_id,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="inFlow != null">#{inFlow},</if>
<if test="sumFlow != null">#{sumFlow},</if>
<if test="deviceNumber != null">#{deviceNumber},</if>
<if test="realTime != null">#{realTime},</if>
<if test="status != null">#{status},</if>
<if test="saveTime != null">#{saveTime},</if>
<if test="deptId != null">#{deptId},</if>
</trim>
</insert>
<update id="updateNgFlowDeviceData" parameterType="NgFlowDeviceData">
update ng_flow_device_data
<trim prefix="SET" suffixOverrides=",">
<if test="inFlow != null">in_flow = #{inFlow},</if>
<if test="sumFlow != null">sum_flow = #{sumFlow},</if>
<if test="deviceNumber != null">device_number = #{deviceNumber},</if>
<if test="realTime != null">real_time = #{realTime},</if>
<if test="status != null">status = #{status},</if>
<if test="saveTime != null">save_time = #{saveTime},</if>
<if test="deptId != null">dept_id = #{deptId},</if>
</trim>
where id = #{id}
</update>
<delete id="deleteNgFlowDeviceDataById" parameterType="Long">
delete from ng_flow_device_data where id = #{id}
</delete>
<delete id="deleteNgFlowDeviceDataByIds" parameterType="String">
delete from ng_flow_device_data where id in
<foreach item="id" collection="array" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
</mapper>

View File

@ -64,4 +64,14 @@ private static final long serialVersionUID = 1L;
@ApiModelProperty("联系方式") @ApiModelProperty("联系方式")
private String contactInformation; private String contactInformation;
/** 小程序用户id */
@Excel(name = "小程序用户id")
@ApiModelProperty("小程序用户id")
private Long userId;
/** 所属机构id */
@Excel(name = "所属机构id")
@ApiModelProperty("所属机构id")
private Long deptId;
} }

View File

@ -19,10 +19,12 @@
<result property="createBy" column="create_by" /> <result property="createBy" column="create_by" />
<result property="updateTime" column="update_time" /> <result property="updateTime" column="update_time" />
<result property="updateBy" column="update_by" /> <result property="updateBy" column="update_by" />
<result property="userId" column="user_id" />
<result property="deptId" column="dept_id" />
</resultMap> </resultMap>
<sql id="selectNgInformationWaterUserVo"> <sql id="selectNgInformationWaterUserVo">
select water_user_id, name, account, water_consumption, water_consumptionIndex, warning_status, irrigated_area, belonging_gegion, contact_information, remark, create_time, create_by, update_time, update_by from ng_information_water_user select water_user_id, name, account, water_consumption, water_consumptionIndex, warning_status, irrigated_area, belonging_gegion, contact_information, remark, create_time, create_by, update_time, update_by,user_id,dept_id from ng_information_water_user
</sql> </sql>
<select id="selectNgInformationWaterUserList" parameterType="NgInformationWaterUser" resultMap="NgInformationWaterUserResult"> <select id="selectNgInformationWaterUserList" parameterType="NgInformationWaterUser" resultMap="NgInformationWaterUserResult">
@ -36,6 +38,8 @@
<if test="irrigatedArea != null "> and irrigated_area = #{irrigatedArea}</if> <if test="irrigatedArea != null "> and irrigated_area = #{irrigatedArea}</if>
<if test="belongingGegion != null and belongingGegion != ''"> and belonging_gegion = #{belongingGegion}</if> <if test="belongingGegion != null and belongingGegion != ''"> and belonging_gegion = #{belongingGegion}</if>
<if test="contactInformation != null and contactInformation != ''"> and contact_information = #{contactInformation}</if> <if test="contactInformation != null and contactInformation != ''"> and contact_information = #{contactInformation}</if>
<if test="userId != null "> and user_id = #{userId}</if>
<if test="deptId != null "> and dept_id = #{deptId}</if>
</where> </where>
</select> </select>