diff --git a/app/routes/index.js b/app/routes/index.js index 729f46c72f3fc19b5130a0ca59d9b56cccce34b3..8b7e23e6536af522631c9089a98113d6789c0b33 100644 --- a/app/routes/index.js +++ b/app/routes/index.js @@ -5,6 +5,12 @@ const mongoose = require('mongoose'); const Consommation = require('../models/consommation'); const mongoURI = process.env.MONGO_URI || 'mongodb://localhost/abreuvoir'; +// Constantes +const rayonSeau = 15; // Le rayon du seau en cm +const hauteurInitialeEau = 50; // la hauteur initiale de l'eau en cm +const distanceSupplementaire = 5; // la distance supplémentaire en cm entre le capteur et le bord supérieur du seau +let volumeEauInitial = Math.PI * rayonSeau**2 * hauteurInitialeEau; // Calcul du volume d'eau initial en cm^3 (mL) + const port = 3000; app.use(express.json()); @@ -21,14 +27,6 @@ mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) console.error('MongoDB connection error:', err.message); }); - -// Constantes -const rayonSeau = 15; // Le rayon du seau en cm -const hauteurInitialeEau = 50; // la hauteur initiale de l'eau en cm -const distanceSupplementaire = 5; // la distance supplémentaire en cm entre le capteur et le bord supérieur du seau -let volumeEauInitial = Math.PI * rayonSeau**2 * hauteurInitialeEau; // Calcul du volume d'eau initial en cm^3 (mL) - - app.get('/', (req, res) => { res.render('index'); }); @@ -41,6 +39,15 @@ app.get('/graphique-consommations', (req, res) => { res.render( 'chart.pug'); }); +app.get('/liste-consommations', (req, res) => { + res.render('lastConsumptions.pug'); +}); + +app.get('/consommations-par-periode', (req, res) => { + res.render('consumptionsByPeriod.pug'); +}); + +// Route pour récupérer toutes les consommations app.get('/consommations', async (req, res) => { try { const consommations = await Consommation.find(); @@ -50,6 +57,110 @@ app.get('/consommations', async (req, res) => { } }); +// Route pour récupérer les consommations dans une plage de dates spécifiée +app.get('/consommations/:startDate/:endDate', async (req, res) => { + try { + const { startDate, endDate } = req.params; + + const start = new Date(startDate); + const end = new Date(endDate); + + const consommations = await Consommation.find({ + timestamp: { $gte: start, $lte: end } + }); + + res.json(consommations); + } catch (error) { + res.status(500).json({ message: error.message }); + } +}); + +// Route pour récupérer les dernières consommations +app.get('/last-consommations', async (req, res) => { + try { + const latestConsommations = await Consommation.find().sort({ timestamp: -1 }).limit(10); + res.json(latestConsommations); + } catch (error) { + res.status(500).json({ message: error.message }); + } +}); + +// Route pour obtenir les consommations par jour +app.get('/consommations/par-jour', async (req, res) => { + try { + const consommations = await Consommation.aggregate([ + { + $group: { + _id: { $dateToString: { format: '%Y-%m-%d', date: '$timestamp' } }, + totalConsommation: { $sum: '$consommation' } + } + }, + { $sort: { _id: 1 } } + ]); + + res.json(consommations); + } catch (error) { + res.status(500).json({ message: error.message }); + } +}); + +// Route pour obtenir les consommations par semaine +app.get('/consommations/par-semaine', async (req, res) => { + try { + const consommations = await Consommation.aggregate([ + { + $group: { + _id: { $isoWeek: '$timestamp' }, + totalConsommation: { $sum: '$consommation' } + } + }, + { $sort: { _id: 1 } } + ]); + + res.json(consommations); + } catch (error) { + res.status(500).json({ message: error.message }); + } +}); + +// Route pour obtenir les consommations par mois +app.get('/consommations/par-mois', async (req, res) => { + try { + const consommations = await Consommation.aggregate([ + { + $group: { + _id: { $dateToString: { format: '%Y-%m', date: '$timestamp' } }, + totalConsommation: { $sum: '$consommation' } + } + }, + { $sort: { _id: 1 } } + ]); + + res.json(consommations); + } catch (error) { + res.status(500).json({ message: error.message }); + } +}); + +// Route pour obtenir les consommations par année +app.get('/consommations/par-annee', async (req, res) => { + try { + const consommations = await Consommation.aggregate([ + { + $group: { + _id: { $year: '$timestamp' }, + totalConsommation: { $sum: '$consommation' } + } + }, + { $sort: { _id: 1 } } + ]); + + res.json(consommations); + } catch (error) { + res.status(500).json({ message: error.message }); + } +}); + app.post('/distance', (req, res) => { const { distance } = req.body; console.log(`Distance reçue: ${distance} cm`); diff --git a/app/views/chart.pug b/app/views/chart.pug index 96e3606041b6174ee8bdd51ed3e19cc241898522..c732d0e7fa37af4e5118c8ae509b466c8c8d39f3 100644 --- a/app/views/chart.pug +++ b/app/views/chart.pug @@ -3,36 +3,74 @@ extends layout block content .container h1.text-center Graphique des Consommations + + .form-group + label(for="startDate") Sélectionnez la date de début: + input#startDate.form-control(type="date", value=today, onchange="updateChart()") + + .form-group + label(for="endDate") Sélectionnez la date de fin: + input#endDate.form-control(type="date", value=tomorrow, onchange="updateChart()") + #chart-container canvas#myChart(width="800" height="400") script. document.addEventListener('DOMContentLoaded', async function () { - const response = await fetch('/consommations'); - const consommations = await response.json(); - - const timestamps = consommations.map(cons => new Date(cons.timestamp).toLocaleString()); - const data = consommations.map(cons => cons.consommation); - - const ctx = document.getElementById('myChart').getContext('2d'); - const myChart = new Chart(ctx, { - type: 'bar', - data: { - labels: timestamps, - datasets: [{ - label: 'Consommations', - data: data, - backgroundColor: 'rgba(75, 192, 192, 0.2)', - borderColor: 'rgba(75, 192, 192, 1)', - borderWidth: 1 - }] - }, - options: { - scales: { - y: { - beginAtZero: true - } - } - } - }); + // Obtenir la date d'aujourd'hui + const today = new Date(); + const todayString = today.toISOString().split('T')[0]; + + // Obtenir la date de demain + const tomorrow = new Date(today); + tomorrow.setDate(today.getDate() + 1); + const tomorrowString = tomorrow.toISOString().split('T')[0]; + + // Définir les valeurs par défaut pour les champs de date + document.getElementById('startDate').value = todayString; + document.getElementById('endDate').value = tomorrowString; + + // Mettre à jour le graphique avec les valeurs par défaut + updateChart(); }); + + function updateChart() { + const startDate = document.getElementById('startDate').value; + const endDate = document.getElementById('endDate').value; + + // Obtenez l'instance du graphique existant et détruisez-la + const existingChart = Chart.getChart('myChart'); + if (existingChart) { + existingChart.destroy(); + } + + fetch(`/consommations/${startDate}/${endDate}`) + .then(response => response.json()) + .then(consommations => { + const timestamps = consommations.map(cons => new Date(cons.timestamp).toLocaleString()); + const data = consommations.map(cons => cons.consommation); + + const ctx = document.getElementById('myChart').getContext('2d'); + const myChart = new Chart(ctx, { + type: 'bar', + data: { + labels: timestamps, + datasets: [{ + label: 'Consommations (cm³)', + data: data, + backgroundColor: 'rgba(75, 192, 192, 0.2)', + borderColor: 'rgba(75, 192, 192, 1)', + borderWidth: 1 + }] + }, + options: { + scales: { + y: { + beginAtZero: true + } + } + } + }); + }) + .catch(error => console.error('Erreur lors de la récupération des consommations :', error)); + } diff --git a/app/views/consumptionsByPeriod.pug b/app/views/consumptionsByPeriod.pug new file mode 100644 index 0000000000000000000000000000000000000000..16074420bb248b5ee055cba1cb8bc0e4ba6c7fdc --- /dev/null +++ b/app/views/consumptionsByPeriod.pug @@ -0,0 +1,53 @@ +extends layout + +block content + .container + h1.text-center Consommations par Période + + // Consommations par jour + #consommations-jour + h2 Consommations par Jour + ul.list-group + + // Consommations par semaine + #consommations-semaine + h2 Consommations par Semaine + ul.list-group + + // Consommations par mois + #consommations-mois + h2 Consommations par Mois + ul.list-group + + // Consommations par année + #consommations-annee + h2 Consommations par Année + ul.list-group + + script. + document.addEventListener('DOMContentLoaded', async function () { + // Consommations par jour + const responseJour = await fetch('/consommations/par-jour'); + const consommationsJour = await responseJour.json(); + updateList('consommations-jour', 'Consommations par Jour', consommationsJour); + + // Consommations par semaine + const responseSemaine = await fetch('/consommations/par-semaine'); + const consommationsSemaine = await responseSemaine.json(); + updateList('consommations-semaine', 'Consommations par Semaine', consommationsSemaine); + + // Consommations par mois + const responseMois = await fetch('/consommations/par-mois'); + const consommationsMois = await responseMois.json(); + updateList('consommations-mois', 'Consommations par Mois', consommationsMois); + + // Consommations par année + const responseAnnee = await fetch('/consommations/par-annee'); + const consommationsAnnee = await responseAnnee.json(); + updateList('consommations-annee', 'Consommations par Année', consommationsAnnee); + }); + + function updateList(containerId, label, data) { + const container = document.getElementById(containerId); + container.innerHTML = `

