设备标识入库与查询统一成一种写法

同一台设备换个分隔符或大小写上报,入库、查重、查询三处算出来的值就不一样,查不到就静默不发凭证也不下发固件。现在入库和查重前先归一成小写冒号分隔,查不到再拿原文试一次,迁移前存的老数据照样能查到。

迁移脚本把存量两列刷成同一种写法,跑过一遍 MySQL 验证:六种写法都能归一,不是地址的行不动,重跑是空操作。
This commit is contained in:
hrz 2026-10-23 03:51:22 +00:00
parent bdaa1d0c24
commit 71d9084af9
5 changed files with 324 additions and 31 deletions

View file

@ -29,6 +29,7 @@ import xiaozhi.modules.device.dto.DeviceReportReqDTO;
import xiaozhi.modules.device.dto.DeviceReportRespDTO;
import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.device.service.DeviceService;
import xiaozhi.modules.device.service.impl.DeviceServiceImpl;
import xiaozhi.modules.sys.service.SysParamsService;
@Tag(name = "设备管理", description = "OTA 相关接口")
@ -49,7 +50,7 @@ public class OTAController {
if (StringUtils.isBlank(deviceId)) {
return createResponse(DeviceReportRespDTO.createError("Device ID is required"), HttpStatus.BAD_REQUEST);
}
deviceId = normalizeDeviceId(deviceId);
deviceId = DeviceServiceImpl.normalizeDeviceId(deviceId);
if (StringUtils.isBlank(clientId)) {
clientId = deviceId;
}
@ -112,32 +113,6 @@ public class OTAController {
.body(json);
}
/**
* 把设备上报的 Device-Id 归一成小写冒号分隔的 MAC 形态。
* 入库存的是用户在智控台填的原始字符串,查询、签名、topic、缓存键
* 统一用归一后的值,否则同一台设备换个写法就会被当成没登记
*
* @param deviceId
* @return 归一后的 Device-Id;不是合法 MAC 时原样返回,交给后续校验拒绝
*/
private static String normalizeDeviceId(String deviceId) {
if (StringUtils.isBlank(deviceId)) {
return deviceId;
}
String hex = deviceId.toLowerCase().replace(":", "").replace("-", "").replace("_", "");
if (hex.length() != 12) {
return deviceId;
}
StringBuilder mac = new StringBuilder(17);
for (int i = 0; i < 12; i += 2) {
if (i > 0) {
mac.append(':');
}
mac.append(hex, i, i + 2);
}
return mac.toString();
}
/**
* 判断 mac 地址是否有效,收紧为严格的十六进制 MAC 形态
*

View file

@ -137,7 +137,7 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
deviceEntity.setBoard(board);
deviceEntity.setAgentId(agentId);
deviceEntity.setAppVersion(appVersion);
deviceEntity.setMacAddress(macAddress);
deviceEntity.setMacAddress(normalizeDeviceId(macAddress));
deviceEntity.setUserId(user.getId());
deviceEntity.setCreator(user.getId());
deviceEntity.setAutoUpdate(1);
@ -409,11 +409,48 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
if (StringUtils.isBlank(macAddress)) {
return null;
}
DeviceEntity device = selectByMacAddress(normalizeDeviceId(macAddress));
if (device != null) {
return device;
}
// 归一之前写进去的存量数据,原文再试一次,别让写法不同就查不到
return selectByMacAddress(macAddress);
}
private DeviceEntity selectByMacAddress(String macAddress) {
QueryWrapper<DeviceEntity> wrapper = new QueryWrapper<>();
wrapper.eq("mac_address", macAddress);
return baseDao.selectOne(wrapper);
}
/**
* 把 Device-Id 归一成小写冒号分隔的 MAC 形态
* <p>
* 入库、查询、签名、订阅地址、缓存键统一走这个值,否则同一台设备换个
* 分隔符或大小写就会被当成没登记,表现为静默不发凭证也不下发固件。
* 不是合法 MAC 时原样返回,交给后续校验拒绝。
*
* @param deviceId 设备上报或用户填写的 Device-Id
* @return 归一后的 Device-Id
*/
public static String normalizeDeviceId(String deviceId) {
if (StringUtils.isBlank(deviceId)) {
return deviceId;
}
String hex = deviceId.toLowerCase().replace(":", "").replace("-", "").replace("_", "");
if (hex.length() != 12) {
return deviceId;
}
StringBuilder mac = new StringBuilder(17);
for (int i = 0; i < 12; i += 2) {
if (i > 0) {
mac.append(':');
}
mac.append(hex, i, i + 2);
}
return mac.toString();
}
private DeviceReportRespDTO.ServerTime buildServerTime() {
DeviceReportRespDTO.ServerTime serverTime = new DeviceReportRespDTO.ServerTime();
TimeZone tz = TimeZone.getDefault();
@ -563,21 +600,22 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
@Override
public void manualAddDevice(Long userId, DeviceManualAddDTO dto) {
String macAddress = normalizeDeviceId(dto.getMacAddress());
// 检查mac是否已存在
QueryWrapper<DeviceEntity> wrapper = new QueryWrapper<>();
wrapper.eq("mac_address", dto.getMacAddress());
wrapper.eq("mac_address", macAddress);
DeviceEntity exist = baseDao.selectOne(wrapper);
if (exist != null) {
throw new RenException(ErrorCode.MAC_ADDRESS_ALREADY_EXISTS);
}
Date now = new Date();
DeviceEntity entity = new DeviceEntity();
entity.setId(dto.getMacAddress());
entity.setId(macAddress);
entity.setUserId(userId);
entity.setAgentId(dto.getAgentId());
entity.setBoard(dto.getBoard());
entity.setAppVersion(dto.getAppVersion());
entity.setMacAddress(dto.getMacAddress());
entity.setMacAddress(macAddress);
entity.setCreateDate(now);
entity.setUpdateDate(now);
entity.setLastConnectedAt(now);

View file

@ -0,0 +1,81 @@
-- 设备 MAC 归一:改成小写冒号分隔,与 OTA 上报归一后的写法对齐
--
-- 之前用户在智控台手填的 MAC 原样入库(可能是 AA-BB-… 、aabbcc… 或全大写),
-- OTA 侧归一后按 aa:bb:… 精确查库,查不到就静默不发凭证、不下发固件。
-- 这里把存量两列刷成归一后的形态。
--
-- 只改 ai_device.mac_address,不动 id:手填设备的 id 就是当时的原始 MAC,
-- 改 id 会牵动外键和缓存键,风险大于收益。查不到归一值时查询侧会拿原文再试一次。
-- mac_address 上只有普通索引不是唯一键,这段不会撞键。
UPDATE `ai_device`
SET `mac_address` = LOWER(CONCAT(
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 1, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 3, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 5, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 7, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 9, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 11, 2)
))
WHERE `mac_address` REGEXP '^([0-9A-Fa-f]{2}[-:_]?){5}[0-9A-Fa-f]{2}$'
AND BINARY `mac_address` <> BINARY LOWER(CONCAT(
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 1, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 3, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 5, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 7, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 9, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 11, 2)
));
-- 通讯录表的主键就是 (mac_address, target_mac),两段拼起来还是同一个 MAC 时会撞键。
-- 撞键说明同一台设备在同一个人的通讯录里存了两条、只是写法不同,属于脏数据,
-- 跑之前先看一眼下面这条,有结果就得先把重复的挑出来删掉:
--
-- SELECT LOWER(REPLACE(REPLACE(REPLACE(`mac_address`,':',''),'-',''),'_','')) AS nmac,
-- LOWER(REPLACE(REPLACE(REPLACE(`target_mac`,':',''),'-',''),'_','')) AS ntmac,
-- COUNT(*) c
-- FROM `ai_device_address_book`
-- GROUP BY nmac, ntmac HAVING c > 1;
--
-- 真撞上了会直接报 Duplicate entry 而不是把数据改坏,这时上面 ai_device 那段
-- 已经生效了;把重复的清掉再跑一遍就行,两段都能重跑。
-- 值已经是对的就整行跳过,重跑一遍是空操作。两段是分开判的:
-- 只改本机地址不改对方地址的行,也要算进去,不然它会一直留着旧写法。
UPDATE `ai_device_address_book`
SET `mac_address` = LOWER(CONCAT(
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 1, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 3, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 5, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 7, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 9, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 11, 2)
)),
`target_mac` = LOWER(CONCAT(
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 1, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 3, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 5, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 7, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 9, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 11, 2)
))
WHERE `mac_address` REGEXP '^([0-9A-Fa-f]{2}[-:_]?){5}[0-9A-Fa-f]{2}$'
AND `target_mac` REGEXP '^([0-9A-Fa-f]{2}[-:_]?){5}[0-9A-Fa-f]{2}$'
AND (
BINARY `mac_address` <> BINARY LOWER(CONCAT(
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 1, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 3, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 5, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 7, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 9, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 11, 2)
))
OR BINARY `target_mac` <> BINARY LOWER(CONCAT(
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 1, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 3, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 5, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 7, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 9, 2), ':',
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 11, 2)
))
);

View file

@ -753,3 +753,10 @@ databaseChangeLog:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202609172100.sql
- changeSet:
id: 202610231200
author: wk01
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202610231200.sql

View file

@ -0,0 +1,192 @@
package xiaozhi.modules.device.service.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.MockedStatic;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import xiaozhi.common.redis.RedisUtils;
import xiaozhi.common.user.UserDetail;
import xiaozhi.modules.device.dao.DeviceDao;
import xiaozhi.modules.device.dto.DeviceManualAddDTO;
import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.security.user.SecurityUser;
/**
* #3448 设备标识归一化回归测试
*
* <p>
* 同一台设备换个分隔符或大小写上报,入库、查重、查询三处必须算成同一个值,
* 否则表现为静默不发凭证、不下发固件,没有任何报错可查。
*/
@DisplayName("设备标识归一化回归测试")
class DeviceMacAddressNormalizeTest {
private static final String CANONICAL = "aa:bb:cc:dd:ee:ff";
@Test
@DisplayName("冒号、连字符、下划线、无分隔符、大小写写法归一到同一个值")
void everySpellingCollapsesToCanonical() {
for (String spelling : new String[] {
"aa:bb:cc:dd:ee:ff", "AA:BB:CC:DD:EE:FF", "aa-bb-cc-dd-ee-ff",
"aa_bb_cc_dd_ee_ff", "aabbccddeeff", "Aa:Bb:Cc:Dd:Ee:Ff" }) {
assertEquals(CANONICAL, DeviceServiceImpl.normalizeDeviceId(spelling), spelling);
}
}
@Test
@DisplayName("不是 MAC 的标识原样返回,交给后续校验拒绝")
void nonMacValuePassesThrough() {
for (String value : new String[] { null, "", " ", "abc", "zz:zz:zz:zz:zz:zz", "00112233445566" }) {
assertEquals(value, DeviceServiceImpl.normalizeDeviceId(value), String.valueOf(value));
}
}
@Test
@DisplayName("按任意写法上报都能查到归一后入库的那台设备")
void lookupFindsRowStoredInCanonicalForm() {
DeviceEntity stored = storedDevice(CANONICAL);
DeviceServiceImpl service = service(daoMatchingOnly(CANONICAL, stored));
for (String spelling : new String[] {
"aa:bb:cc:dd:ee:ff", "aabbccddeeff", "AA-BB-CC-DD-EE-FF", "aa_bb_cc_dd_ee_ff" }) {
assertSame(stored, service.getDeviceByMacAddress(spelling), spelling);
}
}
@Test
@DisplayName("迁移前按原文入库的存量设备仍能查到,不被归一化挡掉")
void lookupFallsBackToLegacyRow() {
DeviceEntity legacy = storedDevice("AA-BB-CC-DD-EE-FF");
DeviceServiceImpl service = service(daoMatchingOnly("AA-BB-CC-DD-EE-FF", legacy));
assertSame(legacy, service.getDeviceByMacAddress("AA-BB-CC-DD-EE-FF"),
"归一后没查到,该退回原文再查一次,否则迁移前的设备直接失联");
}
@Test
@DisplayName("两种写法都查不到时返回 null")
void lookupMissReturnsNull() {
DeviceServiceImpl service = service(daoMatchingOnly(CANONICAL, storedDevice(CANONICAL)));
assertNull(service.getDeviceByMacAddress("11:22:33:44:55:66"));
assertNull(service.getDeviceByMacAddress(" "));
}
@Test
@DisplayName("手工添加按归一值查重、按归一值入库")
void manualAddStoresNormalizedMac() {
DeviceDao dao = mock(DeviceDao.class);
when(dao.selectOne(any())).thenReturn(null);
DeviceServiceImpl service = service(dao);
DeviceManualAddDTO dto = new DeviceManualAddDTO();
dto.setMacAddress("AABBCCDDEEFF");
dto.setAgentId("1");
service.manualAddDevice(9L, dto);
ArgumentCaptor<Wrapper<DeviceEntity>> queried = wrapperCaptor();
verify(dao).selectOne(queried.capture());
assertEquals(CANONICAL, queriedMac(queried.getValue()),
"查重用的不是归一值,同一台设备换个写法就能被重复添加");
ArgumentCaptor<DeviceEntity> inserted = ArgumentCaptor.forClass(DeviceEntity.class);
verify(dao).insert(inserted.capture());
assertEquals(CANONICAL, inserted.getValue().getMacAddress());
assertEquals(CANONICAL, inserted.getValue().getId(), "主键跟着一起归一,否则同一台设备能插进两条");
}
@Test
@DisplayName("设备激活入库的是归一后的 MAC")
void activationStoresNormalizedMac() {
DeviceDao dao = mock(DeviceDao.class);
when(dao.selectById(any())).thenReturn(null);
RedisUtils redisUtils = mock(RedisUtils.class);
Map<String, Object> activation = new HashMap<>();
activation.put("mac_address", "AA-BB-CC-DD-EE-FF");
activation.put("activation_code", "CODE1");
when(redisUtils.get(any())).thenAnswer(invocation -> {
String key = invocation.getArgument(0);
return key.endsWith("CODE1") ? CANONICAL : activation;
});
DeviceServiceImpl service = service(dao, redisUtils);
UserDetail user = new UserDetail();
user.setId(9L);
try (MockedStatic<SecurityUser> securityUser = mockStatic(SecurityUser.class)) {
securityUser.when(SecurityUser::getUser).thenReturn(user);
assertTrue(service.deviceActivation("1", "CODE1"));
}
ArgumentCaptor<DeviceEntity> inserted = ArgumentCaptor.forClass(DeviceEntity.class);
verify(dao).insert(inserted.capture());
assertEquals(CANONICAL, inserted.getValue().getMacAddress());
}
private DeviceServiceImpl service(DeviceDao dao) {
return service(dao, mock(RedisUtils.class));
}
/** baseDao 由父类持有,子类内部赋给 this,测试类自己碰不到它 */
private DeviceServiceImpl service(DeviceDao dao, RedisUtils redisUtils) {
return new DeviceServiceImpl(dao, null, null, redisUtils, null, null) {
{
this.baseDao = dao;
}
};
}
/** 只在查询值等于 storedMac 时才命中,用来验证查的是哪个值 */
private DeviceDao daoMatchingOnly(String storedMac, DeviceEntity row) {
DeviceDao dao = mock(DeviceDao.class);
when(dao.selectOne(any())).thenAnswer(invocation -> {
Wrapper<DeviceEntity> wrapper = invocation.getArgument(0);
return storedMac.equals(queriedMac(wrapper)) ? row : null;
});
return dao;
}
private DeviceEntity storedDevice(String mac) {
DeviceEntity device = new DeviceEntity();
device.setId(mac);
device.setMacAddress(mac);
return device;
}
@SuppressWarnings("unchecked")
private ArgumentCaptor<Wrapper<DeviceEntity>> wrapperCaptor() {
return ArgumentCaptor.forClass(Wrapper.class);
}
/** eq() 绑定的值只在 AbstractWrapper 上,Wrapper 接口看不到 */
private Map<String, Object> boundValues(Wrapper<DeviceEntity> wrapper) {
return ((AbstractWrapper<?, ?, ?>) wrapper).getParamNameValuePairs();
}
/**
* 取出这次查询实际拿去比对的 MAC
*
* <p>
* 绑定值是拼 SQL 时才写进去的,getSqlSegment() 先调一次才读得到
*/
private Object queriedMac(Wrapper<DeviceEntity> wrapper) {
wrapper.getSqlSegment();
return boundValues(wrapper).values().iterator().next();
}
}