Skip to content
Snippets Groups Projects
Select Git revision
  • cf1d5da7403a5f18a2c65a1225504f9c0cf5f11d
  • main default protected
2 results

index.js

Blame
  • index.js 6.42 KiB
    const express = require('express');
    const http = require('http');
    const path = require('path');
    const ip = require('ip');
    const app = express();
    const server = http.createServer(app);
    const fs = require('fs')
    const bodyParser = require('body-parser');
    
    app.use(express.static(path.join(__dirname, 'public')));
    app.use(express.json({limit: '100mb'})); // Use express.json() to parse JSON bodies
    app.use(bodyParser.json({ limit: '5mb' })); // Set maximum payload size to 5 MB
    app.use(bodyParser.urlencoded({ extended: true, limit: '5mb' }));
    
    
     // Use body-parser to parse plain text request bodies
    
    const connectedDevices = {};
    let serverReady = false;
    let serverConfig = {
        NumberOfMeasurements: null,
        Intervals: null,
        Delay: null,
    };
    
    app.get('/', (req, res) => {
        res.sendFile(path.join(__dirname, 'index.html'));
    });
    app.get('/list', (req, res) => {
        res.sendFile(path.join(__dirname, 'list.html'));
    });
    
    // Add route to get server info
    app.get('/server-info', (req, res) => {
        const serverInfo = {
            ip: ip.address(),
            port: PORT,
        };
        res.json(serverInfo);
    });
    
    // POST route for handling "init" messages
    app.post('/init', (req, res) => {
        console.log(`Received "init" message`);
        //If the measurement parameters has not been set yet
        if (!serverReady) {
            const responseToSend = { error: 'ServerNotReady' };
            console.log('Sent JSON:', responseToSend);
            return res.status(503).json(responseToSend);
        }
    
        try {
            const deviceID = generateDeviceID();
            // Store device-specific information
            connectedDevices[deviceID] = {
                state: 'Init',
                current_cnt: 0
            };
            const responseToSend = { error:'',deviceID, serverConfig };
            console.log('Sending response:', responseToSend);
    
            // Send the device ID and configuration back to the client
            res.json(responseToSend);
        } catch (error) {
            console.log(error.message);
            res.status(400).json({ error: error.message });
        }
    });
    
    
    // POST route for checking "am-i-ok" messages
    app.post('/am-i-ok/:deviceID', (req, res) => {
        const deviceID = req.params.deviceID;
        let responseToSend
        // Check if the device is registered
        if (connectedDevices.hasOwnProperty(deviceID)) {
            console.log(`Received "am-i-ok" message from device ${deviceID}`);
    
            // Update the device state to "Ready"
            connectedDevices[deviceID].state = 'Id confirmed';
            responseToSend = { error: '' }
            return res.status(200).json(responseToSend);
    
        } else {
            responseToSend = { error: 'NotOK' }
            return res.status(501).json(responseToSend);
        }
        console.log('Sent JSON:', responseToSend);
    });
    
    app.post('/json/:deviceID/:f_n', (req, res) => {
        const deviceID = req.params.deviceID;
        const f_n = req.params.f_n;
        console.log(`Json incoming form: ${deviceID}`)
        console.log(`Json incoming form: ${f_n}`)
        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 parameters are:")
        console.log(req.params)
        const { filename, ...jsonData } = req.body;
        console.log(`The filename should be: ${filename}`)
    
        // Generate unique filename if not provided
        const fileName = f_n + '.json' || 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;
        let responseToSend
        // Check if the device is registered
        if (connectedDevices.hasOwnProperty(deviceID)) {
            console.log(`Received "ready" message from device ${deviceID}`);
            // Update the device state to "Ready"
            connectedDevices[deviceID].state = 'Ready';
        }
    });
    
    app.post('/stillHere/:deviceID', (req, res) => {
        const deviceID = req.params.deviceID;
        // Check if the device is registered
        if (connectedDevices.hasOwnProperty(deviceID)) {
            console.log(`Received "stillHere" message from device ${deviceID}`);
    
            // Increment the current count for the device
            connectedDevices[deviceID].current_cnt = (connectedDevices[deviceID].current_cnt || 0) + 1;
    
            // Prepare the response with the updated current count
            const responseToSend = {
                error: '',
                current_cnt: connectedDevices[deviceID].current_cnt,
            };
    
            console.log('Sent JSON:', responseToSend);
            return res.status(200).json(responseToSend);
        } else {
            const responseToSend = { error: 'DeviceNotRegistered' };
            console.log('Sent JSON:', responseToSend);
            return res.status(404).json(responseToSend);
        }
    });
    
    
    function generateDeviceID() {
        // Generate a unique device ID (you can use a more robust method if needed)
        return Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
    }
    
    app.get('/get-devices', (req, res) => {
        const devicesList = Object.keys(connectedDevices).map(deviceID => {
            return {
                id: deviceID,
                state: connectedDevices[deviceID].state,
                current_cnt: connectedDevices[deviceID].current_cnt
            };
        });
    
        res.json(devicesList);
    });
    app.post('/set-server-config', (req, res) => {
        // Handle the POST request to set server configuration
        const { NumberOfMeasurements, Intervals, Delay } = req.body;
    
        // Update the server configuration as needed
        serverConfig = {
            NumberOfMeasurements,
            Intervals,
            Delay,
        };
    
        res.send('Server configuration set: ');
        serverReady = true
    });
    
    const PORT = 3000;
    server.listen(PORT, () => {
        console.log(`Server is running on http://${ip.address()}:${PORT}`);
    });