Compare commits

...

7 Commits

Author SHA1 Message Date
Maxim
9bbcd67065 Корректировка последовательности логов 2026-06-18 14:16:11 +03:00
Maxim
627c18c2b3 Инфентировал страницы логи и стили добавил 2026-06-18 13:38:17 +03:00
Maxim
e92c7d8f09 Шрифты 2026-06-18 11:27:03 +03:00
Maxim
fd627257f5 Рефактор 2026-06-18 11:01:56 +03:00
Maxim
35caa2bb72 Доработка Пагинации в логи 2026-06-18 11:01:39 +03:00
Maxim
0cea7d5e9d Рефактор 2026-06-18 10:39:34 +03:00
Maxim
ec16f2467f Добавление makefile 2026-06-18 09:53:31 +03:00
30 changed files with 2879 additions and 1639 deletions

1
.gitignore vendored
View File

@@ -28,6 +28,7 @@ vendor/
# Зависимости node_modules
node_modules/
dist/
package-lock.json
yarn.lock
pnpm-lock.yaml

159
Makefile Normal file
View File

@@ -0,0 +1,159 @@
# Makefile для GPIO Monitor Server
.PHONY: all build clean run test fmt lint help install dev
# Переменные
APP_NAME := gpio-monitor-server
CMD_PATH := ./cmd/server
BUILD_DIR := ./build
BINARY := $(BUILD_DIR)/$(APP_NAME)
WEB_DIR := ./cmd/server/web
# Целевая платформа (по умолчанию)
GOOS ?= linux
GOARCH ?= arm64
# Флаги сборки
LDFLAGS := -ldflags="-s -w"
# Цвета для вывода
RED := \033[0;31m
GREEN := \033[0;32m
YELLOW := \033[0;33m
NC := \033[0m # No Color
# ============================================
# ОСНОВНЫЕ ЦЕЛИ
# ============================================
all: help
## build - Полная сборка проекта (фронтенд + бекенд)
build: build-frontend build-backend
@echo "$(GREEN)Сборка завершена!$(NC)"
@ls -lh $(BINARY)
## build-frontend - Сборка TypeScript фронтенда
build-frontend:
@echo "$(YELLOW)Сборка TypeScript фронтенда...$(NC)"
@cd $(WEB_DIR) && \
if [ ! -d "node_modules" ]; then \
echo " Установка npm зависимостей..."; \
npm install; \
fi && \
echo " Компиляция TypeScript..." && \
npm run build && \
echo "$(GREEN) TypeScript скомпилирован успешно!$(NC)"
## build-backend - Сборка Go сервера
build-backend:
@echo "$(YELLOW)🔧 Сборка Go сервера...$(NC)"
@mkdir -p $(BUILD_DIR)
@echo " Целевая платформа: $(GOOS)/$(GOARCH)"
@GOOS=$(GOOS) GOARCH=$(GOARCH) go build $(LDFLAGS) -o $(BINARY) $(CMD_PATH)
@echo "$(GREEN) Go сервер скомпилирован успешно!$(NC)"
## run - Запуск сервера (сборка + запуск)
run: build
@echo "$(YELLOW)Запуск сервера...$(NC)"
@$(BINARY)
## dev - Режим разработки (без оптимизации, с hot-reload)
dev:
@echo "$(YELLOW) Режим разработки...$(NC)"
@go run $(CMD_PATH) -port :8080
## clean - Очистка артефактов сборки
clean:
@echo "$(YELLOW)Очистка...$(NC)"
@rm -rf $(BUILD_DIR)
@rm -rf $(WEB_DIR)/dist
@rm -rf $(WEB_DIR)/node_modules
@echo "$(GREEN) Очищено$(NC)"
## test - Запуск тестов
test:
@echo "$(YELLOW)Запуск тестов...$(NC)"
@go test -v ./...
## fmt - Форматирование кода
fmt:
@echo "$(YELLOW) Форматирование кода...$(NC)"
@go fmt ./...
@cd $(WEB_DIR) && npm run format 2>/dev/null || true
## lint - Проверка кода
lint:
@echo "$(YELLOW) Проверка кода...$(NC)"
@golangci-lint run ./... 2>/dev/null || echo " Установите golangci-lint: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest"
## deps - Установка зависимостей
deps:
@echo "$(YELLOW) Установка зависимостей...$(NC)"
@go mod download
@go mod tidy
@cd $(WEB_DIR) && npm install
## install - Установка бинарника в систему
install: build
@echo "$(YELLOW)Установка $(APP_NAME)...$(NC)"
@sudo cp $(BINARY) /usr/local/bin/$(APP_NAME)
@echo "$(GREEN) Установлено в /usr/local/bin/$(APP_NAME)$(NC)"
## uninstall - Удаление из системы
uninstall:
@echo "$(YELLOW)Удаление $(APP_NAME)...$(NC)"
@sudo rm -f /usr/local/bin/$(APP_NAME)
@echo "$(GREEN)Удалено$(NC)"
## help - Показать справку
help:
@echo "$(GREEN)GPIO Monitor Server - команды Makefile$(NC)"
@echo ""
@echo "Доступные команды:"
@awk '/^##/ { \
cmd = $$0; \
gsub(/^## /, "", cmd); \
printf " $(GREEN)%-20s$(NC) %s\n", $$2, cmd \
}' $(MAKEFILE_LIST) | sort
@echo ""
@echo "Примеры:"
@echo " make build - Полная сборка"
@echo " make run - Сборка и запуск"
@echo " make dev - Запуск в режиме разработки"
@echo " make clean - Очистка"
@echo " make install - Установка в систему"
# ============================================
# ДОПОЛНИТЕЛЬНЫЕ ЦЕЛИ
# ============================================
## build-arm64 - Сборка для ARM64 (Raspberry Pi)
build-arm64:
@$(MAKE) build GOOS=linux GOARCH=arm64
## build-amd64 - Сборка для AMD64
build-amd64:
@$(MAKE) build GOOS=linux GOARCH=amd64
## build-mac - Сборка для macOS
build-mac:
@$(MAKE) build GOOS=darwin GOARCH=amd64
## build-windows - Сборка для Windows
build-windows:
@$(MAKE) build GOOS=windows GOARCH=amd64
## build-all - Сборка для всех платформ
build-all: build-arm64 build-amd64 build-mac build-windows
@echo "$(GREEN)Все платформы собраны$(NC)"
## docker-build - Сборка Docker образа
docker-build:
@echo "$(YELLOW)Сборка Docker образа...$(NC)"
@docker build -t gpio-monitor:latest .
## docker-run - Запуск в Docker
docker-run:
@echo "$(YELLOW)Запуск в Docker...$(NC)"
@docker run -p 8080:8080 gpio-monitor:latest

View File

@@ -24,10 +24,10 @@ echo " Компиляция TypeScript в JavaScript..."
npm run build
if [ -d "dist" ]; then
echo " TypeScript скомпилирован успешно!"
echo " 📁 Скомпилированные файлы: $(ls dist/ | wc -l) файлов"
echo " TypeScript скомпилирован успешно!"
echo " Скомпилированные файлы: $(ls dist/ | wc -l) файлов"
else
echo " Ошибка: папка dist не создана!"
echo " Ошибка: папка dist не создана!"
exit 1
fi
@@ -53,9 +53,9 @@ GOOS=linux GOARCH=arm64 go build -o ${BUILD_DIR}/${APP_NAME} ${CMD_PATH}
# Проверяем успешность сборки
if [ -f "${BUILD_DIR}/${APP_NAME}" ]; then
echo " Go сервер скомпилирован успешно!"
echo " Go сервер скомпилирован успешно!"
else
echo " Ошибка компиляции Go сервера!"
echo " Ошибка компиляции Go сервера!"
exit 1
fi
@@ -70,15 +70,15 @@ echo " Размер бинарного файла: ${SIZE}"
# Проверяем наличие embed файлов
echo " Проверка встроенных файлов..."
if [ -d "cmd/server/web/dist" ]; then
echo " TypeScript файлы (dist) включены в сборку"
echo " TypeScript файлы (dist) включены в сборку"
fi
if [ -d "cmd/server/web/css" ]; then
echo " CSS файлы включены в сборку"
echo " CSS файлы включены в сборку"
fi
if [ -f "cmd/server/web/dashboard.html" ]; then
echo " HTML файлы включены в сборку"
echo " HTML файлы включены в сборку"
fi
echo "СБОРКА ЗАВЕРШЕНА!"

View File

@@ -96,7 +96,7 @@ func (a *API) HandleLogFiles(w http.ResponseWriter, r *http.Request) {
})
}
// Сортируем по времени (новые сверху)
// Сортируем по времени
sort.Slice(result, func(i, j int) bool {
return result[i].ModTime.After(result[j].ModTime)
})
@@ -104,60 +104,121 @@ func (a *API) HandleLogFiles(w http.ResponseWriter, r *http.Request) {
writeJSON(w, result)
}
// HandleLogEvents - чтение событий
// HandleLogEvents - чтение событий с пагинацией
func (a *API) HandleLogEvents(w http.ResponseWriter, r *http.Request) {
limit := 100
if l := r.URL.Query().Get("limit"); l != "" {
if parsed, err := strconv.Atoi(l); err == nil {
limit = parsed
}
}
// Параметры пагинации
page := 1
if p := r.URL.Query().Get("page"); p != "" {
if parsed, err := strconv.Atoi(p); err == nil && parsed > 0 {
page = parsed
}
}
eventsPath, err := logger.GetEventHumanLogPath()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
pageSize := 100
if ps := r.URL.Query().Get("page_size"); ps != "" {
if parsed, err := strconv.Atoi(ps); err == nil && parsed > 0 {
pageSize = parsed
}
}
content, err := os.ReadFile(eventsPath)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
eventsPath, err := logger.GetEventHumanLogPath()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
lines := strings.Split(string(content), "\n")
// Берем последние N строк
if len(lines) > limit+1 {
lines = lines[len(lines)-limit-1:]
}
content, err := os.ReadFile(eventsPath)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// Парсим строки для JSON
type Event struct {
Time string `json:"time"`
Event string `json:"event"`
}
// Разбиваем на строки
lines := strings.Split(string(content), "\n")
var events []Event
for _, line := range lines {
if line == "" {
continue
}
// Формат: [2026-06-16 11:23:45.123] EVENT: СЕРВЕР_ЗАПУЩЕН
parts := strings.SplitN(line, "] EVENT: ", 2)
if len(parts) == 2 {
events = append(events, Event{
Time: strings.TrimPrefix(parts[0], "["),
Event: parts[1],
})
}
}
// Удаляем пустые строки
var nonEmptyLines []string
for _, line := range lines {
if line != "" {
nonEmptyLines = append(nonEmptyLines, line)
}
}
lines = nonEmptyLines
writeJSON(w, map[string]any{
"events": events,
"total": len(events),
})
total := len(lines)
totalPages := (total + pageSize - 1) / pageSize
if totalPages == 0 {
totalPages = 1
}
// Корректируем номер страницы
if page > totalPages {
page = totalPages
}
if page < 1 {
page = 1
}
start := total - page*pageSize
if start < 0 {
start = 0
}
end := start + pageSize
if end > total {
end = total
}
// Получаем строки для текущей страницы
var pageLines []string
if start < total && start >= 0 {
pageLines = lines[start:end]
} else {
pageLines = []string{}
}
var reversedLines []string
for i := len(pageLines) - 1; i >= 0; i-- {
reversedLines = append(reversedLines, pageLines[i])
}
// Парсим строки для JSON
type Event struct {
Time string `json:"time"`
Event string `json:"event"`
}
var events []Event
for _, line := range reversedLines {
if line == "" {
continue
}
parts := strings.SplitN(line, "] EVENT: ", 2)
if len(parts) == 2 {
events = append(events, Event{
Time: strings.TrimPrefix(parts[0], "["),
Event: parts[1],
})
}
}
writeJSON(w, map[string]any{
"events": events,
"total": total,
"page": page,
"page_size": pageSize,
"total_pages": totalPages,
"has_previous": page > 1,
"has_next": page < totalPages,
"returned": len(events),
"start_index": start + 1,
"end_index": end,
"order": "newest_first",
})
}
// HandleLogData - чтение данных из конкретного bin файла
func (a *API) HandleLogData(w http.ResponseWriter, r *http.Request) {
filename := r.URL.Query().Get("file")

View File

@@ -0,0 +1,30 @@
/* Стили аудио-индикатора */
@keyframes pulse {
0%, 100% {
opacity: 1;
transform: scale(1);
}
50% {
opacity: 0.6;
transform: scale(0.95);
}
}
#audio-indicator {
font-family: var(--font-tech);
font-size: var(--font-size-lg);
padding: 4px 12px;
border-radius: 6px;
background: rgba(0, 0, 0, 0.4);
border: 1px solid #333;
min-width: 50px;
text-align: center;
user-select: none;
transition: all 0.3s ease;
}
#audio-indicator.active {
border-color: #00ff88;
box-shadow: 0 0 15px rgba(0, 255, 136, 0.3);
animation: pulse 1s ease-in-out infinite;
}

130
cmd/server/web/css/base.css Normal file
View File

@@ -0,0 +1,130 @@
/* ===== БАЗОВЫЕ СТИЛИ ===== */
:root {
/* Основные шрифты */
--font-mono: 'JetBrains Mono', 'Fira Code', 'Courier New', monospace;
--font-display: 'Orbitron', 'Share Tech Mono', 'Segoe UI', sans-serif;
--font-tech: 'Share Tech Mono', 'Courier New', monospace;
/* Размеры */
--font-size-xs: 11px;
--font-size-sm: 13px;
--font-size-base: 15px;
--font-size-lg: 17px;
--font-size-xl: 20px;
--font-size-2xl: 24px;
--font-size-3xl: 30px;
/* Веса */
--font-weight-normal: 400;
--font-weight-semibold: 600;
--font-weight-bold: 700;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: var(--font-mono);
background: #0a0f0a; /* Чуть светлее для лучшего контраста */
color: #00ff88;
padding: 12px;
font-size: var(--font-size-base);
line-height: 1.7;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* ===== ЗАГОЛОВКИ ===== */
h1, h2, h3, h4, h5, h6 {
font-family: var(--font-display);
letter-spacing: 0.08em;
text-transform: uppercase;
font-weight: var(--font-weight-bold);
margin: 0;
color: #00ff88;
}
h1 {
font-size: var(--font-size-2xl);
text-shadow: 0 0 30px rgba(0, 255, 136, 0.2);
}
h2 {
font-size: var(--font-size-xl);
}
h3 {
font-size: var(--font-size-lg);
}
/* ===== МОНОШИРИННЫЙ ТЕКСТ ===== */
code, pre, .mono {
font-family: var(--font-mono);
font-weight: var(--font-weight-normal);
}
/* ===== ТЕХНИЧЕСКИЙ ТЕКСТ ===== */
.status-text,
.value-text,
.signal-text,
.tech-text {
font-family: var(--font-tech);
letter-spacing: 0.03em;
}
/* ===== УЛУЧШЕНИЯ ЧИТАЕМОСТИ ===== */
.text-muted {
opacity: 0.6;
color: #88ffbb;
}
.text-bold {
font-weight: var(--font-weight-bold);
}
.text-semibold {
font-weight: var(--font-weight-semibold);
}
/* ===== ССЫЛКИ ===== */
a {
color: #00ff88;
text-decoration: none;
transition: all 0.3s ease;
font-weight: var(--font-weight-semibold);
}
a:hover {
color: #66ffbb;
text-shadow: 0 0 25px rgba(0, 255, 136, 0.2);
}
/* ===== УЛУЧШЕННЫЙ СКРОЛЛ НА МОБИЛЬНЫХ ===== */
* {
-webkit-tap-highlight-color: transparent;
}
/* Плавный скролл */
html {
scroll-behavior: smooth;
}
/* Улучшенный скролл на мобильных */
.panel,
.logs-content,
.logs-sidebar,
#history,
#dataTableContainer {
-webkit-overflow-scrolling: touch;
overscroll-behavior: contain;
}
/* Убираем скролл-бары на мобильных где не нужно */
@media (max-width: 768px) {
.panel::-webkit-scrollbar,
.logs-content::-webkit-scrollbar,
.logs-sidebar::-webkit-scrollbar {
width: 3px;
}
}

View File

@@ -0,0 +1,82 @@
/* Стили камеры (cam-modal, cam-frame, crosshair) */
.cam-modal {
height: 100%;
display: flex;
flex-direction: column;
background: black;
}
.cam-header {
display: flex;
justify-content: space-between;
padding: 8px;
background: #111;
color: #00ff88;
font-family: var(--font-display);
font-size: var(--font-size-base);
letter-spacing: 0.05em;
}
.cam-frame-wrapper {
position: relative;
flex: 1;
width: 100%;
background: black;
overflow: hidden;
}
.cam-frame {
width: 100%;
height: 100%;
object-fit: contain;
background: black;
}
/* Перекрестие (crosshair) */
.cam-crosshair {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 10;
}
/* Вертикальная линия */
.crosshair-v {
position: absolute;
top: 0;
left: 50%;
transform: translateX(-50%);
width: 1px;
height: 100%;
background: #00ff88;
box-shadow: 0 0 4px rgba(0, 255, 136, 0.3);
}
/* Горизонтальная линия */
.crosshair-h {
position: absolute;
top: 50%;
left: 0;
transform: translateY(-50%);
width: 100%;
height: 1px;
background: #00ff88;
box-shadow: 0 0 4px rgba(0, 255, 136, 0.3);
}
/* Центральный квадрат */
.crosshair-box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 120px;
height: 120px;
border: 2px solid #00ff88;
box-shadow:
0 0 10px rgba(0, 255, 136, 0.3),
inset 0 0 10px rgba(0, 255, 136, 0.1);
}

View File

@@ -0,0 +1,126 @@
/* Стили карточек (card, accordion, статусы) */
/* ===== CARD ===== */
.card {
border: 1px solid #00ff88;
border-radius: 10px;
padding: 14px;
background: rgba(0,255,136,0.05);
overflow: hidden;
height: 100%;
display: flex;
flex-direction: column;
transition: all 0.3s ease;
}
.card:hover {
box-shadow: 0 0 30px rgba(0, 255, 136, 0.05);
}
.card h3 {
margin: 0 0 10px;
font-size: var(--font-size-lg);
font-family: var(--font-display);
letter-spacing: 0.1em;
font-weight: var(--font-weight-bold);
}
/* ===== STATUS ===== */
#status {
font-family: var(--font-tech);
font-size: var(--font-size-3xl);
font-weight: var(--font-weight-bold);
margin-bottom: 8px;
letter-spacing: 0.05em;
}
.status-ok {
color: #00ff88 !important;
text-shadow: 0 0 30px rgba(0, 255, 136, 0.3);
}
.status-lost {
color: #ffffff !important;
animation: blink 1.5s infinite;
text-shadow: 0 0 30px rgba(255, 255, 255, 0.1);
}
.status-error {
color: #ff4444 !important;
text-shadow: 0 0 30px rgba(255, 68, 68, 0.3);
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0.2; }
}
/* ===== META ===== */
#meta {
font-family: var(--font-mono);
font-size: var(--font-size-base);
opacity: 0.8;
letter-spacing: 0.02em;
}
/* ===== ACCORDION ===== */
.accordion-header {
cursor: pointer;
user-select: none;
padding: 10px 0;
margin: 0;
font-family: var(--font-display);
font-weight: var(--font-weight-bold);
letter-spacing: 0.05em;
transition: all 0.3s ease;
}
.accordion-header:hover {
opacity: 0.7;
text-shadow: 0 0 20px rgba(0, 255, 136, 0.2);
}
.accordion-body {
max-height: 520px;
overflow: hidden;
transition: max-height 0.3s ease, opacity 0.3s ease;
}
.accordion-body.collapsed {
max-height: 0;
opacity: 0;
}
/* ===== LAST BYTE ===== */
#last-byte {
font-family: var(--font-tech);
font-size: var(--font-size-xl);
font-weight: var(--font-weight-bold);
color: #00ff88;
text-shadow: 0 0 20px rgba(0, 255, 136, 0.2);
}
/* ===== HISTORY ===== */
#history {
font-family: var(--font-mono);
font-size: var(--font-size-sm);
line-height: 1.35;
max-height: 420px;
overflow-y: auto;
white-space: nowrap;
padding-right: 4px;
margin: 0;
letter-spacing: 0.02em;
}
#history::-webkit-scrollbar {
width: 6px;
}
#history::-webkit-scrollbar-track {
background: rgba(0, 255, 136, 0.05);
}
#history::-webkit-scrollbar-thumb {
background: #00ff88;
border-radius: 3px;
}

View File

@@ -0,0 +1,93 @@
/* Компоненты (прогресс-бары, сигнальные иконки) */
/* ===== PROGRESS BARS ===== */
.progress-row {
margin-bottom: 16px;
}
.progress-label {
font-family: var(--font-mono);
font-size: var(--font-size-base);
margin-bottom: 6px;
color: #ffffff;
opacity: 0.9;
letter-spacing: 0.03em;
}
.progress {
width: 100%;
height: 34px;
padding: 6px;
border: 3px solid #8a8a8a;
background: #222;
box-shadow:
inset 0 0 6px rgba(255,255,255,0.15),
0 0 4px rgba(0,0,0,0.8);
}
.progress-with-signal {
display: flex;
align-items: center;
gap: 0;
}
.progress-90 {
flex: 0 0 86%;
margin-right: 10px;
}
.fill {
height: 100%;
width: 0;
background: #e6852d;
box-shadow:
inset 0 0 4px rgba(255,255,255,0.2),
0 0 6px rgba(230,133,45,0.5);
transition: width 0.25s linear;
}
.fill.no-connection {
background: #555555 !important;
box-shadow: none !important;
width: 0 !important;
}
/* ===== SIGNAL ICON ===== */
.signal-icon {
display: flex;
align-items: flex-end;
gap: 4px;
width: 34px;
height: 34px;
flex-shrink: 0;
}
.sig-bar {
flex: 1;
border-radius: 2px;
min-width: 5px;
border: 2px solid #e6852d;
background-color: transparent;
transition: background-color 0.3s, border-color 0.3s;
}
.sig-bar-1 { height: 33%; }
.sig-bar-2 { height: 66%; }
.sig-bar-3 { height: 100%; }
.sig-bar.dim {
background-color: transparent;
border-color: #1a3a1a;
}
.sig-bar.active-1,
.sig-bar.active-2,
.sig-bar.active-3 {
background-color: #e6852d;
border-color: #c46b1f;
}
.sig-bar.no-connection {
background-color: #555555 !important;
border-color: #555555 !important;
opacity: 0.3 !important;
}

View File

@@ -0,0 +1,60 @@
/* ===== ЛОКАЛЬНЫЕ ШРИФТЫ ===== */
/* JetBrains Mono */
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
src: url('/fonts/JetBrainsMono/ttf/JetBrainsMono-Regular.ttf') format('truetype');
font-display: swap;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
src: url('/fonts/JetBrainsMono/ttf/JetBrainsMono-Bold.ttf') format('truetype');
font-display: swap;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 700;
src: url('/fonts/JetBrainsMono/ttf/JetBrainsMono-ExtraBold.ttf') format('truetype');
font-display: swap;
}
/* Orbitron - для заголовков */
@font-face {
font-family: 'Orbitron';
font-style: normal;
font-weight: 400;
src: url('/fonts/Orbitron/static/Orbitron-Regular.ttf') format('truetype');
font-display: swap;
}
@font-face {
font-family: 'Orbitron';
font-style: normal;
font-weight: 600;
src: url('/fonts/Orbitron/static/Orbitron-SemiBold.ttf') format('truetype');
font-display: swap;
}
@font-face {
font-family: 'Orbitron';
font-style: normal;
font-weight: 700;
src: url('/fonts/Orbitron/static/Orbitron-Bold.ttf') format('truetype');
font-display: swap;
}
/* Share Tech Mono - для статусов и значений */
@font-face {
font-family: 'Share Tech Mono';
font-style: normal;
font-weight: 400;
src: url('/fonts/ShareTechMono-Regular.ttf') format('truetype');
font-display: swap;
}

View File

@@ -0,0 +1,201 @@
/* ===== HEADER BAR ===== */
.header-bar {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
margin-bottom: 15px;
gap: 16px;
}
.header-bar h1 {
font-family: var(--font-display);
font-weight: var(--font-weight-bold);
font-size: var(--font-size-2xl);
letter-spacing: 0.1em;
text-shadow: 0 0 20px rgba(0, 255, 136, 0.3);
}
.header-time {
font-family: var(--font-tech);
font-size: var(--font-size-lg);
text-align: center;
white-space: nowrap;
padding: 6px 12px;
border: 1px solid rgba(0, 255, 136, 0.35);
border-radius: 8px;
background: rgba(0, 255, 136, 0.05);
letter-spacing: 0.05em;
}
.header-bar .cam-btn {
justify-self: end;
}
/* ===== CAMERA BUTTON ===== */
.cam-btn {
padding: 8px 16px;
background: rgba(0, 0, 0, 0.6);
color: #00ff88;
border: 1px solid #00ff88;
border-radius: 8px;
cursor: pointer;
font-family: var(--font-mono);
font-size: var(--font-size-base);
font-weight: var(--font-weight-semibold);
display: flex;
align-items: center;
gap: 8px;
white-space: nowrap;
flex-shrink: 0;
transition: all 0.3s ease;
letter-spacing: 0.03em;
}
.cam-btn:hover {
background: rgba(0, 255, 136, 0.2);
box-shadow: 0 0 20px rgba(0, 255, 136, 0.1);
transform: translateY(-1px);
}
.cam-btn-icon {
font-size: 16px;
}
/* ===== HEADER CONTROLS ===== */
.header-controls {
display: flex;
gap: 12px;
align-items: center;
flex-wrap: wrap;
justify-content: flex-end;
}
.header-link {
color: #00ff88;
text-decoration: none;
font-size: var(--font-size-base);
border: 1px solid rgba(0, 255, 136, 0.3);
padding: 6px 14px;
border-radius: 6px;
transition: all 0.3s ease;
font-family: var(--font-mono);
font-weight: var(--font-weight-semibold);
white-space: nowrap;
}
.header-link:hover {
background: rgba(0, 255, 136, 0.1);
border-color: #00ff88;
box-shadow: 0 0 20px rgba(0, 255, 136, 0.05);
}
.audio-indicator {
font-size: var(--font-size-lg);
padding: 4px 12px;
border-radius: 6px;
background: rgba(0, 0, 0, 0.4);
border: 1px solid #333;
min-width: 50px;
text-align: center;
font-family: var(--font-tech);
transition: all 0.3s ease;
user-select: none;
}
.audio-indicator.active {
border-color: #00ff88;
box-shadow: 0 0 15px rgba(0, 255, 136, 0.3);
animation: pulse 1s ease-in-out infinite;
}
/* ===== CAMERA CLOSE BUTTON ===== */
.cam-close-btn {
background: rgba(255, 68, 68, 0.2);
color: #ff4466;
border: 1px solid rgba(255, 68, 68, 0.3);
border-radius: 4px;
padding: 4px 10px;
cursor: pointer;
font-size: var(--font-size-base);
font-family: var(--font-mono);
transition: all 0.3s ease;
}
.cam-close-btn:hover {
background: rgba(255, 68, 68, 0.3);
border-color: #ff4466;
box-shadow: 0 0 20px rgba(255, 68, 68, 0.1);
}
/* ===== МОБИЛЬНАЯ АДАПТАЦИЯ ХЕДЕРА ===== */
@media (max-width: 768px) {
.header-bar {
display: flex;
flex-direction: column;
align-items: stretch;
gap: 8px;
margin-bottom: 12px;
}
.header-bar h1 {
text-align: center;
font-size: var(--font-size-lg);
}
.header-controls {
justify-content: center;
gap: 6px;
}
.header-link {
font-size: var(--font-size-sm);
padding: 6px 10px;
}
.header-time {
font-size: var(--font-size-sm);
padding: 4px 8px;
}
.audio-indicator {
font-size: var(--font-size-base);
padding: 4px 8px;
min-width: 40px;
}
.cam-btn {
font-size: var(--font-size-sm);
padding: 6px 10px;
}
}
@media (max-width: 480px) {
.header-bar h1 {
font-size: var(--font-size-base);
}
.header-controls {
gap: 4px;
flex-wrap: wrap;
}
.header-link {
font-size: var(--font-size-xs);
padding: 4px 8px;
}
.header-time {
font-size: var(--font-size-xs);
padding: 3px 6px;
}
.audio-indicator {
font-size: var(--font-size-sm);
padding: 3px 6px;
min-width: 32px;
}
.cam-btn {
font-size: var(--font-size-xs);
padding: 4px 8px;
}
}

