This commit is contained in:
6028570
2024-03-13 13:48:36 +01:00
parent 19a256a251
commit bf51b595b7
8 changed files with 979 additions and 3062 deletions

View File

@@ -17,6 +17,10 @@ Zorg dat je in de hoofdmap "GoodGarden" zit. Kijk in je path: "/GoodGarden". Als
npm install body-parser npm install body-parser
npm install python-shell npm install python-shell
npm install --save-dev npm-run-all npm install --save-dev npm-run-all
npm install wait-on --save-dev
npm install concurrently --save-dev
pip install mysql-connector-python pip install mysql-connector-python

5
app.js
View File

@@ -4,6 +4,7 @@ const bodyParser = require('body-parser');
const { PythonShell } = require('python-shell'); const { PythonShell } = require('python-shell');
const path = require('path'); const path = require('path');
const urlElectron = path.join(__dirname, "src/index.html"); const urlElectron = path.join(__dirname, "src/index.html");
// Create an Express app // Create an Express app
@@ -55,7 +56,7 @@ function createWindow() {
args: args, args: args,
}; };
PythonShell.run('../src/py/calculate.py', options, (err, results) => { PythonShell.run('../src/py/script/calculate.py', options, (err, results) => {
if (err) { if (err) {
console.error('Error running python script', err); console.error('Error running python script', err);
event.reply('python-script-response', 'error'); event.reply('python-script-response', 'error');
@@ -85,7 +86,7 @@ app.whenReady().then(() => {
args: [/* arguments for the Python script */] args: [/* arguments for the Python script */]
}; };
PythonShell.run('calculate.py', options, (err, results) => { PythonShell.run('../src/py/script/calculate.py', options, (err, results) => {
if (err) { if (err) {
console.error('Error running python script', err); console.error('Error running python script', err);
mainWindow.webContents.send('python-script-response', 'error'); mainWindow.webContents.send('python-script-response', 'error');

70
app.py
View File

@@ -1,56 +1,42 @@
import requests from flask import Flask, jsonify
import mysql.connector # 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') app = Flask(__name__)
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"
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c" # Replace this with your actual access token
headers = {"Authorization": f"Token {access_token}"}
response = requests.get(api_url, headers=headers)
if response.ok:
return response.json().get('results', [])
else:
print(f"Error fetching data from the API. Status code: {response.status_code}")
return []
# Function to get data from the MySQL database # Function to get data from the MySQL database
def get_database_data(): def get_database_data():
connection = mysql.connector.connect( try:
host='localhost', connection = mysql.connector.connect(
user='root', host='localhost',
password='', user='root',
database='goodgarden' # Specify the correct database name here password='',
) database='goodgarden'
cursor = connection.cursor() )
cursor = connection.cursor()
# Query to retrieve the latest battery voltage data # Query to retrieve the latest battery voltage data
query = "SELECT timestamp, gateway_receive_time, device, value FROM battery_voltage_events ORDER BY timestamp DESC LIMIT 1" query = "SELECT id, timestamp, gateway_receive_time, device, value FROM battery_voltage_events ORDER BY timestamp DESC LIMIT 1"
cursor.execute(query) cursor.execute(query)
battery_data = cursor.fetchone() battery_data = cursor.fetchone()
connection.close() connection.close()
return battery_data return battery_data
except Exception as e:
print("Error fetching data from database:", e)
@app.route('/') return None
def index():
# Get data from the API
api_data = get_api_data()
print("API Data:", api_data) # Add this line for debugging
@app.route('/', methods=['GET'])
def get_data():
# Get data from the database # Get data from the database
battery_data = get_database_data() battery_data = get_database_data()
print("Battery Data:", battery_data) # Add this line for debugging
# Pass data to the HTML template, including the latest ID if battery_data is None:
return render_template('kas_informatie.html', api_data=api_data, battery_data=battery_data) # Pass the latest_id to the template return jsonify({"error": "Failed to fetch data from database"})
print(battery_data)
# Return the data as JSON
if __name__ == "__main__": if __name__ == "__main__":
app.run(host='127.0.0.1', port=5000) app.run(host='127.0.0.1', port=5000)

3456
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -3,21 +3,21 @@
"description": "", "description": "",
"main": "app.js", "main": "app.js",
"scripts": { "scripts": {
"start": "npm-run-all --parallel start-electron start-flask", "start": "npm-run-all --parallel start-flask start-electron",
"start-electron": "electron main.js", "start-electron": "wait-on http://localhost:5000 && electron app.js",
"start-flask": "python app.py" "start-flask": "python app.py"
}, },
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"devDependencies": { "devDependencies": {
"electron": "^23.3.13", "electron": "^23.3.13",
"npm-run-all": "^4.1.5" "npm-run-all": "^4.1.5",
"wait-on": "^7.2.0"
}, },
"dependencies": { "dependencies": {
"axios": "^1.6.7",
"body-parser": "^1.20.2", "body-parser": "^1.20.2",
"elctron": "^0.0.1-security",
"express": "^4.18.3", "express": "^4.18.3",
"flask": "^0.2.10",
"mysql2": "^3.9.1", "mysql2": "^3.9.1",
"python-shell": "^5.0.0" "python-shell": "^5.0.0"
} }

View File

@@ -1,187 +1,7 @@
# import requests #** TYPE IN TERMINAL: "pip install requests"
# import time
# import mysql.connector #** TYPE IN TERMINAL: "pip install mysql-connector-python"
# # Import python db_connect.py script
# from db_connect import database_connect
# # Functie voor het aanmaken van gegevens in de database
# def create_data(url, access_token, repeat_count=5):
# for _ in range(repeat_count):
# try:
# headers = {
# "Authorization": f"Token {access_token}"
# }
# response = requests.get(url, headers=headers)
# response.raise_for_status()
# data = response.json()
# # print(f"Data from {url}:")
# print(data)
# insert_data(data)
# except requests.exceptions.RequestException as e:
# print(f"Error fetching data from {url}: {e}")
# print("Waiting for the next create action...")
# time.sleep(10)
# # time.sleep(300)
# # Functie voor het invoegen van gegevens in de database
# def insert_data(data):
# mydb = database_connect()
# if mydb.is_connected():
# mycursor = mydb.cursor()
# insert_query = """
# INSERT INTO goodgarden.battery_voltage_events (timestamp, gateway_receive_time, device, value)
# VALUES (%s, %s, %s, %s)
# """
# for record in data['results']: # Pas dit aan op basis van de werkelijke structuur van de JSON
# timestamp = record.get('timestamp', '')
# gateway_receive_time = record.get('gateway_receive_time', '')
# device = record.get('device', '')
# value = record.get('value', '')
# print(f"Inserting data: timestamp={timestamp}, gateway_receive_time={gateway_receive_time}, device={device}, value={value}")
# # Voer de query uit
# mycursor.execute(insert_query, (timestamp, gateway_receive_time, device, value))
# # Bevestig de wijzigingen
# mydb.commit()
# # Sluit cursor en verbinding
# mycursor.close()
# mydb.close()
# # Functie voor het lezen van gegevens uit de database
# def read_data(url, access_token, repeat_count=5):
# for _ in range(repeat_count):
# try:
# headers = {
# "Authorization": f"Token {access_token}"
# }
# response = requests.get(url, headers=headers)
# response.raise_for_status()
# data = response.json()
# print(f"Data from {url}:")
# print(data)
# except requests.exceptions.RequestException as e:
# print(f"Error fetching data from {url}: {e}")
# # Wacht een bepaalde tijd in secondes
# print("Waiting for the next read action...")
# time.sleep(300)
# # Functie voor het bijwerken van gegevens in de database
# def update_data(record_id, new_value):
# try:
# mydb = database_connect()
# if mydb.is_connected():
# mycursor = mydb.cursor()
# # Controleer of het record bestaat voordat je het bijwerkt
# mycursor.execute("SELECT * FROM goodgarden.battery_voltage_events WHERE id = %s", (record_id,))
# existing_record = mycursor.fetchone()
# if not existing_record:
# print(f"Record with ID {record_id} not found. Update operation aborted.")
# return
# # Hier moet je de juiste kolomnamen aanpassen op basis van de structuur van je database
# update_query = """
# UPDATE goodgarden.battery_voltage_events
# SET value = %s
# WHERE id = %s
# """
# # Voer de query uit
# print(f"Executing update query: {update_query}")
# print(f"Updating record with ID {record_id} to new value: {new_value}")
# mycursor.execute(update_query, (new_value, record_id)) # Provide the tuple with values here
# # Bevestig de wijzigingen
# mydb.commit()
# print(f"Update executed. Rowcount: {mycursor.rowcount}")
# except mysql.connector.Error as update_err:
# print(f"Error updating data: {update_err}")
# finally:
# # Zorg ervoor dat je altijd de cursor en de databaseverbinding sluit
# if 'mycursor' in locals() and mycursor is not None:
# mycursor.close()
# if 'mydb' in locals() and mydb.is_connected():
# mydb.close()
# # Functie voor het verwijderen van gegevens uit de database
# def delete_data(record_id):
# mydb = database_connect()
# if mydb.is_connected():
# mycursor = mydb.cursor()
# # Hier moet je de juiste kolomnamen aanpassen op basis van de structuur van je database
# delete_query = """
# DELETE FROM goodgarden.battery_voltage_events
# WHERE id = %s
# """
# # Voer de query uit
# mycursor.execute(delete_query, (record_id,))
# # Bevestig de wijzigingen
# mydb.commit()
# # Sluit cursor en verbinding
# mycursor.close()
# mydb.close()
# print(f"Data with ID {record_id} deleted.")
# if __name__ == "__main__":
# url = "https://garden.inajar.nl/api/battery_voltage_events/?format=json"
# access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c"
# repeat_count = 10
# operation_choice = input("Choose operation (C for Create, R for Read, U for Update, D for Delete): ").upper()
# # Maak gegevens aan
# if operation_choice == "C":
# create_data(url, access_token, repeat_count)
# # Lees gegevens
# elif operation_choice == "R":
# read_data(url, access_token, repeat_count)
# # Update gegevens
# elif operation_choice == "U":
# record_id = int(input("Enter record ID to update: "))
# new_value = input("Enter new value: ")
# update_data(record_id, new_value)
# # Verwijder gegevens
# elif operation_choice == "D":
# record_id = int(input("Enter record ID to delete: "))
# delete_data(record_id)
# else:
# print("Invalid operation choice. Please choose C, R, U, or D.")
import mysql.connector import mysql.connector
import requests import requests
from datetime import datetime, timezone, timedelta from datetime import datetime, timezone, timedelta
import time import time
# from py.script.servermqtt import servermqtt
# Function to make a connection to the database # Function to make a connection to the database
def database_connect(): def database_connect():
@@ -192,21 +12,6 @@ def database_connect():
database="goodgarden" database="goodgarden"
) )
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-%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)
# Formateer het datetime-object als een leesbare datumstring
formatted_date = datetime_obj_nl.strftime("%Y-%m-%d %H:%M:%S")
return formatted_date
# Functie voor het aanmaken van gegevens in de database
# ...
# Functie voor het aanmaken van gegevens in de database
# Functie voor het aanmaken van gegevens in de database # Functie voor het aanmaken van gegevens in de database
def create_data(url, access_token, repeat_count=5): def create_data(url, access_token, repeat_count=5):
for _ in range(repeat_count): for _ in range(repeat_count):
@@ -234,10 +39,7 @@ def create_data(url, access_token, repeat_count=5):
device = record.get('device', '') device = record.get('device', '')
value = record.get('value', '') value = record.get('value', '')
# Voeg de timestamp-berekening toe print(f"\nInserted data: Timestamp: {timestamp}, Device: {device}, Battery Voltage: {value}V\n")
calculated_timestamp = calculate_timestamp(gateway_receive_time)
print(f"\nInserted data: Timestamp: {calculated_timestamp}, Device: {device}, Battery Voltage: {value}V\n")
if float(value) < 3.0: if float(value) < 3.0:
print("Waarschuwing: Batterijspanning is lager dan 3.0 volt. Opladen aanbevolen.\n") print("Waarschuwing: Batterijspanning is lager dan 3.0 volt. Opladen aanbevolen.\n")
# Controleer of de batterijspanning hoger is dan 4.2 volt en geef een melding # Controleer of de batterijspanning hoger is dan 4.2 volt en geef een melding
@@ -255,7 +57,6 @@ def create_data(url, access_token, repeat_count=5):
print("Waiting for the next create action...\n") print("Waiting for the next create action...\n")
time.sleep(1) time.sleep(1)
# Functie voor het invoegen van gegevens in de database # Functie voor het invoegen van gegevens in de database
def insert_data(record): def insert_data(record):
mydb = database_connect() mydb = database_connect()
@@ -268,7 +69,7 @@ def insert_data(record):
VALUES (%s, %s, %s, %s) VALUES (%s, %s, %s, %s)
""" """
# Pas dit aan op basis van de werkelijke structuur van de JSON # Pas dit aan op basis van de werkelijke structuur van de JSON
timestamp = calculate_timestamp(record.get('gateway_receive_time', '')) timestamp = record.get('timestamp', '')
gateway_receive_time = record.get('gateway_receive_time', '') gateway_receive_time = record.get('gateway_receive_time', '')
device = record.get('device', '') device = record.get('device', '')
value = record.get('value', '') value = record.get('value', '')
@@ -287,9 +88,6 @@ def insert_data(record):
print("Data inserted into the database.") print("Data inserted into the database.")
# Functie voor het lezen van gegevens uit de database # Functie voor het lezen van gegevens uit de database
def read_data(url, access_token, repeat_count=5): def read_data(url, access_token, repeat_count=5):
for _ in range(repeat_count): for _ in range(repeat_count):
@@ -423,4 +221,3 @@ if __name__ == "__main__":
delete_data(record_id) delete_data(record_id)
else: else:
print("Invalid operation choice. Please choose C, R, U, or D.") print("Invalid operation choice. Please choose C, R, U, or D.")

View File

@@ -1,4 +1,5 @@
const { ipcRenderer } = require("electron"); const { ipcRenderer } = require("electron");
const axios = require('axios');
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
// Send a message to the main process to execute the Python script // Send a message to the main process to execute the Python script
@@ -13,39 +14,42 @@ document.addEventListener('DOMContentLoaded', () => {
} }
}); });
// Additional IPC event to update HTML data // Listen for updates to HTML data from the main process
ipcRenderer.on('update-html-data', (event, data) => { ipcRenderer.on('update-html-data', (event, data) => {
document.getElementById('battery_data_device_placeholder').innerText = data.battery_data_device; // Update the HTML with the received data
document.getElementById('battery_data_voltage_placeholder').innerText = data.battery_data_voltage; document.getElementById('batteryVoltage').innerText = data.batteryVoltage;
document.getElementById('battery_data_time_placeholder').innerText = data.battery_data_time; // Add similar lines for other data fields
}); });
// Trigger an event to request data update
ipcRenderer.send('request-update-data');
// Function to open the modal // Function to open the modal
function openModal() { function openModal() {
const modal = document.getElementById("myModal"); const modal = document.getElementById("myModal");
const button = document.getElementById("modalButton"); const button = document.getElementById("modalButton");
const close = document.getElementsByClassName("close")[0]; const close = document.getElementsByClassName("close")[0];
// Check if elements are found before attaching events // Check if elements are found before attaching events
if (modal && button && close) { if (modal && button && close) {
// Show the modal when the button is clicked // Show the modal when the button is clicked
button.onclick = function () { button.onclick = function () {
modal.style.display = "block"; modal.style.display = "block";
} }
// Close the modal when the 'close' icon is clicked // Close the modal when the 'close' icon is clicked
close.onclick = function () { close.onclick = function () {
modal.style.display = "none";
}
// Close the modal when clicked outside the modal
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none"; modal.style.display = "none";
} }
}
// 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 // Call the function to open the modal
openModal(); openModal();
@@ -62,4 +66,31 @@ document.addEventListener('DOMContentLoaded', () => {
// Call the function to draw the line chart // Call the function to draw the line chart
drawLineChart(); drawLineChart();
// Function to fetch battery data from Flask API
function fetchBatteryData() {
axios.get('http://127.0.0.1:5000')
.then(response => {
const batteryData = response.data;
updateBatteryData(batteryData);
})
.catch(error => {
console.error('Error fetching battery data:', error);
});
}
// Function to update HTML content with battery data
function updateBatteryData(batteryData){
document.getElementById('deviceNumber').innerText = batteryData.device;
document.getElementById('voltage').innerText = batteryData.value;
document.getElementById('time').innerText = batteryData.gateway_receive_time;
document.getElementById('tevredenheid').innerText = batteryData.timestamp;
// Voeg andere eigenschappen toe zoals nodig
}
// Fetch battery data when the page loads
fetchBatteryData();
}); });

View File

@@ -1,112 +1,110 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../static/css/style.css" /> <meta http-equiv="Content-Security-Policy" content="script-src 'self'">
<!-- <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> <title>Informatie Kas</title>
</head> <link rel="stylesheet" href="../static/css/style.css">
<body> </head>
<body>
<section class="mainContainer"> <section class="mainContainer">
<article>
<img src="../static/images/logo.png" class="goodgarden-logo">
</article>
<section class="mainBorder informatie-kas-main-container">
<article> <article>
<h1 class="pagina-titel">Informatie Kas</h1> <img src="../static/images/logo.png" class="goodgarden-logo">
<section id="sectie-1">
<article class="parent-algemeen-overzicht">
<article class="algemeen-overzicht">
<table class="table-informatie-kas">
<tr class="tr-informatie-kas">
<td>Device </td>
<td id="batteryVoltage">{{battery_data[2]}}</td>
</tr>
<tr class="tr-informatie-kas">
<td>Batterij Voltage</td>
<td id="batteryVoltage">{{battery_data[3]}}</td>
</tr>
<tr class="tr-informatie-kas">
<td>Tijden</td>
<td id="batteryVoltage">{{battery_data[1]}}</td>
</tr>
<tr class="tr-informatie-kas">
<td>Tevredenheid</td>
<td id="batteryVoltage">{{battery_data[0]}}</td>
</tr>
</table>
</article>
</article>
<article class="grafiek">
<article class="grafiek-innerbox">
<h2>Zonlicht</h2>
<canvas
id="myCanvas" class="canvas-informatie-kas" width="275" height="275"></canvas>
</article>
</article>
</section>
<!-- <section id="sectie-2"></section> -->
</article> </article>
<article class="grid-column-2"> <section class="mainBorder informatie-kas-main-container">
<article class="grid-2-child"> <article>
<section class="parent-table"> <h1 class="pagina-titel">Informatie Kas</h1>
<table class="kas-table-1"> <section id="sectie-1">
<tr> <article class="parent-algemeen-overzicht">
<td>Aantal geplant:</td> <article class="algemeen-overzicht">
<td>2</td> <table class="table-informatie-kas">
</tr> <tr class="tr-informatie-kas">
<tr> <td>Device</td>
<td>Succesvolle Oogst:</td> <td id="deviceNumber"></td> <!-- Update this ID -->
<td>2</td> </tr>
</tr> <tr class="tr-informatie-kas">
<tr> <td>Batterij Voltage</td>
<td>Gefaalde Oogst:</td> <td id="voltage"></td> <!-- Update this ID -->
<td>2</td> </tr>
</tr> <tr class="tr-informatie-kas">
</table> <td>Tijden</td>
<table class="kas-table-2"> <td id="time"></td> <!-- Update this ID -->
<tr> </tr>
<td>Warmste Maand:</td> <tr class="tr-informatie-kas">
<td>n.v.t.</td> <td>Zulu</td>
</tr> <td id="tevredenheid"></td> <!-- Update this ID -->
<tr> </tr>
<td>koudste Maand:</td> </table>
<td>December</td> </article>
</tr> </article>
<tr> <article class="grafiek">
<td>Gemiddelde Bodemtemp.:</td> <article class="grafiek-innerbox">
<td id="bodem-temperatuur">2˚C</td> <h2>Zonlicht</h2>
</tr> <canvas id="myCanvas" class="canvas-informatie-kas" width="275" height="275"></canvas>
<tr> </article>
<td>Gemiddelde Uren Zonlicht:</td> </article>
<td>2u</td> </section>
</tr> </article>
</table> <article class="grid-column-2">
<table class="kas-table-3"> <article class="grid-2-child">
<tr> <section class="parent-table">
<td>Laatste Irrigatie:</td> <table class="kas-table-1">
<td>2u</td> <tr>
</tr> <td>Aantal geplant:</td>
<tr> <td>2</td>
<td>Aankomende Irrigatie:</td> </tr>
<td>2u</td> <tr>
</tr> <td>Succesvolle Oogst:</td>
<tr> <td>2</td>
<td>Laatste Bemesting</td> </tr>
<td>2d</td> <tr>
</tr> <td>Gefaalde Oogst:</td>
<tr> <td>2</td>
<td>Aankomende Bemesting:</td> </tr>
<td>2w</td> </table>
</tr> <table class="kas-table-2">
</table> <tr>
</section> <td>Warmste Maand:</td>
</article> <td>n.v.t.</td>
</article> </tr>
</section> <tr>
<td>Koudste Maand:</td>
<td>December</td>
</tr>
<tr>
<td>Gemiddelde Bodemtemp.:</td>
<td id="bodem-temperatuur">2˚C</td>
</tr>
<tr>
<td>Gemiddelde Uren Zonlicht:</td>
<td>2u</td>
</tr>
</table>
<table class="kas-table-3">
<tr>
<td>Laatste Irrigatie:</td>
<td>2u</td>
</tr>
<tr>
<td>Aankomende Irrigatie:</td>
<td>2u</td>
</tr>
<tr>
<td>Laatste Bemesting</td>
<td>2d</td>
</tr>
<tr>
<td>Aankomende Bemesting:</td>
<td>2w</td>
</tr>
</table>
</section>
</article>
</article>
</section>
</section> </section>
</body>
<script src="../static/js/main.js" defer></script>
</body>
</html> </html>