HETWERKT
This commit is contained in:
@@ -17,6 +17,10 @@ Zorg dat je in de hoofdmap "GoodGarden" zit. Kijk in je path: "/GoodGarden". Als
|
||||
npm install body-parser
|
||||
npm install python-shell
|
||||
npm install --save-dev npm-run-all
|
||||
npm install wait-on --save-dev
|
||||
npm install concurrently --save-dev
|
||||
|
||||
|
||||
|
||||
|
||||
pip install mysql-connector-python
|
||||
|
||||
5
app.js
5
app.js
@@ -4,6 +4,7 @@ const bodyParser = require('body-parser');
|
||||
const { PythonShell } = require('python-shell');
|
||||
const path = require('path');
|
||||
|
||||
|
||||
const urlElectron = path.join(__dirname, "src/index.html");
|
||||
|
||||
// Create an Express app
|
||||
@@ -55,7 +56,7 @@ function createWindow() {
|
||||
args: args,
|
||||
};
|
||||
|
||||
PythonShell.run('../src/py/calculate.py', options, (err, results) => {
|
||||
PythonShell.run('../src/py/script/calculate.py', options, (err, results) => {
|
||||
if (err) {
|
||||
console.error('Error running python script', err);
|
||||
event.reply('python-script-response', 'error');
|
||||
@@ -85,7 +86,7 @@ app.whenReady().then(() => {
|
||||
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) {
|
||||
console.error('Error running python script', err);
|
||||
mainWindow.webContents.send('python-script-response', 'error');
|
||||
|
||||
48
app.py
48
app.py
@@ -1,56 +1,42 @@
|
||||
import requests
|
||||
import mysql.connector # Import MySQL connector
|
||||
from flask import Flask, render_template, jsonify
|
||||
from flask_cors import CORS
|
||||
from flask import Flask, jsonify
|
||||
import mysql.connector
|
||||
|
||||
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"
|
||||
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 []
|
||||
app = Flask(__name__)
|
||||
|
||||
# Function to get data from the MySQL database
|
||||
def get_database_data():
|
||||
try:
|
||||
connection = mysql.connector.connect(
|
||||
host='localhost',
|
||||
user='root',
|
||||
password='',
|
||||
database='goodgarden' # Specify the correct database name here
|
||||
database='goodgarden'
|
||||
)
|
||||
cursor = connection.cursor()
|
||||
|
||||
# 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)
|
||||
battery_data = cursor.fetchone()
|
||||
|
||||
connection.close()
|
||||
|
||||
return battery_data
|
||||
except Exception as e:
|
||||
print("Error fetching data from database:", e)
|
||||
return None
|
||||
|
||||
|
||||
@app.route('/')
|
||||
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
|
||||
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
|
||||
return render_template('kas_informatie.html', api_data=api_data, battery_data=battery_data) # Pass the latest_id to the template
|
||||
if battery_data is None:
|
||||
return jsonify({"error": "Failed to fetch data from database"})
|
||||
|
||||
print(battery_data)
|
||||
|
||||
# Return the data as JSON
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host='127.0.0.1', port=5000)
|
||||
3436
package-lock.json
generated
3436
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
10
package.json
10
package.json
@@ -3,21 +3,21 @@
|
||||
"description": "",
|
||||
"main": "app.js",
|
||||
"scripts": {
|
||||
"start": "npm-run-all --parallel start-electron start-flask",
|
||||
"start-electron": "electron main.js",
|
||||
"start": "npm-run-all --parallel start-flask start-electron",
|
||||
"start-electron": "wait-on http://localhost:5000 && electron app.js",
|
||||
"start-flask": "python app.py"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"electron": "^23.3.13",
|
||||
"npm-run-all": "^4.1.5"
|
||||
"npm-run-all": "^4.1.5",
|
||||
"wait-on": "^7.2.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.6.7",
|
||||
"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"
|
||||
}
|
||||
|
||||
@@ -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 requests
|
||||
from datetime import datetime, timezone, timedelta
|
||||
import time
|
||||
# from py.script.servermqtt import servermqtt
|
||||
|
||||
# Function to make a connection to the database
|
||||
def database_connect():
|
||||
@@ -192,21 +12,6 @@ def database_connect():
|
||||
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
|
||||
def create_data(url, access_token, repeat_count=5):
|
||||
for _ in range(repeat_count):
|
||||
@@ -234,10 +39,7 @@ def create_data(url, access_token, repeat_count=5):
|
||||
device = record.get('device', '')
|
||||
value = record.get('value', '')
|
||||
|
||||
# Voeg de timestamp-berekening toe
|
||||
calculated_timestamp = calculate_timestamp(gateway_receive_time)
|
||||
|
||||
print(f"\nInserted data: Timestamp: {calculated_timestamp}, Device: {device}, Battery Voltage: {value}V\n")
|
||||
print(f"\nInserted data: Timestamp: {timestamp}, Device: {device}, Battery Voltage: {value}V\n")
|
||||
if float(value) < 3.0:
|
||||
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
|
||||
@@ -255,7 +57,6 @@ def create_data(url, access_token, repeat_count=5):
|
||||
print("Waiting for the next create action...\n")
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
# Functie voor het invoegen van gegevens in de database
|
||||
def insert_data(record):
|
||||
mydb = database_connect()
|
||||
@@ -268,7 +69,7 @@ def insert_data(record):
|
||||
VALUES (%s, %s, %s, %s)
|
||||
"""
|
||||
# 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', '')
|
||||
device = record.get('device', '')
|
||||
value = record.get('value', '')
|
||||
@@ -287,9 +88,6 @@ def insert_data(record):
|
||||
|
||||
print("Data inserted into the database.")
|
||||
|
||||
|
||||
|
||||
|
||||
# Functie voor het lezen van gegevens uit de database
|
||||
def read_data(url, access_token, repeat_count=5):
|
||||
for _ in range(repeat_count):
|
||||
@@ -423,4 +221,3 @@ if __name__ == "__main__":
|
||||
delete_data(record_id)
|
||||
else:
|
||||
print("Invalid operation choice. Please choose C, R, U, or D.")
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const { ipcRenderer } = require("electron");
|
||||
const axios = require('axios');
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Send a message to the main process to execute the Python script
|
||||
@@ -13,13 +14,16 @@ 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) => {
|
||||
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;
|
||||
// Update the HTML with the received data
|
||||
document.getElementById('batteryVoltage').innerText = data.batteryVoltage;
|
||||
// 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 openModal() {
|
||||
const modal = document.getElementById("myModal");
|
||||
@@ -62,4 +66,31 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
|
||||
// Call the function to draw the line chart
|
||||
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();
|
||||
});
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<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>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="Content-Security-Policy" content="script-src 'self'">
|
||||
<title>Informatie Kas</title>
|
||||
<link rel="stylesheet" href="../static/css/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<section class="mainContainer">
|
||||
@@ -23,19 +21,19 @@
|
||||
<table class="table-informatie-kas">
|
||||
<tr class="tr-informatie-kas">
|
||||
<td>Device</td>
|
||||
<td id="batteryVoltage">{{battery_data[2]}}</td>
|
||||
<td id="deviceNumber"></td> <!-- Update this ID -->
|
||||
</tr>
|
||||
<tr class="tr-informatie-kas">
|
||||
<td>Batterij Voltage</td>
|
||||
<td id="batteryVoltage">{{battery_data[3]}}</td>
|
||||
<td id="voltage"></td> <!-- Update this ID -->
|
||||
</tr>
|
||||
<tr class="tr-informatie-kas">
|
||||
<td>Tijden</td>
|
||||
<td id="batteryVoltage">{{battery_data[1]}}</td>
|
||||
<td id="time"></td> <!-- Update this ID -->
|
||||
</tr>
|
||||
<tr class="tr-informatie-kas">
|
||||
<td>Tevredenheid</td>
|
||||
<td id="batteryVoltage">{{battery_data[0]}}</td>
|
||||
<td>Zulu</td>
|
||||
<td id="tevredenheid"></td> <!-- Update this ID -->
|
||||
</tr>
|
||||
</table>
|
||||
</article>
|
||||
@@ -43,12 +41,10 @@
|
||||
<article class="grafiek">
|
||||
<article class="grafiek-innerbox">
|
||||
<h2>Zonlicht</h2>
|
||||
<canvas
|
||||
id="myCanvas" class="canvas-informatie-kas" width="275" height="275"></canvas>
|
||||
<canvas id="myCanvas" class="canvas-informatie-kas" width="275" height="275"></canvas>
|
||||
</article>
|
||||
</article>
|
||||
</section>
|
||||
<!-- <section id="sectie-2"></section> -->
|
||||
</article>
|
||||
<article class="grid-column-2">
|
||||
<article class="grid-2-child">
|
||||
@@ -73,7 +69,7 @@
|
||||
<td>n.v.t.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>koudste Maand:</td>
|
||||
<td>Koudste Maand:</td>
|
||||
<td>December</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -108,5 +104,7 @@
|
||||
</article>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<script src="../static/js/main.js" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user