View File

@@ -0,0 +1,78 @@
/* ===== SPLIT LAYOUT ===== */
.layout {
display: flex;
height: calc(100vh - 100px);
width: 100%;
margin: 0;
padding: 0;
}
/* панели */
.panel {
height: 100%;
overflow-y: auto;
overflow-x: hidden;
}
/* LEFT */
.left {
flex: 1 1 auto;
min-width: 300px;
padding: 10px;
}
/* RIGHT */
.right {
flex: 0 0 40%;
min-width: 0;
background: black;
position: relative;
overflow: hidden;
}
.right.hidden {
flex: 0 0 0 !important;
width: 0 !important;
min-width: 0 !important;
opacity: 0;
pointer-events: none;
}
/* ===== RESIZER ===== */
.resizer {
width: 8px;
min-width: 8px;
cursor: col-resize;
background: #00ff88;
opacity: 0.3;
flex-shrink: 0;
z-index: 10;
}
.resizer:hover {
opacity: 0.8;
}
.resizer.hidden {
width: 0 !important;
min-width: 0 !important;
opacity: 0;
pointer-events: none;
}
/* ===== GRID ===== */
.grid {
display: grid;
grid-template-columns: 1fr;
gap: 12px;
align-items: stretch;
}
@media (min-width: 900px) {
.grid {
grid-template-columns: 1fr 1fr;
}
.wide {
grid-column: span 2;
}
}

548
cmd/server/web/css/logs.css Normal file
View File

@@ -0,0 +1,548 @@
/* ===== СТИЛИ СТРАНИЦЫ ЖУРНАЛА ===== */
/* Общие улучшения читаемости */
.logs-container {
display: flex;
gap: 20px;
height: calc(100vh - 120px);
overflow: visible; /* Разрешаем выход за границы */
}
.logs-sidebar {
flex: 0 0 280px;
border-right: 1px solid #00ff88;
padding-right: 16px;
padding-left: 4px;
overflow-y: auto;
overflow-x: visible;
}
.logs-content {
flex: 1;
overflow-y: auto;
overflow-x: visible;
padding: 0 4px;
}
/* ===== ФАЙЛЫ В БОКОВОЙ ПАНЕЛИ ===== */
.log-file-item {
padding: 10px 14px;
margin: 4px 0;
cursor: pointer;
border-radius: 4px;
border: 1px solid transparent;
transition: all 0.2s ease;
font-family: var(--font-mono);
background: rgba(0, 255, 136, 0.03);
transform: scale(1);
box-sizing: border-box;
}
.log-file-item:hover {
background: rgba(0, 255, 136, 0.15);
border-color: #00ff88;
transform: scale(1.02);
box-shadow: 0 0 20px rgba(0, 255, 136, 0.03);
margin-left: 4px;
}
.log-file-item.active {
background: rgba(0, 255, 136, 0.2);
border-color: #00ff88;
box-shadow: 0 0 20px rgba(0, 255, 136, 0.05);
transform: scale(1);
margin-left: 0;
}
.log-file-item .file-name {
font-size: var(--font-size-base);
font-family: var(--font-mono);
font-weight: var(--font-weight-semibold);
color: #00ff88;
}
.log-file-item .file-info {
font-size: var(--font-size-sm);
opacity: 0.7;
color: #88ffbb;
margin-top: 2px;
}
/* ===== СТАТИСТИКА ===== */
.log-stats {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
margin-bottom: 16px;
padding: 0 4px;
}
.log-stat-card {
padding: 14px 12px;
border: 1px solid rgba(0, 255, 136, 0.3);
border-radius: 6px;
text-align: center;
background: rgba(0, 255, 136, 0.05);
transition: all 0.3s ease;
transform: scale(1);
}
.log-stat-card:hover {
background: rgba(0, 255, 136, 0.1);
border-color: #00ff88;
box-shadow: 0 0 25px rgba(0, 255, 136, 0.05);
transform: scale(1.02);
}
.log-stat-card .value {
font-family: var(--font-tech);
font-size: var(--font-size-2xl);
font-weight: var(--font-weight-bold);
color: #00ff88;
text-shadow: 0 0 20px rgba(0, 255, 136, 0.2);
display: block;
margin-bottom: 4px;
}
.log-stat-card .label {
font-family: var(--font-mono);
font-size: var(--font-size-xs);
opacity: 0.7;
color: #88ffbb;
letter-spacing: 0.05em;
text-transform: uppercase;
}
/* ===== ТАБЛИЦА ДАННЫХ ===== */
.data-table {
width: 100%;
font-size: var(--font-size-base);
border-collapse: collapse;
font-family: var(--font-mono);
}
.data-table th {
text-align: left;
padding: 8px 12px;
border-bottom: 2px solid #00ff88;
position: sticky;
top: 0;
background: #050805;
font-family: var(--font-display);
font-weight: var(--font-weight-bold);
letter-spacing: 0.08em;
font-size: var(--font-size-sm);
color: #00ff88;
text-shadow: 0 0 20px rgba(0, 255, 136, 0.1);
}
.data-table td {
padding: 6px 12px;
border-bottom: 1px solid rgba(0, 255, 136, 0.08);
font-family: var(--font-mono);
font-size: var(--font-size-base);
font-weight: var(--font-weight-normal);
}
.data-table tr:hover {
background: rgba(0, 255, 136, 0.06);
}
/* ===== УЛУЧШЕННЫЕ ЦВЕТА ДЛЯ АМПЛИТУДЫ ===== */
.strength-0 {
color: #666666;
opacity: 0.5;
}
.strength-1 {
color: #66ff88;
font-weight: var(--font-weight-semibold);
text-shadow: 0 0 15px rgba(102, 255, 136, 0.2);
}
.strength-2 {
color: #ffbb44;
font-weight: var(--font-weight-bold);
text-shadow: 0 0 20px rgba(255, 187, 68, 0.25);
}
.strength-3 {
color: #ff3355;
font-weight: var(--font-weight-bold);
text-shadow: 0 0 20px rgba(255, 51, 85, 0.4), 0 0 40px rgba(255, 51, 85, 0.2);
background: rgba(255, 51, 85, 0.08);
border-radius: 3px;
padding: 0 4px;
}
/* ===== СПИСОК СОБЫТИЙ ===== */
.events-list {
font-family: var(--font-mono);
font-size: var(--font-size-base);
line-height: 1.8;
}
.events-list > div {
padding: 4px 8px;
border-bottom: 1px solid rgba(0, 255, 136, 0.04);
transition: background 0.2s ease;
}
.events-list > div:hover {
background: rgba(0, 255, 136, 0.04);
}
.events-list .event-time {
opacity: 0.6;
font-family: var(--font-tech);
color: #88ffbb;
font-size: var(--font-size-sm);
margin-right: 8px;
}
.events-list .event-message {
color: #00ff88;
font-weight: var(--font-weight-normal);
}
/* ===== ТАБЫ ===== */
.tabs {
display: flex;
gap: 8px;
margin-bottom: 16px;
padding: 4px 8px;
overflow: visible;
}
.tab-btn {
padding: 8px 20px;
background: transparent;
color: #88ffbb;
border: 1px solid rgba(0, 255, 136, 0.3);
border-radius: 6px;
cursor: pointer;
font-family: var(--font-mono);
font-size: var(--font-size-base);
font-weight: var(--font-weight-semibold);
transition: all 0.2s ease;
letter-spacing: 0.03em;
transform: scale(1);
flex-shrink: 0;
}
.tab-btn:hover {
background: rgba(0, 255, 136, 0.1);
border-color: #00ff88;
transform: scale(1.04);
box-shadow: 0 0 25px rgba(0, 255, 136, 0.05);
}
.tab-btn.active {
background: rgba(0, 255, 136, 0.15);
border-color: #00ff88;
color: #00ff88;
box-shadow: 0 0 30px rgba(0, 255, 136, 0.05);
transform: scale(1);
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
/* ===== ПАГИНАЦИЯ ===== */
.pagination-container {
margin: 16px 0;
padding: 14px 8px;
border-top: 1px solid rgba(0, 255, 136, 0.15);
border-bottom: 1px solid rgba(0, 255, 136, 0.15);
background: rgba(0, 255, 136, 0.02);
border-radius: 4px;
overflow: visible;
}
.pagination-controls {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
flex-wrap: wrap;
padding: 4px 4px;
overflow: visible;
}
.pagination-btn {
padding: 8px 16px;
background: rgba(0, 255, 136, 0.08);
color: #00ff88;
border: 1px solid rgba(0, 255, 136, 0.3);
border-radius: 6px;
cursor: pointer;
font-family: var(--font-mono);
font-size: var(--font-size-base);
font-weight: var(--font-weight-semibold);
transition: all 0.2s ease;
min-width: 44px;
transform: scale(1);
flex-shrink: 0;
}
.pagination-btn:hover:not(:disabled) {
background: rgba(0, 255, 136, 0.2);
border-color: #00ff88;
transform: scale(1.04);
box-shadow: 0 0 25px rgba(0, 255, 136, 0.05);
}
.pagination-btn:disabled {
opacity: 0.25;
cursor: not-allowed;
transform: none !important;
box-shadow: none !important;
}
.pagination-info {
padding: 0 16px;
color: #88ffbb;
font-size: var(--font-size-base);
font-family: var(--font-mono);
min-width: 220px;
text-align: center;
font-weight: var(--font-weight-semibold);
}
.pagination-goto {
display: flex;
align-items: center;
gap: 6px;
margin-left: 8px;
}
.pagination-input {
width: 60px;
padding: 6px 8px;
background: rgba(0, 0, 0, 0.7);
color: #00ff88;
border: 1px solid rgba(0, 255, 136, 0.3);
border-radius: 4px;
font-family: var(--font-mono);
font-size: var(--font-size-base);
font-weight: var(--font-weight-bold);
text-align: center;
}
.pagination-input:focus {
outline: none;
border-color: #00ff88;
box-shadow: 0 0 20px rgba(0, 255, 136, 0.15);
}
.pagination-goto-btn {
padding: 6px 14px;
font-size: var(--font-size-sm);
background: rgba(0, 255, 136, 0.12);
}
.loading-indicator {
text-align: center;
padding: 30px;
color: #88ffbb;
opacity: 0.8;
font-family: var(--font-mono);
font-size: var(--font-size-lg);
}
/* ===== СКРОЛЛБАРЫ ===== */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: rgba(0, 255, 136, 0.05);
border-radius: 4px;
}
::-webkit-scrollbar-thumb {
background: rgba(0, 255, 136, 0.3);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(0, 255, 136, 0.5);
}
/* ===== АДАПТИВНОСТЬ ===== */
@media (max-width: 768px) {
.logs-container {
flex-direction: column;
height: auto;
gap: 12px;
}
.logs-sidebar {
flex: 0 0 auto;
border-right: none;
border-bottom: 1px solid rgba(0, 255, 136, 0.2);
padding-right: 0;
padding-bottom: 12px;
max-height: 180px;
overflow-y: auto;
}
.logs-sidebar h3 {
font-size: var(--font-size-sm);
margin-bottom: 8px;
}
.logs-content {
overflow-y: visible;
}
.log-file-item {
padding: 8px 12px;
margin: 3px 0;
min-height: 44px;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
}
.log-file-item .file-name {
font-size: var(--font-size-sm);
}
.log-file-item .file-info {
font-size: var(--font-size-xs);
}
.log-stats {
grid-template-columns: repeat(2, 1fr);
gap: 8px;
}
.log-stat-card {
padding: 10px 8px;
}
.log-stat-card .value {
font-size: var(--font-size-xl);
}
.log-stat-card .label {
font-size: var(--font-size-xs);
}
.data-table {
font-size: var(--font-size-sm);
}
.data-table th,
.data-table td {
padding: 4px 6px;
font-size: var(--font-size-sm);
}
.tabs {
gap: 6px;
flex-wrap: wrap;
}
.tab-btn {
padding: 6px 14px;
font-size: var(--font-size-sm);
min-height: 40px;
flex: 1;
min-width: 60px;
text-align: center;
}
.events-list {
font-size: var(--font-size-sm);
line-height: 1.6;
}
.pagination-container {
padding: 10px 8px;
margin: 12px 0;
}
.pagination-controls {
gap: 4px;
}
.pagination-btn {
padding: 6px 10px;
font-size: var(--font-size-sm);
min-height: 40px;
min-width: 36px;
}
.pagination-info {
font-size: var(--font-size-xs);
min-width: 80px;
padding: 0 6px;
}
.pagination-goto {
margin-left: 4px;
}
.pagination-input {
width: 44px;
min-height: 36px;
font-size: var(--font-size-sm);
padding: 4px 6px;
}
.pagination-goto-btn {
padding: 4px 10px;
font-size: var(--font-size-xs);
min-height: 36px;
}
}
@media (max-width: 480px) {
.log-stats {
grid-template-columns: 1fr 1fr;
gap: 6px;
}
.log-stat-card {
padding: 8px 6px;
}
.log-stat-card .value {
font-size: var(--font-size-lg);
}
.data-table th,
.data-table td {
padding: 3px 4px;
font-size: var(--font-size-xs);
}
.tab-btn {
font-size: var(--font-size-xs);
padding: 4px 10px;
min-height: 34px;
}
.pagination-btn {
padding: 4px 8px;
font-size: var(--font-size-xs);
min-height: 34px;
min-width: 30px;
}
.pagination-input {
width: 38px;
min-height: 32px;
font-size: var(--font-size-xs);
padding: 3px 4px;
}
}

View File

