Input Velden Electron

This commit is contained in:
Atilla
2024-02-16 17:19:52 +01:00
23 changed files with 1957 additions and 269 deletions

View File

@@ -1,10 +1,13 @@
import requests
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
def fetch_and_display_all(urls, access_token):
for url in urls:
# 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}"
@@ -14,17 +17,19 @@ def fetch_and_display_all(urls, access_token):
data = response.json()
print(f"Data from {url}:")
# print(data)
load_data(data)
# 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)
print("Waiting for the next retrieval action...")
time.sleep(300) # Time here is in seconds.
def load_data(data):
# Functie voor het invoegen van gegevens in de database
def insert_data(data):
mydb = database_connect()
if mydb.is_connected():
mycursor = mydb.cursor()
@@ -33,7 +38,9 @@ def load_data(data):
INSERT INTO goodgarden.battery_voltage_events (timestamp, gateway_receive_time, device, value)
VALUES (%s, %s, %s, %s)
"""
for record in data['results']:
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', '')
@@ -41,24 +48,131 @@ def load_data(data):
print(f"Inserting data: timestamp={timestamp}, gateway_receive_time={gateway_receive_time}, device={device}, value={value}")
# Execute the query
# Voer de query uit
mycursor.execute(insert_query, (timestamp, gateway_receive_time, device, value))
# Commit the changes
# Bevestig de wijzigingen
mydb.commit()
# Close cursor and connection
# Sluit cursor en verbinding
mycursor.close()
mydb.close()
# 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):
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__":
urls = [
"https://garden.inajar.nl/api/battery_voltage_events/?format=json",
]
url = "https://garden.inajar.nl/api/battery_voltage_events/?format=json"
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c"
repeat_count = 10
fetch_and_display_all(urls, access_token)
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.")

View File

@@ -1,4 +1,4 @@
import mysql.connector
import mysql.connector #** TYPE IN TERMINAL: "pip install mysql-connector-python"
from mysql.connector import Error
def database_connect():

50
script/db_connect_form.py Normal file
View File

@@ -0,0 +1,50 @@
import sys
import json
import mysql.connector #** TYPE IN TERMINAL: "pip install mysql-connector-python"
from mysql.connector import Error
# Voeg de data uit het formulier toe aan de database
def insert_plant_name(plant_naam, plantensoort, plant_geteelt):
# Als er "true" is meegeven als waarde dan komt in de database 1 anders 0 (false)
plant_geteelt_value = 1 if plant_geteelt.lower() == "true" else 0
try:
connection = mysql.connector.connect(
host='localhost',
database='goodgarden',
user='root',
password=''
)
# Als er verbinding gemaakt kan worden voer dan onderstaande query uit
if connection.is_connected():
# De crusor() zorgt ervoor dat er een verbinding met de database gelegt kan worden en de data gemanipuleerd
cursor = connection.cursor()
query = "INSERT INTO goodgarden.planten (plant_naam, plantensoort, plant_geteelt) VALUES (%s, %s, %s)"
cursor.execute(query, (plant_naam, plantensoort, plant_geteelt_value)) # "%s" wordt hier ingevuld doormiddel van de variable (parameter)
connection.commit()
print(json.dumps({"success": True}))
else:
print(json.dumps({"success": False, "error": "Database connection failed"}))
except Error as e:
print(json.dumps({"success": False, "error": str(e)}))
finally:
if connection and connection.is_connected():
cursor.close()
connection.close()
# Wordt alleen uitgevoerd als het een standalone script is (geen import!!!)
if __name__ == "__main__":
# Dit zijn de variables die door het JavaScript bestand (app.js) worden meegegeven --- NOTE: sys.argv[0] is altijd de naam van het script!
plant_naam = sys.argv[1]
plantensoort = sys.argv[2]
plant_geteelt = sys.argv[3]
# Call de function met de variables
insert_plant_name(plant_naam, plantensoort, plant_geteelt)

View File

@@ -3,8 +3,8 @@ import time
from db_connect import database_connect
def fetch_and_display_all(urls, access_token):
for url in urls:
def fetch_and_display_all(url, access_token, repeat_count=5):
for _ in range(repeat_count):
try:
headers = {
"Authorization": f"Token {access_token}"
@@ -21,7 +21,10 @@ def fetch_and_display_all(urls, access_token):
print(f"Error fetching data from {url}: {e}")
print("Waiting for the next retrieval action...")
time.sleep(300) # Time here is in seconds.
# time.sleep(300) # Time here is in seconds.
time.sleep(1) # Time here is in seconds.
def load_data(data):
mydb = database_connect()
@@ -55,10 +58,14 @@ def load_data(data):
print("Data inserted into the database.")
if __name__ == "__main__":
urls = [
"https://garden.inajar.nl/api/devices/?format=json"
]
url = "https://garden.inajar.nl/api/devices/?format=json"
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c" # Replace this with your actual access token
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c"
# access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c"
# You can change the repeat_count to control how many times you want to repeat the process
repeat_count = 10
fetch_and_display_all(urls, access_token)
fetch_and_display_all(url, access_token, repeat_count)

View File

@@ -2,6 +2,7 @@ import requests
import time
from db_connect import database_connect
# Establish a database connection
connection = database_connect()
@@ -47,26 +48,6 @@ def load_data(data):
# Execute the query
mycursor.execute(insert_query, (timestamp, gateway_receive_time, device, value))
# insert_query = """ Voor deze code werktengid te krijgen moet je in de datebase een ''id, serial_number, name, label, last_seen, last_battery_voltage)' aanmaken en dan werkt het.
# INSERT INTO goodgarden.fetch (id, serial_number, name, label, last_seen, last_battery_voltage) Hier de tabel naam veranderen
# VALUES (%s, %s, %s, %s, %s, %s)
# """
# for record in data['results']: # Adjust this based on the actual structure of the JSON
# id = record.get('id', '')
# serial_number = record.get('serial_number', '')
# name = record.get('name', '')
# label = record.get('label', '')
# last_seen = record.get('last_seen', '')
# last_battery_voltage = record.get('last_battery_voltage', '')
# print(f"Inserting data: id={id}, serial_number={serial_number}, name={name}, label={label}, last_seen={last_seen}, last_battery_voltage={last_battery_voltage}") # Print the data being inserted
# # Execute the query
# mycursor.execute(insert_query, (id, serial_number, name, label, last_seen, last_battery_voltage))
# Commit the changes
mydb.commit()

