Clean versie mqtt

This commit is contained in:
Atilla
2024-03-12 19:56:49 +01:00
parent af6c0ba971
commit 925f73469b
14 changed files with 513 additions and 584 deletions

View File

@@ -1,64 +1,24 @@
import requests
import time
import sys
import uuid
from db_connect import database_connect
from os.path import dirname, abspath, join
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()
root_dir = dirname(dirname(abspath(__file__)))
sys.path.append(root_dir)
data = response.json()
print(f"Data from {url}:")
print(data)
load_data(data)
from mqtt.mqtt_client import create_client, start_loop
except requests.exceptions.RequestException as e:
print(f"Error fetching data from {url}: {e}")
mqtt_topic = "goodgarden/par_events"
print("Waiting for the next retrieval action...")
def on_connect(client, userdata, flags, rc):
client.subscribe(mqtt_topic)
print(f"Subscribed to {mqtt_topic}")
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.")
def on_message(client, userdata, msg):
message = msg.payload.decode()
print(f"Message received on topic {msg.topic}: {message}")
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)
unique_client_id = f"subscriber_{uuid.uuid4()}"
client = create_client(unique_client_id, on_connect, on_message)
start_loop(client)