@@ -0,0 +1,567 @@
/* ===== РЕСПОНСИВНЫЙ ДИЗАЙН ===== */
/* ============================================
ПЛАНШЕТЫ (768px - 1024px)
============================================ */
@media (max-width: 1024px) {
/* Уменьшаем отступы */
body {
padding: 10px;
}
/* Хедер */
.header-bar {
gap: 10px;
grid-template-columns: 1fr auto;
}
.header-bar h1 {
font-size: var(--font-size-xl);
}
.header-time {
font-size: var(--font-size-sm);
padding: 4px 10px;
}
.cam-btn {
font-size: var(--font-size-sm);
padding: 6px 12px;
}
/* Карточки */
.card {
padding: 12px 14px;
}
.card h3 {
font-size: var(--font-size-base);
}
#status {
font-size: var(--font-size-2xl);
}
/* Прогресс-бары */
.progress {
height: 28px;
padding: 4px;
}
.progress-label {
font-size: var(--font-size-sm);
}
/* Сигнальные иконки */
.signal-icon {
width: 28px;
height: 28px;
}
}
/* ============================================
МОБИЛЬНЫЕ УСТРОЙСТВА (до 768px)
============================================ */
@media (max-width: 768px) {
/* ===== ОБЩИЕ ===== */
body {
padding: 8px;
font-size: var(--font-size-base);
}
/* Увеличиваем область касания для всех интерактивных элементов */
button,
.cam-btn,
.tab-btn,
.pagination-btn,
.log-file-item {
min-height: 44px;
min-width: 44px;
}
/* ===== ХЕДЕР ===== */
.header-bar {
display: flex;
flex-direction: column;
align-items: stretch;
gap: 8px;
margin-bottom: 12px;
}
.header-bar h1 {
font-size: var(--font-size-lg);
text-align: center;
letter-spacing: 0.05em;
}
.header-bar > div {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 6px;
}
.header-time {
font-size: var(--font-size-sm);
padding: 4px 10px;
flex: 1;
min-width: 80px;
}
#audio-indicator {
font-size: var(--font-size-base);
padding: 4px 10px;
min-width: 40px;
}
.cam-btn {
font-size: var(--font-size-sm);
padding: 8px 14px;
justify-content: center;
flex: 1;
min-width: 80px;
}
/* Ссылка "Журнал" */
.header-bar a[href="/logs.html"] {
font-size: var(--font-size-sm);
padding: 6px 12px;
text-align: center;
flex: 1;
min-width: 60px;
}
/* ===== МАКЕТ ===== */
.layout {
flex-direction: column;
height: auto;
gap: 8px;
}
.panel {
height: auto;
overflow-y: visible;
}
.left {
flex: 1 1 auto !important;
min-width: 0 !important;
padding: 0;
width: 100% !important;
}
.right {
flex: 0 0 auto !important;
min-width: 100% !important;
width: 100% !important;
height: 40vh;
min-height: 300px;
opacity: 1 !important;
pointer-events: auto !important;
}
.right.hidden {
display: none !important;
flex: 0 0 0 !important;
height: 0 !important;
min-height: 0 !important;
}
.resizer {
display: none !important;
}
/* ===== СЕТКА ===== */
.grid {
grid-template-columns: 1fr;
gap: 8px;
}
.wide {
grid-column: span 1;
}
/* ===== КАРТОЧКИ ===== */
.card {
padding: 12px;
border-radius: 8px;
}
.card h3 {
font-size: var(--font-size-base);
margin-bottom: 8px;
}
#status {
font-size: var(--font-size-2xl);
}
#meta {
font-size: var(--font-size-sm);
}
/* ===== ПРОГРЕСС-БАРЫ ===== */
.progress-row {
margin-bottom: 12px;
}
.progress-label {
font-size: var(--font-size-sm);
margin-bottom: 4px;
}
.progress {
height: 30px;
padding: 4px;
border-width: 2px;
}
.progress-with-signal {
flex-wrap: nowrap;
}
.progress-90 {
flex: 1;
margin-right: 8px;
}
.signal-icon {
width: 30px;
height: 30px;
flex-shrink: 0;
}
.sig-bar {
min-width: 4px;
border-width: 1.5px;
}
/* ===== АККОРДЕОН ===== */
.accordion-header {
padding: 8px 0;
font-size: var(--font-size-base);
}
.accordion-body {
max-height: 400px;
}
#history {
font-size: var(--font-size-sm);
max-height: 300px;
line-height: 1.5;
}
/* ===== КАМЕРА ===== */
.cam-modal {
height: 100%;
min-height: 300px;
}
.cam-header {
padding: 6px 10px;
font-size: var(--font-size-sm);
}
.cam-frame {
object-fit: cover;
}
.crosshair-box {
width: 80px;
height: 80px;
border-width: 1.5px;
}
/* ===== ГОРЯЧИЕ КЛАВИШИ ===== */
.hotkey-hint {
font-size: var(--font-size-xs);
padding: 4px 0;
}
.hotkey-hint kbd {
padding: 2px 6px;
font-size: var(--font-size-xs);
}
}
/* ============================================
МАЛЕНЬКИЕ ТЕЛЕФОНЫ (до 480px)
============================================ */
@media (max-width: 480px) {
body {
padding: 6px;
}
/* Хедер */
.header-bar h1 {
font-size: var(--font-size-base);
}
.header-bar > div {
flex-wrap: wrap;
}
.header-time {
font-size: var(--font-size-xs);
padding: 4px 8px;
min-width: 60px;
}
#audio-indicator {
font-size: var(--font-size-sm);
padding: 4px 8px;
min-width: 35px;
}
.cam-btn {
font-size: var(--font-size-xs);
padding: 6px 10px;
min-width: 60px;
}
/* Карточки */
.card {
padding: 10px;
border-radius: 6px;
}
.card h3 {
font-size: var(--font-size-sm);
}
#status {
font-size: var(--font-size-xl);
}
#meta {
font-size: var(--font-size-xs);
}
/* Прогресс-бары */
.progress {
height: 24px;
padding: 3px;
border-width: 2px;
}
.progress-label {
font-size: var(--font-size-xs);
}
.signal-icon {
width: 24px;
height: 24px;
}
.sig-bar {
min-width: 3px;
border-width: 1px;
}
.sig-bar-1 { height: 30%; }
.sig-bar-2 { height: 60%; }
.sig-bar-3 { height: 90%; }
/* Камера */
.right {
height: 35vh;
min-height: 200px;
}
.cam-header {
padding: 4px 8px;
font-size: var(--font-size-xs);
}
.crosshair-box {
width: 60px;
height: 60px;
}
/* Аккордеон */
#history {
font-size: var(--font-size-xs);
max-height: 200px;
}
}
/* ============================================
ОРИЕНТАЦИЯ (ALBUM / PORTRAIT)
============================================ */
@media (max-width: 768px) and (orientation: landscape) {
.layout {
flex-direction: row;
height: calc(100vh - 80px);
}
.left {
flex: 1 1 60% !important;
min-width: 0 !important;
padding-right: 8px;
overflow-y: auto;
height: 100%;
}
.right {
flex: 0 0 40% !important;
min-width: 0 !important;
height: 100%;
min-height: 0;
}
.grid {
grid-template-columns: 1fr 1fr;
gap: 6px;
}
.wide {
grid-column: span 2;
}
#status {
font-size: var(--font-size-xl);
}
}
/* ============================================
УЛУЧШЕНИЯ ДЛЯ ТАЧ-ИНТЕРФЕЙСА
============================================ */
@media (hover: none) and (pointer: coarse) {
/* Увеличиваем область касания */
button,
.cam-btn,
.tab-btn,
.pagination-btn,
.log-file-item,
.accordion-header,
.pagination-goto-btn {
min-height: 44px;
min-width: 44px;
padding: 8px 16px;
}
/* Убираем hover-эффекты, оставляем active */
.cam-btn:hover,
.tab-btn:hover,
.pagination-btn:hover,
.log-file-item:hover {
transform: none;
}
.cam-btn:active,
.tab-btn:active,
.pagination-btn:active,
.log-file-item:active {
transform: scale(0.95);
background: rgba(0, 255, 136, 0.15);
}
/* Увеличиваем отступы для скролла */
.panel,
.logs-content,
.logs-sidebar {
-webkit-overflow-scrolling: touch;
scroll-behavior: smooth;
}
/* Увеличиваем размер полей ввода */
.pagination-input {
min-height: 44px;
font-size: var(--font-size-base);
padding: 8px 12px;
}
/* Увеличиваем чекбоксы и переключатели */
input[type="checkbox"],
input[type="radio"] {
width: 20px;
height: 20px;
}
}
/* ============================================
ТЁМНАЯ ТЕМА (опционально)
============================================ */
@media (prefers-color-scheme: dark) {
body {
background: #0a0f0a;
}
}
/* ============================================
ПЕЧАТЬ
============================================ */
@media print {
.header-bar,
.cam-btn,
.resizer,
.right,
.pagination-container,
.hotkey-hint {
display: none !important;
}
.layout {
display: block !important;
height: auto !important;
}
.panel {
height: auto !important;
overflow: visible !important;
}
.card {
break-inside: avoid;
border: 1px solid #00ff88;
}
}
/* ===== ДОПОЛНИТЕЛЬНЫЕ УЛУЧШЕНИЯ ДЛЯ ХЕДЕРА ===== */
@media (max-width: 768px) {
.header-bar {
display: flex !important;
flex-direction: column !important;
align-items: stretch !important;
gap: 8px !important;
}
.header-controls {
display: flex !important;
flex-wrap: wrap !important;
justify-content: center !important;
gap: 6px !important;
}
}
@media (max-width: 480px) {
.header-controls {
gap: 4px !important;
}
}
/* ===== УЛУЧШЕНИЯ ДЛЯ ТАЧ-ИНТЕРФЕЙСА ===== */
@media (hover: none) and (pointer: coarse) {
.header-link,
.cam-btn,
.cam-close-btn {
min-height: 44px !important;
min-width: 44px !important;
padding: 8px 14px !important;
}
.header-link:active,
.cam-btn:active {
transform: scale(0.95);
}
}
/* ===== КНОПКА ЗАКРЫТИЯ КАМЕРЫ НА МОБИЛЬНЫХ ===== */
@media (max-width: 768px) {
.cam-close-btn {
font-size: var(--font-size-lg);
padding: 6px 14px;
min-height: 44px;
min-width: 44px;
}
}

View File

