Skip to content
Snippets Groups Projects
Commit 11ed0583 authored by miklosimate's avatar miklosimate
Browse files

Initial commit

parents
No related branches found
No related tags found
No related merge requests found
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/szakdoga_node.iml" filepath="$PROJECT_DIR$/.idea/szakdoga_node.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.tmp" />
<excludeFolder url="file://$MODULE_DIR$/temp" />
<excludeFolder url="file://$MODULE_DIR$/tmp" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Server Dashboard</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1 {
color: #333;
}
.server-parameters {
margin-bottom: 20px;
}
.device-list {
width: 50%;
margin-top: 20px;
border-collapse: collapse;
}
.device-list th, .device-list td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
.device-list th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>Server Dashboard</h1>
<div class="server-parameters">
<h2>Server Parameters</h2>
<label for="numberOfMeasurements">Number of Measurements:</label>
<input type="text" id="numberOfMeasurements" placeholder="Enter number of measurements">
<br>
<label for="intervals">Intervals:</label>
<input type="text" id="intervals" placeholder="Enter intervals">
<br>
<label for="delay">Delay:</label>
<input type="text" id="delay" placeholder="Enter delay">
<br>
<button onclick="updateServerConfig()">Update Server Config</button>
</div>
<h2>Device List</h2>
<table class="device-list">
<thead>
<tr>
<th>ID</th>
<th>State</th>
<th>Count</th>
</tr>
</thead>
<tbody id="deviceTableBody">
<!-- Device entries will be added dynamically here -->
</tbody>
</table>
<script>
async function updateServerConfig() {
const numberOfMeasurements = document.getElementById('numberOfMeasurements').value;
const intervals = document.getElementById('intervals').value;
const delay = document.getElementById('delay').value;
try {
const response = await fetch('/set-server-config', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
NumberOfMeasurements: numberOfMeasurements,
Intervals: intervals,
Delay: delay,
}),
});
const data = await response.text();
alert(data);
} catch (error) {
console.error('Error updating server config:', error);
}
}
async function populateDeviceList() {
try {
const response = await fetch('/get-devices');
const data = await response.json();
const deviceTableBody = document.getElementById('deviceTableBody');
deviceTableBody.innerHTML = '';
data.forEach(device => {
const row = document.createElement('tr');
const idCell = document.createElement('td');
const stateCell = document.createElement('td');
const dotCell = document.createElement('td'); // New cell for dots
idCell.textContent = device.id;
stateCell.textContent = device.state;
dotCell.textContent = device.current_cnt
// Create dots based on current_cnt and numberOfMeasurements
const numberOfMeasurements = document.getElementById('numberOfMeasurements').value;
const dotContainer = document.createElement('div');
dotContainer.style.display = 'flex';
for (let i = 0; i < numberOfMeasurements; i++) {
const dot = document.createElement('div');
dot.style.width = '10px';
dot.style.height = '10px';
dot.style.borderRadius = '50%';
dot.style.marginRight = '2px';
// Check if the measurement is done (green) or will be done (gray)
if (i < (device.current_cnt || 0)) {
dot.style.backgroundColor = 'green';
} else {
dot.style.backgroundColor = 'gray';
}
dotContainer.appendChild(dot);
}
// Append cells to the row
row.appendChild(idCell);
row.appendChild(stateCell);
dotCell.appendChild(dotContainer);
row.appendChild(dotCell);
deviceTableBody.appendChild(row);
});
} catch (error) {
console.error('Error fetching devices:', error);
}
}
async function handleStillHereMessageAndRefresh(deviceID) {
try {
const response = await fetch(`/stillHere/${deviceID}`, {
method: 'POST',
});
const data = await response.json();
// Refresh the device list after receiving "stillHere" message
await populateDeviceList();
} catch (error) {
console.error('Error handling stillHere message:', error);
}
}
async function handleReadyMessageAndRefresh(deviceID) {
try {
const response = await fetch(`/ready/${deviceID}`, {
method: 'POST',
});
const data = await response.json();
// Refresh the device list after receiving "ready" message
await populateDeviceList();
} catch (error) {
console.error('Error handling ready message:', error);
}
}
// Populate device list on page load
populateDeviceList();
</script>
</body>
</html>
index.js 0 → 100644
const express = require('express');
const http = require('http');
const path = require('path');
const ip = require('ip');
const app = express();
const server = http.createServer(app);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json()); // Use express.json() to parse JSON bodies
// 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('/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}`);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Device List</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1 {
color: #333;
}
.device-list {
width: 50%;
margin-top: 20px;
border-collapse: collapse;
}
.device-list th, .device-list td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
.device-list th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>Device List</h1>
<table class="device-list">
<thead>
<tr>
<th>ID</th>
<th>State</th>
<th>Count</th>
</tr>
</thead>
<tbody id="deviceTableBody">
<!-- Device entries will be added dynamically here -->
</tbody>
</table>
<script>
async function populateDeviceList() {
try {
const response = await fetch('/get-devices');
const data = await response.json();
const deviceTableBody = document.getElementById('deviceTableBody');
deviceTableBody.innerHTML = '';
data.forEach(device => {
const row = document.createElement('tr');
const idCell = document.createElement('td');
const stateCell = document.createElement('td');
const currentCntCell = document.createElement('td');
idCell.textContent = device.id;
stateCell.textContent = device.state;
// Display current_cnt if available, otherwise display a placeholder
currentCntCell.textContent = device.current_cnt || 'N/A';
// Append cells to the row
row.appendChild(idCell);
row.appendChild(stateCell);
row.appendChild(currentCntCell);
deviceTableBody.appendChild(row);
});
} catch (error) {
console.error('Error fetching devices:', error);
}
}
// Populate device list on page load
populateDeviceList();
</script>
</body>
</html>
This diff is collapsed.
{
"name": "szakdoga_node",
"version": "1.0.0",
"description": "Sensor collector app connection ",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"ip": "^1.1.8",
"node-arp": "^1.0.6",
"node-ssdp": "^4.0.1"
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment