Gen table via rrdtool and push to tg how photo
This commit is contained in:
parent
7a4d80e140
commit
fa34df53e4
6 changed files with 181 additions and 1 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -19,3 +19,4 @@ pyvenv.cfg
|
|||
share/
|
||||
kaluga/lib64
|
||||
*/*.xlsx
|
||||
*/*.rrd
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
,q,q,26.11.2024 20:34,file:///home/q/.config/libreoffice/4;
|
||||
9
vodynoi/create_rrd-bd.sh
Executable file
9
vodynoi/create_rrd-bd.sh
Executable file
|
|
@ -0,0 +1,9 @@
|
|||
#!/bin/bash
|
||||
rrdtool create temperature_data.rrd \
|
||||
--step 60 \
|
||||
DS:temp_low:GAUGE:120:-40:100 \
|
||||
DS:temp_high:GAUGE:120:-40:100 \
|
||||
RRA:AVERAGE:0.5:1:1440 \
|
||||
RRA:AVERAGE:0.5:60:720 \
|
||||
RRA:MAX:0.5:60:720 \
|
||||
RRA:MIN:0.5:60:720
|
||||
62
vodynoi/gen_graph.py
Normal file
62
vodynoi/gen_graph.py
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import rrdtool
|
||||
import time
|
||||
import requests
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
load_dotenv()
|
||||
|
||||
def send_telegram():
|
||||
token = os.getenv("TELEGRAM_TOKEN")
|
||||
channel_id = os.getenv("TELEGRAM_CHANNEL_ID")
|
||||
if not token or not channel_id:
|
||||
raise ValueError("Telegram токен или ID канала не заданы в .env")
|
||||
|
||||
url = f"https://api.telegram.org/bot{token}/sendPhoto"
|
||||
with open('temperature_graph.png', 'rb') as file:
|
||||
r = requests.post(url, data={
|
||||
"chat_id": channel_id
|
||||
}, files={
|
||||
"photo": file
|
||||
})
|
||||
print(r.text)
|
||||
if r.status_code != 200:
|
||||
raise Exception(f"Ошибка отправки в Telegram: {r.text}")
|
||||
|
||||
def create_graph(rrd_file: str, output_file: str):
|
||||
# Получаем текущее время
|
||||
now = int(time.time())
|
||||
# Время начала (24 часа назад)
|
||||
start_time = now - 86400 # 86400 секунд = 1 день
|
||||
|
||||
# Форматируем даты для заголовка
|
||||
start_date = time.strftime("%d-%m-%Y", time.localtime(start_time))
|
||||
end_date = time.strftime("%d-%m-%Y", time.localtime(now))
|
||||
|
||||
try:
|
||||
rrdtool.graph(
|
||||
output_file,
|
||||
"--start", str(start_time), # Начало графика
|
||||
"--end", str(now), # Конец графика
|
||||
"--vertical-label", "Temperature (°C)",
|
||||
"--title", f"Temperature Readings from {start_date} to {end_date}",
|
||||
"DEF:low_temp={}:temp_low:AVERAGE".format(rrd_file), # Средние значения нижней температуры
|
||||
"DEF:high_temp={}:temp_high:AVERAGE".format(rrd_file), # Средние значения верхней температуры
|
||||
"LINE1:low_temp#0000FF:Low Temperature", # Линия для нижней температуры (синий)
|
||||
"LINE1:high_temp#FF0000:High Temperature", # Линия для верхней температуры (красный)
|
||||
r"GPRINT:low_temp:MIN:Min Low Temp\: %2.2lf°C",
|
||||
r"GPRINT:low_temp:MAX:Max Low Temp\: %2.2lf°C",
|
||||
r"GPRINT:low_temp:AVERAGE:Avg Low Temp\: %2.2lf°C\n",
|
||||
r"GPRINT:high_temp:MIN:Min High Temp\: %2.2lf°C",
|
||||
r"GPRINT:high_temp:MAX:Max High Temp\: %2.2lf°C",
|
||||
r"GPRINT:high_temp:AVERAGE:Avg High Temp\: %2.2lf°C\n",
|
||||
)
|
||||
print(f"График успешно создан: {output_file}")
|
||||
send_telegram()
|
||||
|
||||
except Exception as e:
|
||||
print(f"Ошибка создания графика: {e}")
|
||||
|
||||
# Пример использования
|
||||
rrd_file = "temperature_data.rrd"
|
||||
output_file = "temperature_graph.png"
|
||||
create_graph(rrd_file, output_file)
|
||||
109
vodynoi/pars_graph.py
Normal file
109
vodynoi/pars_graph.py
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
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()
|
||||
BIN
vodynoi/temperature_graph.png
Normal file
BIN
vodynoi/temperature_graph.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
Loading…
Reference in a new issue