Gen graph and upload

This commit is contained in:
q00 2024-12-01 16:52:34 +03:00
parent fa34df53e4
commit b74d0d9dbf
5 changed files with 194 additions and 20 deletions

1
.gitignore vendored
View file

@ -20,3 +20,4 @@ share/
kaluga/lib64
*/*.xlsx
*/*.rrd
*/*xlsx#

View file

@ -3,18 +3,26 @@ import time
import requests
from dotenv import load_dotenv
import os
load_dotenv()
def send_telegram():
def send_telegram(min_temp, min_time, max_temp, max_time):
token = os.getenv("TELEGRAM_TOKEN")
channel_id = os.getenv("TELEGRAM_CHANNEL_ID")
if not token or not channel_id:
raise ValueError("Telegram токен или ID канала не заданы в .env")
# Форматируем текст комментария
comment = (
f"Min Temp: {min_temp:.2f}°C at {min_time}\n"
f"Max Temp: {max_temp:.2f}°C at {max_time}"
)
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
"chat_id": channel_id,
"caption": comment # Текст комментария
}, files={
"photo": file
})
@ -22,40 +30,82 @@ def send_telegram():
if r.status_code != 200:
raise Exception(f"Ошибка отправки в Telegram: {r.text}")
def get_extreme_timestamps(rrd_file: str, start_time: int, end_time: int):
# Извлекаем данные из RRD-файла
info = rrdtool.fetch(rrd_file, 'AVERAGE', '--start', str(start_time), '--end', str(end_time))
data = info[2] # Сырые данные
timestamps = range(info[0][0], info[0][1], info[0][2]) # Генерация временных меток
# Поиск минимального и максимального значений
min_low_temp, max_high_temp = float('inf'), float('-inf')
min_low_time, max_high_time = None, None
for idx, row in enumerate(data):
if row[0] is not None: # Проверяем, что данные не отсутствуют
if row[0] < min_low_temp:
min_low_temp = row[0]
min_low_time = timestamps[idx]
if row[1] is not None and row[1] > max_high_temp:
max_high_temp = row[1]
max_high_time = timestamps[idx]
return min_low_temp, min_low_time, max_high_temp, max_high_time
def create_graph(rrd_file: str, output_file: str):
# Получаем текущее время
now = int(time.time())
# Время начала (24 часа назад)
start_time = now - 86400 # 86400 секунд = 1 день
# Форматируем даты для заголовка
start_time = now - 86400 # 24 часа назад
start_date = time.strftime("%d-%m-%Y", time.localtime(start_time))
end_date = time.strftime("%d-%m-%Y", time.localtime(now))
# Получаем минимальные и максимальные значения с временными метками
min_low_temp, min_low_time, max_high_temp, max_high_time = get_extreme_timestamps(rrd_file, start_time, now)
# Форматирование времени
min_low_time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(min_low_time))
max_high_time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(max_high_time))
# Вывод значений в терминал
print(f"\033[32m{'Min Temp:':<20}\033[0m{min_low_temp:>10.2f}°C at {min_low_time_str}")
print(f"\033[31m{'Max Temp:':<20}\033[0m{max_high_temp:>10.2f}°C at {max_high_time_str}")
try:
rrdtool.graph(
output_file,
"--start", str(start_time), # Начало графика
"--end", str(now), # Конец графика
"--start", str(start_time),
"--end", str(now),
"--title", f"Temperature from {start_date} to {end_date}",
"--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", # Линия для верхней температуры (красный)
"--width", "800",
"--height", "400",
# Определение данных
"DEF:low_temp={}:temp_low:AVERAGE".format(rrd_file),
"DEF:high_temp={}:temp_high:AVERAGE".format(rrd_file),
# Линии графика
"LINE1:low_temp#0000FF:Low Temperature",
"LINE2:high_temp#FF0000:Top Temperature",
# Вертикальные линии для экстремумов
f"VRULE:{min_low_time}#00FF00:Min Temp Time",
f"VRULE:{max_high_time}#FF0000:Max Temp Time",
# Подписи
"COMMENT: \\n",
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",
"COMMENT: \\n",
r"GPRINT:high_temp:MAX:Max Top Temp\: %2.2lf°C",
"COMMENT: \\n",
r"GPRINT:low_temp:AVERAGE:Avg Low Temp\: %2.2lf°C",
"COMMENT: \\n",
r"GPRINT:high_temp:AVERAGE:Avg Top Temp\: %2.2lf°C"
)
print(f"График успешно создан: {output_file}")
send_telegram()
send_telegram(min_low_temp, min_low_time_str, max_high_temp, max_high_time_str)
except Exception as e:
print(f"Ошибка создания графика: {e}")
# Пример использования
rrd_file = "temperature_data.rrd"
output_file = "temperature_graph.png"

View file

@ -0,0 +1,41 @@
import rrdtool
import time
import requests
import os
def create_graph(rrd_file: str, output_file: str):
# Получаем текущее время
now = int(time.time())
start_time = now - 86400 # 24 часа назад
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),
"--title", f"Temperature from {start_date} to {end_date}",
"--vertical-label", "Temperature (°C)",
"--width", "800",
"--height", "400",
"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:Top Temperature",
r"GPRINT:low_temp:MIN:Min Low Temp\: %2.2lf°C",
r"GPRINT:high_temp:MAX:Max Top Temp\: %2.2lf°C",
r"GPRINT:low_temp:AVERAGE:Avg Low Temp\: %2.2lf°C",
r"GPRINT:high_temp:AVERAGE:Avg Top Temp\: %2.2lf°C",
)
print(f"График успешно создан: {output_file}")
except Exception as e:
print(f"Ошибка создания графика: {e}")
except Exception as e:
print(f"Ошибка создания графика: {e}")
# Пример использования
rrd_file = "temperature_data.rrd"
output_file = "temperature_graph.png"
create_graph(rrd_file, output_file)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 40 KiB

82
vodynoi/test.py Normal file
View file

@ -0,0 +1,82 @@
import rrdtool
import time
import requests
import os
def get_extreme_timestamps(rrd_file: str, start_time: int, end_time: int):
# Извлекаем данные из RRD-файла
info = rrdtool.fetch(rrd_file, 'AVERAGE', '--start', str(start_time), '--end', str(end_time))
data = info[2] # Сырые данные
timestamps = range(info[0][0], info[0][1], info[0][2]) # Генерация временных меток
# Поиск минимального и максимального значений
min_low_temp, max_high_temp = float('inf'), float('-inf')
min_low_time, max_high_time = None, None
for idx, row in enumerate(data):
if row[0] is not None: # Проверяем, что данные не отсутствуют
if row[0] < min_low_temp:
min_low_temp = row[0]
min_low_time = timestamps[idx]
if row[1] is not None and row[1] > max_high_temp:
max_high_temp = row[1]
max_high_time = timestamps[idx]
return min_low_temp, min_low_time, max_high_temp, max_high_time
def create_graph(rrd_file: str, output_file: str):
# Получаем текущее время
now = int(time.time())
start_time = now - 86400 # 24 часа назад
start_date = time.strftime("%d-%m-%Y", time.localtime(start_time))
end_date = time.strftime("%d-%m-%Y", time.localtime(now))
# Получаем минимальные и максимальные значения с временными метками
min_low_temp, min_low_time, max_high_temp, max_high_time = get_extreme_timestamps(rrd_file, start_time, now)
# Форматирование времени для терминала
min_low_time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(min_low_time))
max_high_time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(max_high_time))
# Вывод значений в терминал
print(f"\033[32m{'Min Temp:':<20}\033[0m{min_low_temp:>10.2f}°C at {min_low_time_str}")
print(f"\033[31m{'Max Temp:':<20}\033[0m{max_high_temp:>10.2f}°C at {max_high_time_str}")
try:
rrdtool.graph(
output_file,
"--start", str(start_time),
"--end", str(now),
"--title", f"Temperature from {start_date} to {end_date}",
"--vertical-label", "Temperature (°C)",
"--width", "800",
"--height", "400",
# Определение данных
"DEF:low_temp={}:temp_low:AVERAGE".format(rrd_file),
"DEF:high_temp={}:temp_high:AVERAGE".format(rrd_file),
# Линии графика
"LINE1:low_temp#0000FF:Low Temperature",
"LINE2:high_temp#FF0000:Top Temperature",
# Вертикальные линии для экстремумов
f"VRULE:{min_low_time}#00FF00:Min Temp Time",
f"VRULE:{max_high_time}#FF0000:Max Temp Time",
# Подписи
"COMMENT: \\n",
r"GPRINT:low_temp:MIN:Min Low Temp\: %2.2lf°C",
"COMMENT: \\n",
r"GPRINT:high_temp:MAX:Max Top Temp\: %2.2lf°C",
"COMMENT: \\n",
r"GPRINT:low_temp:AVERAGE:Avg Low Temp\: %2.2lf°C",
"COMMENT: \\n",
r"GPRINT:high_temp:AVERAGE:Avg Top Temp\: %2.2lf°C"
)
print(f"График успешно создан: {output_file}")
except Exception as e:
print(f"Ошибка создания графика: {e}")
rrd_file = "temperature_data.rrd"
output_file = "temperature_graph.png"
create_graph(rrd_file, output_file)