27
script/main.js Normal file
View File

@@ -0,0 +1,27 @@
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()
{
modal.style.display = "block";
}
// Sluit de modal wanneer op het 'sluiten' icoon wordt geklikt
close.onclick = function()
{
modal.style.display = "none";
}
// Sluit de modal wanneer buiten de modal wordt geklikt
window.onclick = function(event)
{
if (event.target == modal)
{
modal.style.display = "none";
}
}
}

0
script/main.py Normal file
View File

View File

@@ -3,8 +3,8 @@ import time
from db_connect import database_connect
def fetch_and_display_all(urls, access_token):
for url in urls:
def fetch_and_display_all(url, access_token, repeat_count=5):
for _ in range(repeat_count):
try:
headers = {
"Authorization": f"Token {access_token}"
@@ -21,7 +21,9 @@ def fetch_and_display_all(urls, access_token):
print(f"Error fetching data from {url}: {e}")
print("Waiting for the next retrieval action...")
time.sleep(300) # Time here is in seconds.
time.sleep(1) # Time here is in seconds.
def load_data(data):
mydb = database_connect()
@@ -54,10 +56,9 @@ def load_data(data):
print("Data inserted into the database.")
if __name__ == "__main__":
urls = [
"https://garden.inajar.nl/api/par_events/?format=json"
]
url = "https://garden.inajar.nl/api/par_events/?format=json"
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c"
# You can change the repeat_count to control how many times you want to repeat the process
repeat_count = 10
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c"
fetch_and_display_all(urls, access_token)
fetch_and_display_all(url, access_token, repeat_count)

View File

@@ -3,8 +3,8 @@ import time
from db_connect import database_connect
def fetch_and_display_all(urls, access_token):
for url in urls:
def fetch_and_display_all(url, access_token, repeat_count=5):
for _ in range(repeat_count):
try:
headers = {
"Authorization": f"Token {access_token}"
@@ -21,7 +21,8 @@ def fetch_and_display_all(urls, access_token):
print(f"Error fetching data from {url}: {e}")
print("Waiting for the next retrieval action...")
time.sleep(300) # Time here is in seconds.
time.sleep(1) # Time here is in seconds.
def load_data(data):
mydb = database_connect()
@@ -54,10 +55,10 @@ def load_data(data):
print("Data inserted into the database.")
if __name__ == "__main__":
urls = [
"https://garden.inajar.nl/api/relative_humidity_events/?format=json"
]
url = "https://garden.inajar.nl/api/relative_humidity_events/?format=json"
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c"
fetch_and_display_all(urls, access_token)
# You can change the repeat_count to control how many times you want to repeat the process
repeat_count = 10
fetch_and_display_all(url, access_token, repeat_count)

View File

@@ -3,8 +3,8 @@ import time
from db_connect import database_connect
def fetch_and_display_all(urls, access_token):
for url in urls:
def fetch_and_display_all(url, access_token, repeat_count=5):
for _ in range(repeat_count):
try:
headers = {
"Authorization": f"Token {access_token}"
@@ -21,7 +21,8 @@ def fetch_and_display_all(urls, access_token):
print(f"Error fetching data from {url}: {e}")
print("Waiting for the next retrieval action...")
time.sleep(300) # Time here is in seconds.
time.sleep(1) # Time here is in seconds.
def load_data(data):
mydb = database_connect()
@@ -52,12 +53,11 @@ def load_data(data):
mydb.close()
print("Data inserted into the database.")
if __name__ == "__main__":
urls = [
"https://garden.inajar.nl/api/soil_electric_conductivity_events/?format=json"
]
url = "https://garden.inajar.nl/api/soil_electric_conductivity_events/?format=json"
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c" # Replace this with your actual access token
# You can change the repeat_count to control how many times you want to repeat the process
repeat_count = 10
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c"
fetch_and_display_all(urls, access_token)
fetch_and_display_all(url, access_token, repeat_count)

View File

@@ -3,10 +3,8 @@ import time
from db_connect import database_connect
# connection = database_connect()
def fetch_and_display_all(urls, access_token):
for url in urls:
def fetch_and_display_all(url, access_token, repeat_count=5):
for _ in range(repeat_count):
try:
headers = {
"Authorization": f"Token {access_token}"
@@ -23,7 +21,9 @@ def fetch_and_display_all(urls, access_token):
print(f"Error fetching data from {url}: {e}")
print("Waiting for the next retrieval action...")
time.sleep(300) # Time here is in seconds.
time.sleep(1) # Time here is in seconds.
def load_data(data):
mydb = database_connect()
@@ -32,7 +32,7 @@ def load_data(data):
# Here you need to adjust the correct column names and data formats based on the API response
insert_query = """
INSERT INTO goodgarden.soil_relative_permittivity_events (timestamp, gateway_receive_time, device, value)
INSERT INTO goodgarden.soil_temperature_events (timestamp, gateway_receive_time, device, value)
VALUES (%s, %s, %s, %s)
"""
for record in data['results']:
@@ -56,10 +56,11 @@ def load_data(data):
print("Data inserted into the database.")
if __name__ == "__main__":
urls = [
"https://garden.inajar.nl/api/soil_relative_permittivity_events/?format=json"
]
url = "https://garden.inajar.nl/api/soil_relative_permittivity_events/?format=json"
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c"
# You can change the repeat_count to control how many times you want to repeat the process
repeat_count = 10
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c"
fetch_and_display_all(urls, access_token)
# fetch_and_display_all(urls, access_token)
fetch_and_display_all(url, access_token, repeat_count)

View File

@@ -1,12 +1,12 @@
import requests
import time
from db_connect import database_connect
# connection = database_connect()
def fetch_and_display_all(url, access_token, repeat_count=5):
for _ in range(repeat_count):
def fetch_and_display_all(urls, access_token):
for url in urls:
try:
headers = {
"Authorization": f"Token {access_token}"
@@ -23,7 +23,8 @@ def fetch_and_display_all(urls, access_token):
print(f"Error fetching data from {url}: {e}")
print("Waiting for the next retrieval action...")
time.sleep(300) # Time here is in seconds.
time.sleep(1) # Time here is in seconds.
def load_data(data):
mydb = database_connect()
@@ -54,12 +55,11 @@ def load_data(data):
mydb.close()
print("Data inserted into the database.")
if __name__ == "__main__":
urls = [
"https://garden.inajar.nl/api/soil_temperature_events/?format=json"
]
url = "https://garden.inajar.nl/api/soil_temperature_events/?format=json"
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c" # Replace this with your actual access token
# You can change the repeat_count to control how many times you want to repeat the process
repeat_count = 10
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c"
fetch_and_display_all(urls, access_token)
fetch_and_display_all(url, access_token, repeat_count)