@@ -1,516 +0,0 @@
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: monospace;
background: #050805;
color: #00ff88;
padding: 12px;
}
/* ===== HEADER BAR ===== */
.header-bar {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
margin-bottom: 15px;
gap: 16px;
}
h1 {
font-size: 22px;
margin: 0;
}
.header-time {
font-size: 16px;
text-align: center;
white-space: nowrap;
padding: 6px 12px;
border: 1px solid rgba(0, 255, 136, 0.35);
border-radius: 8px;
background: rgba(0, 255, 136, 0.05);
}
.header-bar .cam-btn {
justify-self: end;
}
/* ===== CAMERA BUTTON (теперь в header) ===== */
.cam-btn {
padding: 8px 16px;
background: rgba(0, 0, 0, 0.6);
color: #00ff88;
border: 1px solid #00ff88;
border-radius: 8px;
cursor: pointer;
font-family: monospace;
font-size: 14px;
display: flex;
align-items: center;
gap: 8px;
white-space: nowrap;
flex-shrink: 0;
}
.cam-btn:hover {
background: rgba(0, 255, 136, 0.2);
}
.cam-btn-icon {
font-size: 16px;
}
/* ===== GRID ===== */
.grid {
display: grid;
grid-template-columns: 1fr;
gap: 12px;
align-items: stretch;
}
@media (min-width: 900px) {
.grid {
grid-template-columns: 1fr 1fr;
}
.wide {
grid-column: span 2;
}
}
/* ===== CARD ===== */
.card {
border: 1px solid #00ff88;
border-radius: 10px;
padding: 14px;
background: rgba(0,255,136,0.05);
overflow: hidden;
height: 100%;
display: flex;
flex-direction: column;
}
.card h3 {
margin: 0 0 10px;
font-size: 18px;
}
/* ===== STATUS ===== */
#status {
font-size: 28px;
font-weight: bold;
margin-bottom: 8px;
}
.status-ok {
color: #00ff88 !important;
}
.status-lost {
color: #ffffff !important;
animation: blink 1.5s infinite;
}
.status-error {
color: #ff4444 !important;
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0.2; }
}
/* ===== META ===== */
#meta {
font-size: 14px;
opacity: 0.8;
word-break: break-word;
}
/* ===== PROGRESS BARS ===== */
.progress-row {
margin-bottom: 16px;
}
.progress-label {
font-size: 16px;
margin-bottom: 6px;
color: #ffffff;
opacity: 0.9;
}
.progress {
width: 100%;
height: 34px;
padding: 6px;
border: 3px solid #8a8a8a;
background: #222;
box-shadow:
inset 0 0 6px rgba(255,255,255,0.15),
0 0 4px rgba(0,0,0,0.8);
}
.progress-with-signal {
display: flex;
align-items: center;
gap: 0;
}
.progress-90 {
flex: 0 0 86%;
margin-right: 10px;
}
.fill {
height: 100%;
width: 0;
background: #e6852d;
box-shadow:
inset 0 0 4px rgba(255,255,255,0.2),
0 0 6px rgba(230,133,45,0.5);
transition: width 0.25s linear;
}
.fill.no-connection {
background: #555555 !important;
box-shadow: none !important;
width: 0 !important;
}
/* ===== SIGNAL ICON ===== */
.signal-icon {
display: flex;
align-items: flex-end;
gap: 4px;
width: 34px;
height: 34px;
flex-shrink: 0;
}
.sig-bar {
flex: 1;
border-radius: 2px;
min-width: 5px;
border: 2px solid #e6852d;
background-color: transparent;
transition: background-color 0.3s, border-color 0.3s;
}
.sig-bar-1 { height: 33%; }
.sig-bar-2 { height: 66%; }
.sig-bar-3 { height: 100%; }
.sig-bar.dim {
background-color: transparent;
border-color: #1a3a1a;
}
.sig-bar.active-1,
.sig-bar.active-2,
.sig-bar.active-3 {
background-color: #e6852d;
border-color: #c46b1f;
}
.sig-bar.no-connection {
background-color: #555555 !important;
border-color: #555555 !important;
opacity: 0.3 !important;
}
/* ===== LAST BYTE ===== */
#last-byte {
font-size: 18px;
font-weight: bold;
color: #00ff88;
}
/* ===== CHART ===== */
#signalChart {
width: 100%;
background: #050805;
border: 1px solid #e6852d;
border-radius: 8px;
}
/* ===== HISTORY ===== */
#history {
font-size: 13px;
line-height: 1.35;
max-height: 420px;
overflow-y: auto;
white-space: nowrap;
padding-right: 4px;
margin: 0;
}
/* ===== ACCORDION ===== */
.accordion-header {
cursor: pointer;
user-select: none;
padding: 10px 0;
margin: 0;
}
.accordion-header:hover {
opacity: 0.7;
}
.accordion-body {
max-height: 520px;
overflow: hidden;
transition: max-height 0.3s ease, opacity 0.3s ease;
}
.accordion-body.collapsed {
max-height: 0;
opacity: 0;
}
/* ===== SPLIT LAYOUT (FIXED) ===== */
.layout {
display: flex;
height: calc(100vh - 100px);
width: 100%;
margin: 0;
padding: 0;
}
/* панели */
.panel {
height: 100%;
overflow-y: auto;
overflow-x: hidden;
}
/* LEFT */
.left {
flex: 1 1 auto;
min-width: 300px;
padding: 10px;
}
/* RIGHT */
.right {
flex: 0 0 40%;
min-width: 0;
background: black;
position: relative;
overflow: hidden;
}
.right.hidden {
flex: 0 0 0 !important;
width: 0 !important;
min-width: 0 !important;
opacity: 0;
pointer-events: none;
}
/* ===== RESIZER ===== */
.resizer {
width: 8px;
min-width: 8px;
cursor: col-resize;
background: #00ff88;
opacity: 0.3;
flex-shrink: 0;
z-index: 10;
}
.resizer:hover {
opacity: 0.8;
}
.resizer.hidden {
width: 0 !important;
min-width: 0 !important;
opacity: 0;
pointer-events: none;
}
/* камера */
.cam-modal {
height: 100%;
display: flex;
flex-direction: column;
background: black;
}
.cam-header {
display: flex;
justify-content: space-between;
padding: 8px;
background: #111;
color: #00ff88;
}
.cam-frame {
flex: 1;
width: 100%;
object-fit: contain;
background: black;
}
/* ===== CAMERA OVERLAY ===== */
.cam-frame-wrapper {
position: relative;
flex: 1;
width: 100%;
background: black;
overflow: hidden;
}
.cam-frame {
width: 100%;
height: 100%;
object-fit: contain;
background: black;
}
/* Перекрестие (crosshair) */
.cam-crosshair {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 10;
}
/* Вертикальная линия */
.crosshair-v {
position: absolute;
top: 0;
left: 50%;
transform: translateX(-50%);
width: 1px;
height: 100%;
background: #00ff88;
box-shadow: 0 0 4px rgba(0, 255, 136, 0.3);
}
/* Горизонтальная линия */
.crosshair-h {
position: absolute;
top: 50%;
left: 0;
transform: translateY(-50%);
width: 100%;
height: 1px;
background: #00ff88;
box-shadow: 0 0 4px rgba(0, 255, 136, 0.3);
}
/* Центральный квадрат */
.crosshair-box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 120px;
height: 120px;
border: 2px solid #00ff88;
box-shadow:
0 0 10px rgba(0, 255, 136, 0.3),
inset 0 0 10px rgba(0, 255, 136, 0.1);
}
/* ===== AUDIO INDICATOR ===== */
@keyframes pulse {
0%, 100% {
opacity: 1;
transform: scale(1);
}
50% {
opacity: 0.6;
transform: scale(0.95);
}
}
#audio-indicator {
transition: all 0.3s ease;
font-family: monospace;
font-size: 16px;
padding: 4px 12px;
border-radius: 6px;
background: rgba(0, 0, 0, 0.4);
border: 1px solid #333;
min-width: 50px;
text-align: center;
user-select: none;
}
#audio-indicator.active {
border-color: #00ff88;
box-shadow: 0 0 15px rgba(0, 255, 136, 0.3);
animation: pulse 1s ease-in-out infinite;
}
/* ===== ГОРЯЧИЕ КЛАВИШИ (подсказка) ===== */
.hotkey-hint {
font-size: 11px;
opacity: 0.4;
text-align: center;
padding: 4px 0;
}
.hotkey-hint kbd {
background: rgba(0, 255, 136, 0.1);
padding: 1px 6px;
border-radius: 3px;
border: 1px solid rgba(0, 255, 136, 0.2);
font-size: 10px;
}
/* ===== MOBILE ===== */
@media (max-width: 500px) {
.header-bar {
flex-direction: column;
gap: 8px;
}
h1 {
font-size: 18px;
}
#status {
font-size: 22px;
}
.progress {
height: 30px;
padding: 5px;
}
.progress-label {
font-size: 15px;
}
#history {
font-size: 16px;
line-height: 1.5;
max-height: 55vh;
}
.layout {
flex-direction: column;
height: auto;
}
.left {
min-height: 50vh;
}
.right {
flex: 0 0 50vh !important;
min-width: 100% !important;
}
.resizer {
display: none;
}
}

View File

@@ -1,107 +1,127 @@
<!-- web/dashboard.html -->
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>GPIO Панель</title>
<link rel="icon" type="image/png" href="/favicon.png">
<link rel="stylesheet" href="/css/style.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="theme-color" content="#050805">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<title>Грид Панель</title>
<link rel="icon" type="image/png" href="/favicon.png">
<!-- Локальные шрифты -->
<link rel="stylesheet" href="/css/fonts.css">
<!-- ===== СТИЛИ ===== -->
<link rel="stylesheet" href="/css/base.css">
<link rel="stylesheet" href="/css/header.css">
<link rel="stylesheet" href="/css/layout.css">
<link rel="stylesheet" href="/css/cards.css">
<link rel="stylesheet" href="/css/components.css">
<link rel="stylesheet" href="/css/camera.css">
<link rel="stylesheet" href="/css/audio.css">
<link rel="stylesheet" href="/css/responsive.css">
</head>
<body>
<div class="header-bar">
<h1>GPIO МОНИТОРИНГ В РЕАЛЬНОМ ВРЕМЕНИ</h1>
<div style="display:flex; gap:12px; align-items:center;">
<a href="/logs.html" style="color:#00ff88; text-decoration:none; font-size:14px; border:1px solid #00ff88; padding:6px 14px; border-radius:6px;">📋 Журнал</a>
<div id="server-time" class="header-time">--:--:--</div>
<div id="audio-indicator" style="font-size:18px; padding:4px 12px; border-radius:6px; background:rgba(0,0,0,0.4); border:1px solid #333; min-width:50px; text-align:center;">🔇</div>
<button id="camToggle" class="cam-btn">📷 КАМЕРА</button>
<div class="header-bar">
<h1>ЗВЕЗДНЫЙ ГРИД</h1>
<div class="header-controls">
<a href="/logs.html" class="header-link">Журнал</a>
<div id="server-time" class="header-time">--:--:--</div>
<div id="audio-indicator" class="audio-indicator">🔇</div>
<button id="camToggle" class="cam-btn">КАМЕРА</button>
</div>
</div>
</div>
<div class="layout">
<!-- LEFT: графики / дашборд -->
<div class="panel left" id="leftPanel">
<div class="grid">
<div class="layout">
<!-- LEFT: графики / дашборд -->
<div class="panel left" id="leftPanel">
<div class="grid">
<div class="card wide">
<h3>СОСТОЯНИЕ</h3>
<div id="status">...</div>
<div id="meta"></div>
</div>
<div class="card wide">
<h3>📊 СОСТОЯНИЕ</h3>
<div id="status">...</div>
<div id="meta"></div>
</div>
<div class="card wide">
<h3>УРОВНИ КАНАЛОВ</h3>
<div class="card wide">
<h3>📈 УРОВНИ КАНАЛОВ</h3>
<div class="progress-row">
<div class="progress-label">Канал 1 — <span id="last-byte">0</span></div>
<div class="progress-with-signal">
<div class="progress progress-90">
<div class="fill" id="bar1"></div>
<div class="progress-row">
<div class="progress-label">
Канал 1 — <span id="last-byte">0</span>
</div>
<div class="signal-icon" id="signal-icon" aria-label="Уровень сигнала" role="img">
<div class="sig-bar sig-bar-1"></div>
<div class="sig-bar sig-bar-2"></div>
<div class="sig-bar sig-bar-3"></div>
<div class="progress-with-signal">
<div class="progress progress-90">
<div class="fill" id="bar1"></div>
</div>
<div class="signal-icon" id="signal-icon" aria-label="Уровень сигнала" role="img">
<div class="sig-bar sig-bar-1"></div>
<div class="sig-bar sig-bar-2"></div>
<div class="sig-bar sig-bar-3"></div>
</div>
</div>
</div>
<div class="progress-row">
<div class="progress-label">🔊 Звук</div>
<div class="progress">
<div class="fill" id="bar2"></div>
</div>
</div>
<div class="progress-row">
<div class="progress-label">📐 Высота</div>
<div class="progress">
<div class="fill" id="bar3"></div>
</div>
</div>
</div>
<div class="progress-row">
<div class="progress-label">Звук</div>
<div class="progress">
<div class="fill" id="bar2"></div>
<div class="card wide">
<h3 class="accordion-header" id="history-header">▶ ПРИНЯТЫЕ ДАННЫЕ</h3>
<div class="accordion-body" id="history-body">
<div id="history"></div>
</div>
</div>
<div class="progress-row">
<div class="progress-label">Высота</div>
<div class="progress">
<div class="fill" id="bar3"></div>
</div>
</div>
<!-- DRAG HANDLE -->
<div class="resizer" id="dragBar"></div>
<!-- RIGHT: камера -->
<div class="panel right hidden" id="rightPanel">
<div class="cam-modal">
<div class="cam-header">
<span>📹 Видео с камеры</span>
<button id="camCloseBtn" class="cam-close-btn" aria-label="Закрыть камеру"></button>
</div>
<div class="cam-frame-wrapper">
<img id="camImage" src="" alt="Camera" class="cam-frame">
<!-- ПЕРЕКРЕСТИЕ -->
<div class="cam-crosshair" id="crosshair">
<div class="crosshair-v"></div>
<div class="crosshair-h"></div>
<div class="crosshair-box"></div>
</div>
</div>
</div>
<div class="card wide">
<h3 class="accordion-header" id="history-header">▶ ПРИНЯТЫЕ ДАННЫЕ</h3>
<div class="accordion-body" id="history-body">
<div id="history"></div>
</div>
</div>
</div>
</div>
<!-- DRAG HANDLE -->
<div class="resizer" id="dragBar"></div>
<!-- RIGHT: камера -->
<div class="panel right hidden" id="rightPanel">
<div class="cam-modal">
<div class="cam-header">
<span>Видео с камеры</span>
</div>
<div class="cam-frame-wrapper">
<img id="camImage" src="" alt="Camera" class="cam-frame">
<!-- ПЕРЕКРЕСТИЕ -->
<div class="cam-crosshair" id="crosshair">
<!-- Основные линии -->
<div class="crosshair-v"></div>
<div class="crosshair-h"></div>
<!-- Центральный квадрат -->
<div class="crosshair-box"></div>
</div>
</div>
</div>
<!-- Подсказка по горячим клавишам -->
<div class="hotkey-hint">
<kbd>C</kbd> — камера &nbsp;|&nbsp; <kbd>F</kbd> — полный экран &nbsp;|&nbsp; <kbd>M</kbd> — звук &nbsp;|&nbsp; <kbd>Esc</kbd>сброс
</div>
</div>
<script type="module" src="/dist/app.js"></script>
<script type="module" src="/dist/app.js"></script>
</body>
</html>
</html>

View File

@@ -1,18 +0,0 @@
// accordion.ts
import { DOM } from "./ui.js";
export function initAccordion() {
if (!DOM.historyHeader || !DOM.historyBody)
return;
let open = false;
DOM.historyBody.classList.add("collapsed");
DOM.historyHeader.textContent = "▶ ПРИНЯТЫЕ ДАННЫЕ";
DOM.historyHeader.addEventListener("click", () => {
open = !open;
if (DOM.historyHeader) {
DOM.historyHeader.textContent = (open ? "▼" : "▶") + " ПРИНЯТЫЕ ДАННЫЕ";
}
if (DOM.historyBody) {
DOM.historyBody.classList.toggle("collapsed", !open);
}
});
}

View File

