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

index.js

Blame
  • index.js 6.74 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'}));
    app.use(bodyParser.json({ limit: '5mb' }));
    app.use(bodyParser.urlencoded({ extended: true, limit: '5mb' }));
    
    
    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'));
    });
    
    //This function was written by chatGPT (3.5), the rest of the code and the "Write me the route for server info" input was given.
    app.get('/server-info', (req, res) => {
        const serverInfo = {
            ip: ip.address(),
            port: PORT,
        };
        res.json(serverInfo);
    });
    //This function was written by chatGPT (3.5) with many iterations and manual corrections.
    app.post('/init', (req, res) => {
        console.log(`Received "init" message\n`);
        //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
    //This function was written by chatGPT (3.5) with many iterations and manual corrections.
    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}\n`);
    
            // 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);
    });
    //This function was written by chatGPT (3.5) with many iterations and manual corrections.
    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(`Filename: ${f_n}`)
        let responseToSend = {error: ''}
    
        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 });
        }
        const { filename, ...jsonData } = req.body;
    
        // Generate unique filename if not provided
        const fileName = f_n + '.json' || deviceID + '.json';
    
        //connectedDevices[deviceID].current_cnt = f_n[0]
        try {
            connectedDevices[deviceID].current_cnt = f_n[0];
        } catch (error) {
            console.log("Not valid id");
        }
    
        // Path to save the file
        const filePath = path.join(measurementsFolderPath, fileName);
    
        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';
        }
    });
    //This function was written by chatGPT (3.5) with many iterations and manual corrections.
    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);
    }
    //This function was written by chatGPT (3.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);
    });
    //This function was written by chatGPT (3.5) manual corrections was needed.
    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}`);
    });