Files
nxxmdata/backend/create-test-sensor-data.js

71 lines
2.1 KiB
JavaScript
Raw Normal View History

const { SensorData } = require('./models');
const { sequelize } = require('./config/database-simple');
(async () => {
try {
console.log('开始创建测试传感器数据...');
// 清除现有数据
await SensorData.destroy({ where: {} });
console.log('已清除现有传感器数据');
// 创建过去24小时的测试数据
const testData = [];
const now = new Date();
// 生成24小时的数据每小时一个数据点
for (let i = 23; i >= 0; i--) {
const time = new Date(now.getTime() - i * 60 * 60 * 1000);
// 温度数据 (20-30度之间波动)
testData.push({
device_id: 2,
farm_id: 1,
sensor_type: 'temperature',
value: 20 + Math.random() * 10,
unit: '°C',
status: 'normal',
recorded_at: time
});
// 湿度数据 (50-80%之间波动)
testData.push({
device_id: 3,
farm_id: 1,
sensor_type: 'humidity',
value: 50 + Math.random() * 30,
unit: '%',
status: 'normal',
recorded_at: time
});
}
// 批量插入数据
await SensorData.bulkCreate(testData);
console.log(`成功创建 ${testData.length} 条测试传感器数据`);
// 验证数据
const temperatureCount = await SensorData.count({ where: { sensor_type: 'temperature' } });
const humidityCount = await SensorData.count({ where: { sensor_type: 'humidity' } });
console.log(`温度数据条数: ${temperatureCount}`);
console.log(`湿度数据条数: ${humidityCount}`);
// 显示最新的几条数据
const latestData = await SensorData.findAll({
limit: 5,
order: [['recorded_at', 'DESC']],
attributes: ['sensor_type', 'value', 'unit', 'recorded_at']
});
console.log('\n最新的5条数据:');
latestData.forEach(data => {
console.log(`${data.sensor_type}: ${data.value}${data.unit} at ${data.recorded_at}`);
});
} catch (error) {
console.error('创建测试数据时出错:', error);
} finally {
process.exit();
}
})();