Gen graph and upload
This commit is contained in:
parent
fa34df53e4
commit
b74d0d9dbf
5 changed files with 194 additions and 20 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -20,3 +20,4 @@ share/
|
||||||
kaluga/lib64
|
kaluga/lib64
|
||||||
*/*.xlsx
|
*/*.xlsx
|
||||||
*/*.rrd
|
*/*.rrd
|
||||||
|
*/*xlsx#
|
||||||
|
|
|
||||||
|
|
@ -3,18 +3,26 @@ import time
|
||||||
import requests
|
import requests
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
import os
|
import os
|
||||||
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
||||||
def send_telegram():
|
def send_telegram(min_temp, min_time, max_temp, max_time):
|
||||||
token = os.getenv("TELEGRAM_TOKEN")
|
token = os.getenv("TELEGRAM_TOKEN")
|
||||||
channel_id = os.getenv("TELEGRAM_CHANNEL_ID")
|
channel_id = os.getenv("TELEGRAM_CHANNEL_ID")
|
||||||
if not token or not channel_id:
|
if not token or not channel_id:
|
||||||
raise ValueError("Telegram токен или ID канала не заданы в .env")
|
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"
|
url = f"https://api.telegram.org/bot{token}/sendPhoto"
|
||||||
with open('temperature_graph.png', 'rb') as file:
|
with open('temperature_graph.png', 'rb') as file:
|
||||||
r = requests.post(url, data={
|
r = requests.post(url, data={
|
||||||
"chat_id": channel_id
|
"chat_id": channel_id,
|
||||||
|
"caption": comment # Текст комментария
|
||||||
}, files={
|
}, files={
|
||||||
"photo": file
|
"photo": file
|
||||||
})
|
})
|
||||||
|
|
@ -22,40 +30,82 @@ def send_telegram():
|
||||||
if r.status_code != 200:
|
if r.status_code != 200:
|
||||||
raise Exception(f"Ошибка отправки в Telegram: {r.text}")
|
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):
|
def create_graph(rrd_file: str, output_file: str):
|
||||||
# Получаем текущее время
|
# Получаем текущее время
|
||||||
now = int(time.time())
|
now = int(time.time())
|
||||||
# Время начала (24 часа назад)
|
start_time = now - 86400 # 24 часа назад
|
||||||
start_time = now - 86400 # 86400 секунд = 1 день
|
|
||||||
|
|
||||||
# Форматируем даты для заголовка
|
|
||||||
start_date = time.strftime("%d-%m-%Y", time.localtime(start_time))
|
start_date = time.strftime("%d-%m-%Y", time.localtime(start_time))
|
||||||
end_date = time.strftime("%d-%m-%Y", time.localtime(now))
|
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:
|
try:
|
||||||
rrdtool.graph(
|
rrdtool.graph(
|
||||||
output_file,
|
output_file,
|
||||||
"--start", str(start_time), # Начало графика
|
"--start", str(start_time),
|
||||||
"--end", str(now), # Конец графика
|
"--end", str(now),
|
||||||
|
"--title", f"Temperature from {start_date} to {end_date}",
|
||||||
"--vertical-label", "Temperature (°C)",
|
"--vertical-label", "Temperature (°C)",
|
||||||
"--title", f"Temperature Readings from {start_date} to {end_date}",
|
"--width", "800",
|
||||||
"DEF:low_temp={}:temp_low:AVERAGE".format(rrd_file), # Средние значения нижней температуры
|
"--height", "400",
|
||||||
"DEF:high_temp={}:temp_high:AVERAGE".format(rrd_file), # Средние значения верхней температуры
|
# Определение данных
|
||||||
"LINE1:low_temp#0000FF:Low Temperature", # Линия для нижней температуры (синий)
|
"DEF:low_temp={}:temp_low:AVERAGE".format(rrd_file),
|
||||||
"LINE1:high_temp#FF0000:High Temperature", # Линия для верхней температуры (красный)
|
"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:MIN:Min Low Temp\: %2.2lf°C",
|
||||||
r"GPRINT:low_temp:MAX:Max Low Temp\: %2.2lf°C",
|
"COMMENT: \\n",
|
||||||
r"GPRINT:low_temp:AVERAGE:Avg Low Temp\: %2.2lf°C\n",
|
r"GPRINT:high_temp:MAX:Max Top Temp\: %2.2lf°C",
|
||||||
r"GPRINT:high_temp:MIN:Min High Temp\: %2.2lf°C",
|
"COMMENT: \\n",
|
||||||
r"GPRINT:high_temp:MAX:Max High Temp\: %2.2lf°C",
|
r"GPRINT:low_temp:AVERAGE:Avg Low Temp\: %2.2lf°C",
|
||||||
r"GPRINT:high_temp:AVERAGE:Avg High Temp\: %2.2lf°C\n",
|
"COMMENT: \\n",
|
||||||
|
r"GPRINT:high_temp:AVERAGE:Avg Top Temp\: %2.2lf°C"
|
||||||
)
|
)
|
||||||
print(f"График успешно создан: {output_file}")
|
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:
|
except Exception as e:
|
||||||
print(f"Ошибка создания графика: {e}")
|
print(f"Ошибка создания графика: {e}")
|
||||||
|
|
||||||
|
|
||||||
# Пример использования
|
# Пример использования
|
||||||
rrd_file = "temperature_data.rrd"
|
rrd_file = "temperature_data.rrd"
|
||||||
output_file = "temperature_graph.png"
|
output_file = "temperature_graph.png"
|
||||||
|
|
|
||||||
41
vodynoi/local_gen_graph.py
Normal file
41
vodynoi/local_gen_graph.py
Normal 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
82
vodynoi/test.py
Normal 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)
|
||||||
Loading…
Reference in a new issue