2.4G设备上报技术方案

This commit is contained in:
2026-03-02 16:37:50 +08:00
parent 1ce87aaec5
commit fa5dfab939
2 changed files with 113 additions and 4 deletions

View File

@ -1,12 +1,21 @@
package com.fuyuanshen.global.mqtt.receiver;
import cn.hutool.core.lang.Dict;
import cn.hutool.json.JSONObject;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.DeviceType;
import com.fuyuanshen.equipment.domain.form.DeviceForm;
import com.fuyuanshen.equipment.domain.query.DeviceTypeQueryCriteria;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
import com.fuyuanshen.equipment.service.DeviceService;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleContext;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleEngine;
import com.fuyuanshen.global.mqtt.config.MqttGateway;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.queue.MqttMessageQueueConstants;
import lombok.extern.slf4j.Slf4j;
@ -22,6 +31,9 @@ import java.util.Objects;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
/**
* 注册设备消息接收处理
*/
@Service
@Slf4j
public class RegisEquipReceiverMessageHandler implements MessageHandler {
@ -29,23 +41,103 @@ public class RegisEquipReceiverMessageHandler implements MessageHandler {
@Autowired
private NewMqttRuleEngine newRuleEngine;
@Autowired
private MqttGateway mqttGateway;
@Autowired
private DeviceMapper deviceMapper;
@Autowired
private DeviceService deviceService;
@Autowired
private DeviceTypeMapper deviceTypeMapper;
@Override
public void handleMessage(Message<?> message) throws MessagingException {
Object payload = message.getPayload();
MessageHeaders headers = message.getHeaders();
String receivedTopic = Objects.requireNonNull(headers.get("mqtt_receivedTopic")).toString();
// 只处理 regis/equip/# 主题的消息
if (!receivedTopic.startsWith("regis/equip/")) {
return;
}
// 从主题中提取设备ID
String[] topicParts = receivedTopic.split("/");
if (topicParts.length < 3) {
log.warn("Invalid topic format: {}", receivedTopic);
return;
}
String deviceTypeName = topicParts[2]; // HBY100-J
String receivedQos = Objects.requireNonNull(headers.get("mqtt_receivedQos")).toString();
String timestamp = Objects.requireNonNull(headers.get("timestamp")).toString();
log.info("MQTT3 payload= {} \n receivedTopic = {} \n receivedQos = {} \n timestamp = {}",
payload, receivedTopic, receivedQos, timestamp);
// 解析JSON payload获取imei和mac
Dict payloadDict = JsonUtils.parseMap(payload.toString());
if (receivedTopic == null || payloadDict == null) {
if (payloadDict == null) {
log.warn("Failed to parse payload JSON");
return;
}
String imei = payloadDict.getStr("imei");
String mac = payloadDict.getStr("mac");
log.info("Extracted IMEI: {}, MAC: {}", imei, mac);
// 验证必要字段
if (StringUtils.isEmpty(imei) || StringUtils.isEmpty(mac)) {
log.warn("Missing required fields - IMEI: {}, MAC: {}", imei, mac);
return;
}
DeviceTypeQueryCriteria criteria = new DeviceTypeQueryCriteria();
criteria.setTypeName(deviceTypeName);
DeviceType deviceType = deviceTypeMapper.queryByName(criteria);
if (deviceType == null) {
log.warn("Device type not found for name: {}", deviceTypeName);
return;
}
Device device = deviceMapper.selectDeviceByImei(imei);
if (device != null) {
log.warn("Device already exists for IMEI: {}", imei);
return;
}
// 提取MAC地址后6位
String macSuffix = mac.replaceAll(":", "").substring(6); // 43:73:43:33:53:33 -> 335333
// 构建设备名称和蓝牙名称:设备类型+MAC后6位
String deviceName = deviceTypeName + "-" + macSuffix; // HBY100-335333
DeviceForm deviceForm = new DeviceForm();
deviceForm.setDeviceImei(imei);
deviceForm.setDeviceMac(mac);
deviceForm.setDeviceName(deviceName);
deviceForm.setBluetoothName(deviceName);
deviceForm.setDeviceType(deviceType.getId());
try {
deviceService.addDevice(deviceForm);
} catch (Exception e) {
throw new RuntimeException(e);
}
// 解析原始JSON数据
JSONObject originalData = new JSONObject();
originalData.put("code", 200);
// 发送到MQTT
String topic = "regis/" + imei;
mqttGateway.sendMsgToMqtt(topic, originalData.toString());
}
}

View File

@ -209,6 +209,20 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
DeviceTypeGrants typeGrants = new DeviceTypeGrants();
// 修改为:
Long userId;
LoginUser loginUser;
try {
loginUser = LoginHelper.getLoginUser();
userId = loginUser != null ? loginUser.getUserId() : 1938143703108689922L; // 如果没有登录用户使用默认系统用户ID
} catch (Exception e) {
userId = 1938143703108689922L; // 出现异常时使用默认系统用户ID
loginUser = new LoginUser();
loginUser.setUserId(userId);
loginUser.setNickname("admin");
loginUser.setTenantId("894078"); // 设置租户ID
}
if (deviceForm.getDeviceType() != null) {
DeviceTypeQueryCriteria queryCriteria = new DeviceTypeQueryCriteria();
queryCriteria.setDeviceTypeId(deviceForm.getDeviceType());
@ -281,8 +295,8 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
throw new RuntimeException("设备类型名称已存在,无法新增!!!");
}
LoginUser loginUser = LoginHelper.getLoginUser();
newDeviceType.setCreateByName(loginUser.getNickname());
newDeviceType.setTenantId(loginUser.getTenantId());
deviceTypeMapper.insert(newDeviceType);
// 重新查询确保获取到正确的ID
@ -294,6 +308,7 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
deviceTypeGrants.setCustomerId(loginUser.getUserId());
deviceTypeGrants.setGrantorCustomerId(loginUser.getUserId());
deviceTypeGrants.setGrantedAt(new Date());
deviceTypeGrants.setTenantId(loginUser.getTenantId());
deviceTypeGrantsMapper.insert(deviceTypeGrants);
}
@ -318,13 +333,13 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
BeanUtil.copyProperties(deviceForm, device, true);
device.setDeviceNo(createDeviceNo());
LoginUser loginUser = LoginHelper.getLoginUser();
device.setCurrentOwnerId(loginUser.getUserId());
device.setOriginalOwnerId(loginUser.getUserId());
device.setCreateByName(loginUser.getNickname());
device.setTypeName(deviceType.getTypeName());
device.setDeviceType(deviceType.getId());
device.setDevicePic(deviceType.getDevicePic());
device.setTenantId(loginUser.getTenantId());
if (device.getDeviceImei() != null) {
device.setPubTopic("A/" + device.getDeviceImei());
device.setSubTopic("B/" + device.getDeviceImei());
@ -351,10 +366,12 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
assignments.setActive(DeviceActiveStatusEnum.ACTIVE.getCode());
String lever = USER_ID_SEPARATOR + loginUser.getUserId();
assignments.setLever(lever);
assignments.setTenantId(loginUser.getTenantId());
deviceAssignmentsService.save(assignments);
}
private String createDeviceNo() {
String uuidStr = UUID.fastUUID().toString(); // 获取带 - 的标准格式字符串
return uuidStr.replaceAll("-", "");