owen-script/vodynoi/pars_graph_old.py
2024-12-22 00:17:37 +03:00

109 lines
4.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import requests
import json
import os
import time
import rrdtool
from dotenv import load_dotenv
# Конфигурация файла базы данных RRD
rrd_file = "temperature_data.rrd"
load_dotenv()
# Функция для инициализации базы данных RRDTool
def initialize_rrd_database(rrd_file: str):
if not os.path.exists(rrd_file):
rrdtool.create(
rrd_file,
"--step", "60", # Шаг в 60 секунд
"DS:temp_low:GAUGE:120:-40:100", # Источник данных: нижняя температура
"DS:temp_high:GAUGE:120:-40:100", # Источник данных: верхняя температура
"RRA:AVERAGE:0.5:1:1440", # Средние значения с шагом 1 минута за сутки
"RRA:AVERAGE:0.5:60:720" # Средние значения с шагом 1 час за месяц
)
print(f"Создана база данных: {rrd_file}")
else:
print(f"База данных уже существует: {rrd_file}")
# Функция обновления базы данных RRDTool
def update_rrd_database(rrd_file: str, temp_low: float, temp_high: float):
timestamp = int(time.time())
try:
rrdtool.update(rrd_file, f"{timestamp}:{temp_low}:{temp_high}")
print(f"Data update: Time: {timestamp}, down {temp_low}, Up {temp_high}")
except Exception as e:
print(f"Ошибка обновления базы данных RRD: {e}")
# Получение токена OwenCloud
def get_token():
login = os.getenv("LOGIN")
password = os.getenv("PASSWORD")
if not login or not password:
raise ValueError("Логин или пароль не заданы в .env")
data = {'login': login, 'password': password}
headers = {
"Content-Type": "application/json",
"Accept": "application/json"
}
req = requests.post("https://api.owencloud.ru/v1/auth/open/", json=data, headers=headers)
if req.status_code == 200:
answer = req.json()
token = "Bearer " + answer["token"]
return token
else:
print(f"Ошибка авторизации: {req.status_code}, {req.text}")
return None
# Основная функция
def main():
initialize_rrd_database(rrd_file) # Инициализируем RRD базу данных
while True: # Бесконечный цикл для записи данных каждую минуту
token = get_token()
if not token:
print("Не удалось получить токен. Пропускаем итерацию.")
time.sleep(60) # Ждем минуту и пробуем снова
continue
device_id = "296613"
headers = {'Authorization': token}
data = json.dumps({'filter': ''})
req = requests.post(f"https://api.owencloud.ru/v1/device/{device_id}", data=data, headers=headers)
if req.status_code != 200:
print(f"Ошибка запроса устройства: {req.status_code}, {req.text}")
time.sleep(60)
continue
nswer = req.json()
if "parameters" not in nswer:
print("Не удалось найти параметры в ответе.")
time.sleep(60)
continue
parameters = nswer['parameters']
# Извлечение температуры
try:
temperature_1 = next(param for param in parameters if param['name'] == "Температура_1 (НИЗ)")
temperature_2 = next(param for param in parameters if param['name'] == "Температура_2 (ВЕРХ)")
except StopIteration:
print("Не удалось найти необходимые параметры.")
time.sleep(60)
continue
temp_low = float(temperature_1['value'])
temp_high = float(temperature_2['value'])
# Обновление базы данных RRDTool
try:
update_rrd_database(rrd_file, temp_low, temp_high)
except Exception as e:
print(f"Error with RRDTool: {e}")
# Ждем минуту перед следующей итерацией
time.sleep(60)
if __name__ == "__main__":
main()