${label}

`; + } diff --git a/app/views/lastConsumptions.pug b/app/views/lastConsumptions.pug new file mode 100644 index 0000000000000000000000000000000000000000..758b58c95e643a91e660f74490d24dc287d19192 --- /dev/null +++ b/app/views/lastConsumptions.pug @@ -0,0 +1,43 @@ +extends layout + +block content + .container + h1.text-center Dernières Consommations + + #consommations-list.list-group + + script. + async function updateList() { + try { + const response = await fetch('/last-consommations'); + const latestConsommations = await response.json(); + + // Mise à jour de la liste des dernières consommations + const consommationsList = document.getElementById('consommations-list'); + consommationsList.innerHTML = ''; // Efface le contenu précédent + + latestConsommations.forEach(cons => { + const listItem = document.createElement('li'); + listItem.className = 'list-group-item'; // Utilise la classe list-group-item de Bootstrap + + const dateItem = document.createElement('p'); + dateItem.textContent = `Date: ${new Date(cons.timestamp).toLocaleString()}`; + listItem.appendChild(dateItem); + + const consommationItem = document.createElement('p'); + consommationItem.textContent = `Consommation: ${cons.consommation} (cm³)`; + listItem.appendChild(consommationItem); + + consommationsList.appendChild(listItem); + }); + + } catch (error) { + console.error('Error fetching latest consommations:', error); + } + } + + // Appelle updateList une fois au chargement de la page + updateList(); + + // Appelle updateList toutes les 10 secondes ici + setInterval(updateList, 10000); diff --git a/app/views/layout.pug b/app/views/layout.pug index c567479f2c673c9234f38a131b9aeade98552347..eb887eefc7a2240d9c55a0c1a47316a876c1138e 100644 --- a/app/views/layout.pug +++ b/app/views/layout.pug @@ -18,6 +18,10 @@ html(lang="en") a.nav-link(href="/information-generale") Information Générale li.nav-item a.nav-link(href="/graphique-consommations") Graphique des Consommations + li.nav-item + a.nav-link(href="/liste-consommations") Liste des Consommations + li.nav-item + a.nav-link(href="/consommations-par-periode") Consommations par Période block content