【代码评审】IoT:模拟设备数据

This commit is contained in:
YunaiV 2025-01-25 11:46:26 +08:00
parent 03462a103c
commit 269dec1b2e
13 changed files with 66 additions and 142 deletions

View File

@ -3,7 +3,6 @@ package cn.iocoder.yudao.module.iot.controller.admin.device;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.iot.api.device.dto.IotDevicePropertyReportReqDTO;
import cn.iocoder.yudao.module.iot.controller.admin.device.vo.deviceData.*;
import cn.iocoder.yudao.module.iot.dal.dataobject.device.IotDeviceDataDO;
import cn.iocoder.yudao.module.iot.dal.dataobject.device.IotDeviceLogDO;
@ -52,7 +51,7 @@ public class IotDeviceDataController {
return success(BeanUtils.toBean(list, IotTimeDataRespVO.class));
}
// TODO:数据权限
// TODO:功能权限
@PostMapping("/simulator")
@Operation(summary = "模拟设备")
public CommonResult<Boolean> simulatorDevice(@Valid @RequestBody IotDeviceDataSimulatorSaveReqVO simulatorReqVO) {
@ -62,7 +61,7 @@ public class IotDeviceDataController {
return success(true);
}
// TODO:数据权限
// TODO:功能权限
@GetMapping("/log/page")
@Operation(summary = "获得设备日志分页")
public CommonResult<PageResult<IotDeviceLogRespVO>> getDeviceLogPage(@Valid IotDeviceLogPageReqVO pageReqVO) {

View File

@ -19,7 +19,6 @@ public class IotDeviceDataSimulatorSaveReqVO {
@NotEmpty(message = "产品标识不能为空")
private String productKey;
// TODO @super中文写作规范中英文之间要有空格例如说设备 IDps这里应该是设备标识
@Schema(description = "设备标识", requiredMode = Schema.RequiredMode.REQUIRED, example = "device123")
@NotEmpty(message = "设备标识不能为空")
private String deviceKey;
@ -38,6 +37,7 @@ public class IotDeviceDataSimulatorSaveReqVO {
@NotEmpty(message = "数据内容不能为空")
private String content;
// TODO @芋艿需要讨论下reportTime 到底以那个为准
@Schema(description = "上报时间", requiredMode = Schema.RequiredMode.REQUIRED)
private Long reportTime;

View File

@ -25,7 +25,6 @@ public class IotDeviceLogDO {
*/
private String id;
// TODO @super关联要 @下
/**
* 产品标识
* <p>
@ -33,7 +32,6 @@ public class IotDeviceLogDO {
*/
private String productKey;
// TODO @super关联要 @下
/**
* 设备标识
* <p>

View File

@ -10,9 +10,7 @@ import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* IOT 设备日志数据 Mapper 接口
*
* 基于 TDengine 实现设备日志的存储
* 设备日志 {@link IotDeviceLogDO} Mapper 接口
*/
@Mapper
@TDengineDS
@ -21,12 +19,11 @@ public interface IotDeviceLogDataMapper {
/**
* 创建设备日志超级表
* 初始化只创建一次
*/
void createDeviceLogSTable();
// TODO @super单个参数不用加 @Param
// TODO @芋艿在瞅瞅
//讨论艿菇这里有些特殊情况我也学习了一下这块知识
// 如果使用的是Java 8及以上版本并且编译器保留了参数名通过编译器选项-parameters启用则可以去掉@Param注解MyBatis会自动使用参数的实际名称
// 但在TDengine中 @Param去掉后TDengine会报错以下是大模型的回答
@ -65,18 +62,12 @@ public interface IotDeviceLogDataMapper {
*/
Long selectCount(@Param("reqVO") IotDeviceLogPageReqVO reqVO);
// TODO @芋艿这个方法名后续看看叫啥好
/**
* 查询设备日志表是否存在
*
* @return 不存在返回null
* @return 不存在返回 null
*/
Object checkDeviceLogSTableExists();
/**
* 检查设备日志子表是否存在
*
* @param deviceKey 设备标识
* @return 不存在返回null
*/
Object checkDeviceLogTableExists(@Param("deviceKey") String deviceKey);
}

View File

@ -6,17 +6,15 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
/**
* TDengine 表初始化的 Configuration
*
* @author alwayssuper
*/
@Configuration
@Slf4j
@RequiredArgsConstructor
@Configuration
@Order
public class TDengineTableInitConfiguration implements ApplicationRunner {
private final IotDeviceLogDataService deviceLogService;
@ -26,9 +24,7 @@ public class TDengineTableInitConfiguration implements ApplicationRunner {
try {
// 初始化设备日志表
deviceLogService.defineDeviceLog();
// TODO @super这个日志是不是不用打不然重复啦
} catch (Exception ex) {
// TODO @super初始化失败打印 error 日志退出系统不然跑起来就初始啦
// 初始化失败时打印错误日志并退出系统
log.error("[TDengine] 初始化设备日志表结构失败,系统无法正常运行,即将退出", ex);
System.exit(1);

View File

@ -1,7 +1,6 @@
package cn.iocoder.yudao.module.iot.mq.consumer.deviceconsumer;
import cn.iocoder.yudao.module.iot.api.device.dto.IotDevicePropertyReportReqDTO;
import cn.iocoder.yudao.module.iot.dal.dataobject.tdengine.ThingModelMessage;
import cn.iocoder.yudao.module.iot.service.device.IotDeviceLogDataService;
import cn.iocoder.yudao.module.iot.service.device.IotDevicePropertyDataService;
@ -20,8 +19,9 @@ import javax.annotation.Resource;
@Component
@Slf4j
public class DeviceConsumer {
@Resource
private IotDeviceLogDataService iotDeviceLogDataService;
private IotDeviceLogDataService deviceLogDataService;
@Resource
private IotDevicePropertyDataService deviceDataService;
@ -35,7 +35,7 @@ public class DeviceConsumer {
// 设备数据记录
deviceDataService.saveDeviceDataTest(message);
// 设备日志记录
iotDeviceLogDataService.saveDeviceLog(message);
deviceLogDataService.saveDeviceLog(message);
}
}

View File

@ -6,7 +6,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
// TODO @alwayssuper是不是还没用起来哈Producer 最好属于某个模块
// TODO @芋艿@alwayssuper是不是还没用起来哈Producer 最好属于某个模块
/**
* SimulateSend 模拟设备上报的 Producer
*
@ -28,4 +28,5 @@ public class SimulateSendProducer {
public void sendSimulateMessage(ThingModelMessage thingModelMessage) {
applicationContext.publishEvent(thingModelMessage);
}
}

View File

@ -16,7 +16,7 @@ public interface IotDeviceLogDataService {
/**
* 初始化 TDengine 超级表
*
*系统启动时会自动初始化一次
* 系统启动时会自动初始化一次
*/
void defineDeviceLog();
@ -40,8 +40,8 @@ public interface IotDeviceLogDataService {
/**
* 插入设备日志
*
* @param msg 设备数据
* @param message 设备数据
*/
void saveDeviceLog(ThingModelMessage msg);
void saveDeviceLog(ThingModelMessage message);
}

View File

@ -13,7 +13,6 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import java.util.Date;
import java.util.List;
/**
@ -27,28 +26,18 @@ import java.util.List;
public class IotDeviceLogDataServiceImpl implements IotDeviceLogDataService{
@Resource
private IotDeviceLogDataMapper iotDeviceLogDataMapper;
private IotDeviceLogDataMapper deviceLogDataMapper;
// TODO @super方法名defineDeviceLog未来有可能别人使用别的记录日志例如说 es 之类的
@Override
public void defineDeviceLog() {
// TODO @super改成不存在才创建
// try {
// // 创建超级表使用 IF NOT EXISTS 语句避免重复创建错误
// iotDeviceLogDataMapper.createDeviceLogSTable();
// } catch (Exception e) {
// if (e.getMessage().contains("already exists")) {
// log.info("[TDengine] 设备日志超级表已存在,跳过创建");
// return;
// }
// throw e;
// }
if(iotDeviceLogDataMapper.checkDeviceLogSTableExists()==null){
log.info("[TDengine] 设备日志超级表不存在,开始创建");
iotDeviceLogDataMapper.createDeviceLogSTable();
}else{
log.info("[TDengine] 设备日志超级表已存在,跳过创建");
if (deviceLogDataMapper.checkDeviceLogSTableExists() != null) {
log.info("[defineDeviceLog][设备日志超级表已存在,跳过创建]");
return;
}
log.info("[defineDeviceLog][设备日志超级表不存在,开始创建]");
deviceLogDataMapper.createDeviceLogSTable();
log.info("[defineDeviceLog][设备日志超级表不存在,创建完成]");
}
@Override
@ -57,47 +46,32 @@ public class IotDeviceLogDataServiceImpl implements IotDeviceLogDataService{
IotDeviceLogDO iotDeviceLogDO = BeanUtils.toBean(simulatorReqVO, IotDeviceLogDO.class);
// 2. 处理时间字段
// TODO @super一次性的字段不用单独给个变量
// long currentTime = System.currentTimeMillis();
// 2.1 设置时序时间为当前时间
// iotDeviceLogDO.setTs(currentTime); // TODO @superTS在SQL中直接NOW 咱们的TS数据获取是走哪一种 now()
// 3. 插入数据
// TODO @super不要直接调用对方的 IotDeviceLogDataMapper通过 service
// 讨论艿菇 这就是iotDeviceLogDataService的Impl
iotDeviceLogDataMapper.insert(iotDeviceLogDO);
deviceLogDataMapper.insert(iotDeviceLogDO);
}
// TODO @super iotDeviceLogDataService
// 讨论艿菇 这就是iotDeviceLogDataService的Impl
@Override
public PageResult<IotDeviceLogDO> getDeviceLogPage(IotDeviceLogPageReqVO pageReqVO) {
// 当设备日志表未创建时查询会出现报错
if(iotDeviceLogDataMapper.checkDeviceLogTableExists(pageReqVO.getDeviceKey())==null){
return null;
}
// 查询数据
List<IotDeviceLogDO> list = iotDeviceLogDataMapper.selectPage(pageReqVO);
Long total = iotDeviceLogDataMapper.selectCount(pageReqVO);
// 构造分页结果
// TODO @芋艿增加一个表不存在的 try catch
List<IotDeviceLogDO> list = deviceLogDataMapper.selectPage(pageReqVO);
Long total = deviceLogDataMapper.selectCount(pageReqVO);
return new PageResult<>(list, total);
}
@Override
public void saveDeviceLog(ThingModelMessage msg) {
// 1. 构建设备日志对象
IotDeviceLogDO iotDeviceLogDO = IotDeviceLogDO.builder()
.id(msg.getId()) // 消息ID
.deviceKey(msg.getDeviceKey()) // 设备标识
.productKey(msg.getProductKey()) // 产品标识
.type(msg.getMethod()) // 消息类型使用method作为类型
.subType("property") // TODO:这块先写死后续优化
.content(JSONUtil.toJsonStr(msg)) // TODO:后续优化
.reportTime(msg.getTime()) // 上报时间
public void saveDeviceLog(ThingModelMessage message) {
IotDeviceLogDO log = IotDeviceLogDO.builder()
.id(message.getId())
.deviceKey(message.getDeviceKey())
.productKey(message.getProductKey())
.type(message.getMethod()) // 消息类型使用method作为类型 TODO 芋艿在看看
.subType("property") // TODO 芋艿:这块先写死后续优化
.content(JSONUtil.toJsonStr(message)) // TODO 芋艿:后续优化
.reportTime(message.getTime()) // 上报时间 TODO 芋艿在想想时间
.build();
// 2. 插入设备日志
iotDeviceLogDataMapper.insert(iotDeviceLogDO);
deviceLogDataMapper.insert(log);
}
}

View File

@ -32,7 +32,6 @@ public interface IotDevicePropertyDataService {
*/
void saveDeviceData(IotDevicePropertyReportReqDTO createDTO);
/**
* 保存设备数据
*
@ -45,7 +44,6 @@ public interface IotDevicePropertyDataService {
*
* @param simulatorReqVO 设备数据
*/
void simulatorSend(IotDeviceDataSimulatorSaveReqVO simulatorReqVO);
/**

View File

@ -159,7 +159,7 @@ public class IotDevicePropertyDataServiceImpl implements IotDevicePropertyDataSe
thingModelMessageService.saveThingModelMessage(device, thingModelMessage);
}
//TODO:后续捋一捋这块逻辑先借鉴一下目前的代码
//TODO @芋艿:后续捋一捋这块逻辑先借鉴一下目前的代码
@Override
public void saveDeviceDataTest(ThingModelMessage thingModelMessage) {
// 1. 根据产品 key 和设备名称获得设备信息
@ -168,7 +168,7 @@ public class IotDevicePropertyDataServiceImpl implements IotDevicePropertyDataSe
thingModelMessageService.saveThingModelMessage(device, thingModelMessage);
}
//TODO: copy saveDeviceData 的逻辑后续看看这块怎么优化
//TODO @芋艿:copy saveDeviceData 的逻辑后续看看这块怎么优化
@Override
public void simulatorSend(IotDeviceDataSimulatorSaveReqVO simulatorReqVO) {
// 1. 根据设备 key 获得设备信息

View File

@ -4,28 +4,20 @@
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.iocoder.yudao.module.iot.dal.tdengine.IotDeviceLogDataMapper">
<!-- 创建设备日志超级表 初始化只创建一次-->
<update id="createDeviceLogSTable">
CREATE STABLE IF NOT EXISTS device_log (
ts TIMESTAMP,
id NCHAR(50),
product_key NCHAR(50),
type NCHAR(50),
<!-- TODO @super下划线 sub_type -->
sub_type NCHAR(50),
content NCHAR(1024),
report_time TIMESTAMP
ts TIMESTAMP,
id NCHAR(50),
product_key NCHAR(50),
type NCHAR(50),
sub_type NCHAR(50),
content NCHAR(1024),
report_time TIMESTAMP
) TAGS (
device_key NCHAR(50)
)
</update>
<!-- 创建设备日志子表 讨论TDengine 在子表不存在的情况下 可在数据插入时 自动建表 要不要去掉创建子表的逻辑 由第一次插入数据时自动创建-->
<update id="createDeviceLogTable">
CREATE TABLE device_log_${deviceKey} USING device_log TAGS('${deviceKey}')
</update>
<!-- 插入设备日志数据 在子表不存在的情况下 可在数据插入时 自动建表 -->
<insert id="insert">
INSERT INTO device_log_${log.deviceKey} (ts, id, product_key, type, subType, content, report_time)
USING device_log
@ -42,7 +34,7 @@
</insert>
<select id="selectPage" resultType="cn.iocoder.yudao.module.iot.dal.dataobject.device.IotDeviceLogDO">
SELECT ts, id, device_key, product_key, type, subType, content, report_time
SELECT ts, id, device_key, product_key, type, sub_type, content, report_time
FROM device_log_${reqVO.deviceKey}
<where>
<if test="reqVO.type != null and reqVO.type != ''">
@ -75,15 +67,12 @@
</where>
</select>
<!-- 检查设备日志超级表是否存在 -->
<select id="checkDeviceLogSTableExists" resultType="Object">
SHOW STABLES LIKE 'device_log'
</select>
<!-- 检查设备日志子表是否存在 -->
<select id="checkDeviceLogTableExists" resultType="Object">
SHOW TABLES LIKE 'device_log_${deviceKey}'
</select>
</mapper>

View File

@ -45,7 +45,7 @@ spring:
primary: master
datasource:
master:
url: jdbc:mysql://chaojiniu.top:23306/ruoyi-vue-pro?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true # MySQL Connector/J 8.X 连接的示例
url: jdbc:mysql://127.0.0.1:3307/ruoyi-vue-pro?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true # MySQL Connector/J 8.X 连接的示例
# url: jdbc:mysql://127.0.0.1:3306/ruoyi-vue-pro?useSSL=true&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai # MySQL Connector/J 5.X 连接的示例
# url: jdbc:postgresql://127.0.0.1:5432/ruoyi-vue-pro # PostgreSQL 连接的示例
# url: jdbc:oracle:thin:@127.0.0.1:1521:xe # Oracle 连接的示例
@ -53,8 +53,8 @@ spring:
# url: jdbc:dm://127.0.0.1:5236?schema=RUOYI_VUE_PRO # DM 连接的示例
# url: jdbc:kingbase8://127.0.0.1:54321/test # 人大金仓 KingbaseES 连接的示例
# url: jdbc:postgresql://127.0.0.1:5432/postgres # OpenGauss 连接的示例
username: ruoyi-vue-pro
password: ruoyi-@h2ju02hebp
username: root
password: ahh@123456
# username: sa # SQL Server 连接的示例
# password: Yudao@2024 # SQL Server 连接的示例
# username: SYSDBA # DM 连接的示例
@ -63,25 +63,17 @@ spring:
# password: Yudao@2024 # OpenGauss 连接的示例
slave: # 模拟从库,可根据自己需要修改
lazy: true # 开启懒加载,保证启动速度
url: jdbc:mysql://chaojiniu.top:23306/ruoyi-vue-pro?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
username: ruoyi-vue-pro
password: ruoyi-@h2ju02hebp
tdengine: # IOT 数据库
# lazy: true # 开启懒加载,保证启动速度
url: jdbc:TAOS-RS://chaojiniu.top:6041/ruoyi_vue_pro
driver-class-name: com.taosdata.jdbc.rs.RestfulDriver
url: jdbc:mysql://127.0.0.1:3307/ruoyi-vue-pro?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
username: root
password: taosdata
druid:
validation-query: SELECT SERVER_STATUS() # TDengine 数据源的有效性检查 SQL
password: ahh@123456
# Redis 配置。Redisson 默认的配置足够使用,一般不需要进行调优
data:
redis:
host: chaojiniu.top # 地址
host: 127.0.0.1 # 地址
port: 6379 # 端口
database: 15 # 数据库索引
password: fsknKD7UvQYZsyf2hXXn # 密码,建议生产环境开启
database: 0 # 数据库索引
# password: dev # 密码,建议生产环境开启
--- #################### 定时任务相关配置 ####################
@ -191,12 +183,12 @@ debug: false
--- #################### 微信公众号、小程序相关配置 ####################
wx:
mp: # 公众号配置(必填),参见 https://github.com/Wechat-Group/WxJava/blob/develop/spring-boot-starters/wx-java-mp-spring-boot-starter/README.md 文档
# app-id: wx041349c6f39b268b # 测试号(牛希尧提供的)
# secret: 5abee519483bc9f8cb37ce280e814bd0
# app-id: wx041349c6f39b268b # 测试号(牛希尧提供的)
# secret: 5abee519483bc9f8cb37ce280e814bd0
app-id: wx5b23ba7a5589ecbb # 测试号(自己的)
secret: 2a7b3b20c537e52e74afd395eb85f61f
# app-id: wxa69ab825b163be19 # 测试号Kongdy 提供的)
# secret: bd4f9fab889591b62aeac0d7b8d8b4a0
# app-id: wxa69ab825b163be19 # 测试号Kongdy 提供的)
# secret: bd4f9fab889591b62aeac0d7b8d8b4a0
# 存储配置,解决 AccessToken 的跨节点的共享
config-storage:
type: RedisTemplate # 采用 RedisTemplate 操作 Redis会自动从 Spring 中获取
@ -205,10 +197,10 @@ wx:
miniapp: # 小程序配置(必填),参见 https://github.com/Wechat-Group/WxJava/blob/develop/spring-boot-starters/wx-java-miniapp-spring-boot-starter/README.md 文档
# appid: wx62056c0d5e8db250 # 测试号(牛希尧提供的)
# secret: 333ae72f41552af1e998fe1f54e1584a
# appid: wx63c280fe3248a3e7 # wenhualian的接口测试号
# secret: 6f270509224a7ae1296bbf1c8cb97aed
# appid: wxc4598c446f8a9cb3 # 测试号Kongdy 提供的)
# secret: 4a1a04e07f6a4a0751b39c3064a92c8b
# appid: wx63c280fe3248a3e7 # wenhualian的接口测试号
# secret: 6f270509224a7ae1296bbf1c8cb97aed
# appid: wxc4598c446f8a9cb3 # 测试号Kongdy 提供的)
# secret: 4a1a04e07f6a4a0751b39c3064a92c8b
appid: wx66186af0759f47c9 # 测试号puhui 提供的)
secret: 3218bcbd112cbc614c7264ceb20144ac
config-storage:
@ -267,7 +259,7 @@ justauth:
iot:
emq:
# 账号
username: haohao
username: anhaohao
# 密码
password: ahh@123456
# 主机地址
@ -279,18 +271,4 @@ iot:
# 保持连接
keepalive: 60
# 清除会话(设置为false,断开连接,重连后使用原来的会话 保留订阅的主题,能接收离线期间的消息)
clearSession: true
# MQTT-RPC 配置
mqtt:
broker: tcp://chaojiniu.top:1883
username: haohao
password: ahh@123456
clientId: mqtt-rpc-server-${random.int}
requestTopic: rpc/request
responseTopicPrefix: rpc/response/
# 插件配置
pf4j:
pluginsDir: /Users/anhaohao/code/gitee/ruoyi-vue-pro/plugins # 插件目录
clearSession: true