diff --git a/index.js b/index.js index b56aa24763a4858007d2b2eca54f8eb1d7e9e495..601f5e3d9315baf3836bde42fdc6596446a69cb5 100644 --- a/index.js +++ b/index.js @@ -4,6 +4,7 @@ const path = require('path'); const ip = require('ip'); const app = express(); const server = http.createServer(app); +const fs = require('fs') app.use(express.static(path.join(__dirname, 'public'))); app.use(express.json()); // Use express.json() to parse JSON bodies @@ -82,6 +83,51 @@ app.post('/am-i-ok/:deviceID', (req, res) => { console.log('Sent JSON:', responseToSend); }); +app.post('/json/:deviceID', (req, res) => { + const deviceID = req.params.deviceID; + console.log(`Json incoming form: ${deviceID}`) + let responseToSend + + const measurementsFolderPath = path.join(__dirname, 'measurements', deviceID); + + // Check if the folder exists, if not create it + if (!fs.existsSync(measurementsFolderPath)) { + fs.mkdirSync(measurementsFolderPath, { recursive: true }); + } + + // Get filename from request body + console.log("The body of the request is:") + console.log(req.body) + console.log("The paramteres are:") + console.log(req.params) + const { filename, ...jsonData } = req.body; + console.log("The filename shold be:", filename) + + // Generate unique filename if not provided + const fileName = filename || deviceID + '.json'; + + // Path to save the file + const filePath = path.join(measurementsFolderPath, fileName); + + // Write JSON data to the file + + + + fs.writeFile(filePath, JSON.stringify(jsonData, null, 2), (err) => { + if (err) { + console.error('Error saving file:', err); + responseToSend = { error: err } + return res.status(500).json(responseToSend); + } else { + console.log('File saved successfully:', filePath); + responseToSend = { error: '' } + return res.status(200).json(responseToSend); + } + }); + + console.log('Sent JSON:', responseToSend); +}); + app.post('/ready/:deviceID', (req, res) => { const deviceID = req.params.deviceID; @@ -91,7 +137,6 @@ app.post('/ready/:deviceID', (req, res) => { console.log(`Received "ready" message from device ${deviceID}`); // Update the device state to "Ready" connectedDevices[deviceID].state = 'Ready'; - } });