RQteafactory-NodeJS/server.js
2024-07-20 16:47:45 +08:00

91 lines
2.2 KiB
JavaScript

const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
const port = 8000;
// 允许所有来源的请求
app.use(cors());
// 创建 MySQL 连接
const db = mysql.createConnection({
host: '172.17.0.1',
user: 'RQteafactory',
password: 'Guoswork105',
database: 'RQteafactory'
});
// 连接数据库
db.connect((err) => {
if (err) {
console.error('MySQL connection error: ', err);
return;
}
console.log('MySQL connected...');
});
// 折线图获取数据库数据
function getSensorData(callback) {
const sql = 'SELECT timestamp, temperature, humidity, co2, pressure FROM sensor_data';
db.query(sql, (err, results) => {
if (err) {
console.error('Error fetching sensor data: ', err);
callback({ error: 'Error fetching sensor data' });
return;
}
const timestamps = results.map(row => new Date(row.timestamp).toISOString().slice(0, 19).replace('T', ' '));
const temperatures = results.map(row => row.temperature);
const humidities = results.map(row => row.humidity);
const co2 = results.map(row => row.co2);
const pressure = results.map(row => row.pressure);
callback({
timestamps,
temperatures,
humidities,
co2,
pressure
});
});
}
// 获取数据库中最新的数据
function getLatestSensorData(callback) {
const sql = 'SELECT temperature, humidity, co2, pressure FROM sensor_data ORDER BY timestamp DESC LIMIT 1';
db.query(sql, (err, results) => {
if (err) {
console.error('Error fetching latest sensor data: ', err);
callback({ error: 'Error fetching latest sensor data' });
return;
}
const data = results[0];
callback({
temperature: data.temperature,
humidity: data.humidity,
co2: data.co2,
pressure: data.pressure
});
});
}
// 获取数据
app.get('/get_sensor_data', (req, res) => {
getSensorData(data => {
res.json(data);
});
});
// 获取最新的数据
app.get('/get_latest_sensor_data', (req, res) => {
getLatestSensorData(data => {
res.json(data);
});
});
// 启动服务器
app.listen(port, () => {
console.log(`Server running on http://0.0.0.0:${port}`);
});