planten class V1.1
This commit is contained in:
113
src/py/script/DUMMY.json
Normal file
113
src/py/script/DUMMY.json
Normal file
@@ -0,0 +1,113 @@
|
||||
{ "battery_voltage_events": [
|
||||
{
|
||||
"timestamp": 1707825721,
|
||||
"gateway_receive_time": "2024-02-13T12:02:01Z",
|
||||
"device": 256,
|
||||
"value": 4.098901271820068
|
||||
|
||||
},
|
||||
{
|
||||
"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
|
||||
}
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"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
|
||||
}
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
"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
|
||||
}
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"soil_electric_conductivity_events": [
|
||||
{
|
||||
"timestamp": 1707851215,
|
||||
"gateway_receive_time": "2024-02-13T19:06:55Z",
|
||||
"device": 322,
|
||||
"value": 0.0
|
||||
}
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"soil_relative_permittivity_events": [
|
||||
{
|
||||
"timestamp": 1707851215,
|
||||
"gateway_receive_time": "2024-02-13T19:06:55Z",
|
||||
"device": 322,
|
||||
"value": 1.52
|
||||
}
|
||||
],
|
||||
|
||||
|
||||
|
||||
"soil_temperature_events": [
|
||||
{
|
||||
"timestamp": 1707851215,
|
||||
"gateway_receive_time": "2024-02-13T19:06:55Z",
|
||||
"device": 322,
|
||||
"value": 12.06
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
223
src/py/script/battery_voltage_events.py
Normal file
223
src/py/script/battery_voltage_events.py
Normal file
@@ -0,0 +1,223 @@
|
||||
import mysql.connector
|
||||
import requests
|
||||
from datetime import datetime, timezone, timedelta
|
||||
import time
|
||||
|
||||
# Function to make a connection to the database
|
||||
def database_connect():
|
||||
return mysql.connector.connect(
|
||||
host="localhost",
|
||||
user="root",
|
||||
password="",
|
||||
database="goodgarden"
|
||||
)
|
||||
|
||||
# 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', '')
|
||||
|
||||
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
|
||||
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 = 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 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.")
|
||||
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
|
||||
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)
|
||||
36
src/py/script/devices.py
Normal file
36
src/py/script/devices.py
Normal file
@@ -0,0 +1,36 @@
|
||||
import json
|
||||
|
||||
from paho.mqtt import subscribe
|
||||
|
||||
def on_message(client, userdata, message):
|
||||
payload_str = message.payload.decode("utf-8")
|
||||
data = json.loads(payload_str)
|
||||
|
||||
device_256 = None
|
||||
last_seen = None
|
||||
last_battery_voltage = None
|
||||
|
||||
device_322 = None
|
||||
last_seen = None
|
||||
last_battery_voltage = None
|
||||
|
||||
for key in data["results"]:
|
||||
if int(key["id"]) == 256:
|
||||
device_256 = int(key["id"])
|
||||
last_seen = int(key["last_seen"])
|
||||
last_battery_voltage = float(key["last_battery_voltage"])
|
||||
# print(f"{device_256}")
|
||||
print(f"Het device {device_256} is voor het laatst geien op: {last_seen} met de voltage als {last_battery_voltage}")
|
||||
|
||||
elif int(key["id"]) == 322:
|
||||
device_322 = int(key["id"])
|
||||
last_seen = int(key["last_seen"])
|
||||
last_battery_voltage = float(key["last_battery_voltage"])
|
||||
# print(f"{device_256}")
|
||||
print(f"Het device {device_322} is voor het laatst gezien op: {last_seen} met de voltage als {last_battery_voltage}")
|
||||
|
||||
print(f"\033[92mMessage received on topic\033[0m {message.topic}: {data}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
topic = "goodgarden/devices"
|
||||
subscribe.callback(on_message, topic)
|
||||
346
src/py/script/goodgarden.sql
Normal file
346
src/py/script/goodgarden.sql
Normal file
@@ -0,0 +1,346 @@
|
||||
-- phpMyAdmin SQL Dump
|
||||
-- version 5.2.1
|
||||
-- https://www.phpmyadmin.net/
|
||||
--
|
||||
-- Host: 127.0.0.1
|
||||
-- Gegenereerd op: 14 feb 2024 om 14:36
|
||||
-- Serverversie: 10.4.28-MariaDB
|
||||
-- PHP-versie: 8.2.4
|
||||
|
||||
DROP DATABASE IF EXISTS goodgarden;
|
||||
CREATE DATABASE goodgarden;
|
||||
|
||||
USE goodgarden;
|
||||
|
||||
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
|
||||
START TRANSACTION;
|
||||
SET time_zone = "+00:00";
|
||||
|
||||
|
||||
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
|
||||
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
|
||||
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
|
||||
/*!40101 SET NAMES utf8mb4 */;
|
||||
|
||||
--
|
||||
-- Database: `goodgarden`
|
||||
--
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
--
|
||||
-- Tabelstructuur voor tabel `battery_voltage_events`
|
||||
--
|
||||
|
||||
CREATE TABLE `battery_voltage_events` (
|
||||
`id` int(10) UNSIGNED NOT NULL,
|
||||
`timestamp` int(11) DEFAULT NULL,
|
||||
`gateway_receive_time` varchar(50) DEFAULT NULL,
|
||||
`device` int(11) DEFAULT NULL,
|
||||
`value` decimal(10,5) DEFAULT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
--
|
||||
-- Gegevens worden geëxporteerd voor tabel `battery_voltage_events`
|
||||
--
|
||||
|
||||
INSERT INTO `battery_voltage_events` (`id`, `timestamp`, `gateway_receive_time`, `device`, `value`) VALUES
|
||||
(1, 1707825721, '2024-02-13T12:02:01Z', 256, 4.09890),
|
||||
(2, 1707837460, '2024-02-13T15:17:40Z', 322, 4.10501),
|
||||
(3, 1707825721, '2024-02-13T12:02:01Z', 256, 4.09890),
|
||||
(4, 1707837460, '2024-02-13T15:17:40Z', 322, 4.10501),
|
||||
(5, 1707825721, '2024-02-13T12:02:01Z', 256, 4.09890),
|
||||
(6, 1707837460, '2024-02-13T15:17:40Z', 322, 4.10501),
|
||||
(7, 1707825721, '2024-02-13T12:02:01Z', 256, 4.09890),
|
||||
(8, 1707837460, '2024-02-13T15:17:40Z', 322, 4.10501),
|
||||
(9, 1707825721, '2024-02-13T12:02:01Z', 256, 4.09890),
|
||||
(10, 1707837460, '2024-02-13T15:17:40Z', 322, 4.10501);
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
--
|
||||
-- Tabelstructuur voor tabel `devices`
|
||||
--
|
||||
|
||||
CREATE TABLE `devices` (
|
||||
`id` int(10) UNSIGNED NOT NULL,
|
||||
`serial_number` varchar(255) DEFAULT NULL,
|
||||
`name` varchar(255) DEFAULT NULL,
|
||||
`label` varchar(255) DEFAULT NULL,
|
||||
`last_seen` int(11) DEFAULT NULL,
|
||||
`last_battery_voltage` float DEFAULT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
--
|
||||
-- Gegevens worden geëxporteerd voor tabel `devices`
|
||||
--
|
||||
|
||||
INSERT INTO `devices` (`id`, `serial_number`, `name`, `label`, `last_seen`, `last_battery_voltage`) VALUES
|
||||
(1, '0033889B1BAB1169', 'firefly2_0051', 'The Field', 1707765066, 4.09768),
|
||||
(2, '006FE1FC316ED7D8', 'firefly2_0111', 'The Field', 1707764966, 4.10745);
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
--
|
||||
-- Tabelstructuur voor tabel `fetch`
|
||||
--
|
||||
|
||||
CREATE TABLE `fetch` (
|
||||
`id` int(10) UNSIGNED NOT NULL,
|
||||
`timestamp` int(11) DEFAULT NULL,
|
||||
`gateway_receive_time` varchar(50) DEFAULT NULL,
|
||||
`device` int(11) DEFAULT NULL,
|
||||
`value` decimal(10,5) DEFAULT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
--
|
||||
-- Gegevens worden geëxporteerd voor tabel `fetch`
|
||||
--
|
||||
|
||||
INSERT INTO `fetch` (`id`, `timestamp`, `gateway_receive_time`, `device`, `value`) VALUES
|
||||
(70, 1707851215, '2024-02-13T19:06:55Z', 322, 0.00000),
|
||||
(71, 1707851215, '2024-02-13T19:06:55Z', 322, 1.52000),
|
||||
(72, 1707851215, '2024-02-13T19:06:55Z', 322, 12.06000),
|
||||
(73, 1707825721, '2024-02-13T12:02:01Z', 256, 4.09890),
|
||||
(74, 1707837460, '2024-02-13T15:17:40Z', 322, 4.10501),
|
||||
(75, 0, '', 0, 0.00000),
|
||||
(76, 0, '', 0, 0.00000),
|
||||
(77, 1707844638, '2024-02-13T17:17:18Z', 322, 0.00000),
|
||||
(78, 1707851099, '2024-02-13T19:04:59Z', 256, 0.00000),
|
||||
(79, 1707844638, '2024-02-13T17:17:18Z', 322, 71.08984),
|
||||
(80, 1707851099, '2024-02-13T19:04:59Z', 256, 66.72949),
|
||||
(81, 1707851215, '2024-02-13T19:06:55Z', 322, 0.00000),
|
||||
(82, 1707851215, '2024-02-13T19:06:55Z', 322, 1.52000),
|
||||
(83, 1707851215, '2024-02-13T19:06:55Z', 322, 12.06000),
|
||||
(84, 0, '', 0, 0.00000),
|
||||
(85, 0, '', 0, 0.00000),
|
||||
(86, 1707844638, '2024-02-13T17:17:18Z', 322, 0.00000),
|
||||
(87, 1707851099, '2024-02-13T19:04:59Z', 256, 0.00000),
|
||||
(88, 1707844638, '2024-02-13T17:17:18Z', 322, 71.08984),
|
||||
(89, 1707851099, '2024-02-13T19:04:59Z', 256, 66.72949),
|
||||
(90, 1707825721, '2024-02-13T12:02:01Z', 256, 4.09890),
|
||||
(91, 1707837460, '2024-02-13T15:17:40Z', 322, 4.10501),
|
||||
(92, 0, '', 0, 0.00000),
|
||||
(93, 0, '', 0, 0.00000),
|
||||
(94, 1707844638, '2024-02-13T17:17:18Z', 322, 0.00000),
|
||||
(95, 1707851099, '2024-02-13T19:04:59Z', 256, 0.00000),
|
||||
(96, 1707844638, '2024-02-13T17:17:18Z', 322, 71.08984),
|
||||
(97, 1707851099, '2024-02-13T19:04:59Z', 256, 66.72949);
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
--
|
||||
-- Tabelstructuur voor tabel `par_events`
|
||||
--
|
||||
|
||||
CREATE TABLE `par_events` (
|
||||
`id` int(10) UNSIGNED NOT NULL,
|
||||
`timestamp` int(11) DEFAULT NULL,
|
||||
`gateway_receive_time` varchar(50) DEFAULT NULL,
|
||||
`device` int(11) DEFAULT NULL,
|
||||
`value` decimal(10,5) DEFAULT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
--
|
||||
-- Gegevens worden geëxporteerd voor tabel `par_events`
|
||||
--
|
||||
|
||||
INSERT INTO `par_events` (`id`, `timestamp`, `gateway_receive_time`, `device`, `value`) VALUES
|
||||
(1, 1707844638, '2024-02-13T17:17:18Z', 322, 0.00000),
|
||||
(2, 1707851099, '2024-02-13T19:04:59Z', 256, 0.00000);
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
--
|
||||
-- Tabelstructuur voor tabel `relative_humidity_events`
|
||||
--
|
||||
|
||||
CREATE TABLE `relative_humidity_events` (
|
||||
`id` int(10) UNSIGNED NOT NULL,
|
||||
`timestamp` int(11) DEFAULT NULL,
|
||||
`gateway_receive_time` varchar(50) DEFAULT NULL,
|
||||
`device` int(11) DEFAULT NULL,
|
||||
`value` decimal(10,5) DEFAULT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
--
|
||||
-- Gegevens worden geëxporteerd voor tabel `relative_humidity_events`
|
||||
--
|
||||
|
||||
INSERT INTO `relative_humidity_events` (`id`, `timestamp`, `gateway_receive_time`, `device`, `value`) VALUES
|
||||
(3, 1707844638, '2024-02-13T17:17:18Z', 322, 71.08984),
|
||||
(4, 1707851099, '2024-02-13T19:04:59Z', 256, 66.72949),
|
||||
(5, 1707844638, '2024-02-13T17:17:18Z', 322, 71.08984),
|
||||
(6, 1707851099, '2024-02-13T19:04:59Z', 256, 66.72949);
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
--
|
||||
-- Tabelstructuur voor tabel `soil_electric_conductivity_events`
|
||||
--
|
||||
|
||||
CREATE TABLE `soil_electric_conductivity_events` (
|
||||
`id` int(10) UNSIGNED NOT NULL,
|
||||
`timestamp` int(11) DEFAULT NULL,
|
||||
`gateway_receive_time` varchar(50) DEFAULT NULL,
|
||||
`device` int(11) DEFAULT NULL,
|
||||
`value` decimal(10,5) DEFAULT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
--
|
||||
-- Gegevens worden geëxporteerd voor tabel `soil_electric_conductivity_events`
|
||||
--
|
||||
|
||||
INSERT INTO `soil_electric_conductivity_events` (`id`, `timestamp`, `gateway_receive_time`, `device`, `value`) VALUES
|
||||
(3, 1707851215, '2024-02-13T19:06:55Z', 322, 0.00000);
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
--
|
||||
-- Tabelstructuur voor tabel `soil_relative_permittivity_events`
|
||||
--
|
||||
|
||||
CREATE TABLE `soil_relative_permittivity_events` (
|
||||
`id` int(10) UNSIGNED NOT NULL,
|
||||
`timestamp` int(11) DEFAULT NULL,
|
||||
`gateway_receive_time` varchar(50) DEFAULT NULL,
|
||||
`device` int(11) DEFAULT NULL,
|
||||
`value` decimal(10,5) DEFAULT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
--
|
||||
-- Gegevens worden geëxporteerd voor tabel `soil_relative_permittivity_events`
|
||||
--
|
||||
|
||||
INSERT INTO `soil_relative_permittivity_events` (`id`, `timestamp`, `gateway_receive_time`, `device`, `value`) VALUES
|
||||
(3, 1707851215, '2024-02-13T19:06:55Z', 322, 1.52000);
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
--
|
||||
-- Tabelstructuur voor tabel `soil_temperature_events`
|
||||
--
|
||||
|
||||
CREATE TABLE `soil_temperature_events` (
|
||||
`id` int(10) NOT NULL,
|
||||
`timestamp` int(11) DEFAULT NULL,
|
||||
`gateway_receive_time` varchar(50) DEFAULT NULL,
|
||||
`device` int(11) DEFAULT NULL,
|
||||
`value` decimal(10,5) DEFAULT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
--
|
||||
-- Gegevens worden geëxporteerd voor tabel `soil_temperature_events`
|
||||
--
|
||||
|
||||
INSERT INTO `soil_temperature_events` (`id`, `timestamp`, `gateway_receive_time`, `device`, `value`) VALUES
|
||||
(3, 1707851215, '2024-02-13T19:06:55Z', 322, 12.06000);
|
||||
|
||||
--
|
||||
-- Indexen voor geëxporteerde tabellen
|
||||
--
|
||||
|
||||
--
|
||||
-- Indexen voor tabel `battery_voltage_events`
|
||||
--
|
||||
ALTER TABLE `battery_voltage_events`
|
||||
ADD PRIMARY KEY (`id`);
|
||||
|
||||
--
|
||||
-- Indexen voor tabel `devices`
|
||||
--
|
||||
ALTER TABLE `devices`
|
||||
ADD PRIMARY KEY (`id`);
|
||||
|
||||
--
|
||||
-- Indexen voor tabel `fetch`
|
||||
--
|
||||
ALTER TABLE `fetch`
|
||||
ADD PRIMARY KEY (`id`);
|
||||
|
||||
--
|
||||
-- Indexen voor tabel `par_events`
|
||||
--
|
||||
ALTER TABLE `par_events`
|
||||
ADD PRIMARY KEY (`id`);
|
||||
|
||||
--
|
||||
-- Indexen voor tabel `relative_humidity_events`
|
||||
--
|
||||
ALTER TABLE `relative_humidity_events`
|
||||
ADD PRIMARY KEY (`id`);
|
||||
|
||||
--
|
||||
-- Indexen voor tabel `soil_electric_conductivity_events`
|
||||
--
|
||||
ALTER TABLE `soil_electric_conductivity_events`
|
||||
ADD PRIMARY KEY (`id`);
|
||||
|
||||
--
|
||||
-- Indexen voor tabel `soil_relative_permittivity_events`
|
||||
--
|
||||
ALTER TABLE `soil_relative_permittivity_events`
|
||||
ADD PRIMARY KEY (`id`);
|
||||
|
||||
--
|
||||
-- Indexen voor tabel `soil_temperature_events`
|
||||
--
|
||||
ALTER TABLE `soil_temperature_events`
|
||||
ADD PRIMARY KEY (`id`);
|
||||
|
||||
--
|
||||
-- AUTO_INCREMENT voor geëxporteerde tabellen
|
||||
--
|
||||
|
||||
--
|
||||
-- AUTO_INCREMENT voor een tabel `battery_voltage_events`
|
||||
--
|
||||
ALTER TABLE `battery_voltage_events`
|
||||
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
|
||||
|
||||
--
|
||||
-- AUTO_INCREMENT voor een tabel `devices`
|
||||
--
|
||||
ALTER TABLE `devices`
|
||||
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
|
||||
|
||||
--
|
||||
-- AUTO_INCREMENT voor een tabel `fetch`
|
||||
--
|
||||
ALTER TABLE `fetch`
|
||||
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=98;
|
||||
|
||||
--
|
||||
-- AUTO_INCREMENT voor een tabel `par_events`
|
||||
--
|
||||
ALTER TABLE `par_events`
|
||||
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
|
||||
|
||||
--
|
||||
-- AUTO_INCREMENT voor een tabel `relative_humidity_events`
|
||||
--
|
||||
ALTER TABLE `relative_humidity_events`
|
||||
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
|
||||
|
||||
--
|
||||
-- AUTO_INCREMENT voor een tabel `soil_electric_conductivity_events`
|
||||
--
|
||||
ALTER TABLE `soil_electric_conductivity_events`
|
||||
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
|
||||
|
||||
--
|
||||
-- AUTO_INCREMENT voor een tabel `soil_relative_permittivity_events`
|
||||
--
|
||||
ALTER TABLE `soil_relative_permittivity_events`
|
||||
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
|
||||
|
||||
--
|
||||
-- AUTO_INCREMENT voor een tabel `soil_temperature_events`
|
||||
--
|
||||
ALTER TABLE `soil_temperature_events`
|
||||
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
|
||||
COMMIT;
|
||||
|
||||
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
|
||||
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
|
||||
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
||||
25
src/py/script/par_events.py
Normal file
25
src/py/script/par_events.py
Normal file
@@ -0,0 +1,25 @@
|
||||
import json
|
||||
|
||||
from paho.mqtt import subscribe
|
||||
|
||||
def on_message(client, userdata, message):
|
||||
payload_str = message.payload.decode("utf-8")
|
||||
data = json.loads(payload_str)
|
||||
|
||||
device_322_value = None
|
||||
device_256_value = None
|
||||
|
||||
for key in data["results"]:
|
||||
if key["device"] == 322:
|
||||
device_322_value = key["value"]
|
||||
elif key["device"] == 256:
|
||||
device_256_value = key["value"]
|
||||
|
||||
print(f"Device 322 value: {device_322_value}")
|
||||
print(f"Device 256 value: {device_256_value}")
|
||||
|
||||
print(f"Message received on topic {message.topic}: {data}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
topic = "goodgarden/par_events"
|
||||
subscribe.callback(on_message, topic)
|
||||
49
src/py/script/planten.py
Normal file
49
src/py/script/planten.py
Normal file
@@ -0,0 +1,49 @@
|
||||
import json
|
||||
import mysql.connector
|
||||
import os
|
||||
|
||||
# Function to make a connection to the database
|
||||
def database_connect():
|
||||
return mysql.connector.connect(
|
||||
host="localhost",
|
||||
user="root",
|
||||
password="",
|
||||
database="goodgarden"
|
||||
)
|
||||
|
||||
# Function to get the absolute path of the current directory
|
||||
def get_current_directory():
|
||||
return os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
def fetch_plant_and_write_to_json():
|
||||
# Establish a database connection
|
||||
connection = database_connect()
|
||||
|
||||
try:
|
||||
cursor = connection.cursor(dictionary=True) # To fetch rows as dictionaries
|
||||
# Execute the query to fetch data
|
||||
cursor.execute("SELECT id, plant_naam, plantensoort, plant_geteelt FROM planten")
|
||||
# Fetch all rows
|
||||
plants = cursor.fetchall()
|
||||
|
||||
# Get the absolute path of the current directory
|
||||
current_directory = get_current_directory()
|
||||
# Construct the absolute path for the JSON file
|
||||
json_file_path = os.path.join(current_directory, 'plants.json')
|
||||
|
||||
# Write fetched data to JSON file
|
||||
with open(json_file_path, 'w') as json_file:
|
||||
json.dump(plants, json_file, indent=4)
|
||||
|
||||
except mysql.connector.Error as error:
|
||||
print("Error fetching data from MySQL table:", error)
|
||||
|
||||
finally:
|
||||
# Close cursor and connection
|
||||
if 'cursor' in locals():
|
||||
cursor.close()
|
||||
if connection.is_connected():
|
||||
connection.close()
|
||||
|
||||
# Call the function to fetch data and write to JSON
|
||||
fetch_plant_and_write_to_json()
|
||||
32
src/py/script/plants.json
Normal file
32
src/py/script/plants.json
Normal file
@@ -0,0 +1,32 @@
|
||||
[
|
||||
{
|
||||
"id": 47,
|
||||
"plant_naam": "Tomaten",
|
||||
"plantensoort": "Groente",
|
||||
"plant_geteelt": 1
|
||||
},
|
||||
{
|
||||
"id": 49,
|
||||
"plant_naam": "Komkommer",
|
||||
"plantensoort": "Groente",
|
||||
"plant_geteelt": 1
|
||||
},
|
||||
{
|
||||
"id": 50,
|
||||
"plant_naam": "Appel",
|
||||
"plantensoort": "Fruit",
|
||||
"plant_geteelt": 1
|
||||
},
|
||||
{
|
||||
"id": 51,
|
||||
"plant_naam": "Sla",
|
||||
"plantensoort": "Groente",
|
||||
"plant_geteelt": 1
|
||||
},
|
||||
{
|
||||
"id": 52,
|
||||
"plant_naam": "Wietplant",
|
||||
"plantensoort": "Onkruid",
|
||||
"plant_geteelt": 0
|
||||
}
|
||||
]
|
||||
13
src/py/script/relative_humidity_events.py
Normal file
13
src/py/script/relative_humidity_events.py
Normal file
@@ -0,0 +1,13 @@
|
||||
import json
|
||||
|
||||
from paho.mqtt import subscribe
|
||||
|
||||
def on_message(client, userdata, message):
|
||||
payload_str = message.payload.decode("utf-8")
|
||||
data = json.loads(payload_str)
|
||||
|
||||
print(f"Message received on topic {message.topic}: {data}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
topic = "goodgarden/relative_humidity"
|
||||
subscribe.callback(on_message, topic)
|
||||
218
src/py/script/samenvoegen_databases.py
Normal file
218
src/py/script/samenvoegen_databases.py
Normal file
@@ -0,0 +1,218 @@
|
||||
import requests
|
||||
import time
|
||||
|
||||
from db_connect import database_connect
|
||||
|
||||
##########################* DEVICES #######################
|
||||
|
||||
def load_data(data):
|
||||
mydb = database_connect()
|
||||
if mydb.is_connected():
|
||||
mycursor = mydb.cursor()
|
||||
|
||||
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}")
|
||||
|
||||
mycursor.execute(insert_query, (serial_number, name, label, last_seen, last_battery_voltage))
|
||||
|
||||
mydb.commit()
|
||||
|
||||
mycursor.close()
|
||||
mydb.close()
|
||||
|
||||
print("Data inserted into the database.")
|
||||
|
||||
############################### EINDE ########################
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
##########################* PAR_EVENTS #######################
|
||||
|
||||
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.")
|
||||
|
||||
############################### EINDE ########################
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
##########################* RELATIVE_HUMIDITY_EVENTS #######################
|
||||
|
||||
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.")
|
||||
|
||||
############################### EINDE ########################
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
##########################* SOIL_ELECTRIC_CONDUCTIVITY_EVENTS #######################
|
||||
|
||||
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.")
|
||||
|
||||
############################### EINDE ########################
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
##########################* SOIL_TEMPERATURE_EVENTS #######################
|
||||
|
||||
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.")
|
||||
|
||||
############################### EINDE ########################
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
##########################* SOIL_TEMPERATURE_EVENTS #######################
|
||||
|
||||
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.")
|
||||
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()
|
||||
13
src/py/script/soil_electric_conductivity_events.py
Normal file
13
src/py/script/soil_electric_conductivity_events.py
Normal file
@@ -0,0 +1,13 @@
|
||||
import json
|
||||
|
||||
from paho.mqtt import subscribe
|
||||
|
||||
def on_message(client, userdata, message):
|
||||
payload_str = message.payload.decode("utf-8")
|
||||
data = json.loads(payload_str)
|
||||
|
||||
print(f"Message received on topic {message.topic}: {data}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
topic = "goodgarden/soil_electric_conductivity"
|
||||
subscribe.callback(on_message, topic)
|
||||
13
src/py/script/soil_relative_permittivity_events.py
Normal file
13
src/py/script/soil_relative_permittivity_events.py
Normal file
@@ -0,0 +1,13 @@
|
||||
import json
|
||||
|
||||
from paho.mqtt import subscribe
|
||||
|
||||
def on_message(client, userdata, message):
|
||||
payload_str = message.payload.decode("utf-8")
|
||||
data = json.loads(payload_str)
|
||||
|
||||
print(f"Message received on topic {message.topic}: {data}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
topic = "goodgarden/soil_relative_permittivity"
|
||||
subscribe.callback(on_message, topic)
|
||||
13
src/py/script/soil_temperature_events.py
Normal file
13
src/py/script/soil_temperature_events.py
Normal file
@@ -0,0 +1,13 @@
|
||||
import json
|
||||
|
||||
from paho.mqtt import subscribe
|
||||
|
||||
def on_message(client, userdata, message):
|
||||
payload_str = message.payload.decode("utf-8")
|
||||
data = json.loads(payload_str)
|
||||
|
||||
print(f"Message received on topic {message.topic}: {data}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
topic = "goodgarden/soil_temperature"
|
||||
subscribe.callback(on_message, topic)
|
||||
Reference in New Issue
Block a user