diff --git a/app.js b/app.js index 21abde2..ea956ba 100644 --- a/app.js +++ b/app.js @@ -393,6 +393,56 @@ const addProgram = async (programName, machineName) => { } }; +async function recordTimeSeriesData() { + // Get the current timestamp and timestamp for 5 minutes ago + const now = new Date(); + const localPollrate = new Date(now.getTime() - pollrate); + + // Format dates for MySQL + const nowFormatted = now.toISOString().slice(0, 19).replace('T', ' '); + const fiveMinutesAgoFormatted = localPollrate.toISOString().slice(0, 19).replace('T', ' '); + + // Query to count records within the last 5 minutes + const countQuery = ` + SELECT program, COUNT(*) as count + FROM usedLicences + WHERE date >= ? + GROUP BY program + `; + + // Query to insert data into time_data + const insertQuery = ` + INSERT INTO time_data (name, count, date) + VALUES (?, ?, ?) + `; + + connection.connect(); + + connection.query(countQuery, [fiveMinutesAgoFormatted], (err, results) => { + if (err) { + console.error('Error querying count:', err); + connection.end(); + return; + } + + // Insert aggregated data into time_data + results.forEach(row => { + connection.query(insertQuery, [row.program, row.count, nowFormatted], (err) => { + if (err) { + console.error('Error inserting data:', err); + } + }); + }); + + console.log('Time series data recorded successfully.'); + connection.end(); + }); +} + +setTimeout(() => { + recordTimeSeriesData(); +}, pollrate); + setTimeout(() => { testDatabaseConnection(); }, 1000);