mqtt begin
This commit is contained in:
@@ -1,6 +1,8 @@
|
|||||||
import mysql.connector
|
import mysql.connector
|
||||||
import requests
|
import requests
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
import time
|
import time
|
||||||
|
import GoodGarden.servermqtt as servermqtt
|
||||||
|
|
||||||
# Function to make a connection to the database
|
# Function to make a connection to the database
|
||||||
def database_connect():
|
def database_connect():
|
||||||
@@ -11,130 +13,135 @@ def database_connect():
|
|||||||
database="goodgarden"
|
database="goodgarden"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def calculate_timestamp(gateway_receive_time):
|
||||||
|
# Converteer de stringrepresentatie naar een datetime-object in UTC
|
||||||
|
datetime_obj_utc = datetime.strptime(gateway_receive_time, "%Y-%m-%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)
|
||||||
|
|
||||||
# Function for creating data in the database based on battery voltage information from the API
|
# Formateer het datetime-object als een leesbare datumstring
|
||||||
def create_data_from_api(url, access_token, repeat_count=5):
|
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):
|
for _ in range(repeat_count):
|
||||||
try:
|
try:
|
||||||
headers = {
|
headers = {"Authorization": f"Token {access_token}"}
|
||||||
"Authorization": f"Token {access_token}"
|
|
||||||
}
|
|
||||||
response = requests.get(url, headers=headers)
|
response = requests.get(url, headers=headers)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
|
|
||||||
data = response.json()
|
data = response.json()
|
||||||
insert_data(data['results'])
|
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:
|
except requests.exceptions.RequestException as e:
|
||||||
print(f"Error fetching data from {url}: {e}")
|
print(f"Error fetching data from {url}: {e}")
|
||||||
|
|
||||||
# Wait for a certain time (e.g., 1 second) before making the next API call
|
print("Waiting for the next create action...\n")
|
||||||
print("Waiting for the next create action...")
|
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
|
||||||
# Function for inserting data into the database
|
|
||||||
def insert_data(data):
|
# Functie voor het invoegen van gegevens in de database
|
||||||
|
def insert_data(record):
|
||||||
mydb = database_connect()
|
mydb = database_connect()
|
||||||
if mydb.is_connected():
|
if mydb.is_connected():
|
||||||
mycursor = mydb.cursor()
|
mycursor = mydb.cursor()
|
||||||
|
|
||||||
# Adjust column names and data format based on the API response
|
# Hier moet je de juiste kolomnamen en gegevensindeling aanpassen op basis van de API-respons
|
||||||
insert_query = """
|
insert_query = """
|
||||||
INSERT INTO goodgarden.battery_voltage_events (timestamp, gateway_receive_time, device, value)
|
INSERT INTO goodgarden.battery_voltage_events (timestamp, gateway_receive_time, device, value)
|
||||||
VALUES (%s, %s, %s, %s)
|
VALUES (%s, %s, %s, %s)
|
||||||
"""
|
"""
|
||||||
for record in data:
|
# Pas dit aan op basis van de werkelijke structuur van de JSON
|
||||||
timestamp = record.get('timestamp', '')
|
timestamp = calculate_timestamp(record.get('gateway_receive_time', ''))
|
||||||
gateway_receive_time = record.get('gateway_receive_time', '')
|
gateway_receive_time = record.get('gateway_receive_time', '')
|
||||||
device = record.get('device', '')
|
device = record.get('device', '')
|
||||||
value = record.get('value', '')
|
value = record.get('value', '')
|
||||||
|
|
||||||
print(f"Inserting data: timestamp={timestamp}, gateway_receive_time={gateway_receive_time}, device={device}, value={value}")
|
print(f"Inserting data: timestamp={timestamp}, gateway_receive_time={gateway_receive_time}, device={device}, value={value}") # Print de ingevoerde gegevens
|
||||||
|
|
||||||
# Execute the query
|
# Voer de query uit
|
||||||
mycursor.execute(insert_query, (timestamp, gateway_receive_time, device, value))
|
mycursor.execute(insert_query, (timestamp, gateway_receive_time, device, value))
|
||||||
|
|
||||||
# Confirm the changes
|
# Bevestig de wijzigingen
|
||||||
mydb.commit()
|
mydb.commit()
|
||||||
|
|
||||||
# Close cursor and connection
|
# Sluit cursor en verbinding
|
||||||
mycursor.close()
|
mycursor.close()
|
||||||
mydb.close()
|
mydb.close()
|
||||||
|
|
||||||
print("Data inserted into the database.")
|
print("Data inserted into the database.")
|
||||||
# Functie voor het aanmaken van gegevens in de database op basis van batterijspanningsinformatie
|
|
||||||
def create_data_from_battery_info(battery_info, repeat_count=5):
|
|
||||||
for _ in range(repeat_count):
|
|
||||||
try:
|
|
||||||
# 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)
|
|
||||||
"""
|
|
||||||
|
|
||||||
mydb = database_connect()
|
|
||||||
if mydb.is_connected():
|
|
||||||
mycursor = mydb.cursor()
|
|
||||||
|
|
||||||
for record in battery_info:
|
|
||||||
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))
|
|
||||||
|
|
||||||
# Controleer of de batterijspanning lager is dan 4.5 volt en geef een melding
|
|
||||||
if float(value) < 3.4:
|
|
||||||
print("Waarschuwing: Batterijspanning is lager dan 3.4 volt. Opladen aanbevolen.")
|
|
||||||
# Controleer of de batterijspanning hoger is dan 4.3 volt en geef een melding
|
|
||||||
elif float(value) > 3.9:
|
|
||||||
print("Melding: Batterijspanning is hoger dan 3.9 volt. Batterij is vol.")
|
|
||||||
|
|
||||||
|
|
||||||
# Bevestig de wijzigingen
|
|
||||||
mydb.commit()
|
|
||||||
|
|
||||||
# Sluit cursor en verbinding
|
# Functie voor het lezen van gegevens uit de database
|
||||||
mycursor.close()
|
|
||||||
mydb.close()
|
|
||||||
|
|
||||||
print("Data inserted into the database.")
|
|
||||||
|
|
||||||
except mysql.connector.Error as e:
|
|
||||||
print(f"Error inserting data into the database: {e}")
|
|
||||||
|
|
||||||
# Wacht een bepaalde tijd (bijv. 1 seconde) voordat de volgende oproep wordt gedaan
|
|
||||||
print("Waiting for the next create action...")
|
|
||||||
time.sleep(1)
|
|
||||||
|
|
||||||
|
|
||||||
# Function for reading data from the database
|
|
||||||
def read_data(url, access_token, repeat_count=5):
|
def read_data(url, access_token, repeat_count=5):
|
||||||
for _ in range(repeat_count):
|
for _ in range(repeat_count):
|
||||||
try:
|
try:
|
||||||
headers = {
|
headers = {"Authorization": f"Token {access_token}"}
|
||||||
"Authorization": f"Token {access_token}"
|
|
||||||
}
|
|
||||||
response = requests.get(url, headers=headers)
|
response = requests.get(url, headers=headers)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
|
|
||||||
data = response.json()
|
data = response.json()
|
||||||
print(f"Data from {url}:")
|
print(f"Data from {url}:\n")
|
||||||
print(data)
|
|
||||||
|
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:
|
except requests.exceptions.RequestException as e:
|
||||||
print(f"Error fetching data from {url}: {e}")
|
print(f"Error fetching data from {url}: {e}")
|
||||||
|
|
||||||
# Wait for a certain time (e.g., 1 second) before making the next API call
|
print("Waiting for the next read action...\n")
|
||||||
print("Waiting for the next read action...")
|
|
||||||
time.sleep(300)
|
time.sleep(300)
|
||||||
|
|
||||||
# Function for updating data in the database
|
# Functie voor het bijwerken van gegevens in de database
|
||||||
def update_data(record_id):
|
def update_data(record_id):
|
||||||
try:
|
try:
|
||||||
mydb = database_connect()
|
mydb = database_connect()
|
||||||
@@ -142,6 +149,7 @@ def update_data(record_id):
|
|||||||
if mydb.is_connected():
|
if mydb.is_connected():
|
||||||
mycursor = mydb.cursor()
|
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,))
|
mycursor.execute("SELECT * FROM goodgarden.battery_voltage_events WHERE id = %s", (record_id,))
|
||||||
existing_record = mycursor.fetchone()
|
existing_record = mycursor.fetchone()
|
||||||
|
|
||||||
@@ -149,22 +157,26 @@ def update_data(record_id):
|
|||||||
print(f"Record with ID {record_id} not found. Update operation aborted.")
|
print(f"Record with ID {record_id} not found. Update operation aborted.")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
# Vraag de gebruiker om nieuwe waarden voor de andere velden
|
||||||
new_timestamp = input("Enter new timestamp: ")
|
new_timestamp = input("Enter new timestamp: ")
|
||||||
new_gateway_receive_time = input("Enter new gateway_receive_time: ")
|
new_gateway_receive_time = input("Enter new gateway_receive_time: ")
|
||||||
new_device = input("Enter new device: ")
|
new_device = input("Enter new device: ")
|
||||||
new_value = input("Enter new value: ")
|
new_value = input("Enter new value: ")
|
||||||
|
|
||||||
|
# Hier moet je de juiste kolomnamen aanpassen op basis van de structuur van je database
|
||||||
update_query = """
|
update_query = """
|
||||||
UPDATE goodgarden.battery_voltage_events
|
UPDATE goodgarden.battery_voltage_events
|
||||||
SET timestamp = %s, gateway_receive_time = %s, device = %s, value = %s
|
SET timestamp = %s, gateway_receive_time = %s, device = %s, value = %s
|
||||||
WHERE id = %s
|
WHERE id = %s
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
# Voer de query uit
|
||||||
print(f"Executing update query: {update_query}")
|
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}")
|
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))
|
mycursor.execute(update_query, (new_timestamp, new_gateway_receive_time, new_device, new_value, record_id))
|
||||||
|
|
||||||
|
# Bevestig de wijzigingen
|
||||||
mydb.commit()
|
mydb.commit()
|
||||||
|
|
||||||
print(f"Update executed. Rowcount: {mycursor.rowcount}")
|
print(f"Update executed. Rowcount: {mycursor.rowcount}")
|
||||||
@@ -172,46 +184,61 @@ def update_data(record_id):
|
|||||||
except mysql.connector.Error as update_err:
|
except mysql.connector.Error as update_err:
|
||||||
print(f"Error updating data: {update_err}")
|
print(f"Error updating data: {update_err}")
|
||||||
finally:
|
finally:
|
||||||
|
# Zorg ervoor dat je altijd de cursor en de databaseverbinding sluit
|
||||||
if 'mycursor' in locals() and mycursor is not None:
|
if 'mycursor' in locals() and mycursor is not None:
|
||||||
mycursor.close()
|
mycursor.close()
|
||||||
if 'mydb' in locals() and mydb.is_connected():
|
if 'mydb' in locals() and mydb.is_connected():
|
||||||
mydb.close()
|
mydb.close()
|
||||||
|
|
||||||
# Function for deleting data from the database
|
# Functie voor het verwijderen van gegevens uit de database
|
||||||
def delete_data(record_id):
|
def delete_data(record_id):
|
||||||
mydb = database_connect()
|
mydb = database_connect()
|
||||||
if mydb.is_connected():
|
if mydb.is_connected():
|
||||||
mycursor = mydb.cursor()
|
mycursor = mydb.cursor()
|
||||||
|
|
||||||
|
# Hier moet je de juiste kolomnamen aanpassen op basis van de structuur van je database
|
||||||
delete_query = """
|
delete_query = """
|
||||||
DELETE FROM goodgarden.battery_voltage_events
|
DELETE FROM goodgarden.battery_voltage_events
|
||||||
WHERE id = %s
|
WHERE id = %s
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
# Voer de query uit
|
||||||
mycursor.execute(delete_query, (record_id,))
|
mycursor.execute(delete_query, (record_id,))
|
||||||
|
|
||||||
|
# Bevestig de wijzigingen
|
||||||
mydb.commit()
|
mydb.commit()
|
||||||
|
|
||||||
|
# Sluit cursor en verbinding
|
||||||
mycursor.close()
|
mycursor.close()
|
||||||
mydb.close()
|
mydb.close()
|
||||||
|
|
||||||
print(f"Data with ID {record_id} deleted.")
|
print(f"Data with ID {record_id} deleted.")
|
||||||
|
|
||||||
|
# Functie voor het aanmaken van gegevens in de database op basis van batterijspanningsinformatie
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
url = "https://garden.inajar.nl/api/battery_voltage_events/?format=json"
|
url = "https://garden.inajar.nl/api/battery_voltage_events/?format=json"
|
||||||
access_token = "33bb3b42452306c58ecedc3c86cfae28ba22329c" # Replace this with your actual access token
|
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
|
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()
|
operation_choice = input("Choose operation (C for Create, R for Read, U for Update, D for Delete): ").upper()
|
||||||
|
|
||||||
if operation_choice == "C":
|
if operation_choice == "C":
|
||||||
create_data_from_api(url, access_token, repeat_count)
|
# Maak gegevens aan
|
||||||
|
create_data(url, access_token, repeat_count)
|
||||||
elif operation_choice == "R":
|
elif operation_choice == "R":
|
||||||
|
# Lees gegevens
|
||||||
read_data(url, access_token, repeat_count)
|
read_data(url, access_token, repeat_count)
|
||||||
elif operation_choice == "U":
|
elif operation_choice == "U":
|
||||||
|
# Update gegevens
|
||||||
record_id = int(input("Enter record ID to update: "))
|
record_id = int(input("Enter record ID to update: "))
|
||||||
|
# Call the update_data function without additional arguments
|
||||||
update_data(record_id)
|
update_data(record_id)
|
||||||
elif operation_choice == "D":
|
elif operation_choice == "D":
|
||||||
|
# Verwijder gegevens
|
||||||
record_id = int(input("Enter record ID to delete: "))
|
record_id = int(input("Enter record ID to delete: "))
|
||||||
delete_data(record_id)
|
delete_data(record_id)
|
||||||
else:
|
else:
|
||||||
|
|||||||
74
servermqtt.py
Normal file
74
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()
|
||||||
Reference in New Issue
Block a user