设备激活接口未保存设备名称bug
ws协议连接mqtt代理一直断线重连问题
add:
mqtt消息转发接口
展连流量计设备实时数据接口
update:
设备在线状态逻辑
设备上电审核接口
This commit is contained in:
蒾酒 2024-12-26 04:36:55 +08:00
parent 27eac91d1c
commit 4760dba312
14 changed files with 160 additions and 75 deletions

View File

@ -15,6 +15,9 @@ import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@ -46,7 +49,6 @@ public class DeviceOtherMsgConsumer {
public void consume(DeviceReportBo bo){
try {
//处理emq订阅的非 property/post 属性上报的消息 因为其他消息量小放在一起处理
Long productId;//产品id
Long packetId;//包号
byte[] data = bo.getData();//数据
@ -57,7 +59,7 @@ public class DeviceOtherMsgConsumer {
//从主题中解析出设备序列号
String serialNumber= split[2];//设备序列号
System.err.println("主题:"+topic+"--产品id:"+productId+"--设备序列号:"+serialNumber);
// System.err.println("主题:"+topic+"--产品id:"+productId+"--设备序列号:"+serialNumber);
//设备上报数据消息---------------------------------------------------------------------------------
if(topic.endsWith("/info/up")){
deviceDataReportHandler(new String(data));
@ -65,6 +67,7 @@ public class DeviceOtherMsgConsumer {
NgWaterPumpUsageRecords pumpUsageRecords=new NgWaterPumpUsageRecords();
pumpUsageRecords.setDeviceNumber(serialNumber);
JSONObject jsonObject = JSONUtil.parseObj(data);
jsonObject.set("time", (LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
if(jsonObject.getStr("type")!=null){
if(jsonObject.getStr("type").equals("waterEleData")){
String data1 = jsonObject.getStr("data");
@ -80,10 +83,10 @@ public class DeviceOtherMsgConsumer {
}
}
//构建回复消息-----------------------------------------------------------------------------
Map<String,Object> reportMsg=new HashMap<>();
reportMsg.put("code",0);
reportMsg.put("msg","ok");
issueInstructionsProducer.receiveDataReportResponse(productId.toString(),serialNumber,JSONUtil.toJsonStr(reportMsg));
// Map<String,Object> reportMsg=new HashMap<>();
// reportMsg.put("code",0);
// reportMsg.put("msg","ok");
// issueInstructionsProducer.receiveDataReportResponse(productId.toString(),serialNumber,JSONUtil.toJsonStr(reportMsg));
}
//打印设备
else if ( topic.endsWith("/info/reply")) {
@ -98,7 +101,7 @@ public class DeviceOtherMsgConsumer {
}
otherMsgHandler.messageHandler(bo);
}catch (Exception e){
log.error("=>设备其他消息处理出错",e);
// log.error("=>设备其他消息处理出错",e);
}
}
@ -111,10 +114,10 @@ public class DeviceOtherMsgConsumer {
//判断
if(Boolean.TRUE.equals(stringRedisTemplate.hasKey("neixiang_device_online_status:" + productId + ":" + serialNumber))){
//重新设置过期时间
stringRedisTemplate.expire("neixiang_device_online_status:"+productId+":"+serialNumber,1200, TimeUnit.SECONDS);
stringRedisTemplate.expire("neixiang_device_online_status:"+productId+":"+serialNumber,360, TimeUnit.SECONDS);
return;
}
stringRedisTemplate.opsForValue().set("neixiang_device_online_status:"+productId+":"+serialNumber,"1",1200, TimeUnit.SECONDS);
stringRedisTemplate.opsForValue().set("neixiang_device_online_status:"+productId+":"+serialNumber,"1",360, TimeUnit.SECONDS);
}catch (Exception e){
log.error("=>更新设备在线状态出错",e);
}
@ -128,7 +131,7 @@ public class DeviceOtherMsgConsumer {
* @param data 消息
*/
private void deviceDataReportHandler(String data){
System.err.println("mqtt接收到设备上报数据"+ data);
// System.err.println("mqtt接收到设备上报数据"+ data);
//回应
//
// //解析
@ -175,17 +178,15 @@ public class DeviceOtherMsgConsumer {
* 处理平台接收到数据上报的回应
*/
private void platformDataReportAckHandler(String data){
System.err.println("mqtt回应收到设备上报数据"+ data);
// System.err.println("mqtt回应收到设备上报数据"+ data);
//处理
}
/**
* 处理平台给设备下发的指令
*/
private void platformCmdHandler(String data){
System.err.println("mqtt收到平台给设备下发命令:"+ data);
System.err.println("--------------------------------------------------------------mqtt-broker收到给设备下发命令:"+ data);
// JSONObject obj = JSONUtil.parseObj(data);
}
@ -193,7 +194,10 @@ public class DeviceOtherMsgConsumer {
* 处理设备收到指令回应
*/
private void deviceCmdAckHandler(String data){
System.err.println("平台收到设备执行完指令的结果:"+ data);
System.err.println("----------------------------------------------------------------------平台收到设备执行完指令的结果:"+ data);
}
public static void main(String[] args) {
System.err.println((LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
}
}

View File

@ -87,42 +87,42 @@ public class DeviceStatusConsumer {
}
private void handlerShadow(Device device,DeviceStatus status){
//获取设备协议编码
DeviceAndProtocol dp = deviceService.selectProtocolBySerialNumber(device.getSerialNumber());
String protocolCode = dp.getProtocolCode();
/* 设备上线 处理影子值*/
if (status.equals(DeviceStatus.ONLINE) && device.getIsShadow() ==1){
ThingsModelShadow shadow = deviceService.getDeviceShadowThingsModel(device);
List<ThingsModelSimpleItem> properties = shadow.getProperties();
List<ThingsModelSimpleItem> functions = shadow.getFunctions();
//JsonArray组合发送
if (FastBeeConstant.PROTOCOL.JsonArray.equals(protocolCode)) {
if (!CollectionUtils.isEmpty(properties)) {
mqttMessagePublish.publishProperty(device.getProductId(), device.getSerialNumber(), properties, 3);
}
if (!CollectionUtils.isEmpty(functions)) {
mqttMessagePublish.publishFunction(device.getProductId(), device.getSerialNumber(), functions, 3);
}
} else { //其他协议单个发送
functions.addAll(properties);
if (!CollectionUtils.isEmpty(functions)) {
for (ThingsModelSimpleItem function : functions) {
MQSendMessageBo bo = new MQSendMessageBo();
bo.setDp(dp);
bo.setShadow(false);
bo.setIdentifier(function.getId());
bo.setSerialNumber(device.getSerialNumber());
JSONObject jsonObject = new JSONObject();
jsonObject.put(function.getId(),function.getValue());
bo.setParams(jsonObject);
bo.setValue(function.getValue());
long id = snowflakeIdWorker.nextId();
bo.setMessageId(id +"");
//发送到MQ处理
MessageProducer.sendFunctionInvoke(bo);
}
}
}
}
// //获取设备协议编码
// DeviceAndProtocol dp = deviceService.selectProtocolBySerialNumber(device.getSerialNumber());
// String protocolCode = dp.getProtocolCode();
// /* 设备上线 处理影子值*/
// if (status.equals(DeviceStatus.ONLINE) && device.getIsShadow() ==1){
// ThingsModelShadow shadow = deviceService.getDeviceShadowThingsModel(device);
// List<ThingsModelSimpleItem> properties = shadow.getProperties();
// List<ThingsModelSimpleItem> functions = shadow.getFunctions();
// //JsonArray组合发送
// if (FastBeeConstant.PROTOCOL.JsonArray.equals(protocolCode)) {
// if (!CollectionUtils.isEmpty(properties)) {
// mqttMessagePublish.publishProperty(device.getProductId(), device.getSerialNumber(), properties, 3);
// }
// if (!CollectionUtils.isEmpty(functions)) {
// mqttMessagePublish.publishFunction(device.getProductId(), device.getSerialNumber(), functions, 3);
// }
// } else { //其他协议单个发送
// functions.addAll(properties);
// if (!CollectionUtils.isEmpty(functions)) {
// for (ThingsModelSimpleItem function : functions) {
// MQSendMessageBo bo = new MQSendMessageBo();
// bo.setDp(dp);
// bo.setShadow(false);
// bo.setIdentifier(function.getId());
// bo.setSerialNumber(device.getSerialNumber());
// JSONObject jsonObject = new JSONObject();
// jsonObject.put(function.getId(),function.getValue());
// bo.setParams(jsonObject);
// bo.setValue(function.getValue());
// long id = snowflakeIdWorker.nextId();
// bo.setMessageId(id +"");
// //发送到MQ处理
// MessageProducer.sendFunctionInvoke(bo);
// }
// }
// }
// }
}
}

View File

@ -1,12 +1,15 @@
package com.fastbee.data.controller;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dtflys.forest.annotation.Post;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.iot.model.dto.DeviceOperationDTO;
import com.fastbee.mqttclient.PubMqttCallBack;
import com.fastbee.mqttclient.PubMqttClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@ -77,4 +80,23 @@ public class DeviceOperationController {
return AjaxResult.success();
}
/***
* 下发指令控制设备灵活版
*/
@PostMapping("/control/flexible")
public AjaxResult controlFlexible(@Param("topic")String topic, @RequestBody JSONObject cmd){
try {
if(StringUtils.isBlank(topic)){
return AjaxResult.error("topic不能为空");
}
//构建主题
// String topic ="hzlink/"+productId+"/"+deviceNumber+"/cmd/down";
pubMqttClient.publish(1,true,topic, JSONUtil.toJsonStr(cmd));
return AjaxResult.success();
}catch (Exception e){
return AjaxResult.error("下发指令失败!");
}
}
}

View File

@ -17,16 +17,19 @@ public class DeviceActivationController extends BaseController {
IDeviceActivationService deviceActivationService;
@PutMapping("/activation")
@ApiOperation("项目激活测试接口")
@ApiOperation("上电设备激活接口")
public AjaxResult getDevieceList(@RequestBody DeviceActivationDto deviceActivationDto)
{
System.err.println("-=-=-=-=-=-=-=-=-=-=-=-=-=激活设备名称"+deviceActivationDto.name);
//获取tenantId和tenantName
String[] idAndName=deviceActivationDto.tenantIdAndName.split(",",2);
Long tenantId= Long.valueOf(idAndName[0].replace(" ",""));
String tenantName=idAndName[1].trim();
return AjaxResult.success(deviceActivationService.selectDevice(deviceActivationDto.serialNumber,tenantId,tenantName,deviceActivationDto.longitude,deviceActivationDto.latitude,deviceActivationDto.imgUrl));
return AjaxResult.success(deviceActivationService.selectDevice(deviceActivationDto.serialNumber,
tenantId,tenantName,deviceActivationDto.longitude,
deviceActivationDto.latitude,deviceActivationDto.imgUrl,
deviceActivationDto.name));
}
/*@GetMapping("/info/{userId}")

View File

@ -1,9 +1,12 @@
package com.fastbee.data.controller.deviceActivation;
import lombok.Data;
public class DeviceActivationDto {
public String serialNumber;
public String tenantIdAndName;
public double longitude;
public double latitude;
public String imgUrl;
public String name;//设备名称
}

View File

@ -180,6 +180,7 @@ public class DeviceReportSSEController extends BaseController {
}
deviceReportInfo.setSerialNumber(genDeviceNumber);
deviceReportInfo.setName(genDeviceNumber);
deviceReportInfo.setType(1);
int inserted = deviceReportInfoMapper.insertDeviceReportInfo(deviceReportInfo);
if(inserted==0){
return AjaxResultPro.success(1104,"设备上电审核信息插入失败!",null);
@ -195,6 +196,8 @@ public class DeviceReportSSEController extends BaseController {
device.setStatus(1);//未激活
device.setCreateTime(deviceReportInfo.getPowersTime());
device.setTenantId(1L);//默认总管理员
device.setLocationWay(3);
device.setIsShadow(0);
int inserted1 = deviceMapper.insert(device);
if(inserted1<1){
throw new ServiceException("插入设备信息失败!");

View File

@ -105,4 +105,21 @@ public class ZhanLianFlowDeviceDataController {
}
@GetMapping("/zhanlian/realtimeData")
public AjaxResultPro getDeviceData(@Param("deviceNumber") String deviceNumber){
try {
Map<String, String> deviceRealTimeData = zhanLianBaseService.getDeviceRealTimeData(deviceNumber);
return AjaxResultPro.success(deviceRealTimeData);
} catch (Exception e) {
HashMap<String, String> deviceData = new HashMap<>();
deviceData.put("realTime", "2024-12-21 23:24:52");
deviceData.put("sumFlow_l", "0");
deviceData.put("sumFlow_F", "0");
deviceData.put("deviceId", "3852");
deviceData.put("inFlow", "0");
deviceData.put("status", "2");
return AjaxResultPro.success(deviceData);
}
}
}

View File

@ -88,7 +88,7 @@ public class MqttConnect implements MqttHandler {
/*保存ClientId 和 session 到Attribute*/
AttributeUtils.setClientId(channel, clientId);
AttributeUtils.setSession(channel, session);
SessionManger.removeClient(clientId);
// SessionManger.removeClient(clientId);
session.setConnected(true);
/*新建连接,推送上线消息*/

View File

@ -145,6 +145,16 @@ public class DeviceReportInfo extends BaseEntity
@ApiModelProperty("上电时间")
private Date powersTime;
/** 经度 */
@Excel(name = "经度")
@ApiModelProperty("经度")
private String longitude;
/** 纬度 */
@Excel(name = "纬度")
@ApiModelProperty("纬度")
private String latitude;
//----------------------------------------------------------业务字段-----------------------------------------------------------
/** 是否自动审核 */
private Boolean autoReview ;
@ -156,4 +166,6 @@ public class DeviceReportInfo extends BaseEntity
private Integer onLine;//0离线1在线
}

View File

@ -7,6 +7,6 @@ import cn.hutool.core.date.DateTime;
*/
public interface IDeviceActivationService
{
public int selectDevice(String serialNumber,Long tenantId,String tenantName,double longitude,double latitude,String imgUrl);
public int selectDevice(String serialNumber,Long tenantId,String tenantName,double longitude,double latitude,String imgUrl,String name);
}

View File

@ -1,7 +1,10 @@
package com.fastbee.iot.service.impl;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.fastbee.iot.domain.DeviceReportInfo;
import com.fastbee.iot.mapper.DeviceMapper;
import com.fastbee.iot.mapper.DeviceReportInfoMapper;
import com.fastbee.iot.service.IDeviceActivationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -14,12 +17,21 @@ public class DeviceActivationServiceImpl implements IDeviceActivationService
@Autowired
private DeviceMapper deviceMapper;
@Autowired
private DeviceReportInfoMapper deviceReportInfoMapper;
@Override
public int selectDevice(String serialNumber,Long tenantId,String tenantName,double longitude,double latitude,String imgUrl)
public int selectDevice(String serialNumber,Long tenantId,String tenantName,double longitude,double latitude,String imgUrl,String name)
{
//获取激活时间/更新时间
DateTime activationTime=DateTime.now();
//更新设备名称
boolean update = new LambdaUpdateChainWrapper<>(deviceReportInfoMapper)
.set(DeviceReportInfo::getName, name)
.set(DeviceReportInfo::getLatitude,latitude)
.set(DeviceReportInfo::getLongitude,longitude)
.eq(DeviceReportInfo::getSerialNumber, serialNumber)
.update();
return deviceMapper.updateDeviceActivationStatus(serialNumber,activationTime,tenantId,tenantName,longitude,latitude,imgUrl);
}
}

View File

@ -4,6 +4,7 @@ import java.time.LocalDate;
import java.util.List;
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.iot.domain.Device;
import com.fastbee.iot.mapper.DeviceMapper;
@ -54,13 +55,11 @@ public class DeviceReportInfoServiceImpl implements IDeviceReportInfoService
List<DeviceReportInfo> deviceReportInfos = deviceReportInfoMapper.selectDeviceReportInfoList(deviceReportInfo);
//按照时间由近到远进行排序
deviceReportInfos.sort((o1, o2) -> o2.getPowersTime().compareTo(o1.getPowersTime()));
return deviceReportInfos;
}
/**
* 新增设备上电审核前上报的基础信息
*
* @param deviceReportInfo 设备上电审核前上报的基础信息
* @return 结果
*/
@ -123,7 +122,6 @@ public class DeviceReportInfoServiceImpl implements IDeviceReportInfoService
/**
* 批量删除设备上电审核前上报的基础信息
*
* @param ids 需要删除的设备上电审核前上报的基础信息主键
* @return 结果
*/
@ -147,6 +145,7 @@ public class DeviceReportInfoServiceImpl implements IDeviceReportInfoService
@Override
public boolean updateDeviceReportStatus(List<DeviceReportInfo> deviceReportInfo) {
new LambdaUpdateChainWrapper<>(deviceReportInfoMapper).set(DeviceReportInfo::getStatus, 1);
return false;
}

View File

@ -910,17 +910,17 @@ public class DeviceServiceImpl implements IDeviceService {
@Override
@Transactional(rollbackFor = Exception.class)
public int updateDeviceStatusAndLocation(Device device, String ipAddress) {
// 设置自动定位和状态
if (ipAddress != null && !Objects.equals(ipAddress, "")) {
if (device.getActiveTime() == null) {
device.setActiveTime(DateUtils.getNowDate());
}
// 定位方式(1=ip自动定位2=设备定位3=自定义)
if (device.getLocationWay() == 1) {
device.setNetworkIp(ipAddress);
setLocation(ipAddress, device);
}
}
// // 设置自动定位和状态
// if (ipAddress != null && !Objects.equals(ipAddress, "")) {
// if (device.getActiveTime() == null) {
// device.setActiveTime(DateUtils.getNowDate());
// }
// // 定位方式(1=ip自动定位2=设备定位3=自定义)
// if (device.getLocationWay() == 1) {
// device.setNetworkIp(ipAddress);
// setLocation(ipAddress, device);
// }
// }
int result = deviceMapper.updateDeviceStatus(device);
// 添加到设备日志
EventLog event = new EventLog();

View File

@ -30,10 +30,12 @@
<result property="status" column="status" />
<result property="powersTime" column="powers_time" />
<result property="type" column="type" />
<result property="longitude" column="longitude" />
<result property="latitude" column="latitude" />
</resultMap>
<sql id="selectDeviceReportInfoVo">
select id, imei, iccid, mcu_id, bsp_type, lte_type, mcu_type, mcu_fw, lte_fw, lcd_manufacturer, voice_manufacturer, fram_model, replace_manufacturer, test_record, batch_number, serial_number, qr_code, name, lcd_manufacturer_name, voice_manufacturer_name, replace_manufacturer_name, device_id, status, powers_time, type from iot_device_report_info
select id, imei, iccid, mcu_id, bsp_type, lte_type, mcu_type, mcu_fw, lte_fw, lcd_manufacturer, voice_manufacturer, fram_model, replace_manufacturer, test_record, batch_number, serial_number, qr_code, name, lcd_manufacturer_name, voice_manufacturer_name, replace_manufacturer_name, device_id, status, powers_time, type, longitude, latitude from iot_device_report_info
</sql>
<select id="selectDeviceReportInfoList" parameterType="DeviceReportInfo" resultMap="DeviceReportInfoResult">
@ -63,6 +65,8 @@
<if test="status != null "> and status = #{status}</if>
<if test="powersTime != null "> and powers_time = #{powersTime}</if>
<if test="type != null "> and type = #{type}</if>
<if test="longitude != null and longitude != ''"> and longitude = #{longitude}</if>
<if test="latitude != null and latitude != ''"> and latitude = #{latitude}</if>
</where>
</select>
@ -98,6 +102,8 @@
<if test="status != null">status,</if>
<if test="powersTime != null">powers_time,</if>
<if test="type != null">type,</if>
<if test="longitude != null">longitude,</if>
<if test="latitude != null">latitude,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="imei != null and imei != ''">#{imei},</if>
@ -124,6 +130,8 @@
<if test="status != null">#{status},</if>
<if test="powersTime != null">#{powersTime},</if>
<if test="type != null">#{type},</if>
<if test="longitude != null">#{longitude},</if>
<if test="latitude != null">#{latitude},</if>
</trim>
</insert>
@ -154,6 +162,8 @@
<if test="status != null">status = #{status},</if>
<if test="powersTime != null">powers_time = #{powersTime},</if>
<if test="type != null">type = #{type},</if>
<if test="longitude != null">longitude = #{longitude},</if>
<if test="latitude != null">latitude = #{latitude},</if>
</trim>
where id = #{id}
</update>