@@ -1,138 +0,0 @@
// app.js (оркестратор)
import { fetchHealth, fetchHistory } from "./data.js";
import { state, smooth, addSignals, resetBufferTracking } from "./state.js";
import { initDOM, setStatus, setMeta, setBars, setSignal, DOM } from "./ui.js";
import { initAccordion } from "./accordion.js";
import { drawChart } from "./chart.js";
import { initResize } from "./layout.js";
import { initCamera } from "./camera.js";
let lastChart = 0;
let connectionLost = false;
let consecutiveErrors = 0;
const MAX_ERRORS = 3;
let pollTimer = null;
// ================= INIT =================
window.addEventListener("DOMContentLoaded", () => {
initDOM();
initAccordion();
initResize();
initCamera();
});
document.addEventListener("keydown", (e) => {
const leftPanel = document.getElementById("leftPanel");
const rightPanel = document.getElementById("rightPanel");
switch (e.key.toLowerCase()) {
case 'c':
const camBtn = document.getElementById('camToggle');
if (camBtn)
camBtn.click();
break;
case 'f':
if (leftPanel) {
leftPanel.style.width = "100%";
if (rightPanel)
rightPanel.style.display = "none";
}
break;
case 'escape':
if (rightPanel)
rightPanel.style.display = "flex";
if (leftPanel && rightPanel) {
const total = window.innerWidth;
const leftWidth = total * 0.6;
leftPanel.style.flex = `0 0 ${leftWidth}px`;
rightPanel.style.flex = `0 0 ${total - leftWidth}px`;
}
break;
}
});
// ================= UPDATE =================
async function update() {
try {
const [health, history] = await Promise.all([
fetchHealth(),
fetchHistory()
]);
consecutiveErrors = 0;
if (connectionLost) {
console.log("[app] Соединение восстановлено");
}
const isOnline = health.pipe_alive && health.has_data;
if (isOnline) {
setStatus("На связи");
connectionLost = false;
}
else {
setStatus("Нет связи", true);
if (!connectionLost)
resetBufferTracking();
connectionLost = true;
}
const arr = Array.isArray(history.bytes) ? history.bytes : [];
const raw = arr[arr.length - 1] ?? 0;
if (arr.length > 0 && isOnline) {
const bufferSize = health.stats?.filled ?? 0;
addSignals(arr, bufferSize);
}
const value = raw & 0x3F;
const level = (raw >> 6) & 0x3;
const percent = (value / 63) * 100;
if (isOnline) {
setBars(smooth(percent));
setSignal(level);
}
else {
setBars(0, true);
setSignal(0, true);
}
if (DOM.lastByte) {
DOM.lastByte.textContent = isOnline ? value.toString() : "--";
}
const uptime = Math.round(health.uptime_sec || 0);
const filled = health.stats?.filled ?? 0;
const Bps = Math.round(health.stats?.bytes_per_sec ?? 0);
setMeta(`Работа: ${uptime}s | Буфер: ${filled} | Приём: ${Bps} B/s`);
if (DOM.history) {
DOM.history.innerHTML = arr
.map((b, i) => `[${i}] ${(b & 0xFF).toString(2).padStart(8, "0")} = ${b & 0xFF}`)
.join("<br>");
}
const now = performance.now();
if (now - lastChart > 100 && DOM.canvas) {
drawChart(DOM.canvas, state.signalHistory);
lastChart = now;
}
}
catch (e) {
consecutiveErrors++;
if (consecutiveErrors === 1)
console.warn("[app] Сервер недоступен, ждём...");
setStatus("СЕРВЕР НЕДОСТУПЕН", true);
setBars(0, true);
setSignal(0, true);
resetBufferTracking();
if (DOM.lastByte)
DOM.lastByte.textContent = "--";
if (consecutiveErrors >= MAX_ERRORS && pollTimer) {
clearInterval(pollTimer);
pollTimer = window.setInterval(update, 2000);
console.log("[app] Замедлили опрос до 2с");
}
}
}
function startPolling() {
if (pollTimer)
clearInterval(pollTimer);
if (consecutiveErrors > 0)
update();
pollTimer = window.setInterval(update, 500);
}
window.addEventListener("focus", () => {
if (consecutiveErrors >= MAX_ERRORS) {
console.log("[app] Окно в фокусе, ускоряем опрос");
consecutiveErrors = 0;
startPolling();
}
});
startPolling();
update();

View File

@@ -1,148 +0,0 @@
// camera.ts
import { updateResizerVisibility } from './layout.js';
let rightPanel = null;
let camImage = null;
let crosshair = null;
let isOpen = false;
let streamCheckInterval = null;
export function initCamera() {
rightPanel = document.getElementById("rightPanel");
camImage = document.getElementById("camImage");
crosshair = document.getElementById("crosshair");
// Проверяем доступность потока
checkStreamAvailability();
const btn = document.getElementById("camToggle");
const streamUrl = "/api/cam";
function open() {
if (isOpen)
return;
isOpen = true;
if (rightPanel) {
rightPanel.classList.remove("hidden");
}
// Показываем перекрестие
if (crosshair) {
crosshair.style.display = "block";
}
if (camImage) {
camImage.src = streamUrl;
}
if (btn) {
const textSpan = btn.querySelector('.cam-btn-text');
if (textSpan)
textSpan.textContent = 'Скрыть';
}
console.log("[camera] opened");
updateResizerVisibility();
// Запускаем мониторинг потока
startStreamMonitoring();
}
function close() {
if (!isOpen)
return;
isOpen = false;
// Скрываем перекрестие
if (crosshair) {
crosshair.style.display = "none";
}
// остановка stream
if (camImage) {
camImage.src = "";
}
if (rightPanel) {
rightPanel.classList.add("hidden");
}
if (btn) {
const textSpan = btn.querySelector('.cam-btn-text');
if (textSpan)
textSpan.textContent = 'Камера';
}
console.log("[camera] closed");
updateResizerVisibility();
// Останавливаем мониторинг
stopStreamMonitoring();
}
function toggle() {
if (isOpen) {
close();
}
else {
open();
}
}
if (camImage) {
camImage.onload = () => {
console.log("[camera] stream started");
if (crosshair) {
crosshair.style.opacity = '1';
}
};
camImage.onerror = (e) => {
console.error("[camera] stream error", e);
if (crosshair) {
crosshair.style.opacity = '0.3';
}
};
}
btn?.addEventListener("click", toggle);
// Проверка доступности камеры
async function checkStreamAvailability() {
try {
const response = await fetch('/api/stream');
const data = await response.json();
if (data.available && data.cam) {
console.log("[camera] stream available:", data.source);
// Автозапуск если камера доступна
if (!isOpen) {
open();
}
}
else {
console.log("[camera] stream not available");
if (crosshair) {
crosshair.style.display = 'none';
}
}
}
catch (error) {
console.log("[camera] check failed:", error);
}
}
// Мониторинг состояния потока
function startStreamMonitoring() {
stopStreamMonitoring();
streamCheckInterval = window.setInterval(() => {
if (isOpen && camImage) {
if (!camImage.complete || camImage.naturalWidth === 0) {
if (crosshair) {
crosshair.style.opacity = '0.3';
}
}
else {
if (crosshair) {
crosshair.style.opacity = '1';
}
}
}
}, 2000);
}
function stopStreamMonitoring() {
if (streamCheckInterval) {
clearInterval(streamCheckInterval);
streamCheckInterval = null;
}
}
}
// Экспортируем для возможности ручного управления
export function showCrosshair(show = true) {
const crosshairElem = document.getElementById("crosshair");
if (crosshairElem) {
crosshairElem.style.display = show ? "block" : "none";
}
}
export function setCrosshairOpacity(opacity) {
const crosshairElem = document.getElementById("crosshair");
if (crosshairElem) {
crosshairElem.style.opacity = String(opacity);
}
}

View File

@@ -1,114 +0,0 @@
// chart.js
export function drawChart(canvas, history) {
if (!canvas || !history?.length)
return;
const rect = canvas.getBoundingClientRect();
const displayHeight = rect.height || 200;
const displayWidth = rect.width || 800;
canvas.width = displayWidth;
canvas.height = displayHeight;
const ctx = canvas.getContext("2d");
if (!ctx)
return;
const w = canvas.width;
const h = canvas.height;
const padLeft = 45;
const padRight = 15;
const padTop = 10;
const padBottom = 25;
const plotW = w - padLeft - padRight;
const plotH = h - padTop - padBottom;
// Фон
ctx.fillStyle = "#0a0f0a";
ctx.fillRect(0, 0, w, h);
// Сетка
const maxVal = 63;
const gridLines = 4;
ctx.strokeStyle = "#0d2a0d";
ctx.lineWidth = 0.5;
ctx.setLineDash([4, 4]);
for (let i = 0; i <= gridLines; i++) {
const val = (maxVal / gridLines) * i;
const y = padTop + plotH - (val / maxVal) * plotH;
ctx.beginPath();
ctx.moveTo(padLeft, y);
ctx.lineTo(w - padRight, y);
ctx.stroke();
ctx.fillStyle = "#00ff88";
ctx.font = "11px monospace";
ctx.textAlign = "right";
ctx.fillText(Math.round(val).toString(), padLeft - 8, y + 4);
}
ctx.setLineDash([]);
// Подписи осей
ctx.fillStyle = "#00ff88";
ctx.font = "bold 11px monospace";
ctx.save();
ctx.translate(12, padTop + plotH / 2);
ctx.rotate(-Math.PI / 2);
ctx.textAlign = "center";
ctx.fillText("ЗНАЧЕНИЕ", 0, 0);
ctx.restore();
ctx.textAlign = "center";
ctx.fillText("БУФЕР ПРИНЯТЫХ ДАННЫХ", padLeft + plotW / 2, h - 4);
const hasSignal = history.some(v => v > 0);
if (!hasSignal) {
ctx.fillStyle = "#ff4444";
ctx.font = "14px monospace";
ctx.textAlign = "center";
ctx.fillText("Ожидание сигнала...", w / 2, h / 2);
return;
}
let plotData = history;
if (history.length > plotW) {
const step = history.length / plotW;
plotData = [];
for (let i = 0; i < plotW; i++) {
const idx = Math.floor(i * step);
plotData.push(history[idx]);
}
}
ctx.strokeStyle = "#e6852d";
ctx.lineWidth = 1.5;
ctx.shadowColor = "#e6852d";
ctx.shadowBlur = 3;
ctx.beginPath();
const stepX = plotW / Math.max(plotData.length - 1, 1);
for (let i = 0; i < plotData.length; i++) {
const x = padLeft + i * stepX;
const y = padTop + plotH - (plotData[i] / maxVal) * plotH;
if (i === 0)
ctx.moveTo(x, y);
else
ctx.lineTo(x, y);
}
ctx.stroke();
ctx.shadowBlur = 0;
if (history.length > 0) {
const lastVal = history[history.length - 1];
const lastX = padLeft + (plotData.length - 1) * stepX;
const lastY = padTop + plotH - (lastVal / maxVal) * plotH;
ctx.fillStyle = "#c46b1f";
ctx.beginPath();
ctx.arc(lastX, lastY, 4, 0, Math.PI * 2);
ctx.fill();
const labelText = `${lastVal}`;
const labelWidth = ctx.measureText(labelText).width;
ctx.fillStyle = "rgba(0,0,0,0.8)";
ctx.fillRect(lastX - labelWidth / 2 - 4, lastY - 22, labelWidth + 8, 18);
ctx.fillStyle = "#00ff88";
ctx.font = "bold 12px monospace";
ctx.textAlign = "center";
ctx.fillText(labelText, lastX, lastY - 8);
const peak = Math.max(...history);
const min = Math.min(...history);
ctx.fillStyle = "rgba(0,0,0,0.7)";
ctx.fillRect(w - 120, padTop, 110, 42);
ctx.fillStyle = "#00ff88";
ctx.font = "10px monospace";
ctx.textAlign = "left";
ctx.fillText(`Пик: ${peak}`, w - 110, padTop + 14);
ctx.fillText(`Мин: ${min}`, w - 110, padTop + 28);
ctx.fillText(`Точек: ${history.length}`, w - 110, padTop + 42);
}
}

View File

@@ -1,12 +0,0 @@
export async function fetchHealth() {
const r = await fetch("/api/health");
if (!r.ok)
throw new Error(`HTTP ${r.status}`);
return r.json();
}
export async function fetchHistory() {
const r = await fetch("/api/history");
if (!r.ok)
throw new Error(`HTTP ${r.status}`);
return r.json();
}

View File

@@ -1,79 +0,0 @@
// layout.ts
let leftPanel = null;
let rightPanel = null;
let dragBar = null;
let isDragging = false;
let pendingX = null;
export function initResize() {
leftPanel = document.getElementById("leftPanel");
rightPanel = document.getElementById("rightPanel");
dragBar = document.getElementById("dragBar");
if (!leftPanel || !rightPanel || !dragBar)
return;
const savedRatio = localStorage.getItem('layoutRatio');
if (savedRatio) {
applyRatio(parseFloat(savedRatio));
}
dragBar.addEventListener("mousedown", (e) => {
if (rightPanel.classList.contains("hidden"))
return;
isDragging = true;
document.body.style.cursor = "col-resize";
e.preventDefault();
});
document.addEventListener("mouseup", () => {
if (!isDragging)
return;
isDragging = false;
document.body.style.cursor = "default";
if (rightPanel && !rightPanel.classList.contains("hidden")) {
const total = window.innerWidth;
const leftWidth = leftPanel.getBoundingClientRect().width;
localStorage.setItem('layoutRatio', String(leftWidth / total));
}
});
document.addEventListener("mousemove", (e) => {
if (!isDragging)
return;
if (rightPanel && rightPanel.classList.contains("hidden"))
return;
pendingX = e.clientX;
requestAnimationFrame(() => {
if (pendingX === null)
return;
if (!leftPanel || !rightPanel || !dragBar)
return;
const total = window.innerWidth;
let leftWidth = pendingX;
const min = 300;
if (leftWidth < min)
leftWidth = min;
if (leftWidth > total - min)
leftWidth = total - min;
const rightWidth = total - leftWidth - dragBar.offsetWidth;
leftPanel.style.flex = `0 0 ${leftWidth}px`;
rightPanel.style.flex = `0 0 ${rightWidth}px`;
pendingX = null;
});
});
}
function applyRatio(ratio) {
const total = window.innerWidth;
const leftWidth = Math.floor(total * ratio);
const rightWidth = total - leftWidth;
if (leftPanel && rightPanel) {
leftPanel.style.flex = `0 0 ${leftWidth}px`;
rightPanel.style.flex = `0 0 ${rightWidth}px`;
}
}
export function updateResizerVisibility() {
if (!dragBar || !rightPanel || !leftPanel)
return;
if (rightPanel.classList.contains("hidden")) {
dragBar.classList.add("hidden");
leftPanel.style.flex = "1";
}
else {
dragBar.classList.remove("hidden");
}
}

View File

@@ -1,33 +0,0 @@
export const state = {
maxPoints: 1000,
signalHistory: [],
smoothValue: 0,
lastBufferSize: 0,
};
export function smooth(target) {
state.smoothValue += 0.2 * (target - state.smoothValue);
return state.smoothValue;
}
export function addSignal(value) {
state.signalHistory.push(value);
if (state.signalHistory.length > state.maxPoints) {
state.signalHistory = state.signalHistory.slice(-state.maxPoints);
}
}
export function addSignals(values, bufferSize) {
if (!Array.isArray(values) || values.length === 0)
return;
const newBytes = bufferSize - state.lastBufferSize;
if (newBytes > 0 && newBytes <= values.length) {
const fresh = values.slice(-newBytes);
const decoded = fresh.map(b => b & 0x3F);
state.signalHistory.push(...decoded);
}
state.lastBufferSize = bufferSize;
if (state.signalHistory.length > state.maxPoints) {
state.signalHistory = state.signalHistory.slice(-state.maxPoints);
}
}
export function resetBufferTracking() {
state.lastBufferSize = 0;
}

View File

