From 8b89e4a9933475ce9a91430e33d84e44caeabc6a Mon Sep 17 00:00:00 2001 From: Arduinum628 Date: Wed, 21 May 2025 17:48:54 +0300 Subject: [PATCH 1/2] docs: added project description and design of branches and commits --- README.md | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 27fb282..d0d0eed 100644 --- a/README.md +++ b/README.md @@ -1 +1,29 @@ -# robot-pi-service \ No newline at end of file +# Robot-pi-service + +**Robot-pi-service** - сервис для управления роботом на orange pi, работающий на linux Armbian. + +
+ + + Как оформлять ветки и коммиты + + + + Пример ветки `user_name/name_task` + + - **user_name** (имя пользователя); + - **name_task** (название задачи). + + Пример коммита `refactor: renaming a variable` + + - **feat:** (новая функционал кода, БЕЗ учёта функционала для сборок); + - **devops:** (функционал для сборки, - добавление, удаление и исправление); + - **fix:** (исправление ошибок функционального кода); + - **docs:** (изменения в документации); + - **style:** (форматирование, отсутствующие точки с запятой и т.п., без изменения производственного кода); + - **refactor:** (рефакторинг производственного кода, например, переименование переменной); + - **test:** (добавление недостающих тестов, рефакторинг тестов; без изменения производственного кода); + - **chore:** (обновление рутинных задач и т. д.; без изменения производственного кода). + + Оформление основано на https://www.conventionalcommits.org/en/v1.0.0/ +
\ No newline at end of file From d93d039406df1a2e39eaf2919651922c1675ab21 Mon Sep 17 00:00:00 2001 From: Arduinum628 Date: Mon, 2 Jun 2025 12:19:02 +0300 Subject: [PATCH 2/2] feat: added robot_pi_service.py, settings.py; devops: added Makefile for run project; docs: added for run project with Makefile --- .gitignore | 3 ++ Makefile | 3 ++ README.md | 2 + requirements.txt | 2 + robot_pi_service/__init__.py | 0 robot_pi_service/robot_pi_service.py | 68 ++++++++++++++++++++++++++++ robot_pi_service/settings.py | 31 +++++++++++++ 7 files changed, 109 insertions(+) create mode 100644 Makefile create mode 100644 requirements.txt create mode 100644 robot_pi_service/__init__.py create mode 100755 robot_pi_service/robot_pi_service.py create mode 100644 robot_pi_service/settings.py diff --git a/.gitignore b/.gitignore index 0a19790..92bfa85 100644 --- a/.gitignore +++ b/.gitignore @@ -172,3 +172,6 @@ cython_debug/ # PyPI configuration file .pypirc + +# IDE +.vscode/ \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..0449489 --- /dev/null +++ b/Makefile @@ -0,0 +1,3 @@ +run: + chmod +x robot_pi_service/robot_pi_service.py + python3 robot_pi_service/robot_pi_service.py \ No newline at end of file diff --git a/README.md b/README.md index d0d0eed..0d3606f 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ **Robot-pi-service** - сервис для управления роботом на orange pi, работающий на linux Armbian. +**Запуск сервиса (как проекта python3)** - `make run` +
diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..8de613a --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +websockets==15.0.1 +pydantic-settings==2.9.1 \ No newline at end of file diff --git a/robot_pi_service/__init__.py b/robot_pi_service/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/robot_pi_service/robot_pi_service.py b/robot_pi_service/robot_pi_service.py new file mode 100755 index 0000000..a00f7fb --- /dev/null +++ b/robot_pi_service/robot_pi_service.py @@ -0,0 +1,68 @@ +import asyncio +from websockets import serve, exceptions +from websockets.legacy.server import WebSocketServerProtocol + +from settings import settings + + +async def robot_control_gpio(websocket: WebSocketServerProtocol): + """ + Асинхронная функция для управлением gpio робота (через websocket) + """ + + try: + while True: + try: + command = await asyncio.wait_for(websocket.recv(), timeout=30.0) + except asyncio.TimeoutError as err: + print('Таймаут ожидания команды от клиента') + continue # продолжение цикла, чтобы не закрывать соединение + + match command: + case settings.commands_robot.forward: + action = 'Робот едет вперёд' + print(action) + await websocket.send(message=action) + case settings.commands_robot.backward: + action = 'Робот едет назад' + print(action) + await websocket.send(message=action) + case settings.commands_robot.left: + action = 'Робот едет налево' + print(action) + await websocket.send(message=action) + case settings.commands_robot.right: + action = 'Робот едет направо' + print(action) + await websocket.send(message=action) + except exceptions.ConnectionClosed: + pass + except (exceptions.ConnectionClosedOK, exceptions.InvalidMessage, exceptions.InvalidState) as err: + message_err = f'{err.__class__.__name__}: {err}' + print(message_err) + await websocket.send(message=message_err) + except Exception as err: + message_err = f'{err.__class__.__name__}: {err}' + print(message_err) + await websocket.send(message=message_err) + + +async def start(): + """Асинхронная функция запуска вебсокета и бесконечного цикла""" + + async with serve(handler=robot_control_gpio, host=settings.websocket_host, port=settings.websocket_port): + # бесконечный цикл + await asyncio.Future() + + +def run_app(): + """Функция старата приложения""" + + try: + asyncio.run(start()) + except KeyboardInterrupt: + pass + + +if __name__ == '__main__': + run_app() diff --git a/robot_pi_service/settings.py b/robot_pi_service/settings.py new file mode 100644 index 0000000..47e1905 --- /dev/null +++ b/robot_pi_service/settings.py @@ -0,0 +1,31 @@ +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class ModelConfig(BaseSettings): + """Модель конфига""" + + model_config = SettingsConfigDict( + env_file = '.env', + env_file_encoding='utf-8', + extra='ignore' + ) + + +class CommandsRobot(ModelConfig): + """Класс с командами для робота""" + + forward: str + backward: str + left: str + right: str + + +class Settings(ModelConfig): + """Класс для данных конфига""" + + websocket_host: str + websocket_port: int + commands_robot: CommandsRobot = CommandsRobot() + + +settings = Settings()