/
ParaD
/
Server
Обзор
Документация
Войти
/
ParaD
/
Server
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
frontend_server.py
551 строка
29 KB
Rayfaga
first_commit
01 мар 2025, 20:02
01 мар 2025, 20:02
c75de2b
Код
Авторство
О чём код?
import pygame import sys import time import threading from multiprocessing import Process def import_modules(): global robot_run, data_run, camers_run, zakaz_run, ip_run, add_cart, robot_check, funct, deviant, start_server_received, start_file_send from frontend_robot import run as robot_run from frontend_data import run as data_run from frontend_camers import camers as camers_run from frontend_zakaz import run as zakaz_run from frontend_find_IP import get_ipv4_address as ip_run from frontend_add_cart import add_cart as add_cart from frontend_number_train_robot import robot_selection as robot_check from frontend_function import function_selection as funct from frontend_deviant import main as deviant from talk.receive_txt import start_server_received from talk.send_txt import start_file_send # Импортируем модули в основном потоке import_modules() thread = threading.Thread(target=import_modules) thread.start() stop_event = threading.Event() def read_robot_count(file_path): try: with open(file_path, "r") as f: return int(f.read().strip()) except (FileNotFoundError, ValueError): print(f"Ошибка: файл {file_path} не найден или содержит некорректные данные!") return 0 def draw_button(screen, x, y, width, height, text, font, button_color, text_color): pygame.draw.rect(screen, button_color, (x, y, width, height), border_radius=10) text_surface = font.render(text, True, text_color) text_rect = text_surface.get_rect(center=(x + width // 2, y + height // 2)) screen.blit(text_surface, text_rect) def draw_text(surface, text, font, color, x, y): text_surface = font.render(text, True, color) text_rect = text_surface.get_rect() text_rect.topleft = (x, y) surface.blit(text_surface, text_rect) def load_charge_images(robot_count_file): images = {} try: images["1"] = pygame.image.load("./front/low_charge.png") images["2"] = pygame.image.load("./front/medium_charge.png") images["3"] = pygame.image.load("./front/full_charge.png") images["4"] = pygame.image.load("./front/no_charge.png") if read_robot_count(robot_count_file) == 1 or read_robot_count(robot_count_file) == 2: scale = 4 elif read_robot_count(robot_count_file) == 3 or read_robot_count(robot_count_file) == 4: scale = 6 elif read_robot_count(robot_count_file) == 5 or read_robot_count(robot_count_file) == 6: scale = 9 elif read_robot_count(robot_count_file) == 7 or read_robot_count(robot_count_file) == 8: scale = 12 else: scale = 15 for key in images: original_size = images[key].get_size() new_size = (original_size[0] // scale, original_size[1] // scale) images[key] = pygame.transform.scale(images[key], new_size) except pygame.error as e: print(f"Ошибка загрузки изображений заряда: {e}") pygame.quit() sys.exit() return images def draw_text_wrapped(screen, text, font, color, rect, line_spacing): words = text.split(" ") lines = [] current_line = "" for word in words: test_line = f"{current_line} {word}".strip() if font.size(test_line)[0] <= rect.width: current_line = test_line else: lines.append(current_line) current_line = word if current_line: lines.append(current_line) y_offset = rect.top for line in lines: text_surface1 = font.render(line, True, (200,200,200)) text_rect1 = text_surface1.get_rect(midtop=(rect.centerx-1, y_offset-1)) screen.blit(text_surface1, text_rect1) text_surface1 = font.render(line, True, (200,200,200)) text_rect1 = text_surface1.get_rect(midtop=(rect.centerx-1, y_offset+1)) screen.blit(text_surface1, text_rect1) text_surface1 = font.render(line, True, (200,200,200)) text_rect1 = text_surface1.get_rect(midtop=(rect.centerx+1, y_offset-1)) screen.blit(text_surface1, text_rect1) text_surface1 = font.render(line, True, (200,200,200)) text_rect1 = text_surface1.get_rect(midtop=(rect.centerx+1, y_offset+1)) screen.blit(text_surface1, text_rect1) text_surface = font.render(line, True, (52, 52, 52)) text_rect = text_surface.get_rect(midtop=(rect.centerx, y_offset)) screen.blit(text_surface, text_rect) y_offset += font.get_height() + line_spacing def draw_table(screen, robot_count, screen_width, screen_height, charge_images, robot_headers): if robot_count==0: robot_count2=4 else: robot_count2 = robot_count table_x = 0 table_y = 0 table_width = int(screen_width * 0.7) table_height = screen_height cell_height = table_height // 4 cell_width = table_width // (robot_count2 + 1) table_border_color = (51, 51, 51) text_color = (51, 51, 51) font = pygame.font.SysFont("Arial", 24, bold=True) number_train = '' with open('./variable_txt/number_train.txt', 'r') as f: number_train = f.readlines()[0] headers = [f"Поезд №{number_train}", "Заряд", "Ошибки"] clickable_areas = [] for col in range(robot_count + 1): cell_x = table_x + col * cell_width cell_y = table_y pygame.draw.rect(screen, table_border_color, (cell_x, cell_y, cell_width, cell_height), 2) if col == 0: header_text = font.render(headers[0], True, text_color) clickable_areas.append((headers[0], pygame.Rect(cell_x, cell_y, cell_width, cell_height))) else: header_text = font.render(f"Р{col}", True, text_color) clickable_areas.append((col, pygame.Rect(cell_x, cell_y, cell_width, cell_height))) text_rect = header_text.get_rect(center=(cell_x + cell_width // 2, cell_y + cell_height // 2)) screen.blit(header_text, text_rect) for row in range(1, 3): for col in range(robot_count + 1): cell_x = table_x + col * cell_width cell_y = table_y + row * cell_height pygame.draw.rect(screen, table_border_color, (cell_x, cell_y, cell_width, cell_height), 2) if col == 0: row_text = font.render(headers[row], True, text_color) text_rect = row_text.get_rect(center=(cell_x + cell_width // 2, cell_y + cell_height // 2)) screen.blit(row_text, text_rect) elif row == 1: try: with open(f"./variable_txt/robot{col}/charge.txt", "r") as f: charge_level = f.read().strip() if charge_level != '1' and charge_level != '2' and charge_level != '3': charge_level = '4' if charge_level in charge_images: image = charge_images[charge_level] image_rect = image.get_rect(center=(cell_x + cell_width // 2, cell_y + cell_height // 2)) screen.blit(image, image_rect) except FileNotFoundError: pass elif row == 2: try: with open(f"./variable_txt/robot{col}/errors.txt", "r", encoding='utf-8') as f: error_status = f.read().strip().lower() if "нет" in error_status or "ошибок нет" in error_status: error_text = font.render("НЕТ", True, (56, 87, 35)) else: error_text = font.render("ДА", True, (236, 28, 36)) text_rect = error_text.get_rect(center=(cell_x + cell_width // 2, cell_y + cell_height // 2)) screen.blit(error_text, text_rect) except FileNotFoundError: error_text = font.render("НЕТ", True, (56, 87, 35)) text_rect = error_text.get_rect(center=(cell_x + cell_width // 2, cell_y + cell_height // 2)) screen.blit(error_text, text_rect) rect_areas = [pygame.Rect(0, 0, 0, 0)]*6 robot_count_file = "./variable_txt/count_robots.txt" rect = pygame.Rect(0, 3*screen_height//4, cell_width, cell_height) pygame.draw.rect(screen, table_border_color, rect, 3) info_text = "Операции" row_text = font.render(info_text, True, text_color) text_rect = row_text.get_rect(center=(0 + cell_width//2, 3*screen_height//4 + cell_height//2)) screen.blit(row_text, text_rect) rect = pygame.Rect(cell_width, 3*screen_height//4, (table_width-cell_width), cell_height) pygame.draw.rect(screen, table_border_color, rect, 3) if read_robot_count(robot_count_file)==1 or read_robot_count(robot_count_file)==2: font = pygame.font.SysFont("Arial", 24, bold=True) elif read_robot_count(robot_count_file)==3 or read_robot_count(robot_count_file)==4: font = pygame.font.SysFont("Arial", 40, bold=True) else: font = pygame.font.SysFont("Arial", 50, bold=True) info_text = "Открыть окно" row_text = font.render(info_text, True, text_color) text_rect = row_text.get_rect(center=(cell_width + (table_width-cell_width)//2, 3*screen_height//4 + cell_height//2 - cell_height//7)) screen.blit(row_text, text_rect) info_text = "с выбором функций" row_text = font.render(info_text, True, text_color) text_rect = row_text.get_rect(center=(cell_width + (table_width-cell_width)//2, 3*screen_height//4 + cell_height//2 + cell_height//7)) screen.blit(row_text, text_rect) rect_areas[3] = (rect) rect_width = screen_width - table_width rect_height = screen_height // 3 rect_areas2 = [] for i in range(3): if i == 0: vremenno = screen_height // 32 elif i == 1: vremenno = screen_height // 8 else: vremenno = screen_height // 10 rect2 = pygame.Rect(table_width, i * rect_height+vremenno, rect_width, rect_height) pygame.draw.rect(screen, table_border_color, rect, 3) rect_areas2.append(rect2) font_large = pygame.font.SysFont("Arial", 44, bold=True) info_text = "Информация о пассажирах и база данных постоянных покупателей" pygame.draw.rect(screen, '#f97f6e', (table_width, 0 * rect_height, rect_width, rect_height)) line_spacing = 10 draw_text_wrapped(screen, info_text, font_large, (255, 255, 255), rect_areas2[0], line_spacing) font_large = pygame.font.SysFont("Arial", 44, bold=True) info_text = "Данные с камер" pygame.draw.rect(screen, '#f97f6e', (table_width, 1 * rect_height, rect_width, rect_height)) draw_text_wrapped(screen, info_text, font_large, (255, 255, 255), rect_areas2[1], line_spacing) font_large = pygame.font.SysFont("Arial", 44, bold=True) info_text = "Информация о заказах пассажиров" pygame.draw.rect(screen, '#f97f6e', (table_width, 2 * rect_height, rect_width, rect_height)) draw_text_wrapped(screen, info_text, font_large, (255, 255, 255), rect_areas2[2], line_spacing) for i in range(3): rect = pygame.Rect(table_width, i * rect_height, rect_width, rect_height) pygame.draw.rect(screen, table_border_color, rect, 3) rect_areas[i] = (rect) if robot_count == 0: file = open("./variable_txt/count_robots.txt") n = int(file.read().strip()) file.close() draw_text(screen, "Каким образом получить информацию о роботах?", pygame.font.SysFont("Arial", 30, bold=True), text_color, screen_width // 6, screen_height // 16) pygame.draw.rect(screen, (0, 0, 0), (screen_width // 6, 4 * screen_height // 25, 3 * screen_width // 6, 2 * screen_height // 25), 2) rect_areas[4] = pygame.Rect(screen_width // 6, 4 * screen_height // 25, 3 * screen_width // 6, 2 * screen_height // 25) draw_text(screen, f"Взять последние подключения (Было подключено роботов - {n})", pygame.font.SysFont("Arial", 23, bold=True), text_color, screen_width // 6 + 15, 4 * screen_height // 25 + 20) pygame.draw.rect(screen, (0, 0, 0), (screen_width // 6, 8 * screen_height // 25, 3 * screen_width // 6, 2 * screen_height // 25), 2) rect_areas[5] = pygame.Rect(screen_width // 6, 8 * screen_height // 25, 3 * screen_width // 6, 2 * screen_height // 25) draw_text(screen, "Новое соединение", pygame.font.SysFont("Arial", 32, bold=True), text_color, 2 * screen_width // 6, 8 * screen_height // 25 + 20) return clickable_areas, rect_areas def display_error_message(screen, message, screen_width, screen_height, duration=3000): font = pygame.font.SysFont("Arial", 36, bold=True) text_color = (255, 0, 0) background_color = (221, 250, 221) error_text = font.render(message, True, text_color, background_color) text_rect = error_text.get_rect(center=(screen_width // 2, screen_height // 2)) screen.blit(error_text, text_rect) pygame.draw.rect(screen, (0, 0, 0), error_text.get_rect(center=(screen_width // 2, screen_height // 2)), 1) pygame.display.flip() pygame.time.delay(duration) def input_FUNCTION_window(screen, font): window_width, window_height = 1000, 800 window_x = (screen.get_width() - window_width) // 2 window_y = (screen.get_height() - window_height) // 2 border_color = (0, 0, 0) text_color = (0, 0, 0) background_color = (222, 222, 222) button_color = (56, 87, 35) button_text_color = (255, 255, 255) button_texts = [ "Запуск функции работы в поезде", "Запуск функции сканирования паспорта", "Запуск функции работы на вокзале", "Начать перепроверку билетов", "Сказать основную информацию", "Сказать вариативную информацию", "Выбрать номер вагона для робота", "Выбрать компановку вагона", "Вернуться назад" ] button_width, button_height = 850, 70 button_spacing = 10 running = True while running: screen.fill((245, 245, 245)) pygame.draw.rect(screen, background_color, (window_x, window_y, window_width, window_height)) pygame.draw.rect(screen, border_color, (window_x, window_y, window_width, window_height), 2) prompt_text = "Выберите нужную функцию:" prompt_surface = font.render(prompt_text, True, text_color) prompt_rect = prompt_surface.get_rect(center=(window_x + window_width // 2, window_y + 30)) screen.blit(prompt_surface, prompt_rect) for i, text in enumerate(button_texts): button_x = window_x + (window_width - button_width) // 2 button_y = window_y + 70 + i * (button_height + button_spacing) draw_button(screen, button_x, button_y, button_width, button_height, text, font, button_color, button_text_color) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() return None elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: for i in range(len(button_texts)): button_x = window_x + (window_width - button_width) // 2 button_y = window_y + 70 + i * (button_height + button_spacing) if button_x <= event.pos[0] <= button_x + button_width and button_y <= event.pos[1] <= button_y + button_height: return button_texts[i] def input_TRAIN_window(screen, font): window_width, window_height = 600, 260 window_x = (screen.get_width() - window_width) // 2 window_y = (screen.get_height() - window_height) // 2 border_color = (0, 0, 0) text_color = (0, 0, 0) background_color = (222, 222, 222) button_color = (56, 87, 35) button_text_color = (255, 255, 255) input_box_rect = pygame.Rect(window_x + 50, window_y + 80, window_width - 100, 50) input_text = "" button_width = 200 button_height = 60 left_button_x = window_x + 50 left_button_y = window_y + window_height - button_height - 20 right_button_x = window_x + window_width - button_width - 50 right_button_y = left_button_y running = True clock = pygame.time.Clock() while running: pygame.draw.rect(screen, background_color, (window_x, window_y, window_width, window_height)) pygame.draw.rect(screen, border_color, (window_x, window_y, window_width, window_height), 2) prompt_text = "Введите номер для поезда" prompt_surface = font.render(prompt_text, True, text_color) prompt_rect = prompt_surface.get_rect(center=(window_x + window_width // 2, window_y + 30)) screen.blit(prompt_surface, prompt_rect) pygame.draw.rect(screen, (255, 255, 255), input_box_rect) pygame.draw.rect(screen, border_color, input_box_rect, 2) input_surface = font.render(input_text, True, text_color) screen.blit(input_surface, (input_box_rect.x + 5, input_box_rect.y + 5)) draw_button(screen, left_button_x, left_button_y, button_width, button_height, "Принять", font, button_color, button_text_color) draw_button(screen, right_button_x, right_button_y, button_width, button_height, "Назад", font, button_color, button_text_color) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() return 0 elif event.type == pygame.KEYDOWN: if event.key == pygame.K_BACKSPACE: input_text = input_text[:-1] else: if event.unicode.isalnum(): input_text += event.unicode elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: mouse_pos = event.pos if (left_button_x <= mouse_pos[0] <= left_button_x + button_width and left_button_y <= mouse_pos[1] <= left_button_y + button_height): if input_text: with open('./variable_txt/number_train.txt', 'w') as f: f.write(input_text) return 0 if (right_button_x <= mouse_pos[0] <= right_button_x + button_width and right_button_y <= mouse_pos[1] <= right_button_y + button_height): return 0 clock.tick(30) def input_TF_window(screen, font): window_width, window_height = 600, 260 window_x = (screen.get_width() - window_width) // 2 window_y = (screen.get_height() - window_height) // 2 border_color = (0, 0, 0) text_color = (0, 0, 0) background_color = (222, 222, 222) button_color = (56, 87, 35) button_text_color = (255, 255, 255) running = True while running: pygame.draw.rect(screen, background_color, (window_x, window_y, window_width, window_height)) pygame.draw.rect(screen, border_color, (window_x, window_y, window_width, window_height), 2) prompt_text = "Вы уверены?" prompt_surface = font.render(prompt_text, True, text_color) prompt_rect = prompt_surface.get_rect(center=(window_x + window_width // 2, window_y + 30)) screen.blit(prompt_surface, prompt_rect) button_width1, button_height1 = 200, 60 button_x1 = window_x + (window_width - 5*button_width1//2) // 2 button_y1 = window_y + 130 draw_button(screen, button_x1, button_y1, button_width1, button_height1, "Да", font, button_color, button_text_color) button_width2, button_height2 = 200, 60 button_x2 = window_x + (window_width + button_width2//2) // 2 button_y2 = window_y + 130 draw_button(screen, button_x2, button_y2, button_width2, button_height2, "Нет", font, button_color, button_text_color) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: if button_x1 <= event.pos[0] <= button_x1 + button_width1 and button_y1 <= event.pos[1] <= button_y1 + button_height1: running = False return True if button_x2 <= event.pos[0] <= button_x2 + button_width2 and button_y2 <= event.pos[1] <= button_y2 + button_height2: running = False return False def input_CONN_window(screen): second_chapt = 0 URL_robot = [] last_check = 0 count_robots = 0 font = pygame.font.SysFont("Arial", 30, bold=True) window_width, window_height = 600, 260 window_x = (screen.get_width() - window_width) // 2 window_y = (screen.get_height() - window_height) // 2 colors = { 'border': (0, 0, 0), 'text': (0, 0, 0), 'background': (222, 222, 222), 'button': (56, 87, 35), 'button_text': (255, 255, 255) } running = True while running: try: with open('./talk/for_server.txt', 'r') as f: text = f.readlines()[0] open('./talk/for_server.txt', 'w').close() except: text='' if text: print(text) if "WAIT_ADMIN" in text: display_error_message(screen, f'Подойдите к роботу! Вас ожидают', window_width, window_height, duration=2000) display_error_message(screen, f'Пароль - {text.split()[1]}', window_width, window_height, duration=2000) else: parts = text.split(" (ROBOT) ") if len(parts) == 2: if parts[0] not in URL_robot: URL_robot.append(parts[0]) count_robots+=1 second_chapt = 1 pygame.draw.rect(screen, colors['background'], (window_x, window_y, window_width, window_height)) pygame.draw.rect(screen, colors['border'], (window_x, window_y, window_width, window_height), 2) status_text = "Ожидаю подключения робота" if second_chapt == 0 else "Получил соединение от робота!" draw_text(screen, status_text, font, colors['text'], window_x + window_width//16, window_y + 30) instruction_text = "Введите в него следующий URL:" if second_chapt == 0 else '' draw_text(screen, instruction_text, font, colors['text'], window_x + window_width//16, window_y + 85) info_text = f"{ip_run()}" if second_chapt == 0 else f"{URL_robot[count_robots-1]}" draw_text(screen, info_text, font, colors['text'], window_x + window_width//16, window_y + 140) button_width, button_height = 240, 60 button_x = window_x + 30 button_y = window_y + 180 knopka_stop = "Стоп" if second_chapt == 0 else "Закрыть" draw_button(screen, button_x, button_y, button_width, button_height, knopka_stop, font, colors['button'], colors['button_text']) button_width2, button_height2 = 240, 60 button_x2 = window_x + 330 button_y2 = window_y + 180 knopka_stop2 = "Добавить еще" if second_chapt==1: draw_button(screen, button_x2, button_y2, button_width2, button_height2, knopka_stop2, font, colors['button'], colors['button_text']) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: if button_x <= event.pos[0] <= button_x + button_width and button_y <= event.pos[1] <= button_y + button_height: for x in range(count_robots): with open(f"./variable_txt/robot{x+1}/URL_robot{x+1}.txt","w") as f: f.write(str(URL_robot[x])) with open(f"./variable_txt/count_robots.txt","w") as f: f.write(str(count_robots)) running = False if button_x2 <= event.pos[0] <= button_x2 + button_width2 and button_y2 <= event.pos[1] <= button_y2 + button_height2: second_chapt = 0 def main(): pygame.init() screen_info = pygame.display.Info() screen_width, screen_height = screen_info.current_w, screen_info.current_h screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("Российские Железные Дороги - сервер") background_color = (220, 220, 220) robot_count_file = "./variable_txt/count_robots.txt" robot_count = 0 charge_images = load_charge_images(robot_count_file) running = True timer_done = 0 function = '' while running: with open('./talk/for_server.txt', 'r') as f: a=f.readlines() if a!=[]: if "WAIT_ADMIN" in a[0]: display_error_message(screen, f'Подойдите к роботу! Вас ожидают', screen_width, screen_height, duration=2000) display_error_message(screen, f'Пароль - {a.split()[1]}', screen_width, screen_height, duration=2000) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: mouse_pos = event.pos for robot_id, rect in clickable_areas: if rect.collidepoint(mouse_pos): if str(robot_id)[0]=="П": input_TRAIN_window(screen, pygame.font.SysFont("Arial", 40, bold=True)) else: robot_run(screen, robot_id) if rect_areas[0].collidepoint(mouse_pos): data_run(screen) if rect_areas[1].collidepoint(mouse_pos): try: if p.is_alive(): p.terminate() p.join() except NameError: pass camers_run(screen) p = Process(target=deviant) p.start() if rect_areas[2].collidepoint(mouse_pos): zakaz_run(screen) if rect_areas[3].collidepoint(mouse_pos): if robot_count == 0: display_error_message(screen, f'Подключите хотя бы 1 робота!', screen_width, screen_height, duration=2000) elif robot_count!=0: function = input_FUNCTION_window(screen, pygame.font.SysFont("Arial", 40, bold=True)) match function: case "Запуск функции работы в поезде": funct(screen, '1') case "Запуск функции сканирования паспорта": funct(screen, '2') case "Запуск функции работы на вокзале": funct(screen, '3') case "Начать перепроверку билетов": print("Начать перепроверку билетов") case "Сказать основную информацию": print("Сказать основную информацию") case "Сказать вариативную информацию": print("Сказать вариативную информацию") case "Выбрать номер вагона для робота": robot_check(screen) case "Выбрать компановку вагона": add_cart(screen) if rect_areas[4].collidepoint(mouse_pos): boolean = input_TF_window(screen, pygame.font.SysFont("Arial", 40, bold=True)) if boolean == True: file = open("./variable_txt/count_robots.txt") robot_count = int(file.read().strip()) file.close() boolean = False if rect_areas[5].collidepoint(mouse_pos): input_CONN_window(screen) file = open("./variable_txt/count_robots.txt") robot_count = int(file.read().strip()) file.close() screen.fill(background_color) clickable_areas, rect_areas = draw_table(screen, robot_count, screen_width, screen_height, charge_images, []) pygame.display.flip() pygame.quit() if __name__ == "__main__": main()