@@ -1,86 +0,0 @@
export const DOM = {
status: null,
meta: null,
latest: null,
lastByte: null,
history: null,
canvas: null,
bars: document.querySelectorAll(".sig-bar"),
barFill: null,
historyHeader: null,
historyBody: null,
};
export function initDOM() {
DOM.status = document.getElementById("status");
DOM.meta = document.getElementById("meta");
DOM.latest = document.getElementById("latest");
DOM.lastByte = document.getElementById("last-byte");
DOM.history = document.getElementById("history");
DOM.canvas = document.getElementById("signalChart");
DOM.barFill = document.getElementById("bar1");
DOM.historyHeader = document.getElementById("history-header");
DOM.historyBody = document.getElementById("history-body");
DOM.bars = document.querySelectorAll(".sig-bar");
}
export function setStatus(v, isError = false) {
if (!DOM.status)
return;
DOM.status.textContent = v;
DOM.status.classList.remove("status-ok", "status-error", "status-lost");
if (isError) {
if (v === "Нет связи") {
DOM.status.classList.add("status-lost");
}
else {
DOM.status.classList.add("status-error");
}
}
else {
DOM.status.classList.add("status-ok");
}
}
export function setMeta(v) {
if (DOM.meta)
DOM.meta.textContent = v;
}
export function setBars(p, noConnection = false) {
const el = DOM.barFill;
if (!el)
return;
if (noConnection) {
el.style.width = "0%";
el.classList.add("no-connection");
}
else {
el.classList.remove("no-connection");
el.style.width = `${Math.max(0, Math.min(100, p))}%`;
}
}
export function setSignal(level, noConnection = false) {
const bars = DOM.bars;
if (!bars || bars.length < 3)
return;
bars.forEach(bar => {
bar.classList.remove("active-1", "active-2", "active-3", "dim", "no-connection");
if (noConnection) {
bar.classList.add("no-connection");
}
else {
bar.classList.add("dim");
}
});
if (noConnection)
return;
if (level >= 1) {
bars[0].classList.add("active-1");
bars[0].classList.remove("dim");
}
if (level >= 2) {
bars[1].classList.add("active-2");
bars[1].classList.remove("dim");
}
if (level >= 3) {
bars[2].classList.add("active-3");
bars[2].classList.remove("dim");
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -64,6 +64,20 @@ window.addEventListener("DOMContentLoaded", () => {
});
});
document.addEventListener('DOMContentLoaded', () => {
// Обработчик для кнопки закрытия камеры
const closeBtn = document.getElementById('camCloseBtn');
const toggleBtn = document.getElementById('camToggle');
if (closeBtn) {
closeBtn.addEventListener('click', () => {
if (toggleBtn) {
toggleBtn.click(); // Эмулируем нажатие кнопки переключения
}
});
}
});
document.addEventListener("keydown", (e: KeyboardEvent) => {
const leftPanel = document.getElementById("leftPanel");
const rightPanel = document.getElementById("rightPanel");

525
cmd/server/web/js/logs.ts Normal file
View File

@@ -0,0 +1,525 @@
// js/logs.ts - Логика для страницы журнала логов
import { drawChart } from './chart.js';
// ============================================
// ТИПЫ
// ============================================
interface LogFileInfo {
name: string;
path: string;
size: number;
mod_time: string;
time: string;
date: string;
hour: number;
is_active: boolean;
}
interface LogSample {
ts: number;
time: string;
value: number;
count: number;
strength: number;
strength_name: string;
amplitude: number;
signal: number;
}
interface LogDataResponse {
filename: string;
total: number;
samples: LogSample[];
}
interface Event {
time: string;
event: string;
}
interface EventsResponse {
events: Event[];
total: number;
page: number;
page_size: number;
total_pages: number;
has_previous: boolean;
has_next: boolean;
returned: number;
start_index: number;
end_index: number;
order?: string;
}
// ============================================
// СОСТОЯНИЕ
// ============================================
interface AppState {
currentFile: string | null;
currentData: LogDataResponse | null;
currentEvents: Event[];
currentPage: number;
totalPages: number;
isLoading: boolean;
}
const state: AppState = {
currentFile: null,
currentData: null,
currentEvents: [],
currentPage: 1,
totalPages: 1,
isLoading: false,
};
const PAGE_SIZE = 100;
// ============================================
// DOM ЭЛЕМЕНТЫ
// ============================================
const DOM = {
fileList: document.getElementById('fileList') as HTMLElement | null,
logStats: document.getElementById('logStats') as HTMLElement | null,
dataTableContainer: document.getElementById('dataTableContainer') as HTMLElement | null,
logChart: document.getElementById('logChart') as HTMLCanvasElement | null,
eventsContent: document.getElementById('eventsContent') as HTMLElement | null,
serverTime: document.getElementById('server-time') as HTMLElement | null,
// Элементы пагинации
pageInfo: document.getElementById('pageInfo') as HTMLElement | null,
prevPageBtn: document.getElementById('prevPage') as HTMLButtonElement | null,
nextPageBtn: document.getElementById('nextPage') as HTMLButtonElement | null,
firstPageBtn: document.getElementById('firstPage') as HTMLButtonElement | null,
lastPageBtn: document.getElementById('lastPage') as HTMLButtonElement | null,
pageInput: document.getElementById('pageInput') as HTMLInputElement | null,
goToPageBtn: document.getElementById('goToPage') as HTMLButtonElement | null,
};
// ============================================
// ФУНКЦИИ ЗАГРУЗКИ ДАННЫХ
// ============================================
/**
* Загрузка списка файлов
*/
async function loadFileList(): Promise<void> {
try {
const response = await fetch('/api/log/files');
const files: LogFileInfo[] = await response.json();
if (!DOM.fileList) return;
DOM.fileList.innerHTML = '';
files.forEach((file: LogFileInfo) => {
const div = document.createElement('div');
div.className = 'log-file-item';
if (state.currentFile === file.name) {
div.classList.add('active');
}
div.innerHTML = `
<div class="file-name">${file.name}</div>
<div class="file-info">${file.time} | ${(file.size / 1024).toFixed(1)} KB</div>
`;
div.addEventListener('click', () => {
void loadFileData(file.name);
});
DOM.fileList?.appendChild(div);
});
// Автоматически загружаем первый файл
if (files.length > 0 && !state.currentFile) {
await loadFileData(files[0].name);
}
} catch (error) {
console.error('[Logs] Ошибка загрузки списка файлов:', error);
}
}
/**
* Загрузка данных из файла
*/
async function loadFileData(filename: string): Promise<void> {
state.currentFile = filename;
// Обновляем активный элемент в списке
const items = document.querySelectorAll('.log-file-item');
// Используем Array.from для преобразования NodeList в массив
Array.from(items).forEach((el) => {
el.classList.remove('active');
});
// Находим активный элемент
const activeItems = document.querySelectorAll('.log-file-item');
for (let i = 0; i < activeItems.length; i++) {
const item = activeItems[i] as HTMLElement;
if (item.textContent?.includes(filename)) {
item.classList.add('active');
break;
}
}
try {
const response = await fetch(`/api/log/data?file=${encodeURIComponent(filename)}`);
const data: LogDataResponse = await response.json();
state.currentData = data;
renderData(data);
} catch (error) {
console.error('[Logs] Ошибка загрузки данных:', error);
}
}
/**
* Загрузка событий с пагинацией
*/
async function loadEvents(page: number = 1): Promise<void> {
if (state.isLoading) return;
try {
state.isLoading = true;
state.currentPage = page;
// Показываем индикатор загрузки
if (DOM.eventsContent) {
DOM.eventsContent.innerHTML = '<div class="loading-indicator">Загрузка событий...</div>';
}
const url = `/api/log/events?page=${page}&page_size=${PAGE_SIZE}&order=newest_first`;
console.log(`[Logs] Загрузка страницы ${page} (новые сверху)`);
const response = await fetch(url);
const data: EventsResponse = await response.json();
state.totalPages = data.total_pages;
state.currentEvents = data.events || [];
// Отрисовываем события
renderEvents(data);
// Обновляем элементы пагинации
updatePagination(data);
console.log(`[Logs] Загружено: ${data.returned} событий, Страница: ${page}/${data.total_pages}`);
console.log(`[Logs] Порядок: ${data.order || 'newest_first'}, Показаны записи ${data.start_index}-${data.end_index} из ${data.total}`);
} catch (error) {
console.error('[Logs] Ошибка загрузки событий:', error);
if (DOM.eventsContent) {
DOM.eventsContent.innerHTML = '<div style="color:#ff4444;">❌ Ошибка загрузки событий</div>';
}
} finally {
state.isLoading = false;
}
}
// ============================================
// ФУНКЦИИ ОТРИСОВКИ
// ============================================
/**
* Отрисовка данных файла
*/
function renderData(data: LogDataResponse): void {
const samples = data.samples || [];
// Статистика
if (samples.length > 0 && DOM.logStats) {
const totalPoints = samples.length;
const amplitudeOver0Count = samples.filter((s: LogSample) => s.amplitude > 0).length;
const signalOver10Count = samples.filter((s: LogSample) => s.signal > 10).length;
const totalObjects = samples.reduce((sum: number, s: LogSample) => sum + s.signal, 0);
DOM.logStats.innerHTML = `
<div class="log-stat-card">
<div class="value">${totalPoints}</div>
<div class="label">Всего точек</div>
</div>
<div class="log-stat-card">
<div class="value">${amplitudeOver0Count}</div>
<div class="label">Амплитуда > 0</div>
</div>
<div class="log-stat-card">
<div class="value">${signalOver10Count}</div>
<div class="label">Сигнал > 10</div>
</div>
<div class="log-stat-card">
<div class="value">${totalObjects}</div>
<div class="label">Объектов всего</div>
</div>
`;
}
// График
if (DOM.logChart && samples.length > 0) {
const history = samples.map((s: LogSample) => s.signal);
drawChart(DOM.logChart, history);
}
// Таблица
if (samples.length > 0 && DOM.dataTableContainer) {
let html = `<table class="data-table">
<thead>
<tr>
<th>Время</th>
<th>Амплитуда</th>
<th>Сигнал</th>
</tr>
</thead>
<tbody>`;
const displaySamples = samples.slice(-200);
displaySamples.forEach((s: LogSample) => {
let ampClass = '';
if (s.amplitude === 0) ampClass = 'strength-0';
else if (s.amplitude === 1) ampClass = 'strength-1';
else if (s.amplitude === 2) ampClass = 'strength-2';
else if (s.amplitude === 3) ampClass = 'strength-3';
html += `<tr>
<td>${s.time}</td>
<td class="${ampClass}">${s.amplitude}</td>
<td>${s.signal}</td>
</tr>`;
});
html += '</tbody></table>';
DOM.dataTableContainer.innerHTML = html;
} else if (DOM.dataTableContainer) {
DOM.dataTableContainer.innerHTML = '<p>Нет данных</p>';
}
}
/**
* Отрисовка событий
*/
function renderEvents(data: EventsResponse): void {
if (!DOM.eventsContent) return;
let html = '';
if (data.events.length === 0) {
html = '<div style="color:#666;">Нет событий</div>';
} else {
data.events.forEach((e: Event) => {
html += `<div><span class="event-time">[${e.time}]</span> ${e.event}</div>`;
});
}
DOM.eventsContent.innerHTML = html;
}
/**
* Обновление элементов пагинации
*/
function updatePagination(data: EventsResponse): void {
const { page, total_pages, has_previous, has_next, start_index, end_index, total } = data;
// Обновляем информацию о странице
if (DOM.pageInfo) {
if (total === 0) {
DOM.pageInfo.textContent = 'Нет записей';
} else {
const orderText = data.order === 'newest_first' ? 'новые сверху' : 'старые сверху';
DOM.pageInfo.textContent = `Страница ${page} из ${total_pages} (записи ${start_index}-${end_index} из ${total}) ${orderText}`;
}
}
// Кнопки навигации
if (DOM.firstPageBtn) DOM.firstPageBtn.disabled = !has_previous;
if (DOM.prevPageBtn) DOM.prevPageBtn.disabled = !has_previous;
if (DOM.nextPageBtn) DOM.nextPageBtn.disabled = !has_next;
if (DOM.lastPageBtn) DOM.lastPageBtn.disabled = !has_next;
// Поле ввода номера страницы
if (DOM.pageInput) {
DOM.pageInput.value = page.toString();
DOM.pageInput.max = total_pages.toString();
}
}
// ============================================
// НАВИГАЦИЯ ПО СТРАНИЦАМ (ИСПРАВЛЕНО)
// ============================================
function goToPage(page: number): void {
if (page < 1) page = 1;
if (page > state.totalPages) page = state.totalPages;
if (page === state.currentPage) return;
void loadEvents(page);
}
function goToFirstPage(): void {
goToPage(1); // Первая страница = самые новые
}
function goToLastPage(): void {
goToPage(state.totalPages); // Последняя страница = самые старые
}
// "◀ Предыдущая" → страница с номером на 1 меньше (более новые записи)
function goToPreviousPage(): void {
goToPage(state.currentPage - 1);
}
// "Следующая ▶" → страница с номером на 1 больше (более старые записи)
function goToNextPage(): void {
goToPage(state.currentPage + 1);
}
// ============================================
// ОБНОВЛЕНИЕ ВРЕМЕНИ
// ============================================
async function updateTime(): Promise<void> {
try {
const response = await fetch('/api/health');
const data = await response.json();
if (DOM.serverTime) {
DOM.serverTime.textContent = data.server_time || new Date().toLocaleTimeString();
}
} catch (error) {
// Если сервер недоступен, используем локальное время
if (DOM.serverTime) {
DOM.serverTime.textContent = new Date().toLocaleTimeString();
}
}
}
// ============================================
// ИНИЦИАЛИЗАЦИЯ
// ============================================
function initPaginationControls(): void {
// Создаём элементы пагинации, если их нет
const eventsTab = document.getElementById('tab-events');
if (!eventsTab) return;
// Проверяем, есть ли уже контейнер пагинации
let paginationContainer = document.getElementById('paginationContainer');
if (!paginationContainer) {
paginationContainer = document.createElement('div');
paginationContainer.id = 'paginationContainer';
paginationContainer.className = 'pagination-container';
paginationContainer.innerHTML = `
<div class="pagination-controls">
<button id="firstPage" class="pagination-btn" title="Первая страница (самые новые)">⏮</button>
<button id="prevPage" class="pagination-btn" title="Предыдущая страница (более новые)">◀</button>
<span id="pageInfo" class="pagination-info">Страница 1 из 1</span>
<button id="nextPage" class="pagination-btn" title="Следующая страница (более старые)">▶</button>
<button id="lastPage" class="pagination-btn" title="Последняя страница (самые старые)">⏭</button>
<span class="pagination-goto">
<input type="number" id="pageInput" min="1" value="1" class="pagination-input">
<button id="goToPage" class="pagination-btn pagination-goto-btn">Перейти</button>
</span>
</div>
`;
// Вставляем перед содержимым событий
const eventsContent = document.getElementById('eventsContent');
if (eventsContent) {
eventsTab.insertBefore(paginationContainer, eventsContent);
}
}
// Обновляем ссылки на DOM элементы
DOM.firstPageBtn = document.getElementById('firstPage') as HTMLButtonElement | null;
DOM.prevPageBtn = document.getElementById('prevPage') as HTMLButtonElement | null;
DOM.nextPageBtn = document.getElementById('nextPage') as HTMLButtonElement | null;
DOM.lastPageBtn = document.getElementById('lastPage') as HTMLButtonElement | null;
DOM.pageInfo = document.getElementById('pageInfo') as HTMLElement | null;
DOM.pageInput = document.getElementById('pageInput') as HTMLInputElement | null;
DOM.goToPageBtn = document.getElementById('goToPage') as HTMLButtonElement | null;
// Обработчики событий
if (DOM.firstPageBtn) DOM.firstPageBtn.addEventListener('click', goToFirstPage);
if (DOM.prevPageBtn) DOM.prevPageBtn.addEventListener('click', goToPreviousPage);
if (DOM.nextPageBtn) DOM.nextPageBtn.addEventListener('click', goToNextPage);
if (DOM.lastPageBtn) DOM.lastPageBtn.addEventListener('click', goToLastPage);
if (DOM.goToPageBtn) {
DOM.goToPageBtn.addEventListener('click', () => {
if (DOM.pageInput) {
const page = parseInt(DOM.pageInput.value);
if (!isNaN(page) && page >= 1) {
goToPage(page);
}
}
});
}
if (DOM.pageInput) {
DOM.pageInput.addEventListener('keypress', (e: KeyboardEvent) => {
if (e.key === 'Enter' && DOM.goToPageBtn) {
DOM.goToPageBtn.click();
}
});
}
}
function initTabs(): void {
const tabs = document.querySelectorAll('.tab-btn[data-tab]');
tabs.forEach((btn) => {
btn.addEventListener('click', () => {
// Убираем активный класс у всех кнопок
tabs.forEach((b) => b.classList.remove('active'));
btn.classList.add('active');
const tabName = btn.getAttribute('data-tab');
const contents = document.querySelectorAll('.tab-content');
contents.forEach((el) => el.classList.remove('active'));
const targetTab = document.getElementById(`tab-${tabName}`);
if (targetTab) targetTab.classList.add('active');
if (tabName === 'events') {
// Загружаем первую страницу событий
if (state.currentEvents.length === 0) {
void loadEvents(1);
}
}
});
});
}
async function init(): Promise<void> {
console.log('[Logs] Инициализация...');
// Инициализация пагинации
initPaginationControls();
// Инициализация табов
initTabs();
// Загрузка списка файлов
await loadFileList();
// Обновление времени
await updateTime();
setInterval(() => {
void updateTime();
}, 1000);
// Если вкладка "События" активна по умолчанию, загружаем события
const eventsTab = document.getElementById('tab-events');
if (eventsTab && eventsTab.classList.contains('active')) {
await loadEvents(1);
}
console.log('[Logs] Инициализация завершена');
}
// ============================================
// ЗАПУСК
// ============================================
// Запускаем инициализацию после загрузки DOM
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
void init();
});
} else {
void init();
}

