a
This commit is contained in:
123
src/py/script/DUMMY.json
Normal file
123
src/py/script/DUMMY.json
Normal file
@@ -0,0 +1,123 @@
|
||||
|
||||
// Deze spanningswaarden zijn relatief hoog, wat suggereert dat de batterijen van de sensoren goed opgeladen zijn. De meeste sensorapparaten gebruiken batterijen die een nominale spanning van ongeveer 3,7 volt hebben (typisch voor lithium-ion batterijen) en kunnen worden beschouwd als "volledig opgeladen" wanneer ze een spanning dicht bij of iets boven 4,1 volt bereiken
|
||||
"battery_voltage_events": [
|
||||
{
|
||||
"timestamp": 1707825721,
|
||||
"gateway_receive_time": "2024-02-13T12:02:01Z",
|
||||
"device": 256,
|
||||
"value": 4.098901271820068
|
||||
// Volledig opgeladen: Rond 4.2 volt.
|
||||
// Nominale spanning: Ongeveer 3.7 volt.
|
||||
// Kritiek laag: Minder dan 3.0 volt.
|
||||
},
|
||||
{
|
||||
"timestamp": 1707837460,
|
||||
"gateway_receive_time": "2024-02-13T15:17:40Z",
|
||||
"device": 322,
|
||||
"value": 4.105006217956543
|
||||
}
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
"devices": [
|
||||
{
|
||||
"id": 256,
|
||||
"serial_number": "0033889B1BAB1169",
|
||||
"name": "firefly2_0051",
|
||||
"label": "The Field",
|
||||
"last_seen": 1707765066,
|
||||
"last_battery_voltage": 4.09768009185791
|
||||
},
|
||||
{
|
||||
"id": 322,
|
||||
"serial_number": "006FE1FC316ED7D8",
|
||||
"name": "firefly2_0111",
|
||||
"label": "The Field",
|
||||
"last_seen": 1707764966,
|
||||
"last_battery_voltage": 4.107448101043701
|
||||
}
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// Fotosyntese??? (zonlicht)
|
||||
"par_events": [
|
||||
{
|
||||
"timestamp": 1707844638,
|
||||
"gateway_receive_time": "2024-02-13T17:17:18Z",
|
||||
"device": 322,
|
||||
"value": 0.0
|
||||
},
|
||||
{
|
||||
"timestamp": 1707851099,
|
||||
"gateway_receive_time": "2024-02-13T19:04:59Z",
|
||||
"device": 256,
|
||||
"value": 0.0
|
||||
}
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
// Luchtvochtigheid
|
||||
"relative_humidity_events": [
|
||||
{
|
||||
"timestamp": 1707844638,
|
||||
"gateway_receive_time": "2024-02-13T17:17:18Z",
|
||||
"device": 322,
|
||||
"value": 71.08984375
|
||||
},
|
||||
{
|
||||
"timestamp": 1707851099,
|
||||
"gateway_receive_time": "2024-02-13T19:04:59Z",
|
||||
"device": 256,
|
||||
"value": 66.7294921875
|
||||
}
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// De "soil_electric_conductivity_events" gegevens wijzen op metingen van de elektrische geleidbaarheid (EC) van de bodem, een indicator van de hoeveelheid oplosbare zouten of voedingsstoffen in de bodem. EC wordt gemeten in Siemens per meter (S/m) of, voor bodemmetingen, vaak in milliSiemens per centimeter (mS/cm). Een hogere EC-waarde duidt op een hogere concentratie van opgeloste zouten, wat belangrijk is voor het bepalen van de voedingsstatus van de bodem en het beheren van de bemesting voor optimale plantengroei.
|
||||
"soil_electric_conductivity_events": [
|
||||
{
|
||||
"timestamp": 1707851215,
|
||||
"gateway_receive_time": "2024-02-13T19:06:55Z",
|
||||
"device": 322,
|
||||
"value": 0.0
|
||||
}
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// In de context van bodemmetingen, geeft deze waarde inzicht in het vochtgehalte van de bodem, omdat water een relatief hoge diëlektrische constante heeft in vergelijking met droge bodem of lucht.
|
||||
"soil_relative_permittivity_events": [
|
||||
{
|
||||
"timestamp": 1707851215,
|
||||
"gateway_receive_time": "2024-02-13T19:06:55Z",
|
||||
"device": 322,
|
||||
"value": 1.52
|
||||
// Een waarde van 1.52 is relatief laag en suggereert dat de bodem droog kan zijn op het moment van meting. Ter referentie, de diëlektrische constante van lucht is ongeveer 1, terwijl water een diëlektrische constante heeft van ongeveer 80 bij kamertemperatuur.
|
||||
}
|
||||
],
|
||||
|
||||
|
||||
|
||||
//De "soil_temperature_events" gegevens bevatten informatie over de temperatuur van de bodem op een specifiek tijdstip. De waarde geeft de temperatuur van de bodem aan in graden Celsius (°C).
|
||||
"soil_temperature_events": [
|
||||
{
|
||||
"timestamp": 1707851215,
|
||||
"gateway_receive_time": "2024-02-13T19:06:55Z",
|
||||
"device": 322,
|
||||
"value": 12.06
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
0
src/py/script/__init__.py
Normal file
0
src/py/script/__init__.py
Normal file
BIN
src/py/script/__pycache__/db_connect.cpython-311.pyc
Normal file
BIN
src/py/script/__pycache__/db_connect.cpython-311.pyc
Normal file
Binary file not shown.
33
src/py/script/app.py
Normal file
33
src/py/script/app.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from flask import Flask, render_template, jsonify
|
||||
import requests
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# Functie om gegevens van de API op te halen
|
||||
def get_api_data():
|
||||
api_url = "https://garden.inajar.nl/api/battery_voltage_events/?format=json"
|
||||
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c" # Vervang dit met je echte toegangstoken
|
||||
|
||||
headers = {"Authorization": f"Token {access_token}"}
|
||||
response = requests.get(api_url, headers=headers)
|
||||
|
||||
if response.ok:
|
||||
return response.json().get('results', [])
|
||||
else:
|
||||
print(f"Fout bij het ophalen van gegevens van de API. Statuscode: {response.status_code}")
|
||||
return []
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
return render_template('kas_informatie.html')
|
||||
|
||||
@app.route('/battery_voltage_events')
|
||||
def battery_voltage_events():
|
||||
# Haal gegevens op van de API
|
||||
api_data = get_api_data()
|
||||
|
||||
# Return de gegevens als JSON naar de frontend
|
||||
return jsonify(results=api_data)
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True)
|
||||
425
src/py/script/battery_voltage_events.py
Normal file
425
src/py/script/battery_voltage_events.py
Normal file
@@ -0,0 +1,425 @@
|
||||
# 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
|
||||
import GoodGarden.src.py.servermqtt as servermqtt
|
||||
|
||||
# Function to make a connection to the database
|
||||
def database_connect():
|
||||
return mysql.connector.connect(
|
||||
host="localhost",
|
||||
user="root",
|
||||
password="",
|
||||
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-%dT%H:%M:%SZ").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):
|
||||
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}:\n")
|
||||
|
||||
# Check if data is a list (records directly under the root)
|
||||
if isinstance(data, list):
|
||||
records = data
|
||||
elif isinstance(data, dict) and 'results' in data:
|
||||
records = data['results']
|
||||
else:
|
||||
print(f"Unexpected data format received: {data}")
|
||||
continue
|
||||
|
||||
for record in records:
|
||||
# Now, record is assumed to be a dictionary
|
||||
timestamp = record.get('timestamp', '')
|
||||
gateway_receive_time = record.get('gateway_receive_time', '')
|
||||
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")
|
||||
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
|
||||
elif float(value) > 4.2:
|
||||
print("Melding: Batterijspanning is hoger dan 4.2 volt. Batterij is vol.\n")
|
||||
else:
|
||||
print("Melding: Batterijspanning is binnen het gewenste bereik.\n\n")
|
||||
|
||||
# Insert data into the database
|
||||
insert_data(record)
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"Error fetching data from {url}: {e}")
|
||||
|
||||
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()
|
||||
if mydb.is_connected():
|
||||
mycursor = mydb.cursor()
|
||||
|
||||
# Hier moet je de juiste kolomnamen en gegevensindeling aanpassen op basis van de API-respons
|
||||
insert_query = """
|
||||
INSERT INTO goodgarden.battery_voltage_events (timestamp, gateway_receive_time, device, value)
|
||||
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', ''))
|
||||
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}") # Print de ingevoerde gegevens
|
||||
|
||||
# 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()
|
||||
|
||||
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}:\n")
|
||||
|
||||
for record in data['results']:
|
||||
timestamp = record.get('timestamp', '')
|
||||
device = record.get('device', '')
|
||||
value = record.get('value', '')
|
||||
print(f"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
|
||||
elif float(value) > 4.2:
|
||||
print("Melding: Batterijspanning is hoger dan 4.2 volt. Batterij is vol.\n")
|
||||
else:
|
||||
print("Melding: Batterijspanning is binnen het gewenste bereik.\n\n")
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"Error fetching data from {url}: {e}")
|
||||
|
||||
print("Waiting for the next read action...\n")
|
||||
time.sleep(300)
|
||||
|
||||
# Functie voor het bijwerken van gegevens in de database
|
||||
def update_data(record_id):
|
||||
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
|
||||
|
||||
# Vraag de gebruiker om nieuwe waarden voor de andere velden
|
||||
new_timestamp = input("Enter new timestamp: ")
|
||||
new_gateway_receive_time = input("Enter new gateway_receive_time: ")
|
||||
new_device = input("Enter new device: ")
|
||||
new_value = input("Enter new value: ")
|
||||
|
||||
# Hier moet je de juiste kolomnamen aanpassen op basis van de structuur van je database
|
||||
update_query = """
|
||||
UPDATE goodgarden.battery_voltage_events
|
||||
SET timestamp = %s, gateway_receive_time = %s, device = %s, 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 values - timestamp: {new_timestamp}, gateway_receive_time: {new_gateway_receive_time}, device: {new_device}, value: {new_value}")
|
||||
|
||||
mycursor.execute(update_query, (new_timestamp, new_gateway_receive_time, new_device, new_value, record_id))
|
||||
|
||||
# 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.")
|
||||
|
||||
# Functie voor het aanmaken van gegevens in de database op basis van batterijspanningsinformatie
|
||||
|
||||
if __name__ == "__main__":
|
||||
url = "https://garden.inajar.nl/api/battery_voltage_events/?format=json"
|
||||
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c" # Vervang dit door je werkelijke toegangstoken
|
||||
|
||||
# Je kunt repeat_count wijzigen om te bepalen hoe vaak je de bewerking wilt herhalen
|
||||
repeat_count = 10
|
||||
|
||||
# Keuze voor de bewerking
|
||||
operation_choice = input("Choose operation (C for Create, R for Read, U for Update, D for Delete): ").upper()
|
||||
|
||||
if operation_choice == "C":
|
||||
# Maak gegevens aan
|
||||
create_data(url, access_token, repeat_count)
|
||||
elif operation_choice == "R":
|
||||
# Lees gegevens
|
||||
read_data(url, access_token, repeat_count)
|
||||
elif operation_choice == "U":
|
||||
# Update gegevens
|
||||
record_id = int(input("Enter record ID to update: "))
|
||||
# Call the update_data function without additional arguments
|
||||
update_data(record_id)
|
||||
elif operation_choice == "D":
|
||||
# Verwijder gegevens
|
||||
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.")
|
||||
|
||||
7
src/py/script/calculate.py
Normal file
7
src/py/script/calculate.py
Normal file
@@ -0,0 +1,7 @@
|
||||
# In calculate.py
|
||||
|
||||
# Doe je berekeningen hier, vervang 42 door je berekende waarde
|
||||
calculated_value = 42
|
||||
|
||||
# Print het resultaat, dat zal worden gelezen door de PythonShell.run callback
|
||||
print(calculated_value)
|
||||
19
src/py/script/db_connect.py
Normal file
19
src/py/script/db_connect.py
Normal file
@@ -0,0 +1,19 @@
|
||||
import mysql.connector #** TYPE IN TERMINAL: "pip install mysql-connector-python"
|
||||
from mysql.connector import Error
|
||||
|
||||
def database_connect():
|
||||
try:
|
||||
connection = mysql.connector.connect(
|
||||
host="localhost",
|
||||
user="root",
|
||||
password="",
|
||||
database="goodgarden"
|
||||
)
|
||||
if connection.is_connected():
|
||||
# print("Connection gelukt!")
|
||||
return connection
|
||||
except Error as e:
|
||||
print(f"Connection NIET gelukt! ${e}")
|
||||
return None
|
||||
|
||||
# database_connect()
|
||||
50
src/py/script/db_connect_form.py
Normal file
50
src/py/script/db_connect_form.py
Normal 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)
|
||||
71
src/py/script/devices.py
Normal file
71
src/py/script/devices.py
Normal file
@@ -0,0 +1,71 @@
|
||||
import requests
|
||||
import time
|
||||
|
||||
from db_connect import database_connect
|
||||
|
||||
def fetch_and_display_all(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)
|
||||
load_data(data)
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
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()
|
||||
if mydb.is_connected():
|
||||
mycursor = mydb.cursor()
|
||||
|
||||
# Here you need to adjust the correct column names and data formats based on the API response
|
||||
insert_query = """
|
||||
INSERT INTO goodgarden.devices (serial_number, name, label, last_seen, last_battery_voltage)
|
||||
VALUES (%s, %s, %s, %s, %s )
|
||||
"""
|
||||
for record in data['results']:
|
||||
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: serial_number={serial_number}, name={name}, label={label}, last_seen={last_seen}, last_battery_voltage={last_battery_voltage}")
|
||||
|
||||
# Execute the query
|
||||
mycursor.execute(insert_query, (serial_number, name, label, last_seen, last_battery_voltage))
|
||||
|
||||
# Commit the changes
|
||||
mydb.commit()
|
||||
|
||||
# Close cursor and connection
|
||||
mycursor.close()
|
||||
mydb.close()
|
||||
|
||||
print("Data inserted into the database.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
url = "https://garden.inajar.nl/api/devices/?format=json"
|
||||
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c" # Replace this with your actual access token
|
||||
|
||||
|
||||
# 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(url, access_token, repeat_count)
|
||||
73
src/py/script/fetch.py
Normal file
73
src/py/script/fetch.py
Normal file
@@ -0,0 +1,73 @@
|
||||
import requests
|
||||
import time
|
||||
|
||||
from db_connect import database_connect
|
||||
|
||||
# Establish a database connection
|
||||
connection = database_connect()
|
||||
|
||||
def fetch_and_display_all(urls, access_token):
|
||||
for url in urls:
|
||||
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)
|
||||
load_data(data)
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"Error fetching data from {url}: {e}")
|
||||
|
||||
# Wait for a certain time (e.g., 60 seconds) before making the next call
|
||||
print("Waiting for the next retrieval action...")
|
||||
time.sleep(10) # Time here is in seconds.
|
||||
|
||||
def load_data(data):
|
||||
mydb = database_connect()
|
||||
if mydb.is_connected():
|
||||
mycursor = mydb.cursor()
|
||||
|
||||
# Here you need to adjust the correct column names and data formats based on the API response
|
||||
insert_query = """
|
||||
INSERT INTO goodgarden.fetch (timestamp, gateway_receive_time, device, value)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
"""
|
||||
for record in data['results']: # Adjust this based on the actual structure of the 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}") # Print the data being inserted
|
||||
|
||||
# Execute the query
|
||||
mycursor.execute(insert_query, (timestamp, gateway_receive_time, device, value))
|
||||
|
||||
# Commit the changes
|
||||
mydb.commit()
|
||||
|
||||
# Close cursor and connection
|
||||
mycursor.close()
|
||||
mydb.close()
|
||||
|
||||
print("Data inserted into the database.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
urls = [
|
||||
"https://garden.inajar.nl/api/battery_voltage_events/?format=json",
|
||||
"https://garden.inajar.nl/api/devices/?format=json",
|
||||
"https://garden.inajar.nl/api/par_events/?format=json",
|
||||
"https://garden.inajar.nl/api/relative_humidity_events/?format=json",
|
||||
"https://garden.inajar.nl/api/soil_electric_conductivity_events/?format=json",
|
||||
"https://garden.inajar.nl/api/soil_relative_permittivity_events/?format=json",
|
||||
"https://garden.inajar.nl/api/soil_temperature_events/?format=json"
|
||||
]
|
||||
|
||||
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c" # Vervang dit met jouw echte toegangstoken
|
||||
|
||||
fetch_and_display_all(urls, access_token)
|
||||
57
src/py/script/fetch_data.py
Normal file
57
src/py/script/fetch_data.py
Normal file
@@ -0,0 +1,57 @@
|
||||
import requests
|
||||
import time
|
||||
|
||||
from db_connect import database_connect
|
||||
|
||||
def fetch_battery_voltage_events():
|
||||
url = "https://garden.inajar.nl/api/battery_voltage_events/?format=json"
|
||||
headers = {
|
||||
"Authorization": "Token 33bb3b42452306c58ecedc3c86cfae28ba22329c"
|
||||
}
|
||||
|
||||
while True:
|
||||
try:
|
||||
response = requests.get(url, headers=headers)
|
||||
response.raise_for_status()
|
||||
|
||||
data = response.json()
|
||||
load_data(data)
|
||||
|
||||
print("Wachten voor de volgende ophaalactie...")
|
||||
time.sleep(300) # De tijd hier is in seconden.
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"Error fetching data: {e}")
|
||||
# Wacht ook hier bij een fout, om niet in een snelle foutloop te komen
|
||||
time.sleep(300)
|
||||
|
||||
def load_data(data):
|
||||
mydb = database_connect()
|
||||
if mydb.is_connected():
|
||||
mycursor = mydb.cursor()
|
||||
|
||||
# Hier moet je de juiste kolomnamen en dataformaten aanpassen op basis van de API-respons
|
||||
insert_query = """
|
||||
INSERT INTO goodgarden.battery_voltage_events (timestamp, gateway_receive_time, device, value)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
"""
|
||||
for record in data['results']:
|
||||
timestamp = record['timestamp']
|
||||
gateway_receive_time = record['gateway_receive_time']
|
||||
device = record['device']
|
||||
value = record['value']
|
||||
|
||||
# print(f"Inserting data: timestamp={timestamp}, gateway_receive_time={gateway_receive_time}, device={device}, value={value}")
|
||||
mycursor.execute(insert_query, (timestamp, gateway_receive_time, device, value))
|
||||
|
||||
# Commit de wijzigingen
|
||||
mydb.commit()
|
||||
|
||||
# Sluit cursor en verbinding
|
||||
mycursor.close()
|
||||
mydb.close()
|
||||
|
||||
print("Data ingevoegd in de database.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
fetch_battery_voltage_events()
|
||||
0
src/py/script/main.py
Normal file
0
src/py/script/main.py
Normal file
64
src/py/script/par_events.py
Normal file
64
src/py/script/par_events.py
Normal file
@@ -0,0 +1,64 @@
|
||||
import requests
|
||||
import time
|
||||
|
||||
from db_connect import database_connect
|
||||
|
||||
def fetch_and_display_all(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)
|
||||
load_data(data)
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"Error fetching data from {url}: {e}")
|
||||
|
||||
print("Waiting for the next retrieval action...")
|
||||
|
||||
time.sleep(1) # Time here is in seconds.
|
||||
|
||||
|
||||
def load_data(data):
|
||||
mydb = database_connect()
|
||||
if mydb.is_connected():
|
||||
mycursor = mydb.cursor()
|
||||
|
||||
# Here you need to adjust the correct column names and data formats based on the API response
|
||||
insert_query = """
|
||||
INSERT INTO goodgarden.par_events (timestamp, gateway_receive_time, device, value)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
"""
|
||||
for record in data['results']:
|
||||
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}")
|
||||
|
||||
# Execute the query
|
||||
mycursor.execute(insert_query, (timestamp, gateway_receive_time, device, value))
|
||||
|
||||
# Commit the changes
|
||||
mydb.commit()
|
||||
|
||||
# Close cursor and connection
|
||||
mycursor.close()
|
||||
mydb.close()
|
||||
|
||||
print("Data inserted into the database.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
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
|
||||
|
||||
fetch_and_display_all(url, access_token, repeat_count)
|
||||
64
src/py/script/relative_humidity_events.py
Normal file
64
src/py/script/relative_humidity_events.py
Normal file
@@ -0,0 +1,64 @@
|
||||
import requests
|
||||
import time
|
||||
|
||||
from db_connect import database_connect
|
||||
|
||||
def fetch_and_display_all(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)
|
||||
load_data(data)
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"Error fetching data from {url}: {e}")
|
||||
|
||||
print("Waiting for the next retrieval action...")
|
||||
|
||||
time.sleep(1) # Time here is in seconds.
|
||||
|
||||
def load_data(data):
|
||||
mydb = database_connect()
|
||||
if mydb.is_connected():
|
||||
mycursor = mydb.cursor()
|
||||
|
||||
# Here you need to adjust the correct column names and data formats based on the API response
|
||||
insert_query = """
|
||||
INSERT INTO goodgarden.relative_humidity_events (timestamp, gateway_receive_time, device, value)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
"""
|
||||
for record in data['results']:
|
||||
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}")
|
||||
|
||||
# Execute the query
|
||||
mycursor.execute(insert_query, (timestamp, gateway_receive_time, device, value))
|
||||
|
||||
# Commit the changes
|
||||
mydb.commit()
|
||||
|
||||
# Close cursor and connection
|
||||
mycursor.close()
|
||||
mydb.close()
|
||||
|
||||
print("Data inserted into the database.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
url = "https://garden.inajar.nl/api/relative_humidity_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
|
||||
|
||||
fetch_and_display_all(url, access_token, repeat_count)
|
||||
74
src/py/script/servermqtt.py
Normal file
74
src/py/script/servermqtt.py
Normal file
@@ -0,0 +1,74 @@
|
||||
import os
|
||||
import time
|
||||
import requests
|
||||
import paho.mqtt.client as mqtt
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
API_URL = os.getenv("API_URL")
|
||||
MQTT_HOST = os.getenv("MQTT_HOST")
|
||||
MQTT_PORT = int(os.getenv("MQTT_PORT", 1883))
|
||||
|
||||
def get_data_from_api(request):
|
||||
links = {
|
||||
'battery': '/battery_voltage_events/',
|
||||
'devices': '/devices/',
|
||||
'parEvents': '/par_events/',
|
||||
'humidity': '/relative_humidity_events/',
|
||||
'soilConductifity': '/soil_electric_conductivity_events/',
|
||||
'soilPermittivity' : '/soil_relative_permittivity_events/',
|
||||
'soilTemperature': '/soil_temperature_events/'
|
||||
}
|
||||
headers = {
|
||||
'accept': 'application/json',
|
||||
'Authorization': f'Token {os.getenv("API_TOKEN")}'
|
||||
}
|
||||
url = API_URL + links[request]
|
||||
try:
|
||||
response = requests.get(url, headers=headers)
|
||||
response.raise_for_status()
|
||||
except requests.exceptions.HTTPError as errh:
|
||||
print ("HTTP Error:",errh)
|
||||
return None
|
||||
except requests.exceptions.ConnectionError as errc:
|
||||
print ("Error Connecting:",errc)
|
||||
return None
|
||||
except requests.exceptions.Timeout as errt:
|
||||
print ("Timeout Error:",errt)
|
||||
return None
|
||||
except requests.exceptions.RequestException as err:
|
||||
print ("Something went wrong",err)
|
||||
return None
|
||||
|
||||
data = response.json()
|
||||
return data['results']
|
||||
|
||||
def publish_to_mqtt(topic, message):
|
||||
client = mqtt.Client()
|
||||
client.connect(MQTT_HOST, MQTT_PORT, 60)
|
||||
try:
|
||||
client.publish(topic, message)
|
||||
except mqtt.MQTTException as e:
|
||||
print(f"Failed to publish message: {e}")
|
||||
finally:
|
||||
client.disconnect()
|
||||
|
||||
def process_results(link, results):
|
||||
for result in results:
|
||||
if 'timestamp' in result and 'gateway_receive_time' in result and 'device' in result and 'value' in result:
|
||||
message = f"Timestamp: {result['timestamp']}, Gateway Receive Time: {result['gateway_receive_time']}, Device: {result['device']}, Value: {result['value']}"
|
||||
print(message)
|
||||
publish_to_mqtt(link, message)
|
||||
|
||||
def main():
|
||||
links = ['battery', 'devices', 'parEvents', 'humidity', 'soilConductifity', 'soilPermittivity', 'soilTemperature']
|
||||
while True:
|
||||
for link in links:
|
||||
results = get_data_from_api(link)
|
||||
if results is not None:
|
||||
process_results(link, results)
|
||||
time.sleep(5)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
63
src/py/script/soil_electric_conductivity_events.py
Normal file
63
src/py/script/soil_electric_conductivity_events.py
Normal file
@@ -0,0 +1,63 @@
|
||||
import requests
|
||||
import time
|
||||
|
||||
from db_connect import database_connect
|
||||
|
||||
def fetch_and_display_all(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)
|
||||
load_data(data)
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"Error fetching data from {url}: {e}")
|
||||
|
||||
print("Waiting for the next retrieval action...")
|
||||
|
||||
time.sleep(1) # Time here is in seconds.
|
||||
|
||||
def load_data(data):
|
||||
mydb = database_connect()
|
||||
if mydb.is_connected():
|
||||
mycursor = mydb.cursor()
|
||||
|
||||
# Here you need to adjust the correct column names and data formats based on the API response
|
||||
insert_query = """
|
||||
INSERT INTO goodgarden.soil_electric_conductivity_events (timestamp, gateway_receive_time, device, value)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
"""
|
||||
for record in data['results']:
|
||||
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}")
|
||||
|
||||
# Execute the query
|
||||
mycursor.execute(insert_query, (timestamp, gateway_receive_time, device, value))
|
||||
|
||||
# Commit the changes
|
||||
mydb.commit()
|
||||
|
||||
# Close cursor and connection
|
||||
mycursor.close()
|
||||
mydb.close()
|
||||
|
||||
print("Data inserted into the database.")
|
||||
if __name__ == "__main__":
|
||||
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
|
||||
|
||||
fetch_and_display_all(url, access_token, repeat_count)
|
||||
66
src/py/script/soil_relative_permittivity_events.py
Normal file
66
src/py/script/soil_relative_permittivity_events.py
Normal file
@@ -0,0 +1,66 @@
|
||||
import requests
|
||||
import time
|
||||
|
||||
from db_connect import database_connect
|
||||
|
||||
def fetch_and_display_all(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)
|
||||
load_data(data)
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"Error fetching data from {url}: {e}")
|
||||
|
||||
print("Waiting for the next retrieval action...")
|
||||
|
||||
time.sleep(1) # Time here is in seconds.
|
||||
|
||||
|
||||
def load_data(data):
|
||||
mydb = database_connect()
|
||||
if mydb.is_connected():
|
||||
mycursor = mydb.cursor()
|
||||
|
||||
# Here you need to adjust the correct column names and data formats based on the API response
|
||||
insert_query = """
|
||||
INSERT INTO goodgarden.soil_temperature_events (timestamp, gateway_receive_time, device, value)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
"""
|
||||
for record in data['results']:
|
||||
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}")
|
||||
|
||||
# Execute the query
|
||||
mycursor.execute(insert_query, (timestamp, gateway_receive_time, device, value))
|
||||
|
||||
# Commit the changes
|
||||
mydb.commit()
|
||||
|
||||
# Close cursor and connection
|
||||
mycursor.close()
|
||||
mydb.close()
|
||||
|
||||
print("Data inserted into the database.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
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
|
||||
|
||||
# fetch_and_display_all(urls, access_token)
|
||||
|
||||
fetch_and_display_all(url, access_token, repeat_count)
|
||||
65
src/py/script/soil_temperature_events.py
Normal file
65
src/py/script/soil_temperature_events.py
Normal file
@@ -0,0 +1,65 @@
|
||||
import requests
|
||||
import time
|
||||
|
||||
|
||||
from db_connect import database_connect
|
||||
|
||||
def fetch_and_display_all(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)
|
||||
load_data(data)
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"Error fetching data from {url}: {e}")
|
||||
|
||||
print("Waiting for the next retrieval action...")
|
||||
|
||||
time.sleep(1) # Time here is in seconds.
|
||||
|
||||
def load_data(data):
|
||||
mydb = database_connect()
|
||||
if mydb.is_connected():
|
||||
mycursor = mydb.cursor()
|
||||
|
||||
# Here you need to adjust the correct column names and data formats based on the API response
|
||||
insert_query = """
|
||||
INSERT INTO goodgarden.soil_temperature_events (timestamp, gateway_receive_time, device, value)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
"""
|
||||
for record in data['results']:
|
||||
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}")
|
||||
|
||||
# Execute the query
|
||||
mycursor.execute(insert_query, (timestamp, gateway_receive_time, device, value))
|
||||
|
||||
# Commit the changes
|
||||
mydb.commit()
|
||||
|
||||
# Close cursor and connection
|
||||
mycursor.close()
|
||||
mydb.close()
|
||||
|
||||
print("Data inserted into the database.")
|
||||
if __name__ == "__main__":
|
||||
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
|
||||
|
||||
fetch_and_display_all(url, access_token, repeat_count)
|
||||
Reference in New Issue
Block a user