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

147 lines
6.6 KiB
Python
Raw 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
from datetime import datetime
# Конфигурация файла базы данных 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:temp1_low:GAUGE:120:-40:100", # Температура устройства 1 (нижняя)
"DS:temp1_top:GAUGE:120:-40:100", # Температура устройства 1 (верхняя)
"DS:temp2_low:GAUGE:120:-40:100", # Температура устройства 2 (нижняя)
"DS:temp2_top:GAUGE:120:-40:100", # Температура устройства 2 (верхняя)
"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, temp1_low: float, temp1_top: float, temp2_low: float, temp2_top: float):
timestamp = int(time.time())
human_readable_time = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
try:
rrdtool.update(rrd_file, f"{timestamp}:{temp1_low}:{temp1_top}:{temp2_low}:{temp2_top}")
print(f"Data update: Time: {human_readable_time}, Device 1: Down {temp1_low}, Up {temp1_top}, Device 2: Down {temp2_low}, Up {temp2_top}")
except Exception as e:
print(f"Ошибка обновления базы данных RRD: {e}")
# Получение токена OwenCloud
def get_token():
login = os.getenv("LOGIN")
password = os.getenv("PASSWORD")
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 get_last_update_time(device_id, headers):
req = requests.post(f"https://api.owencloud.ru/v1/device/last-dates/{device_id}", headers=headers)
if req.status_code != 200:
print(f"Ошибка получения времени обновления устройства {device_id}: {req.status_code}, {req.text}")
return None
response = req.json()
return int(response.get("last_dt", 0))
# Получение температуры устройства
def get_device_temperature(device_id, headers):
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"Ошибка запроса устройства {device_id}: {req.status_code}, {req.text}")
return None, None
nswer = req.json()
if "parameters" not in nswer:
print(f"Не удалось найти параметры для устройства {device_id}.")
return None, None
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 (ВЕРХ)")
temp_low = float(temperature_1['value'])
temp_top = float(temperature_2['value'])
return temp_low, temp_top
except StopIteration:
print(f"Не удалось найти параметры температуры для устройства {device_id}.")
return None, None
# Основная функция
def main():
initialize_rrd_database(rrd_file) # Инициализируем RRD базу данных
while True: # Бесконечный цикл для записи данных каждую минуту
token = get_token()
if not token:
print("Не удалось получить токен. Пропускаем итерацию.")
time.sleep(60)
continue
headers = {'Authorization': token}
# Устройства для мониторинга
devices = {
"296613": "Device 1",
"278575": "Device 2"
}
# Проверяем данные для каждого устройства
all_temps = {}
for device_id, device_name in devices.items():
last_update_time = get_last_update_time(device_id, headers)
if last_update_time is None:
print(f"Не удалось получить время обновления для {device_name}. Пропускаем.")
continue
current_time = int(time.time())
if current_time - last_update_time > 300: # Разница больше 5 минут
print(f"⚠️ {device_name}: данные не обновлялись более 5 минут.")
continue
temp_low, temp_top = get_device_temperature(device_id, headers)
if temp_low is None or temp_top is None:
print(f"Ошибка получения температур для {device_name}. Пропускаем.")
continue
all_temps[device_id] = (temp_low, temp_top)
# Если у нас есть данные от обоих устройств, обновляем RRD
if "296613" in all_temps and "278575" in all_temps:
temp1_low, temp1_top = all_temps["296613"]
temp2_low, temp2_top = all_temps["278575"]
try:
update_rrd_database(rrd_file, temp1_low, temp1_top, temp2_low, temp2_top)
except Exception as e:
print(f"Ошибка обновления RRD: {e}")
# Ждем минуту перед следующей итерацией
time.sleep(60)
if __name__ == "__main__":
main()