View File

@@ -1,385 +1,74 @@
<!-- web/logs.html -->
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Журнал логов</title>
<link rel="icon" type="image/png" href="/favicon.png">
<link rel="stylesheet" href="/css/style.css">
<style>
/* Дополнительные стили для журнала */
.logs-container {
display: flex;
gap: 20px;
height: calc(100vh - 120px);
}
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="theme-color" content="#050805">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<title>Журнал логов</title>
<link rel="icon" type="image/png" href="/favicon.png">
.logs-sidebar {
flex: 0 0 280px;
border-right: 1px solid #00ff88;
padding-right: 16px;
overflow-y: auto;
}
<!-- Локальные шрифты -->
<link rel="stylesheet" href="/css/fonts.css">
.logs-content {
flex: 1;
overflow-y: auto;
}
<!-- ===== СТИЛИ ===== -->
<link rel="stylesheet" href="/css/base.css">
<link rel="stylesheet" href="/css/header.css">
<link rel="stylesheet" href="/css/layout.css">
<link rel="stylesheet" href="/css/cards.css">
<link rel="stylesheet" href="/css/components.css">
<link rel="stylesheet" href="/css/camera.css">
<link rel="stylesheet" href="/css/audio.css">
<link rel="stylesheet" href="/css/responsive.css">
.log-file-item {
padding: 8px 12px;
margin: 4px 0;
cursor: pointer;
border-radius: 4px;
border: 1px solid transparent;
transition: all 0.2s;
}
.log-file-item:hover {
background: rgba(0,255,136,0.1);
border-color: #00ff88;
}
.log-file-item.active {
background: rgba(0,255,136,0.2);
border-color: #00ff88;
}
.log-file-item .file-name {
font-size: 13px;
}
.log-file-item .file-info {
font-size: 11px;
opacity: 0.6;
}
.log-stats {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
margin-bottom: 16px;
}
.log-stat-card {
padding: 12px;
border: 1px solid #00ff88;
border-radius: 4px;
text-align: center;
}
.log-stat-card .value {
font-size: 24px;
font-weight: bold;
}
.log-stat-card .label {
font-size: 11px;
opacity: 0.6;
}
.data-table {
width: 100%;
font-size: 12px;
border-collapse: collapse;
}
.data-table th {
text-align: left;
padding: 6px 8px;
border-bottom: 1px solid #00ff88;
position: sticky;
top: 0;
background: #050805;
}
.data-table td {
padding: 4px 8px;
border-bottom: 1px solid rgba(0,255,136,0.1);
}
.data-table tr:hover {
background: rgba(0,255,136,0.05);
}
.strength-0 { color: #666; }
.strength-1 { color: #88ff88; }
.strength-2 { color: #ffaa44; }
.strength-3 { color: #ff4444; }
.events-list {
font-family: monospace;
font-size: 13px;
line-height: 1.6;
}
.events-list .event-time {
opacity: 0.5;
}
.tabs {
display: flex;
gap: 8px;
margin-bottom: 16px;
}
.tab-btn {
padding: 6px 16px;
background: transparent;
color: #00ff88;
border: 1px solid #00ff88;
border-radius: 4px;
cursor: pointer;
font-family: monospace;
}
.tab-btn.active {
background: rgba(0,255,136,0.2);
}
.tab-btn:hover {
background: rgba(0,255,136,0.1);
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
</style>
<!-- Специфичные стили для страницы логов -->
<link rel="stylesheet" href="/css/logs.css">
</head>
<body>
<div class="header-bar">
<h1>📋 ЖУРНАЛ ЛОГОВ</h1>
<div id="server-time" class="header-time">--:--:--</div>
<a href="/" style="color:#00ff88; text-decoration:none; font-size:14px;">На главную</a>
</div>
<div class="logs-container">
<div class="logs-sidebar">
<h3 style="margin-top:0;">📁 Файлы данных</h3>
<div id="fileList"></div>
</div>
<div class="logs-content">
<div class="tabs">
<button class="tab-btn active" data-tab="data">📊 Данные</button>
<button class="tab-btn" data-tab="events">📋 События</button>
</div>
<div id="tab-data" class="tab-content active">
<div id="logStats" class="log-stats"></div>
<div id="chartContainer" style="margin-bottom:16px;">
<canvas id="logChart" height="200"></canvas>
</div>
<div id="dataTableContainer" style="max-height:400px; overflow-y:auto;"></div>
</div>
<div id="tab-events" class="tab-content">
<div id="eventsContent" class="events-list">Загрузка...</div>
<div class="header-bar">
<h1>ЖУРНАЛ ЛОГОВ</h1>
<div class="header-controls">
<a href="/" class="header-link">В режим работы</a>
<div id="server-time" class="header-time">--:--:--</div>
</div>
</div>
</div>
<script type="module">
import { drawChart } from '/dist/chart.js';
<div class="logs-container">
<!-- Боковая панель с файлами -->
<div class="logs-sidebar">
<h3>Файлы данных</h3>
<div id="fileList"></div>
</div>
// Состояние
let currentFile = null;
let currentData = null;
let currentEvents = [];
// DOM элементы
const fileList = document.getElementById('fileList');
const logStats = document.getElementById('logStats');
const dataTableContainer = document.getElementById('dataTableContainer');
const logChart = document.getElementById('logChart');
const eventsContent = document.getElementById('eventsContent');
// Загрузка списка файлов
async function loadFileList() {
try {
const response = await fetch('/api/log/files');
const files = await response.json();
fileList.innerHTML = '';
files.forEach(file => {
const div = document.createElement('div');
div.className = 'log-file-item';
if (currentFile === file.name) div.classList.add('active');
div.innerHTML = `
<div class="file-name">${file.name}</div>
<div class="file-info">${file.time} | ${(file.size/1024).toFixed(1)} KB</div>
`;
div.addEventListener('click', () => loadFileData(file.name));
fileList.appendChild(div);
});
// Автоматически загружаем первый файл
if (files.length > 0 && !currentFile) {
loadFileData(files[0].name);
}
} catch (error) {
console.error('Error loading file list:', error);
}
}
// Загрузка данных файла
async function loadFileData(filename) {
currentFile = filename;
// Обновляем активный элемент в списке
document.querySelectorAll('.log-file-item').forEach(el => el.classList.remove('active'));
const items = document.querySelectorAll('.log-file-item');
for (const item of items) {
if (item.textContent.includes(filename)) {
item.classList.add('active');
break;
}
}
try {
const response = await fetch(`/api/log/data?file=${encodeURIComponent(filename)}`);
const data = await response.json();
currentData = data;
renderData(data);
} catch (error) {
console.error('Error loading data:', error);
}
}
// Отрисовка данных
function renderData(data) {
const samples = data.samples || [];
// Статистика
if (samples.length > 0) {
const totalPoints = samples.length;
// Амплитуда > 0 (старшие 2 бита)
const amplitudeOver0Count = samples.filter(s => s.amplitude > 0).length;
// Сигнал > 10 (младшие 6 бит)
const signalOver10Count = samples.filter(s => s.signal > 10).length;
// Общее количество объектов (сумма всех сигналов)
const totalObjects = samples.reduce((sum, s) => sum + s.signal, 0);
logStats.innerHTML = `
<div class="log-stat-card">
<div class="value">${totalPoints}</div>
<div class="label">Всего точек</div>
<!-- Основной контент -->
<div class="logs-content">
<div class="tabs">
<button class="tab-btn active" data-tab="data">Данные</button>
<button class="tab-btn" data-tab="events">События</button>
</div>
<div class="log-stat-card">
<div class="value">${amplitudeOver0Count}</div>
<div class="label">Амплитуда > 0</div>
<!-- Вкладка: Данные -->
<div id="tab-data" class="tab-content active">
<div id="logStats" class="log-stats"></div>
<div id="chartContainer">
<canvas id="logChart" height="200"></canvas>
</div>
<div id="dataTableContainer"></div>
</div>
<div class="log-stat-card">
<div class="value">${signalOver10Count}</div>
<div class="label">Сигнал > 10</div>
<!-- Вкладка: События -->
<div id="tab-events" class="tab-content">
<div id="eventsContent" class="events-list">Загрузка событий...</div>
<!-- Пагинация будет добавлена динамически через JS -->
</div>
<div class="log-stat-card">
<div class="value">${totalObjects}</div>
<div class="label">Объектов всего</div>
</div>
`;
}
</div>
</div>
// График
if (logChart && samples.length > 0) {
const history = samples.map(s => s.signal); // Используем signal вместо count
drawChart(logChart, history);
}
// Таблица - убрали колонку "Объектов"
if (samples.length > 0) {
let html = `<table class="data-table">
<thead>
<tr>
<th>Время</th>
<th>Амплитуда</th>
<th>Сигнал</th>
</tr>
</thead>
<tbody>`;
const displaySamples = samples.slice(-200);
displaySamples.forEach(s => {
// Цвет в зависимости от амплитуды
let ampClass = '';
if (s.amplitude === 0) ampClass = 'strength-0';
else if (s.amplitude === 1) ampClass = 'strength-1';
else if (s.amplitude === 2) ampClass = 'strength-2';
else if (s.amplitude === 3) ampClass = 'strength-3';
html += `<tr>
<td>${s.time}</td>
<td class="${ampClass}">${s.amplitude}</td>
<td>${s.signal}</td>
</tr>`;
});
html += '</tbody></table>';
dataTableContainer.innerHTML = html;
} else {
dataTableContainer.innerHTML = '<p>Нет данных</p>';
}
}
// Загрузка событий
async function loadEvents() {
try {
const response = await fetch('/api/log/events?limit=200');
const data = await response.json();
currentEvents = data.events || [];
let html = '';
currentEvents.forEach(e => {
html += `<div><span class="event-time">[${e.time}]</span> ${e.event}</div>`;
});
eventsContent.innerHTML = html || 'Нет событий';
} catch (error) {
eventsContent.innerHTML = 'Ошибка загрузки событий';
}
}
// Переключение табов
document.querySelectorAll('.tab-btn[data-tab]').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.tab-btn[data-tab]').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const tabName = btn.dataset.tab;
document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
document.getElementById(`tab-${tabName}`).classList.add('active');
if (tabName === 'events') {
loadEvents();
}
});
});
// Инициализация
loadFileList();
// Обновление времени с сервера (единый формат)
async function updateTime() {
try {
const response = await fetch('/api/health');
const data = await response.json();
document.getElementById('server-time').textContent = data.server_time || new Date().toLocaleTimeString();
} catch (error) {
// Если сервер недоступен, используем локальное время
const now = new Date();
document.getElementById('server-time').textContent = now.toLocaleTimeString();
}
}
setInterval(updateTime, 1000);
updateTime();
</script>
<!-- Подключаем скомпилированный JS -->
<script type="module" src="/dist/logs.js"></script>
</body>
</html>