gestuurdd

This commit is contained in:
mohammedcifci78
2024-03-12 11:03:45 +01:00
parent b711d72b3a
commit 19a256a251
11 changed files with 2263 additions and 397 deletions

View File

@@ -16,9 +16,13 @@ Zorg dat je in de hoofdmap "GoodGarden" zit. Kijk in je path: "/GoodGarden". Als
npm install express
npm install body-parser
npm install python-shell
npm install --save-dev npm-run-all
pip install mysql-connector-python
pip install requests
pip install flask-cors
## Gebruik

112
app.js
View File

@@ -1,93 +1,113 @@
const { app, BrowserWindow,ipcMain } = require('electron'); /* TYPE IN TERMINAL: "npm install electron" */
const express = require('express'); /* TYPE IN TERMINAL: "npm install express" */
const bodyParser = require('body-parser'); /* TYPE IN TERMINAL: "npm install body-parser" */
const { PythonShell } = require('python-shell'); /* TYPE IN TERMINAL: "npm install python-shell" */
const { app, BrowserWindow, ipcMain } = require('electron');
const express = require('express');
const bodyParser = require('body-parser');
const { PythonShell } = require('python-shell');
const path = require('path');
const urlElectron = path.join(__dirname, "src/index.html");
// Maak een Express-app
// Create an Express app
const server = express();
server.use(bodyParser.urlencoded({ extended: true }));
// Definieer een route voor form POST verzoeken
// Define a route for form POST requests
server.post('/submit-form', (req, res) => {
const { plant_naam, plantensoort } = req.body; // Verkrijg de plant_naam uit het formulier
const plant_geteelt = req.body.plant_geteelt == 'true' ? 'true' : 'false'; // Zorgt dat de string "true" herkent wordt
const { plant_naam, plantensoort } = req.body;
const plant_geteelt = req.body.plant_geteelt == 'true' ? 'true' : 'false';
let options = {
mode: 'text',
args: [plant_naam, plantensoort, plant_geteelt], // Zet hier een variable bij om de data toe te voegen aan de databas
args: [plant_naam, plantensoort, plant_geteelt],
};
/*Om python te gebruiken*/
// ipcMain.on('request-update-temp', (event, args) => {
// let options = {
// mode: 'text',
// scriptPath: 'path/to/your/python/script',
// args: args
// };
// PythonShell.run('calculate.py', options, (err, results) => {
// if (err) {
// console.error('Error running python script', err);
// event.reply('update-temp-result', 'error');
// } else {
// console.log('Python script results:', results);
// event.reply('update-temp-result', results[0]); // Verstuur het resultaat terug naar de renderer proces
// }
// });
// });
// En dan in je renderer proces, stuur je een bericht om de update te verzoeken
ipcRenderer.send('request-update-temp', [/* hier kunnen argumenten komen die je Python script nodig heeft */]);
// The following line was causing issues and has been commented out
// ipcRenderer.send('request-update-temp', [/* arguments for Python script */]);
});
// Start de server voor verbinding met de database
// Start the server for connecting to the database
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server luistert op port ${PORT}`);
console.log(`Server is listening on port ${PORT}`);
});
// Maak de Electron applicatie aan met bijbehorende waardes
let mainWindow; // Variable to store the reference to the main window
// Create the Electron application with associated values
function createWindow() {
const mainWindow = new BrowserWindow({
mainWindow = new BrowserWindow({
width: 1280,
height: 800,
frame: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
contextIsolation: false,
enableRemoteModule: true,
webSecurity: true,
}
});
mainWindow.loadFile(path.join(__dirname, 'src', 'py', 'templates', 'index.html'));
/*Is om het Python script te kunnen gebruiken*/
// Enable Python script execution
ipcMain.on('run-python-script', (event, args) => {
let options = {
mode: 'text',
args: args
args: args,
};
PythonShell.run('../src/py/calculate.py', options, (err, results) => {
if (err)
{
if (err) {
console.error('Error running python script', err);
event.reply('python-script-response', 'error');
}
else
{
} else {
console.log('Python script results:', results);
event.reply('python-script-response', results);
// Send the Python data to the renderer process
mainWindow.webContents.send('python-script-response', JSON.parse(results[0]));
}
});
});
// IPC event for updating HTML with data received from Python
ipcMain.on('update-html-data', (event, data) => {
mainWindow.webContents.send('update-html-data', data);
});
}
app.whenReady().then(createWindow);
// Start the Electron app
app.whenReady().then(() => {
createWindow();
// Functionaliteit voor het openen en sluiten van de app
// Execute Python script when the app is ready
const options = {
mode: 'text',
scriptPath: path.join(__dirname, 'src', 'py'),
args: [/* arguments for the Python script */]
};
PythonShell.run('calculate.py', options, (err, results) => {
if (err) {
console.error('Error running python script', err);
mainWindow.webContents.send('python-script-response', 'error');
} else {
console.log('Python script results:', results);
// Send the Python data to the renderer process
mainWindow.webContents.send('python-script-response', JSON.parse(results[0]));
}
});
});
// IPC event for requesting data update
ipcMain.on('request-update-data', (event, args) => {
// Implement logic to get data from the database if needed
const databaseData = { timestamp: "2022-01-01", gateway_receive_time: "2022-01-01", device: "Device1", value: 50 };
// Send updated data to the renderer process
event.reply('update-data-result', { databaseData });
});
// Functionalities for opening and closing the app
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();

14
app.py
View File

@@ -1,9 +1,10 @@
from flask import Flask, render_template, jsonify
import requests
import mysql.connector # Import MySQL connector
from flask import Flask, render_template, jsonify
from flask_cors import CORS
app = Flask(__name__, template_folder='src/py/templates', static_folder='src/py/static')
CORS(app)
# Function to get data from the API
def get_api_data():
api_url = "https://garden.inajar.nl/api/battery_voltage_events/?format=json"
@@ -37,6 +38,7 @@ def get_database_data():
return battery_data
@app.route('/')
def index():
# Get data from the API
@@ -47,10 +49,8 @@ def index():
battery_data = get_database_data()
print("Battery Data:", battery_data) # Add this line for debugging
# Pass data to the HTML template
return render_template('kas_informatie.html', api_data=api_data, battery_data=battery_data)
# Pass data to the HTML template, including the latest ID
return render_template('kas_informatie.html', api_data=api_data, battery_data=battery_data) # Pass the latest_id to the template
if __name__ == "__main__":
app.run(debug=True)
app.run(host='127.0.0.1', port=5000)

2288
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -3,18 +3,21 @@
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "electron app.js"
"start": "npm-run-all --parallel start-electron start-flask",
"start-electron": "electron main.js",
"start-flask": "python app.py"
},
"author": "",
"license": "ISC",
"devDependencies": {
"electron": "^23.3.13"
"electron": "^23.3.13",
"npm-run-all": "^4.1.5"
},
"dependencies": {
"body-parser": "^1.20.2",
"elctron": "^0.0.1-security",
"express": "^4.18.3",
"flask": "^0.2.10",
"mysql2": "^3.9.1",
"python-shell": "^5.0.0"
}

View File

@@ -181,7 +181,7 @@ import mysql.connector
import requests
from datetime import datetime, timezone, timedelta
import time
from py.script.servermqtt import servermqtt
# from py.script.servermqtt import servermqtt
# Function to make a connection to the database
def database_connect():
@@ -194,7 +194,7 @@ def database_connect():
def calculate_timestamp(gateway_receive_time):
# Converteer de stringrepresentatie naar een datetime-object in UTC
datetime_obj_utc = datetime.strptime(gateway_receive_time, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
datetime_obj_utc = datetime.strptime(gateway_receive_time, "%Y-%m-%d%H:%M:%S:").replace(tzinfo=timezone.utc)
# Voeg het tijdsverschil van 1 uur toe voor de Nederlandse tijdzone (UTC+1)
datetime_obj_nl = datetime_obj_utc + timedelta(hours=1)
@@ -289,6 +289,7 @@ def insert_data(record):
# Functie voor het lezen van gegevens uit de database
def read_data(url, access_token, repeat_count=5):
for _ in range(repeat_count):

View File

@@ -1,142 +1,65 @@
const { ipcRenderer } = require("electron");
document.addEventListener('DOMContentLoaded', () =>
{
// Stuur een bericht naar de main process om het Python script uit te voeren
// In je renderer.js (geladen met defer in je HTML)
ipcRenderer.send('request-update-temp', ['some', 'arguments']);
document.addEventListener('DOMContentLoaded', () => {
// Send a message to the main process to execute the Python script
ipcRenderer.send('run-python-script', ['some', 'arguments']);
ipcRenderer.on('update-temp-result', (event, newTemperature) => {
if (newTemperature === 'error') {
console.error('Er is een fout opgetreden bij het ophalen van de nieuwe temperatuur');
ipcRenderer.on('python-script-response', (event, pythonData) => {
if (pythonData === 'error') {
console.error('An error occurred while retrieving data from Python');
} else {
document.getElementById('bodem-temperatuur').textContent = newTemperature;
// Update HTML elements with data received from Python
document.getElementById('bodem-temperatuur').textContent = pythonData.bodemTemperatuur; // Adjust the property based on your actual Python response
}
});
// Additional IPC event to update HTML data
ipcRenderer.on('update-html-data', (event, data) => {
document.getElementById('battery_data_device_placeholder').innerText = data.battery_data_device;
document.getElementById('battery_data_voltage_placeholder').innerText = data.battery_data_voltage;
document.getElementById('battery_data_time_placeholder').innerText = data.battery_data_time;
});
// function dataTablePython()
// {
// document.getElementById("")
// }
function openModal()
{
// Function to open the modal
function openModal() {
const modal = document.getElementById("myModal");
const button = document.getElementById("modalButton");
const close = document.getElementsByClassName("close")[0];
// Toon de modal wanneer op de knop wordt geklikt
button.onclick = function()
{
// Check if elements are found before attaching events
if (modal && button && close) {
// Show the modal when the button is clicked
button.onclick = function () {
modal.style.display = "block";
}
// Sluit de modal wanneer op het 'sluiten' icoon wordt geklikt
close.onclick = function()
{
// Close the modal when the 'close' icon is clicked
close.onclick = function () {
modal.style.display = "none";
}
// Sluit de modal wanneer buiten de modal wordt geklikt
window.onclick = function(event)
{
if (event.target == modal)
{
// Close the modal when clicked outside the modal
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
}
}
// Call the function to open the modal
openModal();
/**
* --- Functie om de grafiek te tekenen. Enigste belangrijke is de eerste 2 "const" arrays "data" & "xLabels".
* --- Function to draw the chart. The important arrays are "data" & "xLabels".
*/
function drawLineChart()
{
/*Dit is de data die getoond wordt als "punt" op de grafiek. 20 = y20 / x20, 50 = y50 / x50 enzovoort... De array "data" & "xLabels" moeten beide evenveel array items hebben!!*/
const data = [20, 50, 60, 45, 50, 100, 70, 60, 65, 0, 85, 0];
const xLabels = ["", "", "", "", "", 6, "", "", "", "", "", 12];
// Define Y-axis labels here. The number of labels should match your scale.
const yLabels = ["", 20, "", 40, "", 60, "", 80, "", 100]; /*NIET VERANDEREN!!!*/
function drawLineChart() {
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
const padding = 35; // Increased padding for Y labels
const graphWidth = canvas.width - padding * 2;
const graphHeight = canvas.height - padding * 2;
// Draw the axes
ctx.beginPath();
ctx.moveTo(padding, padding);
ctx.lineTo(padding, canvas.height - padding);
ctx.lineTo(canvas.width - padding, canvas.height - padding);
ctx.stroke();
// Set the color of the line
ctx.strokeStyle = "#008000"; // This sets the line color to green
const xIncrement = graphWidth / (xLabels.length - 1);
const yIncrement = graphHeight / (yLabels.length - 1); // Assuming you have labels for each increment
// Plot the data
ctx.beginPath();
ctx.moveTo(padding, canvas.height - padding - (data[0] / 100) * graphHeight);
for (let i = 1; i < data.length; i++)
{
const xPos = padding + i * xIncrement;
const yPos = canvas.height - padding - (data[i] / 100) * graphHeight;
ctx.lineTo(xPos, yPos);
}
ctx.stroke(); // Apply the stroke to the line
// Draw Y labels
ctx.fillStyle = "black";
ctx.textAlign = "right"; // Align text to the right
ctx.textBaseline = "middle"; // Center vertically
for (let i = 0; i < yLabels.length; i++)
{
if (yLabels[i] !== "")
{
const yPos = canvas.height - padding - i * yIncrement;
ctx.fillText(yLabels[i], padding - 10, yPos);
}
// ... (rest of the function remains unchanged)
}
// Draw X labels
ctx.textAlign = "center"; // Center horizontally for X labels
for (let i = 0; i < xLabels.length; i++)
{
if (xLabels[i] !== "")
{
const xPos = padding + i * xIncrement;
ctx.fillText(xLabels[i], xPos, canvas.height - padding + 20);
}
}
}
document.addEventListener('DOMContentLoaded', function() {
var battery_data = {
device: "{{ battery_data[2] }}",
batteryVoltage: "{{ battery_data[3] }}",
time: "{{ battery_data[1] }}"
};
// Update HTML elements using dynamically generated IDs
document.getElementById('battery_data_device').innerText = battery_data.device;
document.getElementById('battery_data_voltage').innerText = battery_data.batteryVoltage;
document.getElementById('battery_data_time').innerText = battery_data.time;
// Add other updates as needed
});
// Call the function to draw the line chart
drawLineChart();
});

View File

@@ -3,6 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Document</title>
<link rel="stylesheet" href="../static/css/style.css">
<script src="../static/js/main.js" defer></script>

View File

@@ -5,9 +5,9 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="../static/css/style.css" />
<!-- <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> -->
<link rel="stylesheet" href="../static/css/style.css">
<script src="../static/js/main.js" defer></script>
<title>Informatie Kas</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='src/py/script/static/css/style.css') }}">
</head>
<body>
<section class="mainContainer">
@@ -23,19 +23,19 @@
<table class="table-informatie-kas">
<tr class="tr-informatie-kas">
<td>Device </td>
<td id="battery_data_device"></td>
<td id="batteryVoltage">{{battery_data[2]}}</td>
</tr>
<tr class="tr-informatie-kas">
<td>Batterij Voltage</td>
<td id="battery_data_voltage"></td>
<td id="batteryVoltage">{{battery_data[3]}}</td>
</tr>
<tr class="tr-informatie-kas">
<td>Tijden</td>
<td id="battery_data_time"></td>
<td id="batteryVoltage">{{battery_data[1]}}</td>
</tr>
<tr class="tr-informatie-kas">
<td>Tevredenheid</td>
<td>-</td>
<td id="batteryVoltage">{{battery_data[0]}}</td>
</tr>
</table>
</article>