204 Commits
Author SHA1 Message Date
Даниил Грабарь db2751bc78 Merge branch 'dev' 2026-08-13 18:09:02 +03:00
Даниил Грабарь 910afce714 Update MkDocs installation to include static i18n and PDF export dependencies 2026-08-13 18:08:40 +03:00
Даниил Грабарь 9e65a2720c docs: clean up README by removing outdated commands and sections 2026-08-13 18:05:35 +03:00
Даниил Грабарь 047e1b190e Merge branch 'dev' 2026-08-13 18:02:26 +03:00
Даниил Грабарь 79d88db930 Add documentation for KUKA Sunrise features and programs
- Created a new document for the Station interface, detailing its menu structure, process data, safety functions, frames, and smartPAD function buttons.
- Added a document for RobotPowerControl, explaining its purpose for safely shutting down or restarting the KUKA Sunrise Cabinet controller.
- Introduced ServerFriRos2 documentation, outlining its role in establishing an FRI connection between the KUKA LBR iiwa and a ROS 2 computer.
- Documented the TeachKuka application, which allows manual teaching of the KUKA LBR iiwa, including position capturing and trajectory recording.
- Added an overview of Sunrise Workbench, including installation instructions for Windows and Linux.
- Created a section on installing a Windows compatibility tool (PortProton) on Linux.
- Documented the installation process for SunriseWorkbench on Linux using PortProton.
- Added installation instructions for SunriseWorkbench on Windows.
- Created troubleshooting documentation for configuration errors and SSL errors during installation.
- Implemented a hook to generate the shared PDF only during the default-language build.
2026-08-13 18:01:59 +03:00
Даниил Грабарь 08ebd40671 docs: update README files with project features and compatibility details 2026-08-13 17:01:34 +03:00
Даниил Грабарь 4547b786a3 Add ServerFriRos2 documentation for KUKA Sunrise Cabinet integration with ROS 2
- Introduced a comprehensive guide for the ServerFriRos2 program, detailing its purpose, setup, and operational procedures.
- Included instructions on configuring network addresses, tool data, initial positions, and FRI cycle periods.
- Provided step-by-step guidance for launching the application and connecting to ROS 2, including troubleshooting tips for connection issues.
- Emphasized safety warnings and operational considerations for using the program with the KUKA LBR iiwa robot.
2026-08-13 16:51:50 +03:00
Даниил Грабарь b318cb3311 Add instructional videos for HandMode and TeachMode
- Added HandMode.mp4 to demonstrate the hand mode functionality.
- Added TeachMode.mp4 to showcase the teaching mode features.
2026-08-13 14:13:35 +03:00
Даниил Грабарь 2ba4975471 Merge branch 'dev' 2026-08-13 00:14:25 +03:00
Даниил Грабарь c5cbf234cb Document TeachKuka operation and safety 2026-08-13 00:13:52 +03:00
Даниил Грабарь e388e7d168 Merge branch 'dev' 2026-08-12 20:55:47 +03:00
Даниил Грабарь 2478e9956b docs: document RobotPowerControl 2026-08-12 20:54:53 +03:00
Даниил Грабарь ff4b2e30ce Merge branch 'dev' 2026-08-12 20:30:18 +03:00
Даниил Грабарь 5134fadf31 Update REST API documentation for robot control
- Refined introduction to REST API capabilities and usage.
- Added security warnings and best practices for using the API.
- Improved examples for various programming languages (Bash, Python, MATLAB).
- Enhanced endpoint descriptions and added details on request/response structures.
- Clarified the process for moving the robot and handling trajectories.
- Updated sections on sequences and error handling for better clarity.
2026-08-12 20:28:50 +03:00
Даниил Грабарь 41f516bb58 feat: implement stop functionality for robot operations and remove obsolete stop endpoint 2026-07-01 11:17:41 +10:00
Даниил Грабарь 9e3ee7ebc8 feat: add troubleshooting section for SSL errors during installation 2026-06-30 12:13:25 +03:00
Даниил Грабарь 0a7eb067ac Merge branch 'dev' 2026-06-22 06:18:01 +03:00
Даниил Грабарь 4fc9622ee9 вернул все обратно 2026-06-22 06:17:33 +03:00
Даниил ГрабарьandClaude Sonnet 4.6 1b6e211b88 Merge branch 'dev': fix rosdep obsolete sources timeout
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 05:57:47 +03:00
Даниил ГрабарьandClaude Sonnet 4.6 1c47b3f6f5 fix: remove obsolete rosdep sources (ruby, fuerte) before update
Eliminates SSL handshake timeouts during rosdep update caused by
unreachable ruby.yaml and fuerte.yaml (ROS 1 legacy sources not
needed for ROS 2 Jazzy).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 05:56:40 +03:00
Даниил Грабарь d26d60def4 refactor: update setup wizard steps and documentation; remove overview section 2026-06-21 07:29:21 +03:00
Даниил Грабарь a983a06e41 Добавлена документация по CLI-командам, конфигурации системы, управлению через Foxglove Studio и REST API, а также инструкции по установке и удалённому доступу к серверу. Включены разделы о настройке SunriseWorkbench для работы с реальным роботом KUKA LBR IIWA 7. 2026-06-20 13:15:56 +03:00
Даниил Грабарь ed02b59177 refactor: remove unused ai_agent package and related files; add colcon defaults 2026-06-20 07:47:52 +03:00
Даниил Грабарь 6df4ab49ec Update documentation 2026-06-19 09:42:31 +03:00
Даниил Грабарь 7d73ab32dd Добавлены инструкции по установке SunriseWorkbench на Linux и Windows
- Создана документация по установке эмулятора Windows (PortProton) на Linux.
- Добавлены шаги по установке SunriseWorkbench на Linux с использованием PortProton.
- Создана документация по установке SunriseWorkbench на Windows.
2026-06-18 15:52:48 +03:00
Даниил ГрабарьandClaude Sonnet 4.6 76db47d989 fix: add install docs and images ignored by .gitignore
Fixed .gitignore to use /install/ and /build/ with leading slash
so only the root-level colcon dirs are ignored, not
doc/lwc-doc/docs/sunrise/install/.

Adds install pages (Windows, Linux emulator, Linux workbench)
and 22 step-by-step screenshots that were never deployed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-18 15:32:01 +03:00
Даниил Грабарь 3a9f1f5150 del: .gitverse folder 2026-06-18 13:34:02 +03:00
Даниил Грабарь a3394db8fe fix: update MkDocs installation and enable PDF export 2026-06-18 13:27:27 +03:00
Даниил Грабарь f4e2765e69 fix: update installation script URL to use master branch 2026-06-18 13:24:26 +03:00
Даниил Грабарь b7db2e991c Add documentation for SunriseWorkbench project setup and features
- Create libraries.md for library installation instructions in SunriseWorkbench.
- Create load-project.md for importing existing projects in SunriseWorkbench.
- Create new-project.md detailing the process of creating a new project in SunriseWorkbench.
- Add applications.md to describe the applications section in KUKA smartHMI.
- Add extra-menu.md for additional robot control options in KUKA smartHMI.
- Create io-group.md for managing input/output groups in KUKA smartHMI.
- Add robot-menu.md as a placeholder for the robot menu section in KUKA smartHMI.
- Create station.md to outline the main navigation and functionalities in KUKA smartHMI.
- Add LBRserver.md, robot-power-control.md, and teach-kuka.md as placeholders for respective control programs.
- Create config-error.md to provide troubleshooting steps for configuration errors in SunriseWorkbench.
- Add main.html to override base template with site root metadata.
2026-06-18 13:22:55 +03:00
Даниил Грабарь 07edc4faf6 Append live mode view doc 2026-06-18 11:31:45 +03:00
Даниил Грабарь b441590dd8 fix: update installation script URL to use dev branch 2026-06-18 11:19:40 +03:00
Даниил Грабарь 5a8b1c44ff Merge branch 'master' into dev 2026-06-18 11:18:30 +03:00
Даниил Грабарь dca056064a fix: update installation script to use master branch for cloning 2026-06-18 11:15:10 +03:00
Даниил Грабарь ec4e1d87ad fix: update documentation workflows for GitHub and GitVerse compatibility 2026-06-18 07:16:40 +03:00
Даниил Грабарь de0117af94 feat: add GitVerse workflow for documentation build and deployment 2026-06-18 07:05:04 +03:00
Даниил Грабарь 16cb4dc6e7 fix: update GitHub Actions workflow to handle uploads for both GitHub and GitVerse 2026-06-18 06:59:41 +03:00
Даниил Грабарь 985425b866 refactor: update GitHub Actions workflow for documentation build and deployment 2026-06-18 06:37:53 +03:00
Даниил Грабарь 4a2e23ffef fix: update installation script URL to use the master branch 2026-06-18 06:21:22 +03:00
Даниил Грабарь a172ffe038 fix: update installation scripts to use the correct branch for cloning and installation 2026-06-18 06:21:22 +03:00
Даниил Грабарь 78405dfa8a feat: add GitHub Actions workflows for documentation deployment and building 2026-06-18 06:18:12 +03:00
Даниил Грабарь 6768d12fd7 fix: update installation scripts to use the correct branch for cloning and installation 2026-06-18 06:15:55 +03:00
Даниил Грабарь 78c5be2fa5 feat: add GitHub Actions workflows for documentation deployment and building 2026-06-18 06:01:48 +03:00
Даниил Грабарь 8ab341f60a Change pulling dev to master 2026-06-16 13:18:49 +10:00
Даниил Грабарь 1a1ee6f027 Merge branch 'dev' 2026-06-16 13:16:45 +10:00
Даниил Грабарь ddfbbda7db feat: update Dockerfiles and rosdep.yaml to install fastapi and starlette, remove starlette dependency 2026-06-15 16:32:05 +03:00
Даниил Грабарь eb8db5c6c0 feat: update rosdep and package.xml to specify minimum versions for fastapi and starlette 2026-06-15 15:26:09 +03:00
Даниил Грабарь 7ff5616870 feat: update installation scripts to pre-install fastapi and starlette for compatibility 2026-06-15 15:24:19 +03:00
Даниил Грабарь c540733ace feat: install Python build tools in setup scripts for ROS2 2026-06-15 15:06:43 +03:00
Даниил Грабарь 33ebbf8fad add: Script for shutting down and restarting the robot controller 2026-06-15 10:55:52 +10:00
Даниил Грабарь 030e975d59 feat: update installation scripts to pre-install fastmcp for successful rosdep upgrades 2026-06-14 16:22:00 +03:00
Даниил Грабарь 7d508765d0 feat: pre-install typing-extensions to ensure smooth upgrades for apt-installed packages 2026-06-14 16:17:27 +03:00
Даниил Грабарь 0fe84a907f feat: add ai_agent package with setup and configuration scripts; configure pip for system installs 2026-06-14 16:11:15 +03:00
Даниил Грабарь ee047618cd feat: update version and dependencies in setup.py; add privilege management and process handling modules
- Updated version from 2026.05.31 to 2026.06.11 in setup.py
- Replaced 'textual' with 'rich' in install_requires
- Added privilege.py for managing sudo privileges with a keep-alive mechanism
- Introduced process.py for handling subprocesses with enhanced control and output streaming
- Created ui.py for unified console interactions and user prompts
2026-06-11 12:21:02 +10:00
Даниил Грабарь e76a07c8f6 feat: update .gitignore to include CLAUDE.md and retain backup files 2026-06-07 15:36:19 +03:00
Даниил Грабарь 36fa33b032 Refactor tool management and update robot configuration
- Updated iiwa7.srdf to streamline group and end effector definitions, removing unnecessary joint specifications.
- Enhanced setting.yaml to include active tool configuration.
- Removed deprecated gripper URDF and Xacro files, consolidating tool definitions into tools.yaml.
- Introduced tool_manager.py for dynamic tool management, allowing for easy updates to active tools and collision settings.
- Created tool_active.xacro to reflect the currently active tool in the robot's URDF.
- Added comprehensive collision management for the new tool configurations.
2026-06-03 14:03:44 +10:00
Даниил Грабарь 9f9fb24dc3 Delete realsense packages 2026-06-03 13:31:00 +10:00
Даниил Грабарь 91eefe1eea feat: refactor launch files to modularize node creation and improve simulation support 2026-06-03 13:24:08 +10:00
Даниил Грабарь e9e3163ce6 feat: add support for named positions in robot API, including new endpoints and metadata 2026-06-03 13:19:13 +10:00
Даниил Грабарь 75d2c499b2 Update API 2026-05-28 15:20:57 +10:00
Даниил Грабарь 02e0c25847 Append fastMCP model 2026-05-27 17:13:42 +03:00
Даниил Грабарь 4916648f03 Update xacro pos 2026-05-27 08:26:48 +03:00
Даниил Грабарь f365cd491f Update fields 2026-05-26 16:02:08 +03:00
Даниил Грабарь d3912a5a12 feat: enhance API with new trajectory and sequence handling, add TF support and improve endpoint definitions 2026-05-26 20:36:10 +10:00
Даниил Грабарь 30d7785d8c refactor: remove deprecated robot API and implement dynamic routing for endpoints 2026-05-26 17:23:46 +10:00
Даниил Грабарь ec5fb3ccdb refactor: remove commented section headers from motion_sequence_runner.py 2026-05-26 16:10:25 +10:00
Даниил Грабарь a4d318fceb Refactor motion sequence handling: remove old test script, update setup, and implement new runner with configuration support
- Deleted obsolete `test_motion_sequence.py` file.
- Updated `setup.py` to remove references to the old test script and motion configuration file.
- Added `motion_sequence_config.json` to define home position and waypoints for the robot.
- Introduced `motion_sequence_runner.py` to execute motion sequences based on the new configuration format, supporting both joint and pose movements.
2026-05-26 16:09:41 +10:00
Даниил Грабарь a84cfde96c feat: implement ROS node and API for robot control with FastAPI 2026-05-26 08:39:45 +03:00
Даниил Грабарь 2f079df087 Update logic work system 2026-05-25 07:38:07 +03:00
Даниил Грабарь fff46f0ade feat: add rosdep.yaml handling and iiwa_web package to Dockerfiles 2026-05-25 13:16:33 +10:00
Даниил Грабарь e4b8daf754 feat: update package versions to 2026.5.31 and add dependencies for iiwa_web 2026-05-25 12:46:27 +10:00
Даниил Грабарь b560fcf229 refactor: remove command_mode from configuration and related files 2026-05-25 12:30:59 +10:00
grabardm c66de51526 Запрос на слияние 'dev' (#2) из dev в master 2026-05-24 07:38:30 +00:00
Даниил Грабарь e60402c8f2 feat: add English documentation for Lightweight Cobot 2026-05-24 10:35:35 +03:00
Даниил Грабарь cbd05effd2 feat: update package versions and descriptions for all modules; add web interface package 2026-05-24 10:18:04 +03:00
Даниил Грабарь 0b0ef36428 fix: update navigation labels to Russian for consistency 2026-05-23 12:57:06 +03:00
Даниил Грабарь 50d248eb0c feat: update documentation structure and add new content for Lightweight Cobot 2026-05-23 12:51:56 +03:00
Даниил Грабарь 490f8823a5 feat: refactor MultiPickScreen to use SelectionList for multi-choice selection 2026-05-23 12:14:07 +03:00
Даниил Грабарь 3da290a4f3 feat: implement MultiPickScreen for multi-selection in the TUI 2026-05-23 11:07:01 +03:00
Даниил Грабарь 9f59868cec fix: remove sudo keepalive mechanism from installation scripts 2026-05-23 10:50:54 +03:00
Даниил Грабарь ddb6015bfd feat: add clean and rebuild commands for managing ROS2 packages 2026-05-23 09:53:26 +03:00
Даниил Грабарь 19d50d2c09 fix: enhance scripts to keep sudo credentials alive during installation 2026-05-23 09:43:26 +03:00
Даниил Грабарь cc97e2a854 fix: enhance Webots removal and installation scripts to manage WEBOTS_HOME environment variable 2026-05-23 08:21:58 +03:00
Даниил Грабарь 0c677176b0 fix: add COLCON_IGNORE file to exclude specific directories from colcon build 2026-05-23 04:21:43 +03:00
Даниил Грабарь 14a5e6d90a fix: explicitly set Python executables for CMake to use system Python 2026-05-23 04:13:04 +03:00
Даниил Грабарь fc6c08aff3 fix: prioritize system directories in PATH for ament_cmake to use system Python 2026-05-22 19:27:55 +03:00
Даниил Грабарь c57e94dcc4 fix: remove symlink option from colcon build command in _task_build function 2026-05-22 19:23:35 +03:00
Даниил Грабарь b9c7f14a23 fix: update colcon build command to include base paths for improved build process 2026-05-22 19:21:14 +03:00
Даниил Грабарь 0dda077e7f fix: remove symlink option from colcon build command in task_build function 2026-05-22 19:17:35 +03:00
Даниил Грабарь a7dace79ad fix: update progress reporting and improve script clarity in setup scripts 2026-05-22 19:09:32 +03:00
Даниил Грабарь e3ef99d1f0 feat: prompt user to build project workspace after installation 2026-05-22 19:06:10 +03:00
Даниил Грабарь 2a70cdbe75 feat: add installation scripts for ROS2 Jazzy Desktop and ros-base with progress reporting 2026-05-22 19:00:16 +03:00
Даниил Грабарь 7cadd1d673 fix: enhance subprocess management and progress reporting in setup and update commands 2026-05-22 18:30:34 +03:00
Даниил Грабарь 463a1e1423 fix: add docstrings to improve code documentation and clarity 2026-05-22 18:16:59 +03:00
Даниил Грабарь a7590cc93f Implement feature X to enhance user experience and optimize performance 2026-05-22 17:53:09 +03:00
Даниил Грабарь c595365c2b fix: improve apt progress reporting and enhance status handling 2026-05-22 17:24:50 +03:00
Даниил Грабарь 58da9c0814 fix: enhance apt command progress reporting and install dev tools 2026-05-22 17:20:57 +03:00
Даниил Грабарь a1b9a21352 fix: update apt timeouts for improved reliability and adjust add-apt-repository command for no-update 2026-05-22 16:18:34 +03:00
Даниил Грабарь 074896b2dd fix: remove timeout settings from add-apt-repository command for simplicity 2026-05-22 16:02:34 +03:00
Даниил Грабарь dc31589ae0 fix: replace quiet command execution with logged output for better visibility 2026-05-22 16:01:10 +03:00
Даниил Грабарь 523961d432 fix: enhance apt commands with timeout settings and cleanup previous ROS2 repository configuration 2026-05-22 15:52:58 +03:00
Даниил Грабарь 1af22bf2ac fix: refactor ROS2 apt repository setup and improve key import process 2026-05-22 15:49:52 +10:00
Даниил Грабарь a0be3bcd56 fix: remove unnecessary "./" prefix for local apt package installation 2026-05-22 14:50:28 +10:00
Даниил Грабарь 2bdfb139bf Bug fix 2026-05-22 14:27:52 +10:00
Даниил Грабарь e154a41d33 fix: remove leftover ROS2 apt repository files before configuration 2026-05-22 13:56:34 +10:00
Даниил Грабарь 6360023e6f fix: update ROS2 apt repository setup to use ros2-apt-source package and improve installation process 2026-05-22 13:31:30 +10:00
Даниил Грабарь 4202421d5b fix: add process tracking and cancellation support to command execution 2026-05-22 13:23:38 +10:00
Даниил Грабарь 14337aa4e7 fix: add HTTP/HTTPS timeouts for apt commands to prevent hangs and improve reliability 2026-05-22 13:12:23 +10:00
Даниил Грабарь e24f97b12d fix: prompt for sudo password upfront to ensure smooth installation process 2026-05-22 11:56:05 +10:00
Даниил Грабарь 17b1425c78 fix: cache sudo token to prevent silent hangs during installation prompts 2026-05-22 11:43:20 +10:00
Даниил Грабарь 8b71870d2b Merge branch 'dev' of gitverse.ru:daniel-robotics/lightweight-cobot into dev 2026-05-22 11:27:11 +10:00
Даниил Грабарь 5f2d45f63c обновлен процесс загрузки 2026-05-22 11:26:34 +10:00
Даниил Грабарь bdb5fb2418 fix: update robot IP address in configuration and improve process termination handling in run script 2026-05-21 07:56:11 +03:00
Даниил Грабарь fd576dc27a fix: ensure rosdep update does not fail during Docker build 2026-05-21 13:58:54 +10:00
Даниил Грабарь 6be6032838 feat: update robot setup to use ruamel.yaml for preserving YAML comments and formatting
feat: enhance run command with Docker volume for Webots asset caching and GPU detection

feat: improve setup command to sequentially run sub-commands for documentation, environment, and robot parameters

fix: update update command to provide clearer logging during git operations and installation

refactor: enhance TUI components with better threading and logging for long-running tasks

chore: improve install script with better error handling, logging, and interactive setup wizard
2026-05-21 12:46:54 +10:00
Даниил Грабарь e18ff53532 Add run command for launching robot controller and Webots simulator 2026-05-21 11:41:54 +10:00
Даниил Грабарь 2903b8825d Enhance progress reporting in setup and deletion processes across multiple scripts 2026-05-21 11:05:08 +10:00
Даниил Грабарь 11f24172cb Implement retry logic for git clone in installer script to enhance robustness 2026-05-20 18:28:00 +03:00
Даниил Грабарь 615a955767 Refactor subprocess handling in setup scripts for improved error reporting and output management 2026-05-20 18:24:09 +03:00
Даниил Грабарь 6c10d072de Optimize git clone command by adding depth option for faster repository cloning 2026-05-20 18:14:39 +03:00
Даниил Грабарь 9ab76160f0 Enhance ROS2 repository setup by improving key handling and updating installation commands 2026-05-20 18:09:04 +03:00
Даниил Грабарь c8b121958d Improve Python version check in installer script to handle errors gracefully 2026-05-20 18:03:59 +03:00
Даниил Грабарь e153de0bb7 Fix input redirection for quiet command execution and Python version check in installer script 2026-05-20 17:59:37 +03:00
Даниил Грабарь a50ff4e2e6 Add delete and update commands for project management 2026-05-20 17:52:49 +03:00
Даниил Грабарь 5f16825cf7 Refactor Docker and Local Setup Commands
- Enhanced the docker_setup.py to streamline image building and pulling processes with improved logging and error handling.
- Introduced a new LogScreen for better user feedback during long-running tasks.
- Updated local_setup.py to utilize logging for installation steps and improved error handling.
- Refactored robot_setup.py to simplify configuration saving and user interaction.
- Added a new LogScreen class in tui.py for consistent logging across different setup processes.
- Modified install.sh to adjust the installation directory for better organization.
2026-05-20 17:41:11 +03:00
Даниил Грабарь bbfec17876 Add local setup command and enhance docker setup wizard 2026-05-20 17:05:01 +03:00
Даниил Грабарь 86e6e801e9 Add robot setup command and configuration management for cobot-setting.yaml 2026-05-20 14:43:20 +10:00
Даниил Грабарь dedf3e3467 Implement documentation setup and Docker configuration for LWC project 2026-05-20 13:49:21 +10:00
Даниил Грабарь a06470c0c9 Enhance install script with improved logging and error handling 2026-05-19 18:22:37 +03:00
Даниил Грабарь 5315767638 Refactor install script for improved logging and setup process 2026-05-19 17:15:01 +03:00
Даниил Грабарь d1c250e6b9 Add initial implementation of cobot CLI and setup scripts 2026-05-19 17:04:27 +03:00
Даниил Грабарь 6228501581 Refactor Dockerfile and run script for improved GPU handling and environment variable management 2026-05-19 16:26:05 +03:00
Даниил Грабарь 836b03a7ee Update Dockerfiles and configuration for improved package management and controller settings 2026-05-19 12:48:12 +10:00
Даниил Грабарь 24bc5f3aba Update Dockerfiles to support dynamic package installation and build type configuration 2026-05-19 01:51:51 +03:00
Даниил Грабарь 06c50616b4 Add Dockerfile and run script for Webots integration; update package dependencies 2026-05-18 17:53:02 +03:00
Даниил Грабарь 8d27c01b92 Добавлена сборка контроллера 2026-05-18 16:59:16 +03:00
Даниил Грабарь 9bff33608e Добавлены Docker образы 2026-05-18 18:11:05 +10:00
Даниил Грабарь c5d8ecc4c5 Bug fix 2026-05-18 16:59:24 +10:00
Даниил Грабарь aa000c0b02 Fix joint1 axis orientation in joints.xacro for correct kinematic behavior 2026-05-18 07:14:53 +03:00
Даниил Грабарь 04b5c99ec8 Update iiwa_controller and MoveIt configuration: Adjust joint velocity filter and parameters for improved performance 2026-05-18 11:33:35 +10:00
Даниил Грабарь ace4d02b8a Refactor iiwa_controller_v2: Remove obsolete files and update URDF parameters
- Deleted `system_interface_type_values.hpp`, `package.xml`, `fri_client.cpp`, and `system_interface.cpp` as part of the cleanup process.
- Updated `iiwa7.urdf.xacro` to remove deprecated parameters and adjust command interface settings.
- Modified joint definitions in `joints.xacro` to include new friction and soft limit parameters.
- Enhanced `macros.xacro` to support additional joint properties for friction and safety control.
- Adjusted mass properties in `params.xacro` to reflect accurate values for the robot's components.
2026-05-18 11:10:11 +10:00
Даниил Грабарь efaec9b442 Update iiwa_controller configuration for improved joint control and velocity clamping 2026-05-18 03:34:59 +03:00
Даниил Грабарь 86cf252a87 Enhance joint limits and add acceleration scaling to MoveToNamedPose service 2026-05-15 07:20:26 +03:00
Даниил Грабарь 99215c0b20 Add iiwa_controller_v2: Implement hardware interface for KUKA iiwa7 via FRI
- Introduced iiwa_hardware_interface_plugin.xml to define the hardware interface.
- Created command_guard.hpp to enforce joint limits for position and torque commands.
- Developed fri_client.hpp and fri_client.cpp to manage FRI communication and state snapshots.
- Implemented system_interface.hpp and system_interface.cpp for lifecycle management and command handling.
- Added system_interface_type_values.hpp for extended state interface names.
- Defined package.xml for ROS2 integration with necessary dependencies.
2026-05-15 13:10:00 +10:00
Даниил Грабарь d6b4641d9b Update FRI configuration parameters for improved joint control and synchronization 2026-05-14 08:01:58 +03:00
Даниил Грабарь 7eefdd66d5 Refactor controller configuration and update planning parameters for improved performance 2026-05-14 07:29:47 +03:00
Даниил Грабарь c3d1de7b01 Add joint_position_tau parameter for smoother joint control and update related configurations 2026-05-14 11:40:04 +10:00
Даниил Грабарь 302eb3d8d7 fix: Update FRI cycle time and adjust related parameters for improved synchronization 2026-05-13 07:39:18 +03:00
Даниил Грабарь 1f37a07770 Add fri_cycle_ms parameter to configuration and update related components 2026-05-13 04:31:19 +03:00
Даниил Грабарь 68198ed2f8 Add documentation build scripts and initial MkDocs setup 2026-05-08 16:43:22 +10:00
Даниил Грабарь 6744f1963f Переделан контроллер 2026-05-08 08:49:10 +03:00
Даниил Грабарь 2dfe967ca1 fix: Update .gitignore to include .claude and clean up friUdpConnection.cpp code 2026-05-08 04:17:06 +03:00
Даниил Грабарь 225ae50f10 feat: Enhance iiwa_description and iiwa_sunrise functionality
- Added a new link "tcp" and a fixed joint "patron_tcp" in patron.xacro for better tool control.
- Updated ServerFriRos2.java to improve command mode handling and user configuration steps, including clearer logging and better control mode selection.
- Removed the deprecated iiwa_ros2.java file to streamline the codebase.
- Enhanced test_motion_sequence.py to allow dynamic topic recording based on user input, with improved logging for bag file management.
2026-05-07 17:47:47 +03:00
Даниил Грабарь 3c8d157cbe Исправлены баги 2026-05-06 07:39:22 +03:00
Даниил Грабарь 9f30b9ff5d feat: enhance motion sequence capabilities and add configuration support
- Updated README.md to include examples for data collection and motion sequence testing.
- Modified setting.yaml to change the TCP link for planning from "patron" to "link_ee".
- Refactored move_to_pose_server.py to improve planner configuration readability.
- Updated setup.py to include motion_config.json in package resources and added a new console script for testing motion sequences.
- Introduced motion_config.json to define home joints and poses for motion sequences.
- Added test_motion_sequence.py to implement a test runner for executing motion sequences and recording data to a bag file.
2026-05-06 14:03:41 +10:00
Даниил Грабарь cd4dcf97ac Update pose_link in planning configuration to use 'patron' 2026-05-05 17:18:25 +03:00
Даниил Грабарь e4d6bdc1af Add motion planning actions and services for iiwa robot
- Implemented action servers for MoveToPose and MoveToJoints.
- Added service for MoveToNamedPose and stop action.
- Updated README with usage examples for new actions.
- Enhanced planning configurations in YAML and Python files.
- Removed deprecated motion planning scripts.
2026-05-05 17:15:08 +03:00
Даниил Грабарь b3f4bc458b Добавлены управляющие программы для коллаборативного робота 2026-05-05 15:43:56 +03:00
Даниил Грабарь 748f30b1d1 Add move_to_pose_server and iiwa_msgs package with service definition
- Implement move_to_pose_server for motion planning using MoveIt
- Create iiwa_msgs package with MoveToPose service definition
- Update iiwa.launch.py to include move_to_pose_server node
- Modify joint_limits.yaml to add position limits for joints
- Remove iiwa_voice package and related files
2026-05-05 18:37:04 +10:00
Даниил Грабарь 6b4ff4f8b6 Update model versions in docker-compose for Qwen3-TTS services 2026-04-20 15:52:20 +10:00
Даниил Грабарь 8e2cf07303 change struct docker 2026-04-20 13:50:52 +10:00
Даниил Грабарь ce143ff2dd Update docker-compose configuration for Qwen3-TTS services with improved command structure and health check adjustments 2026-04-20 13:21:15 +10:00
Даниил Грабарь f6d5d546d1 Refactor docker-compose commands to use --model flag and add voice generation script 2026-04-20 13:18:49 +10:00
Даниил Грабарь 0445776d48 Add iiwa_voice package with environment setup and docker-compose configuration 2026-04-20 12:42:45 +10:00
Даниил Грабарь 5eefd2fc90 Add realsense2 package installation and new world file for iiwa control cabinet 2026-04-15 16:39:17 +10:00
Даниил Грабарь bd66f314fc Merge branch 'dev' of gitverse.ru:daniel-robotics/kuka_iiwa7_ros2 into dev 2026-04-15 09:55:23 +10:00
Даниил Грабарь 036ac35685 Add documentation and PDF resources for KUKA Sunrise applications 2026-04-15 09:55:09 +10:00
Даниил Грабарь b4ceedd043 Add installation command for rosbag2 storage MCAP in README 2026-04-14 14:50:33 +03:00
Даниил Грабарь c95c94f67b Bug fiix import patron.xacro and append packages realsense2 2026-04-14 14:20:27 +03:00
Даниил Грабарь 1156c768bb Refactor code structure for improved readability and maintainability 2026-04-14 18:06:58 +10:00
Даниил Грабарь a913d512b9 change parametrs 2026-04-14 09:20:05 +03:00
Даниил Грабарь 7736c71760 Add camera spawning functionality and update configuration files 2026-04-14 11:19:53 +10:00
Даниил Грабарь cd450a3476 Add camera spawning functionality and update world configuration 2026-04-13 17:37:24 +03:00
Даниил Грабарь 2dfa8f1c94 Add foxglove_bridge configuration and settings support 2026-04-13 17:20:32 +10:00
Даниил Грабарь d585c4f0b9 update launch file 2026-04-13 07:02:53 +03:00
Даниил Грабарь bfa16be526 update patron and structured 3dd models 2026-04-13 06:49:31 +03:00
Даниил Грабарь 9e643f756a update 3dmodels 2026-04-13 02:11:35 +03:00
Даниил Грабарь deb646c7a9 Add code server java 2026-04-10 10:37:46 +03:00
Даниил Грабарь 6d8d15ba5d Add cameraD455 mesh file to iiwa_description resources 2026-04-10 17:15:16 +10:00
Даниил Грабарь 2eb87077dd Refactor controller launch configuration and remove deprecated URDF files 2026-04-09 16:45:30 +10:00
Даниил Грабарь 47cafe7ea1 Add AMENT_IGNORE file and initial implementation of AAServer and Iiwa_ros2 classes 2026-04-09 13:55:32 +10:00
Даниил Грабарь 845f4ca89c Refactor launch files and update package descriptions for KUKA iiwa7, transitioning from Gazebo to Webots simulation 2026-04-09 13:52:28 +10:00
Даниил Грабарь 58f246e1f2 Add URDF and XACRO files for iiwa7 robot and tool patron
- Created iiwa7_gazebo.urdf to define the iiwa7 robot model with detailed links, joints, and Gazebo integration.
- Introduced patron.xacro for the tool patron, including its inertial properties, visual representation, and collision geometry.
2026-04-09 12:01:43 +10:00
Даниил Грабарь f474d330ad Add URDF model for table and SDF world configuration
- Created a new URDF file for the table model, including links for the table frame, wood palette, robot palette, cabinet frame, and cabinet, along with their respective visual and collision properties.
- Defined joints to connect the various components of the table model.
- Added a new SDF file for the simulation world, setting up the environment with physics properties, a ground plane, and lighting.
2026-04-08 16:38:59 +10:00
Даниил Грабарь 45e134e116 Refactor launch files and update robot description for iiwa7 configuration 2026-04-08 13:52:17 +10:00
Даниил Грабарь 9fae773856 append new render mode 2026-04-08 06:37:57 +03:00
Даниил Грабарь e182f5b7bd Refactor URDF and launch files for iiwa robot
- Updated gripper macros in gripper_macros.xacro to simplify parameters and add Gazebo support.
- Removed unused mesh property in gripper_meshes.xacro.
- Enhanced iiwa7 digital and FRI URDF files with simulation arguments and improved controller setup.
- Added new launch files for Gazebo simulation and universal launch configuration.
- Implemented YAML parameter wrapping for ROS2 in converter.py.
- Introduced a new gz_bridge.yaml configuration for Gazebo to ROS2 topic mapping.
- Cleaned up setting_loader.py and added necessary imports.
2026-04-08 13:21:18 +10:00
Даниил Грабарь 9fb3477466 Test multi repos 2026-04-07 16:06:47 +03:00
Даниил Грабарь 48c0913108 Test ssh-remote 2026-04-07 16:00:58 +03:00
Даниил Грабарь a269ef3a76 Add gripper model and configuration for iiwa7 robot
- Created URDF model for gripper including links and joints.
- Added XACRO files for gripper components: gripper.xacro, gripper_links.xacro, gripper_joints.xacro, gripper_macros.xacro, and gripper_meshes.xacro.
- Integrated gripper into iiwa7 digital twin configuration.
- Defined properties and macros for gripper components to facilitate easier modifications and reuse.
2026-04-07 14:40:23 +10:00
Даниил Грабарь 44dd2505ca Add URDF model for gripper with multiple links and joints
- Created a new URDF file for the gripper, defining its structure.
- Added links: base_frame, plate, screw, craving1, craving2, craving3.
- Defined joints for the gripper's movement, including fixed and revolute joints.
- Included mesh files for visual and collision geometry.
- Set inertial properties for each link with zero mass and inertia.
2026-04-07 01:52:19 +03:00
Даниил Грабарь 1dc17d5949 Enhance IIWA Robot Configuration and Launch Files
- Updated iiwa7 URDF Xacro to include command and state interfaces for position and effort with defined limits for all joints.
- Modified setting_loader.py to include new fields for command_mode and description in the RobotCfg dataclass and settings loading process.
- Created iiwa.launch.py to manage the launch of the IIWA robot, integrating MoveIt configurations and RViz support.
- Added iiwa_controllers.launch.py to set up the controller manager and spawner for the IIWA robot.
- Introduced iiwa_hardware_interface_plugin.xml to define the hardware interface for the KUKA IIWA 7 robot.
- Added iiwa7_fri.urdf.xacro to support FRI (Fast Robot Interface) with appropriate command and state interfaces for each joint.
2026-04-06 09:40:04 +03:00
Даниил Грабарь 032935dec9 Обновлены параметры планирования и добавлены новые файлы для модуля планирования движения, включая C++ и Python реализации. 2026-04-05 12:22:30 +03:00
Даниил Грабарь bce4dd6067 добавлен полноценный модуль планирования траекторных перемещений. Необходимо его оформить правильным образом 2025-12-26 23:03:41 +10:00
Даниил Грабарь fe89d626d3 добавлен модуль iiwa_planning, в котором будет размещен весь код по планированию траекторных перемещений, а также логическое планирование (PDDL, LLM и др.).
Тестовый файл `motion_planning_test.py` внутрь созданного модуля
2025-12-26 15:34:07 +10:00
Даниил Грабарь caa9984abe Обновлены параметры ускорения по каждой из осей 2025-12-26 14:30:18 +10:00
Даниил Грабарь fa39991bcf Переработана вся структура запуска файлов. Теперь в iiwa_bringup хранятся только launch файлы.
Все конфигурационные файлы переехали в пакет `iiwa_config`. также там появился общий конфигурационный файл, который упращает запуск `digital_twin.launch.py`

Добавлен дополнительный пакет  `iiwa_utils`, в который переехал весь код с папки `iiwa_bringup/utils`, а также все тестовые ноды переехали с `iiwa_object_spawner` в этот пакет

Пакеты `iiwa_bringup` и `iiwa_description` переведены на `ament_cmake` для дальнейшего удобсва - пакеты не будут содержать код для реализации
2025-12-25 21:46:40 +10:00
Даниил Грабарь 1a65f48c03 исправлена название группы управления осями, добавле файл конфигуации для управления осями через api moveit, а также добавлен пример на языке python 2025-12-24 21:14:32 +10:00
Даниил Грабарь 7637a215d3 Исправлены ошибки, которые остались с ros2 rolling 2025-12-24 16:26:17 +10:00
Даниил Грабарь 084d4c0aa7 добавлена поддержка moveit 2025-12-24 13:44:55 +10:00
Даниил Грабарь 6acbd7ca6f Исправлены баги, добавлен код Object.proto, в который будут подставлятяь 3д объекты для последующего спавна 2025-12-23 21:48:18 +10:00
Даниил Грабарь 37da67abe5 отформатированы документы согласно нотации pep 2025-11-29 15:51:45 +10:00
Даниил Грабарь b36bd0e98b Изминения:
- В файле `webots_spawn.launch.py` - добавлено использование времени симуляции
- Добавлен новый пакет `iiwa_object_spawne`, который отвечает за появление объектов (в разработке)
2025-11-29 00:40:55 +10:00
Даниил Грабарь 3852340a58 Изменил название файла, поскольку может понадобиться в будущем. Сейчас описанные подходы в нем не используются 2025-11-23 02:23:51 +10:00
363 changed files with 23528 additions and 1711 deletions
+71
View File
@@ -0,0 +1,71 @@
name: Документация
on:
push:
branches:
- master
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: pages
cancel-in-progress: false
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Python 3.12
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install system dependencies (WeasyPrint/PDF)
run: |
sudo apt-get update -qq
sudo apt-get install -y \
libcairo2 libpango-1.0-0 libpangoft2-1.0-0 \
libgdk-pixbuf-2.0-0 libffi-dev \
fontconfig fonts-dejavu
- name: Install MkDocs
run: |
pip install \
mkdocs-material \
mkdocs-static-i18n==1.3.1 \
mkdocs-to-pdf==0.11.2
- name: Build Documentation
env:
ENABLE_PDF_EXPORT: "1"
run: mkdocs build
working-directory: doc/lwc-doc
- name: Upload Pages artifact
uses: actions/upload-pages-artifact@v1.0.0
with:
path: doc/lwc-doc/site/
deploy-github:
if: github.server_url == 'https://github.com'
needs: build
runs-on: ubuntu-latest
environment:
name: github-pages
steps:
- name: Deploy to GitHub Pages
uses: actions/deploy-pages@v4
deploy-gitverse:
if: github.server_url != 'https://github.com'
needs: build
runs-on: ubuntu-latest
steps:
- name: Deploy to GitVerse Pages
uses: actions/deploy-pages@v1.0.0
+16 -2
View File
@@ -1,5 +1,19 @@
# Generated MkDocs site and PDF output
doc/lwc-doc/site/
log/
install/
build/
/install/
/build/
.vscode
.idea
venv
.venv
.claude
.codex
__pycache__
*.egg-info
**.FCBak
CLAUDE.md
AGENTS.md
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [2026] [Daniel Robotics]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+183 -23
View File
@@ -1,31 +1,191 @@
Подмена файла по пути обязательна: `/opt/ros/rolling/lib/webots_ros2_driver/ros2_supervisor.py`
# Lightweight Cobot
> необходимо `warn` заменить на `warning` в логере
<p align="center">
<strong>Русский</strong> · <a href="README_en.md">English</a>
</p>
**Lightweight Cobot (LWC)** — открытая система управления коллаборативным роботом **KUKA LBR iiwa 7 R800** на базе ROS 2. Проект объединяет работу с физическим роботом через FRI и `ros2_control`, цифровой двойник в Webots, планирование движений MoveIt 2, визуализацию в RViz и Foxglove, а также REST API и MCP для внешних приложений и AI-агентов.
<table>
<tr>
<th align="center">LBR IIWA 7 R800</th>
</tr>
<tr>
<td align="center">
<img src="https://raw.githubusercontent.com/lbr-stack/lbr_fri_ros2_stack/jazzy/lbr_fri_ros2_stack/doc/img/foxglove/iiwa7_r800.png" alt="LBR IIWA 7 R800" width="300">
</td>
</tr>
</table>
## Какие задачи решает проект
- Даёт единый программный стек для физического робота и симуляции без дублирования управляющего кода.
- Подключает KUKA Sunrise Cabinet к ROS 2 через FRI и предоставляет стандартные интерфейсы `ros2_control`.
- Выполняет суставные и декартовы движения с помощью MoveIt 2, OMPL и Pilz.
- Упрощает установку, настройку, сборку и запуск через CLI `cobot`.
- Хранит основные параметры робота, инструментов и сервисов в одном файле `cobot-setting.yaml`.
- Предоставляет средства мониторинга и интеграции через RViz, Foxglove, HTTP/WebSocket API и MCP.
## Возможности
| Компонент | Назначение |
|---|---|
| Физический робот | Управление KUKA LBR iiwa 7 R800 через FRI и `ServerFriRos2` |
| Цифровой двойник | Симуляция робота, инструментов и окружения в Webots |
| Планирование | Суставные и декартовы траектории через MoveIt 2 |
| Управление | `ros2_control`, ROS 2 actions/services, REST API и MCP |
| Наблюдение | RViz, Foxglove и состояние системы через веб-интерфейс |
| Инфраструктура | Локальное окружение или Docker, единый CLI и централизованная конфигурация |
## Совместимость
| Компонент | Поддерживаемая версия |
|---|---|
| Операционная система | **Ubuntu 24.04 LTS** — подтверждённая ОС для нативной установки |
| ROS 2 | Jazzy |
| Webots | 2025a |
| Python для CLI | 3.11 |
| KUKA Sunrise OS | 1.16 |
| KUKA FRI | 1.16 |
Docker можно использовать как альтернативную среду на совместимом Linux-хосте. Полноценная работа проекта на Windows и macOS не заявлена. Sunrise Workbench используется отдельно для подготовки и синхронизации проекта контроллера KUKA.
## Репозитории и документация
| Ресурс | Ссылка |
|---|---|
| Основной репозиторий | [GitVerse](https://gitverse.ru/daniel-robotics/lightweight-cobot) |
| Зеркало | [GitHub](https://github.com/Daniel-Robotic/lightweight-cobot) |
| Онлайн-документация | [GitVerse Pages](https://daniel-robotics.gitverse.site/lightweight-cobot/) |
| Зеркало документации | [GitHub Pages](https://daniel-robotic.github.io/lightweight-cobot/) |
Подробные инструкции начинаются со страницы [«Обзор»](doc/lwc-doc/docs/getting-started/index.ru.md). Исходные тексты документации находятся в `doc/lwc-doc/docs`.
## Быстрый старт
### Требования
- Ubuntu 24.04 LTS;
- доступ в интернет;
- права `sudo`;
- физический KUKA LBR iiwa 7 R800 либо компьютер для работы только с симулятором.
### Установка CLI
Запустите установщик:
```bash
sudo apt install -y ros-${ROS_DISTRO}-webots-ros2 \
ros-${ROS_DISTRO}-ros2-control \
ros-${ROS_DISTRO}-ros2-controllers \
ros-${ROS_DISTRO}-moveit-* \
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/install.sh | bash
```
Установка moveit2 (внимательно проверяй)
Установщик проверит базовые инструменты, установит Docker, `uv` и Python 3.11 при необходимости, склонирует проект в `~/.lwc` и установит CLI `cobot`. Каталог можно изменить переменной `COBOT_INSTALL_DIR`.
Откройте новый терминал или обновите окружение оболочки, затем запустите мастер первоначальной настройки:
```bash
sudo apt install -y build-essential \
cmake \
git \
python3-colcon-common-extensions \
python3-flake8 \
python3-rosdep \
python3-setuptools \
python3-vcstool \
wget
cobot setup
```
git clone https://github.com/moveit/moveit2.git
vcs import --recursive < moveit2/moveit2.repos
sudo apt remove ros-$ROS_DISTRO-moveit*
rosdep install -r --from-paths ./src/ --ignore-src --rosdistro $ROS_DISTRO --os=ubuntu:noble -y
Мастер последовательно предложит запустить локальную документацию, настроить `cobot-setting.yaml` и выбрать среду сборки: нативный ROS 2 или Docker.
colcon build --mixin release
```
### Только симуляция
Для работы в Webots физический робот и Sunrise Workbench не требуются. Выполните:
```bash
cobot run
```
Выберите локальную или Docker-среду, а затем пункт **Симулятор Webots**.
### Физический робот
Перед первым запуском подготовьте контроллер и программу `ServerFriRos2` по инструкции [«Настройка SunriseWorkbench»](doc/lwc-doc/docs/getting-started/sunrise-setup.ru.md). Проверьте сеть KONI/KLI, IP-адреса, период FRI, выбранный инструмент и его Load Data.
После настройки запустите:
```bash
cobot run
```
Выберите локальную или Docker-среду, а затем пункт **Физический контроллер**. Подробное описание серверной программы приведено на странице [ServerFriRos2](doc/lwc-doc/docs/sunrise/kuka/programs/server-fri-ros2.ru.md).
## Основные команды
| Команда | Назначение |
|---|---|
| `cobot setup` | Первоначальная настройка документации, робота и среды сборки |
| `cobot robot-setup` | Интерактивное изменение `cobot-setting.yaml` |
| `cobot local-setup` | Установка ROS 2 Jazzy и локальная сборка workspace |
| `cobot docker-setup` | Загрузка или сборка Docker-образов |
| `cobot run` | Интерактивный выбор среды и запуск робота или Webots |
| `cobot run local` | Запуск через нативный ROS 2 с последующим выбором робота или Webots |
| `cobot run docker` | Запуск в Docker с последующим выбором робота или Webots |
| `cobot rebuild` | Пересборка ROS 2 workspace |
| `cobot clean` | Удаление артефактов `build`, `install` и `log` |
| `cobot update` | Обновление проекта и переустановка CLI |
| `cobot --help` | Полный список доступных команд |
## Документация локально
Для локального просмотра необходим Docker.
```bash
cobot doc-setup
```
По умолчанию сайт будет доступен по адресу [http://localhost:8000](http://localhost:8000). Исходные Markdown-файлы отслеживаются автоматически.
| Команда | Назначение |
|---|---|
| `cobot doc-setup` | Запустить локальный сервер документации |
| `cobot doc-setup build` | Собрать статический сайт и единый PDF в `doc/lwc-doc/site` |
| `cobot doc-setup rebuild` | Пересобрать Docker-образ и перезапустить сервер |
| `cobot doc-setup down` | Остановить локальный сервер |
Онлайн-версия доступна на [GitVerse Pages](https://daniel-robotics.gitverse.site/lightweight-cobot/), зеркало — на [GitHub Pages](https://daniel-robotic.github.io/lightweight-cobot/).
## Пакеты
| Пакет | Описание |
|---|---|
| `iiwa_bringup` | Launch-файлы: симуляция Webots, реальный робот через FRI, MoveIt и RViz |
| `iiwa_config` | Конфигурационные файлы: MoveIt, контроллеры ros2_control, кинематика и общие параметры |
| `iiwa_controller` | Hardware interface: управление суставами в реальном времени через FRI |
| `iiwa_description` | URDF/XACRO описание робота и конфигурация мира Webots |
| `iiwa_msgs` | ROS 2 интерфейсы: action-сообщения для движения по суставам и в декартовых координатах, сервисы именованных поз |
| `iiwa_planning` | Планирование движения: C++ и Python узлы на базе MoveIt 2 (OMPL, Pilz, moveit_py) |
| `iiwa_utils` | Утилиты системы: загрузка конфигурации, спавн объектов и камер в Webots, конвертация данных |
| `iiwa_web` | REST API, WebSocket и MCP для мониторинга и внешнего управления |
Java-программы для KUKA Sunrise Cabinet находятся отдельно в `src/iiwa_sunrise` и не входят в сборку colcon.
## Безопасность
Перед отправкой команд на физический робот проверьте рабочую область, ограничения суставов, активный инструмент, модель нагрузки и выбранный режим управления. LWC не заменяет штатные средства безопасности KUKA, оценку рисков роботизированной ячейки и контроль оператора.
## Лицензия
Проект распространяется по лицензии [Apache License 2.0](LICENSE).
## Цитирование
Если вы используете проект в исследовании или разработке, укажите ссылку на репозиторий:
```bibtex
@software{lightweight_cobot_2026,
author = {Грабарь, Даниил},
title = {Lightweight Cobot: ROS 2 stack for KUKA LBR IIWA 7},
year = {2026},
url = {https://gitverse.ru/daniel-robotics/lightweight-cobot}
}
```
---
## Благодарности
| Организация | Примечание |
|---|---|
| [Комсомольский-на-Амуре государственный университет](https://knastu.ru/) | Исследования проводились на базе КнАГУ |
| [Российский научный фонд](https://rscf.ru/) | Работа выполнена при поддержке Российского научного фонда |
+189
View File
@@ -0,0 +1,189 @@
# Lightweight Cobot
<p align="center">
<a href="README.md">Русский</a> · <strong>English</strong>
</p>
**Lightweight Cobot (LWC)** is an open control system for the **KUKA LBR iiwa 7 R800** collaborative robot built on ROS 2. It combines physical robot control through FRI and `ros2_control`, a Webots digital twin, MoveIt 2 motion planning, RViz and Foxglove visualization, plus REST and MCP interfaces for external applications and AI agents.
<table>
<tr>
<th align="center">LBR iiwa 7 R800</th>
</tr>
<tr>
<td align="center">
<img src="https://raw.githubusercontent.com/lbr-stack/lbr_fri_ros2_stack/jazzy/lbr_fri_ros2_stack/doc/img/foxglove/iiwa7_r800.png" alt="LBR iiwa 7 R800" width="300">
</td>
</tr>
</table>
## Problems solved by the project
- Provides one software stack for both the physical robot and simulation without duplicating control code.
- Connects KUKA Sunrise Cabinet to ROS 2 through FRI and exposes standard `ros2_control` interfaces.
- Executes joint-space and Cartesian motions using MoveIt 2, OMPL, and Pilz.
- Simplifies installation, configuration, builds, and startup through the `cobot` CLI.
- Keeps the main robot, tool, and service parameters in one `cobot-setting.yaml` file.
- Provides monitoring and integration through RViz, Foxglove, HTTP/WebSocket APIs, and MCP.
## Features
| Component | Purpose |
|---|---|
| Physical robot | KUKA LBR iiwa 7 R800 control through FRI and `ServerFriRos2` |
| Digital twin | Robot, tool, and environment simulation in Webots |
| Motion planning | Joint-space and Cartesian trajectories through MoveIt 2 |
| Control | `ros2_control`, ROS 2 actions/services, REST API, and MCP |
| Monitoring | RViz, Foxglove, and system state through the web interface |
| Infrastructure | Native or Docker environment, a unified CLI, and centralized configuration |
## Compatibility
| Component | Supported version |
|---|---|
| Operating system | **Ubuntu 24.04 LTS** — verified for native installation |
| ROS 2 | Jazzy |
| Webots | 2025a |
| CLI Python | 3.11 |
| KUKA Sunrise OS | 1.16 |
| KUKA FRI | 1.16 |
Docker is available as an alternative environment on a compatible Linux host. Full Windows and macOS support is not claimed. Sunrise Workbench is used separately to prepare and synchronize the KUKA controller project.
## Repositories and documentation
| Resource | Link |
|---|---|
| Primary repository | [GitVerse](https://gitverse.ru/daniel-robotics/lightweight-cobot) |
| Mirror | [GitHub](https://github.com/Daniel-Robotic/lightweight-cobot) |
| Online documentation | [GitVerse Pages](https://daniel-robotics.gitverse.site/lightweight-cobot/) |
| Documentation mirror | [GitHub Pages](https://daniel-robotic.github.io/lightweight-cobot/) |
The detailed guide starts on the [Overview](doc/lwc-doc/docs/getting-started/index.en.md) page. Documentation sources are stored under `doc/lwc-doc/docs`.
## Quick start
### Requirements
- Ubuntu 24.04 LTS;
- internet access;
- `sudo` privileges;
- a physical KUKA LBR iiwa 7 R800, or a computer if only the simulator will be used.
### Install the CLI
Run the installer:
```bash
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/install.sh | bash
```
The installer checks the basic tools, installs Docker, `uv`, and Python 3.11 when required, clones the project into `~/.lwc`, and installs the `cobot` CLI. Set `COBOT_INSTALL_DIR` to use a different location.
Open a new terminal or reload the shell environment, then start the first-time setup wizard:
```bash
cobot setup
```
The wizard offers to start the local documentation, configure `cobot-setting.yaml`, and prepare either a native ROS 2 or Docker build environment.
### Simulation only
A physical robot and Sunrise Workbench are not required for Webots simulation. Run:
```bash
cobot run
```
Choose the native or Docker environment, then select **Webots simulator**.
### Physical robot
Before the first run, prepare the controller and `ServerFriRos2` as described in [Sunrise Workbench setup](doc/lwc-doc/docs/getting-started/sunrise-setup.en.md). Verify the KONI/KLI network, IP addresses, FRI period, selected tool, and its Load Data.
Then run:
```bash
cobot run
```
Choose the native or Docker environment, then select **Physical controller**. See the [ServerFriRos2](doc/lwc-doc/docs/sunrise/kuka/programs/server-fri-ros2.en.md) page for details about the controller-side application.
## Main commands
| Command | Purpose |
|---|---|
| `cobot setup` | Configure documentation, robot parameters, and the build environment |
| `cobot robot-setup` | Edit `cobot-setting.yaml` interactively |
| `cobot local-setup` | Install ROS 2 Jazzy and build the workspace natively |
| `cobot docker-setup` | Pull or build the Docker images |
| `cobot run` | Select an environment and launch the physical robot or Webots interactively |
| `cobot run local` | Use native ROS 2, then select the physical robot or Webots |
| `cobot run docker` | Use Docker, then select the physical robot or Webots |
| `cobot rebuild` | Rebuild the ROS 2 workspace |
| `cobot clean` | Remove the `build`, `install`, and `log` artifacts |
| `cobot update` | Update the project and reinstall the CLI |
| `cobot --help` | Show every available command |
## Local documentation
Docker is required for the local documentation server.
```bash
cobot doc-setup
```
By default, the site is available at [http://localhost:8000](http://localhost:8000). Markdown source changes are watched automatically.
| Command | Purpose |
|---|---|
| `cobot doc-setup` | Start the local documentation server |
| `cobot doc-setup build` | Build the static site and combined PDF under `doc/lwc-doc/site` |
| `cobot doc-setup rebuild` | Rebuild the Docker image and restart the server |
| `cobot doc-setup down` | Stop the local server |
The online documentation is hosted on [GitVerse Pages](https://daniel-robotics.gitverse.site/lightweight-cobot/), with a mirror on [GitHub Pages](https://daniel-robotic.github.io/lightweight-cobot/).
## Packages
| Package | Description |
|---|---|
| `iiwa_bringup` | Launch files for Webots, the physical FRI robot, MoveIt, and RViz |
| `iiwa_config` | MoveIt, `ros2_control`, kinematics, and shared configuration files |
| `iiwa_controller` | Real-time FRI hardware interface for `ros2_control` |
| `iiwa_description` | URDF/Xacro robot description, meshes, tools, and Webots worlds |
| `iiwa_msgs` | ROS 2 actions and services for joint, Cartesian, and named-pose motions |
| `iiwa_planning` | C++ and Python motion nodes based on MoveIt 2, OMPL, Pilz, and `moveit_py` |
| `iiwa_utils` | Configuration loading, data conversion, and Webots object/camera utilities |
| `iiwa_web` | REST API, WebSocket, and MCP interfaces for monitoring and external control |
Java applications for KUKA Sunrise Cabinet live separately under `src/iiwa_sunrise` and are not part of the colcon build.
## Safety
Before commanding the physical robot, verify the work area, joint limits, active tool, load model, and selected control mode. LWC does not replace KUKA safety functions, a robotic-cell risk assessment, or operator supervision.
## License
This project is available under the [Apache License 2.0](LICENSE).
## Citation
If you use the project in research or development, cite the repository:
```bibtex
@software{lightweight_cobot_2026,
author = {Hrabar, Daniil},
title = {Lightweight Cobot: ROS 2 stack for KUKA LBR IIWA 7},
year = {2026},
url = {https://gitverse.ru/daniel-robotics/lightweight-cobot}
}
```
## Acknowledgements
| Organization | Notes |
|---|---|
| [Komsomolsk-on-Amur State University (KnAGU)](https://knastu.ru/) | Research was conducted at KnAGU |
| [Russian Science Foundation (RSF)](https://rscf.ru/) | Work supported by the Russian Science Foundation |
+82
View File
@@ -0,0 +1,82 @@
robot:
name: "iiwa7"
ip: "192.170.10.2"
port: 30200
fri_cycle_ms: 10 # период FRI-цикла: 5 мс (200 Гц) или 10 мс (100 Гц)
joint_position_tau: 0.04 # EMA фильтр позиций [с]: сглаживает команды перед отправкой в FRI
joint_velocity_tau: 0.01 # EMA фильтр скорости [с]: убирает выбросы конечных разностей
active_controller: "jtc" # "jtc" = MoveIt/JointTrajectoryController, "forward" = ForwardCommandController
description: pkg://iiwa_description/urdf/iiwa7.urdf.xacro
digital_twin:
webots:
world: pkg://iiwa_description/worlds/iiwa.wbt
# world: pkg://iiwa_description/worlds/simple_world.wbt
transform: "-0.25 0 0.79"
rotation: "0 0 1 0"
controller_timer: "50"
cameras:
- pkg://iiwa_config/config/cameras/d455_top.yaml
rviz:
config: pkg://iiwa_config/config/rviz/rviz_moveit.rviz
controller:
controller_path: pkg://iiwa_config/config/moveit/iiwa_controller.yaml
moveit:
srdf: pkg://iiwa_config/config/moveit/iiwa7.srdf
kinematics: pkg://iiwa_config/config/moveit/kinematics.yaml
joint_limits: pkg://iiwa_config/config/moveit/joint_limits.yaml
pilz_limits: pkg://iiwa_config/config/moveit/pilz_cartesian_limits.yaml
initial_positions: pkg://iiwa_config/config/moveit/initial_positions.yaml
moveit_controllers: pkg://iiwa_config/config/moveit/moveit_controllers.yaml
moveit_cpp: pkg://iiwa_config/config/moveit/moveit_cpp.yaml
tool:
active: "patron" # Активный инструмент: none | patron | ... (из tools.yaml)
planning:
pose_link: "tcp" # TCP-линк для декартовых целей
planning_group: "iiwa_arm" # Группа планирования из SRDF
default_frame: "base_link" # Система отсчёта по умолчанию
default_planner: "ompl" # Планировщик по умолчанию
planning_attempts: 3 # Число попыток планирования
web:
enabled: true
host: "0.0.0.0"
port: 8007
endpoints: pkg://iiwa_config/config/api_endpoints.yaml
joint_limits: pkg://iiwa_config/config/moveit/joint_limits.yaml
foxglove:
enabled: true # Запускать ли foxglove_bridge вместе с роботом
port: 8765 # WebSocket-порт, к которому подключается Foxglove Studio (по умолчанию 8765)
debug: false # Включить подробное логирование bridge-процесса
address: 0.0.0.0 # Адрес, на котором слушает сервер. 0.0.0.0 — все интерфейсы, 127.0.0.1 — только локально
tls: false # Включить TLS-шифрование соединения (нужны certfile + keyfile)
certfile: "" # Путь к SSL-сертификату (нужен только при tls: true)Путь к SSL-сертификату (нужен только при tls: true)
keyfile: "" # Путь к SSL-сертификату (нужен только при tls: true)
topic_whitelist: ['.*'] # Regex-список топиков, которые bridge публикует клиенту
param_whitelist: ['.*'] # Regex-список ROS-параметров, видимых клиенту
service_whitelist: ['.*'] # Regex-список сервисов, доступных клиенту
client_topic_whitelist: ['.*'] # Regex-список топиков, в которые клиент может публиковать (clientPublish)
min_qos_depth: 1 # Минимальная глубина QoS-очереди при подписке bridge на топик
max_qos_depth: 10 # Максимальная глубина QoS-очереди
num_threads: 0 # Число потоков исполнения. 0 = автоматически по числу CPU
send_buffer_limit: 10000000 # Максимальный размер буфера отправки в байтах (защита от OOM при медленном клиенте)
use_sim_time: false # Использовать симуляционное время /clock вместо системного
capabilities: # Список возможностей, открытых клиенту
- clientPublish
- parameters
- parametersSubscribe
- services
- connectionGraph
- assets
include_hidden: false # Показывать клиенту скрытые топики и сервисы (начинаются с _)
asset_uri_allowlist: ['^package://(?:[-\w%]+/)*[-\w%.]+\.(?:dae|fbx|glb|gltf|jpeg|jpg|mtl|obj|png|stl|tif|tiff|urdf|webp|xacro)$'] # Regex-список URI вида package://..., из которых bridge разрешает отдавать файлы-ассеты (URDF, mesh и т.п.)
ignore_unresponsive_param_nodes: true # Не падать, если нода не отвечает на запросы параметров (защита от зависания при старте)
+128
View File
@@ -0,0 +1,128 @@
import argparse
# Import each command module so we can register its subparser.
# Импортируем каждый модуль команды, чтобы зарегистрировать его подпарсер.
from cobot.commands import clean as cmd_clean
from cobot.commands import delete as cmd_delete
from cobot.commands import docker_setup as cmd_docker_setup
from cobot.commands import doc_setup as cmd_doc_setup
from cobot.commands import local_setup as cmd_local_setup
from cobot.commands import rebuild as cmd_rebuild
from cobot.commands import robot_setup as cmd_robot_setup
from cobot.commands import run as cmd_run
from cobot.commands import setup as cmd_setup
from cobot.commands import update as cmd_update
# Command groups shown in --help output.
# Add new commands here when introducing other categories.
# Группы команд, отображаемые в --help.
# Добавляйте новые команды сюда при создании новых категорий.
_GROUPS = [
("Setup", [
("setup", "first-time setup: docs, build environment, robot config"),
("local-setup", "install ROS2 Jazzy natively and build the project with colcon"),
("docker-setup", "build or pull Docker images for KUKA iiwa7"),
("doc-setup", "deploy or stop the MkDocs documentation server"),
("robot-setup", "configure cobot-setting.yaml interactively"),
]),
("Run", [
("run", "launch the robot controller or Webots simulator (local or Docker)"),
]),
("Build", [
("rebuild", "rebuild ROS2 packages in src/ with colcon"),
("clean", "remove colcon build artifacts (build/ install/ log/)"),
]),
("Management", [
("update", "pull latest changes from the remote git branch and reinstall cobot"),
("delete", "remove the project, Docker images, containers, and optionally ROS2"),
]),
]
_DESCRIPTION = "Lightweight Cobot"
# Custom --help action that prints commands grouped by category instead of a flat list.
# Кастомный обработчик --help, который выводит команды по категориям, а не одним списком.
class _GroupedHelpAction(argparse.Action):
"""Custom argparse action that replaces the default --help output with a grouped
command listing organized by category (Setup, Run, Management).
Кастомный обработчик argparse, заменяющий стандартный вывод --help на сгруппированный
список команд по категориям (Setup, Run, Management).
"""
def __init__(self, option_strings, dest, default=None, required=False, help=None):
super().__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
default=default,
required=required,
help=help,
)
def __call__(self, parser, namespace, values, option_string=None):
print(f"usage: cobot [-h] <command> ...\n")
print(f"{_DESCRIPTION}\n")
for group_title, commands in _GROUPS:
print(f"{group_title} commands:")
for cmd, help_text in commands:
print(f" {cmd:<22} {help_text}")
print()
print("options:")
print(" -h, --help show this help message and exit")
parser.exit()
def main():
"""Entry point for the cobot CLI. Parses arguments and dispatches to the correct command.
Точка входа CLI cobot. Разбирает аргументы и вызывает нужную команду.
"""
parser = argparse.ArgumentParser(
prog="cobot",
description=_DESCRIPTION,
add_help=False,
)
parser.add_argument(
"-h", "--help",
action=_GroupedHelpAction,
default=argparse.SUPPRESS,
help="show this help message and exit",
)
subparsers = parser.add_subparsers(dest="command", metavar="<command>")
subparsers.required = True
_register_commands(subparsers)
args = parser.parse_args()
# Install one SIGINT handler + atexit cleanup so a single Ctrl-C tears down
# any running subprocesses (builds, ros2 launch, docker) cleanly.
# Устанавливаем один обработчик SIGINT + очистку atexit, чтобы один Ctrl-C
# аккуратно завершал все запущенные подпроцессы (сборку, ros2 launch, docker).
from cobot import process, privilege
process.install_signal_handlers()
try:
args.func(args)
finally:
privilege.stop_keepalive()
def _register_commands(subparsers):
"""Register all command subparsers. Each command module calls register() which adds its
own subparser and sets args.func to its run() function.
Регистрирует все подпарсеры команд. Каждый модуль вызывает register(), добавляет свой
подпарсер и устанавливает args.func на свою функцию run().
"""
# Each module registers its own subparser and sets args.func to its run() function.
# Каждый модуль регистрирует свой подпарсер и устанавливает args.func на свою функцию run().
cmd_setup.register(subparsers)
cmd_local_setup.register(subparsers)
cmd_docker_setup.register(subparsers)
cmd_doc_setup.register(subparsers)
cmd_robot_setup.register(subparsers)
cmd_run.register(subparsers)
cmd_rebuild.register(subparsers)
cmd_clean.register(subparsers)
cmd_update.register(subparsers)
cmd_delete.register(subparsers)
+68
View File
@@ -0,0 +1,68 @@
from __future__ import annotations
import argparse
import shutil
from pathlib import Path
from typing import List
from cobot import ui
from cobot.ui import header, done
_PROJECT_DIR = Path(__file__).parent.parent.parent
_DIR_OPTIONS = ["build/", "install/", "log/"]
_DIR_MAP = {
"build/": _PROJECT_DIR / "build",
"install/": _PROJECT_DIR / "install",
"log/": _PROJECT_DIR / "log",
}
def _clean(dirs: List[str]) -> None:
"""Delete the selected top-level directories, printing the outcome of each.
Удаляет выбранные директории верхнего уровня, печатая результат по каждой.
"""
header("Очистка артефактов сборки")
removed = False
for label in dirs:
path = _DIR_MAP[label]
if path.exists():
shutil.rmtree(path)
ui.info(f" [green]✓[/green] Удалено {label}")
removed = True
else:
ui.info(f" [dim]Нет:[/dim] {label}")
done(True, "Очищено" if removed else "Нечего удалять")
def register(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser(
"clean",
help="Remove colcon build artifacts (build/ install/ log/)",
)
p.add_argument(
"target",
nargs="?",
metavar="all",
default=None,
help="'all' to skip the prompt and delete all three directories at once",
)
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
"""Entry point for the clean command.
Точка входа для команды clean.
"""
if getattr(args, "target", None) == "all":
_clean(_DIR_OPTIONS)
return
dirs = ui.multiselect(
"Какие директории удалить?",
_DIR_OPTIONS,
note="Space — отметить · Enter — подтвердить",
)
if not dirs:
return
_clean(dirs)
+210
View File
@@ -0,0 +1,210 @@
from __future__ import annotations
import argparse
import shutil
import subprocess
from pathlib import Path
from typing import Callable
from cobot import ui
from cobot import privilege
from cobot.ui import done
from cobot.process import StepProgress
_PROJECT_DIR = Path(__file__).parent.parent.parent
Log = Callable[[str], None]
def _stop_docker_containers(log: Log) -> None:
"""Stop and force-remove all Docker containers whose name contains "lwc".
Останавливает и принудительно удаляет все Docker-контейнеры с "lwc" в имени.
"""
log("[cyan]▸[/cyan] Остановка Docker-контейнеров...")
result = subprocess.run(
["docker", "ps", "-a", "--filter", "name=lwc", "--format", "{{.Names}}"],
capture_output=True, text=True,
)
containers = [c for c in result.stdout.strip().splitlines() if c]
if not containers:
log("[dim]Контейнеры проекта не найдены.[/dim]")
return
for name in containers:
subprocess.run(["docker", "rm", "-f", name], capture_output=True)
log(f"[green]✓[/green] Удалён контейнер: {name}")
def _remove_docker_images(log: Log) -> None:
"""Force-remove all local Docker images whose name or tag contains "lwc".
Принудительно удаляет все локальные Docker-образы с "lwc" в имени или теге.
"""
log("[cyan]▸[/cyan] Удаление Docker-образов...")
result = subprocess.run(
["docker", "images", "--format", "{{.Repository}}:{{.Tag}}"],
capture_output=True, text=True,
)
project_images = [img for img in result.stdout.strip().splitlines() if "lwc" in img.lower()]
if not project_images:
log("[dim]Образы проекта не найдены.[/dim]")
return
for img in project_images:
subprocess.run(["docker", "rmi", "-f", img], capture_output=True)
log(f"[green]✓[/green] Удалён образ: {img}")
def _remove_webots_volume(log: Log) -> None:
"""Remove the lwc-webots-cache Docker volume if it exists.
Удаляет Docker volume lwc-webots-cache если он существует.
"""
result = subprocess.run(["docker", "volume", "inspect", "lwc-webots-cache"], capture_output=True)
if result.returncode != 0:
log("[dim]Volume кэша Webots не найден, пропускаем.[/dim]")
return
subprocess.run(["docker", "volume", "rm", "lwc-webots-cache"], capture_output=True)
log("[green]✓[/green] Удалён Docker volume: lwc-webots-cache")
def _remove_ros2(log: Log) -> None:
"""Remove all ros-jazzy-* packages, the ros2-apt-source, and the ROS2 source line.
Удаляет все пакеты ros-jazzy-*, ros2-apt-source и строку source ROS2 из конфигов.
"""
log("[cyan]▸[/cyan] Удаление пакетов ROS2 Jazzy...")
if not Path("/opt/ros/jazzy").exists():
log("[dim]ROS2 Jazzy не найден, пропускаем.[/dim]")
else:
subprocess.run(privilege.sudo(["apt", "remove", "-y", "~nros-jazzy-*"]), capture_output=True)
subprocess.run(privilege.sudo(["apt", "autoremove", "-y"]), capture_output=True)
log("[green]✓[/green] Пакеты ROS2 Jazzy удалены")
subprocess.run(privilege.sudo(["apt", "remove", "-y", "ros2-apt-source"]), capture_output=True)
subprocess.run(privilege.sudo(["apt", "update", "-qq"]), capture_output=True)
subprocess.run(privilege.sudo(["apt", "autoremove", "-y"]), capture_output=True)
log("[green]✓[/green] apt-репозиторий ROS2 удалён")
source_line = "source /opt/ros/jazzy/setup.bash"
for rc_name in [".bashrc", ".zshrc"]:
rc = Path.home() / rc_name
if not rc.exists():
continue
content = rc.read_text()
if source_line not in content:
continue
new_content = content.replace(f"\n# ROS2 Jazzy\n{source_line}\n", "\n")
new_content = new_content.replace(source_line, "")
rc.write_text(new_content)
log(f"[green]✓[/green] Очищен ~/{rc_name}")
def _remove_webots(log: Log) -> None:
"""Remove the webots package and clean WEBOTS_HOME from shell configs.
Удаляет пакет webots и очищает WEBOTS_HOME из конфигов оболочки.
"""
log("[cyan]▸[/cyan] Удаление Webots...")
if not shutil.which("webots"):
log("[dim]Webots не найден, пропускаем.[/dim]")
return
subprocess.run(privilege.sudo(["apt", "remove", "-y", "webots"]), capture_output=True)
subprocess.run(privilege.sudo(["apt", "autoremove", "-y"]), capture_output=True)
log("[green]✓[/green] Webots удалён")
for rc_name in [".bashrc", ".zshrc"]:
rc = Path.home() / rc_name
if not rc.exists():
continue
content = rc.read_text()
if "WEBOTS_HOME" not in content:
continue
new_content = content.replace("\n# Webots\nexport WEBOTS_HOME=/usr/local/webots\n", "\n")
new_content = new_content.replace("export WEBOTS_HOME=/usr/local/webots\n", "")
new_content = new_content.replace("# Webots\n", "")
if new_content != content:
rc.write_text(new_content)
log(f"[green]✓[/green] Очищен WEBOTS_HOME из ~/{rc_name}")
def _uninstall_cobot(log: Log) -> None:
"""Uninstall the lightweight-cobot package from the uv tool store.
Удаляет пакет lightweight-cobot из хранилища инструментов uv.
"""
log("[cyan]▸[/cyan] Удаление cobot CLI...")
result = subprocess.run(["uv", "tool", "uninstall", "lightweight-cobot"],
capture_output=True, text=True)
if result.returncode == 0:
log("[green]✓[/green] cobot удалён")
else:
log(f"[yellow]Предупреждение:[/yellow] {result.stderr.strip() or 'не удалось удалить cobot'}")
def _remove_project_dir(log: Log) -> None:
"""Recursively delete the entire project directory from disk.
Рекурсивно удаляет всю директорию проекта с диска.
"""
log("[cyan]▸[/cyan] Удаление директории проекта...")
shutil.rmtree(_PROJECT_DIR)
log(f"[green]✓[/green] Удалено {_PROJECT_DIR}")
def _delete(remove_ros: bool, remove_webots: bool) -> None:
"""Run all deletion steps in order, with progress split across the active steps.
Выполняет все шаги удаления по порядку, распределяя прогресс между активными шагами.
"""
ok, fail_msg = True, ""
with StepProgress("Удаление проекта") as p:
try:
p.set(0, "Остановка контейнеров...")
_stop_docker_containers(p.raw)
_remove_webots_volume(p.raw)
p.set(20, "Удаление Docker-образов...")
_remove_docker_images(p.raw)
pct = 40
if remove_ros:
p.set(pct, "Удаление ROS2 Jazzy...")
_remove_ros2(p.raw)
pct = 65
if remove_webots:
p.set(pct, "Удаление Webots...")
_remove_webots(p.raw)
pct = 75
p.set(pct, "Удаление cobot CLI...")
_uninstall_cobot(p.raw)
p.set(88, "Удаление директории проекта...")
_remove_project_dir(p.raw)
p.set(100, "Готово")
except Exception as exc:
ok, fail_msg = False, str(exc)
done(ok, "Проект полностью удалён" if ok else fail_msg)
def register(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser(
"delete",
help="Remove the project, Docker images, containers, and optionally ROS2",
)
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
ui.header("Удаление проекта", "контейнеры, образы, опционально ROS2/Webots")
if not ui.confirm(
"Это безвозвратно удалит проект, Docker-образы и контейнеры. Продолжить?",
default=False,
):
return
remove_ros = ui.confirm("Также удалить ROS2 Jazzy из системы?", default=False)
remove_webots = False
if shutil.which("webots"):
remove_webots = ui.confirm("Также удалить Webots из системы?", default=False)
# apt removals need root — acquire sudo once before starting.
# Удаление через apt требует root — получаем sudo один раз перед началом.
if (remove_ros or remove_webots) and not privilege.ensure_sudo():
return
_delete(remove_ros, remove_webots)
+248
View File
@@ -0,0 +1,248 @@
from __future__ import annotations
import argparse
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
from cobot import process, ui
from cobot.ui import done
from cobot.process import StepProgress
_PROJECT_DIR = Path(__file__).parent.parent.parent
# The documentation source lives inside the project; it is mounted into the container
# so MkDocs picks up live edits without rebuilding the image.
# Исходники документации находятся внутри проекта; директория монтируется в контейнер,
# чтобы MkDocs подхватывал изменения вживую без пересборки образа.
_DOC_DIR = _PROJECT_DIR / "doc" / "lwc-doc"
_IMAGE_NAME = "lwc-docs"
_CONTAINER_NAME = "lwc-docs"
_DEFAULT_PORT = "8000"
def _docker(*args: str, capture: bool = False) -> subprocess.CompletedProcess:
"""Run a docker subcommand.
Запускает подкоманду docker.
"""
return subprocess.run(["docker", *args], capture_output=capture, text=True)
def _is_running() -> bool:
"""Return True if the lwc-docs container is currently running.
Возвращает True если контейнер lwc-docs запущен.
"""
r = _docker("ps", "--filter", f"name={_CONTAINER_NAME}", "--format", "{{.Names}}", capture=True)
return _CONTAINER_NAME in r.stdout
def _image_exists() -> bool:
"""Return True if the lwc-docs Docker image exists locally.
Возвращает True если Docker-образ lwc-docs существует локально.
"""
return bool(_docker("images", "-q", _IMAGE_NAME, capture=True).stdout.strip())
def _build_docs_image(p: StepProgress, lo: float, hi: float) -> bool:
"""Build the lwc-docs image, mapping "Step X/Y" to the lo..hi progress slice.
Собирает образ lwc-docs, отображая "Step X/Y" на участок lo..hi прогресса.
"""
p.raw("[cyan]▸[/cyan] Сборка образа документации (один раз)...")
env = {**os.environ, "DOCKER_BUILDKIT": "0"}
def on_line(s: str) -> None:
if s:
p.log(s)
m = re.match(r"Step (\d+)/(\d+) :", s)
if m:
step, total = int(m.group(1)), int(m.group(2))
p.set(lo + step / total * (hi - lo), f"шаг {step}/{total}")
rc = process.stream(["docker", "build", "-t", _IMAGE_NAME, str(_DOC_DIR)],
env=env, on_line=on_line)
if rc != 0:
p.raw("[red]Сборка образа не удалась.[/red]")
return False
p.raw("[green]✓[/green] Образ документации готов")
return True
def _start_container(p: StepProgress, port: str) -> bool:
"""Start the MkDocs container on the given port. Returns True on success.
Запускает контейнер MkDocs на заданном порту. Возвращает True при успехе.
"""
p.set(90, "Запуск сервера MkDocs...")
p.raw("[cyan]▸[/cyan] Запуск сервера MkDocs...")
result = _docker(
"run", "-d", "--name", _CONTAINER_NAME, "--rm",
"-p", f"{port}:8000",
"-v", f"{_DOC_DIR}:/docs",
_IMAGE_NAME, "serve", "--dev-addr=0.0.0.0:8000",
"--watch", "/docs", "--livereload",
capture=True,
)
if result.returncode != 0:
p.raw(f"[red]Не удалось запустить контейнер.[/red]\n{result.stderr}")
return False
return True
def _task_up(port: str) -> None:
"""Build the image if missing, then start the docs container.
Собирает образ если отсутствует, затем запускает контейнер документации.
"""
if _is_running():
ui.info(f"[green]Документация уже запущена:[/green] http://localhost:{port}")
ui.note("Остановить: cobot doc-setup down")
return
if not _DOC_DIR.exists():
ui.error(f"Директория документации не найдена: {_DOC_DIR}")
return
ok, fail_msg = True, ""
with StepProgress("Сервер документации") as p:
if not _image_exists():
p.set(0, "Сборка образа документации...")
if not _build_docs_image(p, 0, 85):
ok, fail_msg = False, "Сборка образа не удалась"
else:
p.log("Образ документации уже собран, пропускаем.")
if ok and not _start_container(p, port):
ok, fail_msg = False, "Не удалось запустить контейнер"
if ok:
p.set(100, "Сервер запущен")
if ok:
done(True, f"Документация доступна: http://localhost:{port}")
ui.note("Правьте файлы в doc/lwc-doc/docs/ — перезагрузка автоматическая.")
ui.note("Остановить: cobot doc-setup down")
else:
done(False, fail_msg)
def _task_build() -> None:
"""Run a one-shot mkdocs build with PDF generation enabled.
Запускает однократную сборку mkdocs с генерацией PDF.
"""
if not _DOC_DIR.exists():
ui.error(f"Директория документации не найдена: {_DOC_DIR}")
return
ok = True
with StepProgress("Сборка документации") as p:
if not _image_exists():
p.set(0, "Сборка образа документации...")
if not _build_docs_image(p, 0, 60):
ok = False
if ok:
p.set(65, "Запуск mkdocs build...")
p.raw("[cyan]▸[/cyan] Генерация сайта и PDF...")
rc = process.stream([
"docker", "run", "--rm",
"-v", f"{_DOC_DIR}:/docs",
"-e", "ENABLE_PDF_EXPORT=1",
_IMAGE_NAME, "build",
], on_line=lambda s: p.log(s) if s else None)
if rc != 0:
p.raw("[red]Сборка не удалась.[/red]")
ok = False
else:
p.set(100, "Готово")
if ok:
done(True, f"Сайт собран: {_DOC_DIR / 'site'} PDF: {_DOC_DIR / 'site' / 'pdf' / 'document.pdf'}")
else:
done(False, "Сборка завершилась с ошибкой")
def _task_down() -> None:
"""Stop the lwc-docs container if it is running.
Останавливает контейнер lwc-docs если он запущен.
"""
if not _is_running():
ui.info("[yellow]Контейнер документации не запущен.[/yellow]")
return
with StepProgress("Сервер документации") as p:
p.set(30, "Остановка контейнера...")
p.raw("[cyan]▸[/cyan] Остановка сервера документации...")
_docker("stop", _CONTAINER_NAME)
p.set(100, "Готово")
done(True, "Контейнер остановлен")
def _task_rebuild(port: str) -> None:
"""Stop the container, remove the old image, rebuild it, and start a fresh container.
Останавливает контейнер, удаляет старый образ, пересобирает и запускает новый контейнер.
"""
ok, fail_msg = True, ""
with StepProgress("Сервер документации — пересборка") as p:
if _is_running():
p.set(5, "Остановка контейнера...")
_docker("stop", _CONTAINER_NAME)
p.raw("[green]✓[/green] Остановлен.")
if _image_exists():
p.set(15, "Удаление старого образа...")
_docker("rmi", "-f", _IMAGE_NAME)
p.raw("[green]✓[/green] Образ удалён.")
p.set(20, "Сборка образа документации...")
if not _build_docs_image(p, 20, 88):
ok, fail_msg = False, "Сборка образа не удалась"
if ok and not _start_container(p, port):
ok, fail_msg = False, "Не удалось запустить контейнер"
if ok:
p.set(100, "Сервер запущен")
if ok:
done(True, f"Документация доступна: http://localhost:{port}")
ui.note("Остановить: cobot doc-setup down")
else:
done(False, fail_msg)
def _normalize_port(value: str) -> str:
"""Return a numeric port string, falling back to the default when invalid.
Возвращает числовой порт, откатываясь на значение по умолчанию при ошибке.
"""
value = (value or "").strip()
return value if value.isdigit() else _DEFAULT_PORT
def register(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser("doc-setup", help="Deploy or stop the documentation server")
p.add_argument(
"action",
nargs="?",
choices=["up", "down", "rebuild", "build"],
default="up",
help="up — start (default), down — stop, rebuild — rebuild image and restart, build — generate static site + PDF",
)
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
if not shutil.which("docker"):
ui.error("Docker не установлен или отсутствует в PATH.")
sys.exit(1)
action = getattr(args, "action", "up")
if action == "down":
_task_down()
return
if action == "build":
_task_build()
return
port_v = ui.text("Порт для сервера документации:", _DEFAULT_PORT)
if port_v is None:
return
port = _normalize_port(port_v)
if action == "rebuild":
_task_rebuild(port)
else:
_task_up(port)
+228
View File
@@ -0,0 +1,228 @@
from __future__ import annotations
import argparse
import os
import re
import shutil
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional
from cobot import process, ui
from cobot.ui import done
from cobot.process import StepProgress
_PROJECT_DIR = Path(__file__).parent.parent.parent
_DOCKER_DIR = _PROJECT_DIR / "docker"
# Default Docker Hub repository and local image prefix used when building locally.
# Репозиторий Docker Hub по умолчанию и локальный префикс образов при локальной сборке.
_DEFAULT_HUB_REPO = "evilfisru/lwc"
_DEFAULT_PREFIX = "lwc-local"
# The images must be built in this order because each one is based on the previous.
# Образы должны собираться в этом порядке, потому что каждый основан на предыдущем.
_CONTROLLER_CHAIN = ["ros-core", "ros-base", "ros-iiwa7"]
_WEBOTS_CHAIN = ["ros-core", "ros-base", "ros-iiwa7-webots"]
# Maps each image to the image it is built FROM. None means it starts from base Ubuntu.
# Сопоставляет каждый образ с тем, на основе которого он собирается. None - базовый Ubuntu.
_IMAGE_PARENT: dict[str, str | None] = {
"ros-core": None,
"ros-base": "ros-core",
"ros-iiwa7": "ros-base",
"ros-iiwa7-webots": "ros-base",
}
# These images need the full project source as Docker build context.
# Эти образы требуют полный исходный код проекта как контекст сборки.
_NEEDS_PROJECT_CTX = {"ros-iiwa7", "ros-iiwa7-webots"}
@dataclass
class _Config:
ros_version: str
variant: str
source: str
build_type: str
image_prefix: str
hub_repo: str
def _build_image(name: str, tag: str, dockerfile: Path, ctx: Path, p: StepProgress,
lo: float, hi: float, parent_tag: Optional[str], build_type: str) -> bool:
"""Build a single Docker image, streaming output and mapping "Step X/Y" to the
lo..hi slice of the progress bar. Returns True on success.
Собирает один Docker-образ, транслируя вывод и отображая "Step X/Y" на участок
lo..hi прогресс-бара. Возвращает True при успехе.
"""
p.raw(f"[cyan]▸[/cyan] Сборка [bold]{name}[/bold]...")
env = {**os.environ, "DOCKER_BUILDKIT": "0"}
cmd = [
"docker", "build", "-t", tag, "-f", str(dockerfile),
"--build-arg", f"BUILD_TYPE={build_type}",
]
if parent_tag:
cmd += ["--build-arg", f"IMAGE={parent_tag}"]
cmd.append(str(ctx))
def on_line(s: str) -> None:
if s:
p.log(s)
m = re.match(r"Step (\d+)/(\d+) :", s)
if m:
step, total = int(m.group(1)), int(m.group(2))
p.set(lo + step / total * (hi - lo), f"{name}: шаг {step}/{total}")
rc = process.stream(cmd, env=env, on_line=on_line)
if rc in (-9, -15):
return False
if rc == 0:
p.raw(f"[green]✓[/green] {name}")
return True
p.raw(f"[red]Сборка не удалась:[/red] {tag}")
return False
def _pull_image(name: str, tag: str, p: StepProgress, lo: float, hi: float) -> bool:
"""Pull a Docker image, tracking progress by counting completed layers.
Скачивает Docker-образ, отслеживая прогресс по числу завершённых слоёв.
"""
p.raw(f"[cyan]▸[/cyan] Скачивание [bold]{name}[/bold] ({tag})...")
layers_total = 0
layers_done = 0
def on_line(s: str) -> None:
nonlocal layers_total, layers_done
if s:
p.log(s)
if "Pulling fs layer" in s or "Waiting" in s:
layers_total += 1
elif "Pull complete" in s or "Already exists" in s:
layers_done += 1
if layers_total > 0:
p.set(lo + layers_done / layers_total * (hi - lo), f"{name}: слои")
rc = process.stream(["docker", "pull", tag], on_line=on_line)
if rc in (-9, -15):
return False
if rc == 0:
p.raw(f"[green]✓[/green] {name}")
return True
p.raw(f"[red]Скачивание не удалось:[/red] {tag}")
return False
def _execute(cfg: _Config) -> None:
"""Build or pull all images in the chain selected by the user's choices.
Собирает или скачивает все образы из цепочки, выбранной пользователем.
"""
chain = _WEBOTS_CHAIN if cfg.variant == "webots" else _CONTROLLER_CHAIN
n = len(chain)
ok = True
fail_msg = ""
if cfg.source == "build":
title = f"Сборка {n} образ(ов) — ROS {cfg.ros_version}{cfg.build_type}"
with StepProgress(title) as p:
for i, name in enumerate(chain):
lo, hi = i / n * 100, (i + 1) / n * 100
p.set(lo, f"Образ {i + 1}/{n}: {name}")
tag = f"{cfg.image_prefix}:{name}-{cfg.ros_version}"
dockerfile = _DOCKER_DIR / cfg.ros_version / name / "Dockerfile"
if not dockerfile.exists():
ok, fail_msg = False, f"Dockerfile не найден: {dockerfile}"
break
ctx = _PROJECT_DIR if name in _NEEDS_PROJECT_CTX else dockerfile.parent
parent_name = _IMAGE_PARENT.get(name)
parent_tag = (f"{cfg.image_prefix}:{parent_name}-{cfg.ros_version}"
if parent_name else None)
if not _build_image(name, tag, dockerfile, ctx, p, lo, hi,
parent_tag, cfg.build_type):
ok, fail_msg = False, f"Сборка образа {name} не удалась"
break
if ok:
p.set(100, "Готово")
done(ok, f"Образы готовы: {cfg.image_prefix}:<name>-{cfg.ros_version}"
if ok else fail_msg)
else:
short = "webots" if cfg.variant == "webots" else "iiwa"
suffix = "-dev" if cfg.build_type == "dev" else ""
full_ref = f"{cfg.hub_repo}:{short}-{cfg.ros_version}{suffix}"
with StepProgress(f"Скачивание из {cfg.hub_repo} — ROS {cfg.ros_version}") as p:
if _pull_image(short, full_ref, p, 0, 100):
p.set(100, "Готово")
else:
ok, fail_msg = False, f"Скачивание {full_ref} не удалось"
done(ok, f"Образ готов: {full_ref}" if ok else fail_msg)
def _discover_versions() -> List[str]:
"""Return ROS versions found in docker/ (jazzy first). Falls back to ["jazzy"].
Возвращает версии ROS из docker/ (jazzy первым). По умолчанию ["jazzy"].
"""
if not _DOCKER_DIR.exists():
return ["jazzy"]
dirs = sorted(d.name for d in _DOCKER_DIR.iterdir() if d.is_dir())
if "jazzy" in dirs:
dirs = ["jazzy"] + [d for d in dirs if d != "jazzy"]
return dirs or ["jazzy"]
def register(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser("docker-setup", help="Build or pull Docker images for KUKA iiwa7")
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
if not shutil.which("docker"):
ui.error("Docker не установлен или отсутствует в PATH.")
sys.exit(1)
ui.header("Настройка Docker", "сборка или скачивание образов KUKA iiwa7")
versions = _discover_versions()
default = "jazzy" if "jazzy" in versions else versions[0]
ros_version = ui.select("Версия ROS:", versions, default)
if ros_version is None:
return
src = ui.select("Источник:", ["Скачать с Docker Hub", "Собрать локально"],
"Скачать с Docker Hub")
if src is None:
return
source = "build" if src == "Собрать локально" else "pull"
variant_v = ui.select(
"Что установить:",
["Только контроллер — ros-core, ros-base, ros-iiwa7",
"Контроллер с Webots — ros-core, ros-base, ros-iiwa7-webots"],
"Только контроллер — ros-core, ros-base, ros-iiwa7",
)
if variant_v is None:
return
variant = "webots" if variant_v.startswith("Контроллер с Webots") else "controller"
build_type = ui.select("Тип сборки:", ["release", "dev"], "release")
if build_type is None:
return
image_prefix, hub_repo = _DEFAULT_PREFIX, _DEFAULT_HUB_REPO
if source == "pull":
v = ui.text("Репозиторий Docker Hub:", _DEFAULT_HUB_REPO)
if v is None:
return
hub_repo = v
else:
v = ui.text("Префикс образов:", _DEFAULT_PREFIX)
if v is None:
return
image_prefix = v
cfg = _Config(
ros_version=ros_version, variant=variant, source=source,
build_type=build_type, image_prefix=image_prefix, hub_repo=hub_repo,
)
_execute(cfg)
+387
View File
@@ -0,0 +1,387 @@
from __future__ import annotations
import argparse
import os
import shutil
import subprocess
from pathlib import Path
from cobot import process, ui
from cobot import privilege
from cobot.ui import done, header
from cobot.commands.docker_setup import run as _docker_setup
# Root directory of the project, used as the working directory for colcon builds.
# Корневая директория проекта, используется как рабочая директория для сборки colcon.
_PROJECT_DIR = Path(__file__).parent.parent.parent
# ROS2 distribution name targeted by this installer.
# Название дистрибутива ROS2, который устанавливает этот скрипт.
_DISTRO = "jazzy"
# Webots simulator version targeted by this installer.
# Версия симулятора Webots, устанавливаемая этим скриптом.
_WEBOTS_VERSION = "2025a"
# Directory that contains the shell scripts used by this command.
# Директория с shell-скриптами, используемыми этой командой.
_SCRIPTS_DIR = _PROJECT_DIR / "scripts"
# apt packages that must exist before rosdep can install the pip-based keys
# (python3-pip / dev / venv). Their absence is what produced the "pip is not
# installed" failure in the screenshots.
# apt-пакеты, необходимые до того как rosdep сможет установить pip-зависимости.
# Именно их отсутствие давало ошибку "pip is not installed" на скриншотах.
_APT_PREREQS = ["python3-pip", "python3-dev", "python3-venv"]
# OS and tool detection helpers
# Вспомогательные функции для определения ОС и наличия инструментов
def _detect_ubuntu_2404() -> bool:
"""Return True if the current OS is Ubuntu 24.04 (Noble).
Возвращает True, если текущая ОС - Ubuntu 24.04 (Noble).
"""
path = Path("/etc/os-release")
if not path.exists():
return False
info: dict[str, str] = {}
for line in path.read_text().splitlines():
if "=" in line:
k, _, v = line.partition("=")
info[k.strip()] = v.strip().strip('"')
return info.get("ID") == "ubuntu" and info.get("VERSION_ID") == "24.04"
def _detect_ros2() -> bool:
"""Return True if ROS2 Jazzy is already installed under /opt/ros/jazzy.
Возвращает True, если ROS2 Jazzy уже установлен в /opt/ros/jazzy.
"""
return Path(f"/opt/ros/{_DISTRO}").is_dir()
def webots_installed() -> bool:
"""Return True if the Webots binary is available on PATH.
Возвращает True, если бинарный файл Webots доступен в PATH.
"""
return shutil.which("webots") is not None
def _ros2_env() -> dict:
"""Build an environment dict with ROS2 variables sourced from setup.bash.
Sources /opt/ros/jazzy/setup.bash in a subprocess, captures all exported
variables and merges them into a copy of os.environ. Falls back to plain
os.environ if the setup file does not exist yet.
Формирует словарь окружения с переменными ROS2, полученными из setup.bash.
Возвращает чистый os.environ если файл setup.bash ещё не существует.
"""
setup = Path(f"/opt/ros/{_DISTRO}/setup.bash")
if not setup.exists():
return os.environ.copy()
result = subprocess.run(
["bash", "-c", f"source {setup} && env"],
capture_output=True, text=True,
)
env = os.environ.copy()
for line in result.stdout.splitlines():
if "=" in line:
k, _, v = line.partition("=")
env[k] = v
# CMake's find_package(Python3) ignores PATH and uses its own search logic,
# so we must pin it explicitly to the system Python where catkin_pkg is installed.
# CMake игнорирует PATH при поиске Python через find_package(Python3),
# поэтому явно указываем системный Python, где установлен catkin_pkg.
env["Python3_EXECUTABLE"] = "/usr/bin/python3"
env["PYTHON_EXECUTABLE"] = "/usr/bin/python3"
# Keep PATH clean so other tools (rosdep, colcon itself) use system Python.
# Чистим PATH чтобы другие инструменты тоже использовали системный Python.
_SYSTEM_PATHS = ["/usr/bin", "/usr/local/bin"]
existing = env.get("PATH", "").split(":")
env["PATH"] = ":".join(
_SYSTEM_PATHS + [p for p in existing if p not in _SYSTEM_PATHS]
)
return env
# Bash-script runner that understands PROGRESS:<pct>:<label> markers
# Запуск bash-скриптов с поддержкой маркеров PROGRESS:<pct>:<метка>
def _run_script(script: Path, title: str) -> int:
"""Run a shell script, streaming its output to a live log and advancing the
progress bar from PROGRESS:<pct>:<label> markers (which are not echoed raw).
Returns the script exit code.
Запускает shell-скрипт, транслируя вывод в живой лог и продвигая прогресс-бар по
маркерам PROGRESS:<pct>:<метка> (сами маркеры не печатаются). Возвращает код возврата.
"""
if not script.exists():
header(title)
ui.error(f"Скрипт не найден: {script}")
done(False, "Скрипт отсутствует")
return 1
with process.StepProgress(title) as p:
def on_line(s: str) -> None:
if s.startswith("PROGRESS:"):
parts = s.split(":", 2)
try:
p.set(float(parts[1]), parts[2] if len(parts) > 2 else "")
except (ValueError, IndexError):
pass
return
if s:
p.log(s)
rc = process.stream(["bash", str(script)], cwd=str(_PROJECT_DIR), on_line=on_line)
ok = rc in (0, -9, -15)
done(ok, "Готово" if ok else f"Скрипт завершился с кодом {rc}")
return rc
def install_ros2(pkg: str) -> bool:
"""Run the ROS2 Jazzy install shell script for the chosen variant (desktop / ros-base).
Запускает shell-скрипт установки ROS2 Jazzy для выбранного варианта (desktop / ros-base).
"""
script = _SCRIPTS_DIR / f"setup_ros2_{pkg.replace('-', '_')}.sh"
rc = _run_script(script, f"Установка ROS2 {_DISTRO} ({pkg})")
return rc in (0, -9, -15)
def install_webots() -> bool:
"""Run the Webots installation shell script.
Запускает shell-скрипт установки Webots.
"""
script = _SCRIPTS_DIR / "install_webots.sh"
rc = _run_script(script, f"Установка Webots {_WEBOTS_VERSION}")
return rc in (0, -9, -15)
# Build prerequisites
# Предусловия сборки
def _missing_apt_prereqs() -> list[str]:
"""Return the subset of _APT_PREREQS that is not currently installed via dpkg.
Возвращает подмножество _APT_PREREQS, которое сейчас не установлено через dpkg.
"""
missing = []
for pkg in _APT_PREREQS:
r = subprocess.run(
["dpkg-query", "-W", "-f=${Status}", pkg],
capture_output=True, text=True,
)
if "install ok installed" not in r.stdout:
missing.append(pkg)
return missing
def _ensure_root_pip_break(p: process.StepProgress) -> None:
"""Let root's pip override PEP 668, scoped to /root/.config/pip/pip.conf.
rosdep installs the pip-based rosdep keys (fastapi, uvicorn, multipart, fastmcp)
as root via sudo; on Ubuntu 24.04 that is blocked by PEP 668 unless break-system-
packages is allowed. Writing root's pip config is idempotent, reversible (just
delete the file), and does not touch the user's own pip configuration.
Разрешает pip от root обходить PEP 668, ограничиваясь /root/.config/pip/pip.conf.
rosdep ставит pip-зависимости от root через sudo; на Ubuntu 24.04 это блокируется
PEP 668, пока не разрешён break-system-packages. Запись конфига pip от root
идемпотентна, обратима (удалить файл) и не трогает пользовательский pip.
"""
snippet = (
"mkdir -p /root/.config/pip && "
"( grep -qs 'break-system-packages' /root/.config/pip/pip.conf || "
"printf '[global]\\nbreak-system-packages = true\\n' "
">> /root/.config/pip/pip.conf )"
)
process.stream(privilege.sudo(["bash", "-c", snippet]), on_line=p.log)
# rosdep calls `pip install -U <pkg>` which upgrades every transitive dependency,
# including packages installed by apt that have no pip RECORD file, causing an
# uninstall failure. Pre-installing with --ignore-installed creates pip RECORD
# files for all transitive deps so the subsequent rosdep upgrade succeeds.
process.stream(
privilege.sudo(["pip3", "install", "--break-system-packages",
"--ignore-installed", "fastmcp"]),
on_line=p.log,
)
def _register_rosdep_source(p: process.StepProgress, env: dict) -> None:
"""Register the project's local rosdep.yaml as a rosdep source and run rosdep update.
Only re-writes / updates when the source file is missing or out of date.
Регистрирует локальный rosdep.yaml проекта как источник rosdep и запускает rosdep update.
Перезаписывает/обновляет только если файл-источник отсутствует или устарел.
"""
rosdep_yaml = _PROJECT_DIR / "rosdep.yaml"
if not rosdep_yaml.exists():
return
sources_list = Path("/etc/ros/rosdep/sources.list.d/50-kuka-local.list")
entry = f"yaml file://{rosdep_yaml}\n"
try:
current = sources_list.read_text() if sources_list.exists() else ""
except Exception:
current = ""
if current == entry:
return
snippet = (
"mkdir -p /etc/ros/rosdep/sources.list.d && "
f"printf '%s\\n' 'yaml file://{rosdep_yaml}' > {sources_list}"
)
process.stream(privilege.sudo(["bash", "-c", snippet]), on_line=p.log)
p.log(f"Зарегистрирован локальный источник rosdep: {rosdep_yaml}")
process.stream(["rosdep", "update"], env=env, cwd=str(_PROJECT_DIR), on_line=p.log)
def _count_colcon_packages(env: dict) -> int:
"""Count colcon packages under src/ so the build bar can show X / total.
Считает пакеты colcon в src/, чтобы бар сборки показывал X / всего.
"""
r = subprocess.run(
["colcon", "list", "--base-paths", "src"],
capture_output=True, text=True, cwd=str(_PROJECT_DIR), env=env,
)
return max(len([l for l in r.stdout.splitlines() if l.strip()]), 1)
def build_workspace() -> bool:
"""Build the workspace: apt prerequisites -> rosdep install -> colcon build.
Step 1 guarantees python3-pip/dev/venv and allows root pip under PEP 668 so the
pip-based rosdep keys install cleanly. Step 2 runs rosdep install with
PIP_BREAK_SYSTEM_PACKAGES=1. Step 3 compiles every package with live progress.
Собирает workspace: apt-предусловия -> rosdep install -> colcon build.
Шаг 1 гарантирует python3-pip/dev/venv и разрешает pip от root под PEP 668. Шаг 2
запускает rosdep install с PIP_BREAK_SYSTEM_PACKAGES=1. Шаг 3 компилирует все пакеты.
"""
env = _ros2_env()
env["PIP_BREAK_SYSTEM_PACKAGES"] = "1"
if not shutil.which("colcon") and not Path(f"/opt/ros/{_DISTRO}/bin/colcon").exists():
header("Сборка проекта")
ui.error("colcon не найден.")
ui.note(f"Сначала выполните: source /opt/ros/{_DISTRO}/setup.bash")
done(False, "colcon недоступен")
return False
ok = True
fail_msg = ""
with process.StepProgress("Сборка проекта") as p:
# --- Шаг 1/3: системные зависимости pip (apt) ---
p.raw("[bold]Шаг 1/3 — системные зависимости pip (apt)[/bold]")
p.set(0, "Проверка python3-pip / dev / venv...")
missing = _missing_apt_prereqs()
if missing:
p.log(f"Установка: {', '.join(missing)}")
process.stream(privilege.sudo(["apt-get", "update", "-q"]), env=env, on_line=p.log)
rc = process.stream(
privilege.sudo(["apt-get", "install", "-y", *missing]),
env=env, on_line=p.log,
)
if rc not in (0, -9, -15):
ok, fail_msg = False, "Не удалось установить apt-зависимости"
else:
p.log("python3-pip / dev / venv уже установлены")
if ok:
_ensure_root_pip_break(p)
# --- Шаг 2/3: rosdep install ---
if ok:
p.set(10, "rosdep install...")
p.raw("\n[bold]Шаг 2/3 — rosdep install[/bold]")
_register_rosdep_source(p, env)
rc = process.stream(
["rosdep", "install", "--from-paths", "src", "-i", "-r", "-y"],
env=env, cwd=str(_PROJECT_DIR), on_line=p.log,
)
if rc not in (0, -9, -15):
ok, fail_msg = False, "rosdep install завершился с ошибкой"
# --- Шаг 3/3: colcon build ---
if ok:
total = _count_colcon_packages(env)
p.set(30, f"0 / {total} пакетов")
p.raw(f"\n[bold]Шаг 3/3 — colcon build ({total} пакетов)[/bold]")
built = 0
def _on_build(s: str) -> None:
nonlocal built
if s:
p.log(s)
if "Finished <<<" in s or "Failed <<<" in s:
built += 1
p.set(30 + built / total * 70, f"{built} / {total} пакетов")
rc = process.stream(
["colcon", "build", "--base-paths", "src"],
env=env, cwd=str(_PROJECT_DIR), on_line=_on_build,
)
if rc not in (0, -9, -15):
ok, fail_msg = False, "colcon build завершился с ошибкой"
else:
p.set(100, "Готово")
done(ok, "Сборка завершена" if ok else fail_msg)
if ok:
ui.note("Активируйте окружение: source install/setup.bash")
return ok
# Interactive flow
# Интерактивный сценарий
def run(args: argparse.Namespace) -> None:
"""Guide the user through installing ROS2 Jazzy and building the workspace.
Проводит пользователя через установку ROS2 Jazzy и сборку workspace.
"""
header("Локальная установка", "ROS2 Jazzy + сборка проекта")
choice = ui.select("Установить ROS2 Jazzy?", ["Да, установить", "Нет, выход"],
"Да, установить")
if not choice or choice.startswith("Нет"):
return
# Acquire sudo once, up front, with the masked prompt + keep-alive thread.
# Получаем sudo один раз, заранее, с маскированным вводом + keep-alive потоком.
if not privilege.ensure_sudo():
return
if not _detect_ubuntu_2404():
v = ui.select(
"Ubuntu 24.04 не обнаружена. Настроить окружение через Docker?",
["Да, запустить docker-setup", "Нет, выход"],
"Да, запустить docker-setup",
)
if v and v.startswith("Да"):
_docker_setup(args)
return
variant = ui.select(
"Какой вариант ROS2 Jazzy установить?",
["Desktop (полный, с GUI-инструментами)", "Base (минимальный, без GUI)"],
"Desktop (полный, с GUI-инструментами)",
)
if not variant:
return
pkg = "desktop" if variant.startswith("Desktop") else "ros-base"
if not install_ros2(pkg):
return
if ui.confirm("Собрать workspace сейчас? (rosdep install + colcon build)", default=True):
build_workspace()
if not webots_installed():
if ui.confirm(f"Установить симулятор Webots {_WEBOTS_VERSION}?", default=False):
install_webots()
def register(subparsers: argparse._SubParsersAction) -> None:
"""Register the local-setup subcommand with the CLI argument parser.
Регистрирует подкоманду local-setup в парсере аргументов командной строки.
"""
p = subparsers.add_parser(
"local-setup",
help="Install ROS2 Jazzy natively and build the project with colcon",
)
p.set_defaults(func=run)
+117
View File
@@ -0,0 +1,117 @@
from __future__ import annotations
import argparse
import subprocess
from pathlib import Path
from typing import List, Optional
from cobot import ui, process
from cobot.commands.local_setup import _ros2_env
_PROJECT_DIR = Path(__file__).parent.parent.parent
def _count_packages(packages: List[str], env: dict) -> int:
"""Count how many colcon packages will be built so we can show X / total progress.
Считает количество пакетов colcon для отображения прогресса X / всего.
"""
list_cmd = ["colcon", "list", "--base-paths", "src"]
if packages:
list_cmd += ["--packages-select"] + packages
result = subprocess.run(list_cmd, capture_output=True, text=True,
cwd=_PROJECT_DIR, env=env)
return max(len([l for l in result.stdout.splitlines() if l.strip()]), 1)
def _rebuild(packages: List[str], symlink: bool) -> None:
"""Run colcon build for the selected packages (or all), streaming live output
with a per-package progress bar.
Запускает colcon build для выбранных пакетов (или всех), транслируя живой вывод
с прогресс-баром по пакетам.
"""
env = _ros2_env()
total = _count_packages(packages, env)
pkg_label = " ".join(packages) if packages else "все пакеты"
symlink_label = " --symlink-install" if symlink else ""
cmd = ["colcon", "build", "--base-paths", "src"]
if symlink:
cmd.append("--symlink-install")
if packages:
cmd += ["--packages-select"] + packages
built = 0
def _parse(line: str):
nonlocal built
if "Finished <<<" in line or "Failed <<<" in line:
built += 1
return (built / total * 100, f"{built} / {total} пакетов")
return None
rc = process.run_step(
f"colcon build{symlink_label}{pkg_label}",
cmd,
env=env,
cwd=str(_PROJECT_DIR),
total=100.0,
parse_progress=_parse,
success_msg="Сборка завершена",
fail_msg="Сборка завершилась с ошибкой",
)
if rc in (0, -9, -15):
ui.note("Активируйте окружение: source install/setup.bash")
def register(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser(
"rebuild",
help="Rebuild ROS2 packages in src/ with colcon",
)
p.add_argument(
"packages",
nargs="*",
metavar="PACKAGE",
help="Packages to rebuild (omit to be asked, or leave empty for all)",
)
p.set_defaults(symlink=None)
p.add_argument(
"--symlink-install",
dest="symlink",
action="store_true",
help="Pass --symlink-install to colcon build",
)
p.add_argument(
"--no-symlink-install",
dest="symlink",
action="store_false",
help="Do not pass --symlink-install to colcon build",
)
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
"""Entry point for the rebuild command.
Точка входа для команды rebuild.
"""
packages: Optional[List[str]] = args.packages if args.packages else None
if packages is None:
value = ui.text(
"Какие пакеты пересобрать? (через пробел, пусто — все)",
"",
note="Пример: iiwa_controller iiwa_bringup",
)
if value is None:
return
packages = value.split() if value.strip() else []
symlink = args.symlink
if symlink is None:
choice = ui.select("Использовать --symlink-install?", ["Да", "Нет"], "Да")
if choice is None:
return
symlink = choice == "Да"
_rebuild(packages, symlink)
+334
View File
@@ -0,0 +1,334 @@
from __future__ import annotations
import argparse
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, List, Optional
from ruamel.yaml import YAML
from cobot import ui
_PROJECT_DIR = Path(__file__).parent.parent.parent
_CONFIG_PATH = _PROJECT_DIR / "cobot-setting.yaml"
_TOOLS_YAML = _PROJECT_DIR / "src" / "iiwa_config" / "config" / "tools.yaml"
_TOOL_ACTIVE_XACRO = (
_PROJECT_DIR / "src" / "iiwa_description" / "urdf" / "tools" / "tool_active.xacro"
)
_SRDF_PATH = _PROJECT_DIR / "src" / "iiwa_config" / "config" / "moveit" / "iiwa7.srdf"
# Use ruamel.yaml instead of PyYAML so comments and formatting in the config are preserved.
# Используем ruamel.yaml вместо PyYAML, чтобы комментарии и форматирование в конфиге сохранялись.
_yaml = YAML()
_yaml.preserve_quotes = True
@dataclass
class _Field:
key: str # dot-separated path within the block, e.g. "webots.world"
question: str
default: Any
note: str = ""
options: Optional[List[str]] = None # if set - select(), else - text()
def label(self) -> str:
return self.key.split(".")[-1]
@dataclass
class _Block:
yaml_key: str # top-level key in cobot-setting.yaml
title: str # shown in "Настроить <title>?" prompt
fields: List[_Field]
def _load_tools_registry() -> dict:
"""Читает tools.yaml и возвращает словарь инструментов."""
if not _TOOLS_YAML.exists():
return {}
_y = YAML()
with open(_TOOLS_YAML, encoding="utf-8") as f:
data = _y.load(f)
return dict(data.get("tools", {}))
def _build_tool_block() -> Optional[_Block]:
"""Строит блок выбора инструмента из реестра tools.yaml.
Возвращает None если реестр недоступен."""
registry = _load_tools_registry()
if not registry:
return None
options = list(registry.keys())
labels = " | ".join(
f"{name}: {registry[name].get('label', '')}" for name in options
)
return _Block(
yaml_key="tool",
title="Инструмент / Захват",
fields=[
_Field("active", "Выберите активный инструмент:", options[0],
note=labels, options=options),
],
)
# All configuration blocks. Each block maps to a top-level key in cobot-setting.yaml.
# Все блоки конфигурации. Каждый блок соответствует ключу верхнего уровня в cobot-setting.yaml.
_BLOCKS: List[_Block] = [
_Block(
yaml_key="foxglove",
title="Foxglove bridge",
fields=[
_Field("enabled", "Включить Foxglove bridge?", "true",
note="Запускать foxglove_bridge вместе с узлом робота",
options=["true", "false"]),
_Field("port", "Порт WebSocket:", "8765",
note="Порт, к которому подключается Foxglove Studio (по умолчанию 8765)"),
_Field("address", "Адрес прослушивания:", "0.0.0.0",
note="0.0.0.0 = все интерфейсы, 127.0.0.1 = только localhost",
options=["0.0.0.0", "127.0.0.1"]),
_Field("use_sim_time", "Использовать симуляционное время (/clock)?", "false",
note="Подписываться на /clock вместо системного времени",
options=["false", "true"]),
_Field("debug", "Подробное логирование bridge?", "false",
options=["false", "true"]),
_Field("num_threads", "Потоки executor (0 = авто):", "0"),
],
),
_Block(
yaml_key="web",
title="Веб-сервер (FastAPI)",
fields=[
_Field("enabled", "Включить веб-сервер?", "true",
note="Запускать FastAPI-сервер для HTTP/WebSocket-управления",
options=["true", "false"]),
_Field("host", "Адрес прослушивания:", "0.0.0.0",
note="0.0.0.0 = все интерфейсы, 127.0.0.1 = только localhost",
options=["0.0.0.0", "127.0.0.1"]),
_Field("port", "Порт HTTP:", "8007",
note="Порт FastAPI-сервера (по умолчанию 8007)"),
],
),
_Block(
yaml_key="planning",
title="MoveIt планирование",
fields=[
_Field("planning_group", "Группа планирования:", "iiwa_arm",
note="Группа планирования MoveIt из SRDF"),
_Field("default_frame", "Система отсчёта по умолчанию:", "base_link"),
_Field("default_planner", "Планировщик по умолчанию:", "ompl",
options=["ompl", "pilz_industrial_motion_planner", "chomp"]),
_Field("planning_attempts", "Попыток планирования:", "3"),
],
),
_Block(
yaml_key="digital_twin",
title="Цифровой двойник (Webots / RViz)",
fields=[
_Field("webots.transform", "Трансформ робота в сцене Webots (x y z, метры):", "-0.25 0 0.79"),
_Field("webots.rotation", "Поворот робота в сцене Webots (ax ay az угол):", "0 0 1 0"),
_Field("webots.controller_timer", "Шаг таймера контроллера Webots (мс):", "50"),
],
),
_Block(
yaml_key="robot",
title="Подключение робота",
fields=[
_Field("name", "Имя модели робота:", "iiwa7"),
_Field("ip", "IP-адрес робота:", "192.170.10.2",
note="IP контроллера KUKA на сетевом интерфейсе FRI"),
_Field("port", "Порт FRI:", "30200"),
_Field("fri_cycle_ms", "Цикл FRI (мс):", "10",
note="5 мс = 200 Гц, 10 мс = 100 Гц",
options=["10", "5"]),
_Field("active_controller", "Активный ROS-контроллер:", "jtc",
note="jtc = JointTrajectoryController (MoveIt), forward = ForwardCommandController",
options=["jtc", "forward"]),
_Field("joint_position_tau", "EMA tau фильтра положения (с):", "0.04",
note="Сглаживает команды положения перед отправкой в FRI"),
_Field("joint_velocity_tau", "EMA tau фильтра скорости (с):", "0.01",
note="Убирает выбросы из оценки скорости конечной разностью"),
],
),
]
def _coerce(value: str, original: Any) -> Any:
"""Convert a string value to match the type of the original YAML value.
Преобразует строковое значение к типу исходного значения YAML.
"""
if isinstance(original, bool):
return value.lower() == "true"
if isinstance(original, int):
try:
return int(value)
except ValueError:
return value
if isinstance(original, float):
try:
return float(value)
except ValueError:
return value
return value
def _get_nested(mapping: Any, path: str) -> Any:
"""Return the value at a dot-separated path inside a nested YAML mapping, or None.
Возвращает значение по пути с точками внутри вложенного YAML-словаря, или None.
"""
keys = path.split(".")
cur = mapping
for k in keys:
if cur is None or k not in cur:
return None
cur = cur[k]
return cur
def _infer(value: str) -> Any:
"""Infer a bool / int / float / str from a raw string when there is no original
value to match the type against (i.e. the key is new in the config).
Выводит bool / int / float / str из строки, когда нет исходного значения для
сопоставления типа (т.е. ключ новый в конфиге).
"""
low = value.strip().lower()
if low in ("true", "false"):
return low == "true"
try:
return int(value)
except ValueError:
pass
try:
return float(value)
except ValueError:
pass
return value
def _set_nested(mapping: Any, path: str, value: Any) -> None:
"""Set the value at a dot-separated path, creating missing intermediate maps.
If the leaf key already exists its type is preserved via _coerce; otherwise the
type is inferred from the string with _infer. This makes the wizard tolerant of
configs that do not yet contain every field (e.g. an older cobot-setting.yaml).
Устанавливает значение по пути с точками, создавая отсутствующие промежуточные
словари. Если конечный ключ уже есть — тип сохраняется через _coerce; иначе тип
выводится из строки через _infer. Это делает мастер устойчивым к конфигам, где
ещё нет всех полей (например, более старый cobot-setting.yaml).
"""
keys = path.split(".")
cur = mapping
for k in keys[:-1]:
if k not in cur or cur[k] is None:
cur[k] = {}
cur = cur[k]
leaf = keys[-1]
if leaf in cur and cur[leaf] is not None:
cur[leaf] = _coerce(value, cur[leaf])
else:
cur[leaf] = _infer(value)
def _load_config() -> Any:
"""Load cobot-setting.yaml preserving comments and key order.
Загружает cobot-setting.yaml, сохраняя комментарии и порядок ключей.
"""
with open(_CONFIG_PATH, "r", encoding="utf-8") as fh:
return _yaml.load(fh)
def _save_config(data: Any) -> None:
"""Write the modified YAML back to cobot-setting.yaml, preserving comments.
Записывает изменённый YAML обратно в cobot-setting.yaml, сохраняя комментарии.
"""
with open(_CONFIG_PATH, "w", encoding="utf-8") as fh:
_yaml.dump(data, fh)
def _run_wizard(data: Any, blocks: List[_Block]) -> bool:
"""Walk every block: ask "Configure X?", and if yes step through its fields.
Returns True if the user completed the wizard (config was saved), False on cancel.
Проходит по каждому блоку: спрашивает "Настроить X?", и если да — проходит по полям.
Возвращает True если мастер завершён (конфиг сохранён), False при отмене.
"""
total = len(blocks)
for bi, block in enumerate(blocks):
ui.header(f"Блок {bi + 1}/{total}", block.title)
if not ui.confirm(f"Настроить {block.title}?", default=True):
continue
for fi, f in enumerate(block.fields):
yaml_val = _get_nested(data[block.yaml_key], f.key)
current = str(yaml_val) if yaml_val is not None else str(f.default)
step_note = f"Поле {fi + 1}/{len(block.fields)}"
note = f"{step_note}\n{f.note}" if f.note else step_note
if f.options:
default_opt = current if current in f.options else f.options[0]
value = ui.select(f.question, f.options, default_opt, note=note)
else:
value = ui.text(f.question, current, note=note)
if value is None:
ui.info("[yellow]Отменено.[/yellow]")
return False
_set_nested(data[block.yaml_key], f.key, value)
_save_config(data)
ui.done(True, f"Конфигурация сохранена в {_CONFIG_PATH.name}")
return True
def register(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser("robot-setup", help="Configure cobot-setting.yaml interactively")
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
ui.header("Настройка робота", "cobot-setting.yaml")
if not _CONFIG_PATH.exists():
ui.error(f"Конфиг не найден: {_CONFIG_PATH}")
sys.exit(1)
data = _load_config()
# Убеждаемся что секция tool существует в данных (для старых конфигов)
if "tool" not in data:
data["tool"] = {"active": "patron"}
tool_block = _build_tool_block()
blocks = ([tool_block] if tool_block else []) + list(_BLOCKS)
if not _run_wizard(data, blocks):
return
# Применяем выбранный инструмент: перезаписываем tool_active.xacro и iiwa7.srdf
active_tool = str(data["tool"].get("active", "patron"))
if not _TOOLS_YAML.exists():
ui.info(f"[yellow]tools.yaml не найден ({_TOOLS_YAML}) — пропуск применения инструмента[/yellow]")
return
try:
registry = _load_tools_registry()
if active_tool not in registry:
raise ValueError(f"Неизвестный инструмент '{active_tool}'. Доступны: {', '.join(registry)}")
tool_cfg = dict(registry[active_tool])
sys.path.insert(0, str(_PROJECT_DIR / "src" / "iiwa_utils"))
from iiwa_utils.tool_manager import apply_tool
apply_tool(tool_cfg=tool_cfg, xacro_out_path=_TOOL_ACTIVE_XACRO, srdf_path=_SRDF_PATH)
# Синхронизируем planning.pose_link с tcp_link выбранного инструмента
tcp_link = tool_cfg.get("tcp_link", "link_ee")
if "planning" in data:
data["planning"]["pose_link"] = tcp_link
_save_config(data)
ui.info(
f"[green]✓[/green] Инструмент [bold]{active_tool}[/bold] применён: "
f"tool_active.xacro, iiwa7.srdf обновлены, "
f"planning.pose_link → [bold]{tcp_link}[/bold]."
)
except Exception as exc:
ui.error(f"Не удалось применить инструмент: {exc}")
+326
View File
@@ -0,0 +1,326 @@
from __future__ import annotations
import argparse
import os
import shutil
import socket
import subprocess
from pathlib import Path
from typing import List, Optional
from cobot import process, ui
from cobot import privilege
from cobot.ui import done, header
from cobot.commands.local_setup import (
_WEBOTS_VERSION,
build_workspace,
install_webots,
webots_installed,
)
_PROJECT_DIR = Path(__file__).parent.parent.parent
_CONFIG_PATH = _PROJECT_DIR / "cobot-setting.yaml"
_INSTALL_DIR = _PROJECT_DIR / "install"
_JAZZY_DIR = Path("/opt/ros/jazzy")
# Default Webots installation path for the official .deb package.
# Путь установки Webots по умолчанию для официального .deb-пакета.
_WEBOTS_DEFAULT_HOME = Path("/usr/local/webots")
# Path where the config file is mounted inside the Docker container.
# Путь по которому конфиг-файл монтируется внутри Docker-контейнера.
_CONFIG_IN_CONTAINER = "/ros2_ws/cobot-setting.yaml"
# Container names used for docker run and docker kill.
# Имена контейнеров, используемые для docker run и docker kill.
_CONTAINER_CONTROLLER = "lwc-controller"
_CONTAINER_WEBOTS = "lwc-webots"
# Named Docker volume that stores the Webots asset cache between container runs.
# Именованный Docker volume для хранения кэша ассетов Webots между запусками контейнера.
_WEBOTS_CACHE_VOLUME = "lwc-webots-cache"
# Candidates checked in order - for the controller the webots image is a valid fallback.
# Кандидаты проверяются по порядку - для контроллера образ webots является допустимым запасным.
_CONTROLLER_IMAGES = [
"lwc-local:ros-iiwa7-jazzy",
"evilfisru/lwc:iiwa-jazzy",
"evilfisru/lwc:iiwa-jazzy-dev",
"lwc-local:ros-iiwa7-webots-jazzy",
"evilfisru/lwc:webots-jazzy",
"evilfisru/lwc:webots-jazzy-dev",
]
_WEBOTS_IMAGES = [
"lwc-local:ros-iiwa7-webots-jazzy",
"evilfisru/lwc:webots-jazzy",
"evilfisru/lwc:webots-jazzy-dev",
]
def _detect_webots_home() -> str:
"""Return the WEBOTS_HOME path for the locally installed Linux Webots, or "".
Возвращает путь WEBOTS_HOME для локально установленного Linux Webots, или "".
"""
def _is_linux_webots(home: str) -> bool:
return (Path(home) / "webots").is_file()
if "WEBOTS_HOME" in os.environ:
home = os.environ["WEBOTS_HOME"]
return home if _is_linux_webots(home) else ""
if _WEBOTS_DEFAULT_HOME.is_dir() and _is_linux_webots(str(_WEBOTS_DEFAULT_HOME)):
return str(_WEBOTS_DEFAULT_HOME)
webots_bin = shutil.which("webots")
if webots_bin:
home = str(Path(webots_bin).resolve().parent)
if _is_linux_webots(home):
return home
return ""
def _detect_gpu() -> str:
"""Return "nvidia", "mesa", or "software" based on available GPU drivers.
Возвращает "nvidia", "mesa" или "software" в зависимости от доступных драйверов GPU.
"""
if shutil.which("nvidia-smi"):
if subprocess.run(["nvidia-smi"], capture_output=True).returncode == 0:
return "nvidia"
if Path("/dev/dri").exists():
return "mesa"
return "software"
def _docker_images() -> set:
"""Return the set of "repository:tag" strings for all local Docker images.
Возвращает множество строк "репозиторий:тег" для всех локальных Docker-образов.
"""
r = subprocess.run(
["docker", "images", "--format", "{{.Repository}}:{{.Tag}}"],
capture_output=True, text=True,
)
return set(r.stdout.strip().splitlines())
def _find_image(candidates: List[str]) -> Optional[str]:
"""Return the first candidate image that exists locally, or None.
Возвращает первый образ-кандидат, присутствующий локально, или None.
"""
available = _docker_images()
for img in candidates:
if img in available:
return img
return None
# Local (non-Docker) launch
# Локальный (не Docker) запуск
def _run_local(mode: str) -> None:
"""Launch iiwa.launch.py natively. The whole ros2 launch tree runs in its own
session so a single Ctrl-C tears down every node cleanly.
Запускает iiwa.launch.py нативно. Всё дерево ros2 launch работает в своей сессии,
поэтому один Ctrl-C аккуратно завершает каждый узел.
"""
config = str(_CONFIG_PATH)
ros_cmd = f"ros2 launch iiwa_bringup iiwa.launch.py setting:={config}"
if mode == "webots":
ros_cmd += " simulate:=1"
webots_home = _detect_webots_home() if mode == "webots" else ""
webots_export = f"export WEBOTS_HOME={webots_home} && " if webots_home else ""
full_cmd = (
f"{webots_export}"
f"source {_JAZZY_DIR}/setup.bash && "
f"source {_INSTALL_DIR}/setup.bash && "
f"{ros_cmd}"
)
label = "симулятор Webots" if mode == "webots" else "контроллер"
header(f"Запуск: {label} (локально)")
ui.note(ros_cmd)
if webots_home:
ui.note(f"WEBOTS_HOME: {webots_home}")
ui.note("Нажмите Ctrl-C чтобы остановить")
rc = process.stream(
["bash", "-c", full_cmd],
cwd=str(_PROJECT_DIR),
new_session=True,
)
done(rc in (0, -2, -15, 130), "Остановлено")
# Docker launch
# Запуск в Docker
def _run_docker(image: str, mode: str, gpu: str) -> None:
"""Launch iiwa.launch.py inside a Docker container, forwarding X11/GPU for Webots.
The container is stopped with ``docker kill`` on Ctrl-C.
Запускает iiwa.launch.py внутри Docker-контейнера, пробрасывая X11/GPU для Webots.
Контейнер останавливается через ``docker kill`` по Ctrl-C.
"""
container = _CONTAINER_WEBOTS if mode == "webots" else _CONTAINER_CONTROLLER
ros_cmd = (
"source /ros2_ws/install/setup.bash && "
f"ros2 launch iiwa_bringup iiwa.launch.py setting:={_CONFIG_IN_CONTAINER}"
)
if mode == "webots":
ros_cmd += " simulate:=1"
# Remove any stale container with the same name from a previous run.
# Удаляем устаревший контейнер с таким же именем от предыдущего запуска.
subprocess.run(["docker", "rm", "-f", container], capture_output=True)
cmd = [
"docker", "run", "--rm",
"--name", container,
"--network", "host",
"--hostname", socket.gethostname(),
"-e", "USER=root",
]
if mode == "webots":
subprocess.run(["xhost", "+local:docker"], capture_output=True)
cmd += [
"-e", f"DISPLAY={os.environ.get('DISPLAY', ':0')}",
"-e", "QT_X11_NO_MITSHM=1",
"-v", "/tmp/.X11-unix:/tmp/.X11-unix:rw",
"-v", f"{_WEBOTS_CACHE_VOLUME}:/root/.cache/Cyberbotics/Webots",
]
if gpu == "nvidia":
cmd += [
"--gpus", "all",
"-e", "NVIDIA_VISIBLE_DEVICES=all",
"-e", "NVIDIA_DRIVER_CAPABILITIES=graphics,utility,compute",
]
elif gpu == "mesa":
cmd += ["--device", "/dev/dri"]
else:
cmd += [
"-e", "LIBGL_ALWAYS_SOFTWARE=1",
"-e", "GALLIUM_DRIVER=llvmpipe",
]
if _CONFIG_PATH.exists():
cmd += ["-v", f"{_CONFIG_PATH}:{_CONFIG_IN_CONTAINER}:ro"]
cmd += [image, "bash", "-c", ros_cmd]
_GPU_LABELS = {
"nvidia": "NVIDIA GPU",
"mesa": "Intel/AMD DRI (Mesa)",
"software": "Программный рендеринг (llvmpipe)",
}
label = "симулятор Webots" if mode == "webots" else "контроллер"
header(f"Запуск: {label} в Docker")
ui.note(f"Образ: {image}")
if mode == "webots":
ui.note(f"GPU: {_GPU_LABELS.get(gpu, gpu)}")
ui.note("Нажмите Ctrl-C чтобы остановить")
rc = process.stream(
cmd,
kill_fn=lambda: subprocess.run(["docker", "kill", container], capture_output=True),
)
done(rc in (0, -2, -15, 130), "Остановлено")
def _local_flow(args: argparse.Namespace) -> None:
"""Interactive flow for local launch: check Webots/ROS2/build, then run.
Интерактивный сценарий локального запуска: проверка Webots/ROS2/сборки, затем запуск.
"""
mode_v = ui.select(
"Что запустить?",
["Контроллер", "Симулятор Webots"],
"Контроллер",
)
if mode_v is None:
return
mode = "webots" if mode_v == "Симулятор Webots" else "controller"
if mode == "webots" and not webots_installed():
if not ui.confirm(f"Webots {_WEBOTS_VERSION} не установлен. Установить сейчас?",
default=True):
return
if not privilege.ensure_sudo() or not install_webots():
return
if not _JAZZY_DIR.is_dir():
if ui.confirm("ROS2 Jazzy не установлен. Запустить local-setup?", default=True):
from cobot.commands.local_setup import run as _local_setup
_local_setup(args)
return
if not (_INSTALL_DIR / "setup.bash").exists():
if not ui.confirm("Проект ещё не собран. Собрать сейчас?", default=True):
return
if not privilege.ensure_sudo() or not build_workspace():
return
_run_local(mode)
def _docker_flow(args: argparse.Namespace) -> None:
"""Interactive flow for Docker launch: pick an image, detect GPU, then run.
Интерактивный сценарий запуска в Docker: выбор образа, определение GPU, затем запуск.
"""
if not shutil.which("docker"):
ui.error("Docker не установлен или отсутствует в PATH.")
return
mode_v = ui.select(
"Что запустить?",
["Контроллер", "Симулятор Webots"],
"Контроллер",
)
if mode_v is None:
return
mode = "webots" if mode_v == "Симулятор Webots" else "controller"
candidates = _WEBOTS_IMAGES if mode == "webots" else _CONTROLLER_IMAGES
image = _find_image(candidates)
if image is None:
what = "Webots" if mode == "webots" else "контроллера или Webots"
if ui.confirm(f"Docker-образ для {what} не найден. Запустить docker-setup?",
default=True):
from cobot.commands.docker_setup import run as _docker_setup
_docker_setup(args)
return
gpu = _detect_gpu() if mode == "webots" else "software"
_run_docker(image, mode, gpu)
def register(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser(
"run",
help="Launch the robot controller or Webots simulator",
)
p.add_argument(
"mode",
nargs="?",
choices=["local", "docker"],
default=None,
help="local — native ROS2, docker — Docker container (default: ask)",
)
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
mode = getattr(args, "mode", None)
if mode == "local":
_local_flow(args)
elif mode == "docker":
_docker_flow(args)
else:
v = ui.select(
"Как запустить проект?",
["Локально (нативный ROS2)", "Docker"],
"Локально (нативный ROS2)",
)
if v is None:
return
if v.startswith("Локально"):
_local_flow(args)
else:
_docker_flow(args)
+52
View File
@@ -0,0 +1,52 @@
import argparse
from cobot import ui
# Import each sub-command's run() so we can call them in sequence.
# Импортируем run() каждой подкоманды, чтобы вызывать их по порядку.
from cobot.commands.doc_setup import run as _doc_setup
from cobot.commands.docker_setup import run as _docker_setup
from cobot.commands.local_setup import run as _local_setup
from cobot.commands.robot_setup import run as _robot_setup
def register(subparsers):
"""Register the "setup" subparser.
Регистрирует подпарсер "setup".
"""
p = subparsers.add_parser("setup", help="First-time project setup")
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
"""Run the three-step first-time setup wizard: docs -> robot config -> build env.
Запускает трёхшаговый мастер первичной настройки: документация -> конфиг робота -> среда сборки.
"""
ui.header("Первичная настройка", "3 шага")
# Step 1 - documentation server.
# Шаг 1 - сервер документации.
if ui.confirm("Шаг 1/3 — настроить сервер документации?", default=True):
_doc_setup(args)
# Step 2 - robot parameters in cobot-setting.yaml.
# Шаг 2 - параметры робота в cobot-setting.yaml.
if ui.confirm("Шаг 2/3 — настроить параметры робота (cobot-setting.yaml)?", default=True):
_robot_setup(args)
# Step 3 - build environment: local ROS2 or Docker.
# Шаг 3 - среда сборки: локальный ROS2 или Docker.
env_choice = ui.select(
"Шаг 3/3 — как настроить среду сборки?",
[
"local-setup — установить ROS2 Jazzy на эту машину и собрать через colcon",
"docker-setup — собрать Docker-образ с предустановленным ROS2 Jazzy",
],
"local-setup — установить ROS2 Jazzy на эту машину и собрать через colcon",
)
if env_choice is None:
return
if env_choice.startswith("local"):
_local_setup(args)
else:
_docker_setup(args)
+79
View File
@@ -0,0 +1,79 @@
from __future__ import annotations
import argparse
import subprocess
from pathlib import Path
from cobot import process, ui
from cobot.ui import done
from cobot.process import StepProgress
_PROJECT_DIR = Path(__file__).parent.parent.parent
def _git(*args: str) -> str:
"""Run a git command in the project dir and return its stripped stdout.
Запускает git-команду в директории проекта и возвращает обрезанный stdout.
"""
return subprocess.check_output(["git", *args], cwd=_PROJECT_DIR, text=True).strip()
def _update() -> None:
"""Fetch the current branch, show incoming commits, pull, and reinstall the cobot CLI.
Progress: fetch (0-30 %), pull (30-80 %), reinstall (80-100 %).
Получает текущую ветку, показывает входящие коммиты, делает pull и переустанавливает CLI.
Прогресс: fetch (0-30 %), pull (30-80 %), переустановка (80-100 %).
"""
ok, fail_msg = True, ""
with StepProgress("Обновление проекта") as p:
try:
branch = _git("rev-parse", "--abbrev-ref", "HEAD")
p.raw(f"[cyan]▸[/cyan] Ветка: [bold]{branch}[/bold]")
p.set(0, "Получение с удалённого репозитория...")
rc = process.stream(["git", "fetch", "origin"], cwd=str(_PROJECT_DIR), on_line=p.log)
if rc not in (0, -9, -15):
done(False, "git fetch завершился с ошибкой")
return
p.set(30)
behind = _git("rev-list", f"HEAD..origin/{branch}", "--count")
if behind == "0":
p.set(100, "Уже актуально")
done(True, "Уже актуальная версия")
return
p.raw(f"\n[bold]{behind} новых коммит(ов):[/bold]")
for line in _git("log", f"HEAD..origin/{branch}", "--oneline").splitlines():
p.log(line)
p.set(30, "Применение изменений...")
rc = process.stream(["git", "pull", "origin", branch],
cwd=str(_PROJECT_DIR), on_line=p.log)
if rc not in (0, -9, -15):
done(False, "git pull завершился с ошибкой")
return
p.set(80)
p.set(80, "Переустановка cobot CLI...")
p.raw("\n[cyan]▸[/cyan] Переустановка cobot CLI...")
rc = process.stream(["uv", "tool", "install", "--editable", str(_PROJECT_DIR)],
on_line=p.log)
if rc in (0, -9, -15):
p.raw("[green]✓[/green] cobot переустановлен")
else:
p.raw("[yellow]Предупреждение:[/yellow] переустановка не удалась")
p.set(100, "Готово")
except subprocess.CalledProcessError as exc:
ok, fail_msg = False, str(exc)
done(ok, "Проект обновлён" if ok else fail_msg)
def register(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser("update", help="Pull latest changes from the remote git branch")
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
_update()
+176
View File
@@ -0,0 +1,176 @@
from __future__ import annotations
import subprocess
import sys
import threading
from typing import List, Optional, Sequence
from cobot import ui
from cobot.ui import console
# How often the keep-alive thread refreshes the sudo timestamp (seconds).
# Sudo's default timeout is 15 min; 60 s gives a huge safety margin.
# Как часто поток keep-alive обновляет токен sudo (секунды).
# Таймаут sudo по умолчанию 15 мин; 60 с даёт большой запас.
_KEEPALIVE_INTERVAL = 60
# Module-level state: whether sudo has been primed and the keep-alive thread.
# Состояние уровня модуля: прогрет ли sudo и поток keep-alive.
_primed = False
_keepalive_thread: Optional[threading.Thread] = None
_keepalive_stop = threading.Event()
def _have_valid_timestamp() -> bool:
"""Return True if a non-interactive ``sudo -n -v`` succeeds (cached token valid).
Возвращает True, если ``sudo -n -v`` проходит без запроса (токен закеширован и валиден).
"""
return subprocess.run(
["sudo", "-n", "-v"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
).returncode == 0
def _read_masked_password(prompt: str) -> Optional[str]:
"""Read a password character-by-character, echoing a ``★`` for each one.
Backspace deletes the last char. Enter submits. Ctrl-C / Esc cancels (None).
Falls back to getpass when stdin is not a TTY.
Читает пароль посимвольно, отображая ``★`` за каждый символ.
Backspace удаляет последний символ. Enter — подтвердить. Ctrl-C / Esc — отмена (None).
Откатывается на getpass, если stdin не является TTY.
"""
if not sys.stdin.isatty():
import getpass
try:
return getpass.getpass(prompt)
except (EOFError, KeyboardInterrupt):
return None
sys.stdout.write(prompt)
sys.stdout.flush()
chars: List[str] = []
while True:
kind, ch = ui._read_key()
if kind == "enter":
sys.stdout.write("\n")
sys.stdout.flush()
return "".join(chars)
if kind in ("esc", "interrupt"):
sys.stdout.write("\n")
sys.stdout.flush()
return None
if kind == "backspace":
if chars:
chars.pop()
# Erase one mask glyph: move back, overwrite with space, move back.
# Стираем один символ маски: назад, пробел, снова назад.
sys.stdout.write("\b \b")
sys.stdout.flush()
continue
# Space and any printable char are part of the password.
# Пробел и любой печатный символ — часть пароля.
if kind == "space":
chars.append(" ")
sys.stdout.write("")
sys.stdout.flush()
elif kind == "char" and ch.isprintable():
chars.append(ch)
sys.stdout.write("")
sys.stdout.flush()
def _validate_password(password: str) -> bool:
"""Feed the password to ``sudo -S -v`` to validate it and cache the timestamp.
Передаёт пароль в ``sudo -S -v`` для проверки и кеширования токена.
"""
proc = subprocess.run(
["sudo", "-S", "-v"],
input=password + "\n",
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
text=True,
)
return proc.returncode == 0
def _keepalive_loop() -> None:
"""Refresh the sudo timestamp periodically until the process exits.
Периодически обновляет токен sudo, пока процесс не завершится.
"""
while not _keepalive_stop.wait(_KEEPALIVE_INTERVAL):
subprocess.run(
["sudo", "-n", "-v"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
def _start_keepalive() -> None:
global _keepalive_thread
if _keepalive_thread is not None and _keepalive_thread.is_alive():
return
_keepalive_stop.clear()
_keepalive_thread = threading.Thread(target=_keepalive_loop, daemon=True)
_keepalive_thread.start()
def ensure_sudo() -> bool:
"""Make sure we hold a valid sudo timestamp, asking for the password once.
If a valid cached timestamp already exists (e.g. the user ran sudo recently),
no password is asked. Otherwise the user is prompted up to 3 times with a masked
input. On success a keep-alive thread is started. Returns True if sudo is ready.
Гарантирует наличие валидного токена sudo, спрашивая пароль один раз.
Если валидный токен уже есть (например, пользователь недавно вызывал sudo), пароль
не спрашивается. Иначе пользователю предлагается до 3 попыток с маскированным вводом.
При успехе запускается поток keep-alive. Возвращает True, если sudo готов.
"""
global _primed
if _primed and _have_valid_timestamp():
return True
if _have_valid_timestamp():
_primed = True
_start_keepalive()
return True
console.print(
"\n[bold]Для установки/удаления системных пакетов нужны права root.[/bold]"
)
console.print(
"[dim]Пароль спросим один раз и будем держать сессию sudo активной "
"до конца операции.[/dim]"
)
for attempt in range(3):
password = _read_masked_password(" [sudo] пароль: ")
if password is None:
console.print("[yellow]Отменено.[/yellow]")
return False
if _validate_password(password):
del password
_primed = True
_start_keepalive()
console.print("[green]✓ sudo активирован[/green]")
return True
remaining = 2 - attempt
if remaining > 0:
console.print(f"[red]Неверный пароль.[/red] Осталось попыток: {remaining}")
else:
console.print("[red]Неверный пароль. Превышено число попыток.[/red]")
return False
def sudo(cmd: Sequence[str]) -> List[str]:
"""Prefix a command with ``sudo -n`` (non-interactive; token already cached).
Префиксует команду ``sudo -n`` (неинтерактивно; токен уже закеширован).
"""
return ["sudo", "-n", *cmd]
def stop_keepalive() -> None:
"""Stop the keep-alive thread. Safe to call even if it was never started.
Останавливает поток keep-alive. Безопасно вызывать, даже если он не запускался.
"""
_keepalive_stop.set()
+332
View File
@@ -0,0 +1,332 @@
from __future__ import annotations
import atexit
import os
import signal
import subprocess
import threading
from typing import Callable, Dict, List, Optional, Sequence
from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn
from cobot.ui import console, done, header
# Type of an optional callback invoked for every streamed output line.
# Тип опционального колбэка, вызываемого для каждой строки потокового вывода.
LineHook = Callable[[str], None]
# Registry of all live subprocesses, so the signal handler can kill them on exit.
# Maps pid -> Popen. Guarded by a lock because procs start/finish in helper calls.
# Реестр всех живых подпроцессов, чтобы обработчик сигнала мог убить их при выходе.
# Сопоставляет pid -> Popen. Защищён блокировкой, т.к. процессы создаются/завершаются в хелперах.
_procs: Dict[int, subprocess.Popen] = {}
_procs_lock = threading.Lock()
_handlers_installed = False
def _register(proc: subprocess.Popen) -> None:
with _procs_lock:
_procs[proc.pid] = proc
def _unregister(proc: subprocess.Popen) -> None:
with _procs_lock:
_procs.pop(proc.pid, None)
def _kill_proc(proc: subprocess.Popen) -> None:
"""Terminate a process and everything it spawned.
Three strategies, in order of how the process was started:
* a custom kill_fn (e.g. ``docker kill <container>``) registered on the proc;
* a new-session process (e.g. ros2 launch) — every node shares the session, so
``pkill -s <sid>`` reaches all of them (killpg would only hit the launcher);
* otherwise the process group (SIGTERM then SIGKILL), or the bare process.
Завершает процесс и всё, что он породил. Три стратегии по способу запуска:
пользовательский kill_fn (например ``docker kill``); процесс в новой сессии
(ros2 launch — все узлы делят сессию, поэтому ``pkill -s`` достаёт каждый);
иначе группа процессов (SIGTERM→SIGKILL) или сам процесс.
"""
if proc.poll() is not None:
return
kill_fn = getattr(proc, "_cobot_kill_fn", None)
if kill_fn is not None:
try:
kill_fn()
try:
proc.wait(timeout=5)
return
except subprocess.TimeoutExpired:
pass
except Exception:
pass
if getattr(proc, "_cobot_new_session", False):
try:
sid = os.getsid(proc.pid)
subprocess.run(["pkill", "-TERM", "-s", str(sid)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
proc.wait(timeout=3)
return
except subprocess.TimeoutExpired:
subprocess.run(["pkill", "-KILL", "-s", str(sid)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return
except Exception:
pass
try:
pgid = os.getpgid(proc.pid)
os.killpg(pgid, signal.SIGTERM)
try:
proc.wait(timeout=3)
except subprocess.TimeoutExpired:
os.killpg(pgid, signal.SIGKILL)
except Exception:
try:
proc.terminate()
except Exception:
pass
def kill_all() -> None:
"""Kill every registered subprocess. Used by the signal handler and atexit.
Убивает каждый зарегистрированный подпроцесс. Используется обработчиком сигнала и atexit.
"""
with _procs_lock:
procs = list(_procs.values())
for proc in procs:
_kill_proc(proc)
def _on_sigint(signum, frame): # noqa: ANN001
"""SIGINT handler: stop all children, print a cancel note, and exit non-zero.
Обработчик SIGINT: останавливает всех потомков, печатает заметку об отмене и выходит с ненулём.
"""
kill_all()
console.print("\n[yellow]Прервано пользователем (Ctrl-C).[/yellow]")
raise SystemExit(130)
def install_signal_handlers() -> None:
"""Install the SIGINT handler and atexit cleanup exactly once.
Устанавливает обработчик SIGINT и очистку atexit ровно один раз.
"""
global _handlers_installed
if _handlers_installed:
return
_handlers_installed = True
signal.signal(signal.SIGINT, _on_sigint)
atexit.register(kill_all)
def spawn(
cmd: Sequence[str],
*,
env: Optional[dict] = None,
cwd: Optional[str] = None,
new_session: bool = False,
shell: bool = False,
kill_fn: Optional[Callable] = None,
) -> subprocess.Popen:
"""Start a subprocess with merged stdout/stderr as text, register it, and return it.
new_session=True puts the process in its own session/process-group so the whole
tree (e.g. all ros2 launch nodes) can be torn down with one signal. kill_fn is an
optional custom teardown (e.g. ``docker kill``) used by the cleanup logic.
Запускает подпроцесс с объединённым stdout/stderr в текстовом режиме, регистрирует
его и возвращает. new_session=True помещает процесс в собственную сессию/группу.
kill_fn — опциональная функция завершения (например ``docker kill``) для очистки.
"""
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
env=env,
cwd=cwd,
start_new_session=new_session,
shell=shell,
)
proc._cobot_new_session = new_session # type: ignore[attr-defined]
proc._cobot_kill_fn = kill_fn # type: ignore[attr-defined]
_register(proc)
return proc
def stream(
cmd: Sequence[str],
*,
env: Optional[dict] = None,
cwd: Optional[str] = None,
on_line: Optional[LineHook] = None,
new_session: bool = False,
shell: bool = False,
echo: bool = True,
kill_fn: Optional[Callable] = None,
) -> int:
"""Run a command and stream every output line to the console (and on_line hook).
Returns the process exit code. SIGKILL (-9) / SIGTERM (-15) are returned as-is so
callers can treat user cancellation differently from real failures.
Запускает команду и транслирует каждую строку вывода в консоль (и в колбэк on_line).
Возвращает код возврата процесса. SIGKILL (-9) / SIGTERM (-15) возвращаются как есть,
чтобы вызывающий код мог отличать отмену пользователем от реальных ошибок.
"""
proc = spawn(cmd, env=env, cwd=cwd, new_session=new_session, shell=shell, kill_fn=kill_fn)
try:
for line in proc.stdout:
s = line.rstrip()
if on_line is not None:
on_line(s)
elif echo and s:
console.print(f" [dim]{_escape(s)}[/dim]")
proc.wait()
finally:
_unregister(proc)
return proc.returncode
def _escape(s: str) -> str:
"""Escape Rich markup so raw command output is never interpreted as markup.
Экранирует разметку Rich, чтобы сырой вывод команды не интерпретировался как разметка.
"""
return s.replace("[", "\\[")
# A progress bar that sticks to the bottom while log lines scroll above it.
# Прогресс-бар, "прилипающий" к низу, пока строки лога прокручиваются над ним.
def make_progress() -> Progress:
"""Create a Progress with a spinner, bar, percentage, and description column.
Создаёт Progress со спиннером, баром, процентами и колонкой описания.
"""
return Progress(
SpinnerColumn(),
BarColumn(bar_width=30),
TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
TextColumn("[dim]{task.description}[/dim]"),
console=console,
transient=True,
)
def run_step(
title: str,
cmd: Sequence[str],
*,
env: Optional[dict] = None,
cwd: Optional[str] = None,
new_session: bool = False,
shell: bool = False,
show_progress: bool = True,
total: float = 100.0,
parse_progress: Optional[Callable[[str], Optional[tuple]]] = None,
on_line: Optional[LineHook] = None,
success_msg: str = "",
fail_msg: str = "",
finish: bool = True,
) -> int:
"""Run one command as a self-contained "block": header, live log + progress, status.
parse_progress(line) may return (pct, label) to advance the bar, or None to ignore.
Returns the exit code. Prints a ✓/✗ line unless finish=False (used when chaining
several commands under one header).
Запускает одну команду как самодостаточный "блок": заголовок, живой лог + прогресс,
статус. parse_progress(line) может вернуть (pct, label) для продвижения бара или None.
Возвращает код возврата. Печатает строку ✓/✗, если finish=True (иначе — при цепочке
нескольких команд под одним заголовком).
"""
if title:
header(title)
if not show_progress:
rc = stream(cmd, env=env, cwd=cwd, on_line=on_line,
new_session=new_session, shell=shell)
else:
progress = make_progress()
with progress:
task = progress.add_task("", total=total)
def _line(s: str) -> None:
if parse_progress is not None:
parsed = parse_progress(s)
if parsed is not None:
pct, label = parsed
progress.update(task, completed=pct,
description=label or "")
if on_line is not None:
on_line(s)
elif s:
progress.console.print(f" [dim]{_escape(s)}[/dim]")
rc = stream(cmd, env=env, cwd=cwd, on_line=_line,
new_session=new_session, shell=shell)
progress.update(task, completed=total)
ok = rc in (0, -9, -15)
if finish:
if ok:
done(True, success_msg or "Готово")
else:
done(False, fail_msg or f"Команда завершилась с кодом {rc}")
return rc
# A live progress context for tasks that run several commands or Python work and
# need to drive the bar manually. Yields a small controller with .log()/.set().
# Живой контекст прогресса для задач, выполняющих несколько команд или Python-работу
# и управляющих баром вручную. Отдаёт небольшой контроллер с .log()/.set().
class StepProgress:
"""Manual progress controller used as a context manager.
Usage:
with StepProgress("Building") as p:
p.set(10, "step one")
p.log("some output")
Ручной контроллер прогресса, используемый как менеджер контекста.
"""
def __init__(self, title: str, total: float = 100.0, show: bool = True):
if title:
header(title)
self._total = total
self._show = show
self._progress: Optional[Progress] = None
self._task = None
def __enter__(self) -> "StepProgress":
if self._show:
self._progress = make_progress()
self._progress.__enter__()
self._task = self._progress.add_task("", total=self._total)
return self
def set(self, pct: float, label: str = "") -> None:
if self._progress is not None:
self._progress.update(self._task, completed=pct, description=label or "")
def log(self, line: str, style: str = "dim") -> None:
out = self._progress.console if self._progress is not None else console
if line == "":
out.print()
else:
out.print(f" [{style}]{_escape(line)}[/{style}]" if style else f" {line}")
def raw(self, renderable) -> None:
"""Print a pre-built Rich renderable/markup string without escaping.
Печатает готовый Rich-объект/строку с разметкой без экранирования.
"""
out = self._progress.console if self._progress is not None else console
out.print(renderable)
def __exit__(self, exc_type, exc, tb) -> None:
if self._progress is not None:
self._progress.__exit__(exc_type, exc, tb)
self._progress = None
+358
View File
@@ -0,0 +1,358 @@
from __future__ import annotations
import os
import select as _select
import sys
from typing import List, Optional, Sequence, Tuple
from rich.console import Console, Group
from rich.live import Live
from rich.panel import Panel
from rich.text import Text
# Raw terminal control is POSIX-only; the project targets Linux/ROS so this is fine.
# Сырой режим терминала только для POSIX; проект под Linux/ROS, так что всё в порядке.
try:
import termios
import tty
_HAS_TERMIOS = True
except ImportError: # pragma: no cover - Windows fallback
_HAS_TERMIOS = False
# Single shared console used everywhere so styling and width stay consistent.
# Единый общий console, используемый везде, чтобы стиль и ширина были согласованы.
console = Console(highlight=False)
# Glyphs used across the UI. Kept here so the whole look can be retuned in one place.
# Глифы, используемые в интерфейсе. Собраны здесь, чтобы весь вид настраивался в одном месте.
_CURSOR = ""
_OK = ""
_FAIL = ""
_CHECK_ON = ""
_CHECK_OFF = ""
def is_interactive() -> bool:
"""Return True if both stdin and stdout are real terminals.
Arrow-key selection needs a real TTY to read raw key presses. When that is
not available (piped input, CI) callers should fall back to defaults.
Возвращает True, если и stdin, и stdout являются настоящими терминалами.
Выбор стрелками требует реального TTY для чтения нажатий клавиш. Если его нет
(перенаправленный ввод, CI), вызывающий код должен использовать значения по умолчанию.
"""
try:
return sys.stdin.isatty() and sys.stdout.isatty()
except Exception:
return False
# Low-level key reader
# Низкоуровневое чтение клавиш
# How long to wait (seconds) after a lone ESC byte before deciding it is really the
# Escape key and not the start of an arrow escape sequence (\x1b[A etc.).
# Сколько ждать (секунд) после одиночного байта ESC, прежде чем решить, что это
# именно клавиша Escape, а не начало escape-последовательности стрелок (\x1b[A и т.п.).
_ESC_TIMEOUT = 0.05
def _read_key() -> Tuple[str, str]:
"""Read one key press in raw mode and classify it.
Returns a (kind, char) tuple where kind is one of: "up", "down", "enter", "esc",
"space", "backspace", "char", "interrupt", "other". This is used instead of
readchar because readchar blocks after a lone ESC (waiting to see whether it is an
arrow sequence); here a short select() timeout distinguishes a real Escape press.
UTF-8 multibyte input (e.g. Cyrillic in a password) is decoded fully.
Читает одно нажатие в сыром режиме и классифицирует его. Возвращает кортеж
(kind, char). Используется вместо readchar, потому что readchar зависает после
одиночного ESC (ожидая, не последовательность ли это стрелок); здесь короткий
таймаут select() отличает настоящий Escape. UTF-8 (например кириллица в пароле)
декодируется полностью.
"""
if not _HAS_TERMIOS: # pragma: no cover
ch = sys.stdin.read(1)
return ("char", ch)
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
b = os.read(fd, 1)
if not b:
return ("other", "")
c = b[0]
if c == 0x1B: # ESC — could be a lone Escape or an arrow/escape sequence
ready, _, _ = _select.select([fd], [], [], _ESC_TIMEOUT)
if not ready:
return ("esc", "")
seq = os.read(fd, 3)
last = seq[-1:] if seq else b""
if last == b"A":
return ("up", "")
if last == b"B":
return ("down", "")
if last in (b"C", b"D"):
return ("other", "")
return ("esc", "")
if c in (0x0D, 0x0A): # Enter
return ("enter", "")
if c == 0x03: # Ctrl-C (raw mode swallows SIGINT)
return ("interrupt", "")
if c == 0x20: # Space
return ("space", " ")
if c in (0x7F, 0x08): # Backspace / Delete
return ("backspace", "")
if c < 0x20: # other control char — ignore
return ("other", "")
# Printable byte — read any UTF-8 continuation bytes so multibyte chars decode.
# Печатный байт — дочитываем продолжения UTF-8, чтобы многобайтовые символы декодировались.
extra = 0
if c >= 0xF0:
extra = 3
elif c >= 0xE0:
extra = 2
elif c >= 0xC0:
extra = 1
if extra:
b += os.read(fd, extra)
return ("char", b.decode("utf-8", errors="ignore"))
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
# Block headers and footers
# Заголовки и завершения блоков
def header(title: str, subtitle: str = "") -> None:
"""Print a styled header block that marks the start of a task or wizard step.
Печатает стилизованный блок-заголовок, обозначающий начало задачи или шага мастера.
"""
console.print()
bar = Text("", style="bold cyan")
bar.append(title, style="bold")
if subtitle:
bar.append(f" {subtitle}", style="dim")
console.print(bar)
def done(success: bool, message: str = "") -> None:
"""Print the final status line of a task (green ✓ on success, red ✗ on failure).
Печатает финальную строку статуса задачи (зелёная ✓ при успехе, красная ✗ при ошибке).
"""
if success:
line = Text(f"{_OK} ", style="bold green")
line.append(message or "Done", style="green")
else:
line = Text(f"{_FAIL} ", style="bold red")
line.append(message or "Failed", style="red")
console.print(line)
def note(message: str) -> None:
"""Print a dim helper/info line.
Печатает приглушённую вспомогательную/информационную строку.
"""
console.print(Text(f" {message}", style="dim"))
def info(message: str) -> None:
"""Print a plain message through the shared console (Rich markup allowed).
Печатает обычное сообщение через общий console (разрешена разметка Rich).
"""
console.print(message)
def error(message: str) -> None:
"""Print an error line.
Печатает строку ошибки.
"""
console.print(f"[bold red]Error:[/bold red] {message}")
# A collapsed answer line, printed after an interactive block is resolved.
# Свёрнутая строка-ответ, печатается после разрешения интерактивного блока.
def _print_answer(question: str, answer: str) -> None:
line = Text(f"{_OK} ", style="bold green")
line.append(f"{question} ", style="dim")
line.append("· ", style="dim")
line.append(answer, style="bold")
console.print(line)
def _print_cancelled(question: str) -> None:
line = Text(f"{_FAIL} ", style="bold red")
line.append(f"{question} ", style="dim")
line.append("· cancelled", style="red")
console.print(line)
def _render_choices(question: str, options: Sequence[str], cursor: int,
note_text: str = "") -> Panel:
"""Build the renderable shown while the user is navigating a single-choice list.
Строит отрисовываемый объект, показываемый пока пользователь навигирует по списку выбора.
"""
rows: List[Text] = []
for i, opt in enumerate(options):
if i == cursor:
row = Text(f" {_CURSOR} ", style="bold cyan")
row.append(opt, style="bold")
else:
row = Text(f" {opt}", style="dim")
rows.append(row)
body = Group(*rows)
title = Text(question, style="bold")
sub = "↑/↓ — выбор · Enter — подтвердить · Esc — отмена"
if note_text:
sub = f"{note_text}\n{sub}"
return Panel(body, title=title, title_align="left", subtitle=Text(sub, style="dim"),
subtitle_align="left", border_style="cyan", padding=(0, 1))
def select(question: str, options: Sequence[str], default: Optional[str] = None,
note: str = "") -> Optional[str]:
"""Show an arrow-key single-choice block and return the chosen option string.
Returns None if the user pressed Escape / Ctrl-C. When the terminal is not
interactive the default (or first option) is returned without prompting.
Показывает блок выбора одного варианта со стрелками и возвращает выбранную строку.
Возвращает None, если пользователь нажал Escape / Ctrl-C. Если терминал не
интерактивный, возвращается значение по умолчанию (или первый вариант) без запроса.
"""
options = list(options)
if not options:
return None
cursor = options.index(default) if default in options else 0
if not is_interactive():
chosen = options[cursor]
_print_answer(question, chosen)
return chosen
with Live(_render_choices(question, options, cursor, note), console=console,
auto_refresh=False, transient=True) as live:
while True:
live.update(_render_choices(question, options, cursor, note), refresh=True)
kind, ch = _read_key()
if kind == "up" or (kind == "char" and ch == "k"):
cursor = (cursor - 1) % len(options)
elif kind == "down" or (kind == "char" and ch == "j"):
cursor = (cursor + 1) % len(options)
elif kind == "enter":
break
elif kind in ("esc", "interrupt"):
_print_cancelled(question)
return None
chosen = options[cursor]
_print_answer(question, chosen)
return chosen
def _render_multi(question: str, options: Sequence[str], cursor: int,
selected: set, note_text: str = "") -> Panel:
"""Build the renderable for a multi-choice checkbox list.
Строит отрисовываемый объект для списка множественного выбора с чекбоксами.
"""
rows: List[Text] = []
for i, opt in enumerate(options):
box = _CHECK_ON if i in selected else _CHECK_OFF
if i == cursor:
row = Text(f" {_CURSOR} {box} ", style="bold cyan")
row.append(opt, style="bold")
else:
row = Text(f" {box} ", style="green" if i in selected else "dim")
row.append(opt, style="" if i in selected else "dim")
rows.append(row)
body = Group(*rows)
title = Text(question, style="bold")
sub = "↑/↓ — навигация · Space — отметить · Enter — подтвердить · Esc — отмена"
if note_text:
sub = f"{note_text}\n{sub}"
return Panel(body, title=title, title_align="left", subtitle=Text(sub, style="dim"),
subtitle_align="left", border_style="cyan", padding=(0, 1))
def multiselect(question: str, options: Sequence[str],
defaults: Optional[Sequence[str]] = None,
note: str = "") -> Optional[List[str]]:
"""Show an arrow-key multi-choice block. Space toggles, Enter confirms.
Returns the list of selected option strings, or None if cancelled.
Показывает блок множественного выбора со стрелками. Space переключает, Enter подтверждает.
Возвращает список выбранных строк или None при отмене.
"""
options = list(options)
if not options:
return []
if defaults is None:
selected = set(range(len(options)))
else:
selected = {i for i, o in enumerate(options) if o in defaults}
cursor = 0
if not is_interactive():
chosen = [options[i] for i in sorted(selected)]
_print_answer(question, ", ".join(chosen) or "")
return chosen
with Live(_render_multi(question, options, cursor, selected, note), console=console,
auto_refresh=False, transient=True) as live:
while True:
live.update(_render_multi(question, options, cursor, selected, note), refresh=True)
kind, ch = _read_key()
if kind == "up" or (kind == "char" and ch == "k"):
cursor = (cursor - 1) % len(options)
elif kind == "down" or (kind == "char" and ch == "j"):
cursor = (cursor + 1) % len(options)
elif kind == "space":
selected.symmetric_difference_update({cursor})
elif kind == "enter":
break
elif kind in ("esc", "interrupt"):
_print_cancelled(question)
return None
chosen = [options[i] for i in sorted(selected)]
_print_answer(question, ", ".join(chosen) or "")
return chosen
def text(question: str, default: str = "", note: str = "") -> Optional[str]:
"""Prompt for a single line of free text, pre-filled with default.
Returns the entered value (or default if left empty), or None on Ctrl-C / EOF.
Запрашивает одну строку произвольного текста, предзаполненную значением по умолчанию.
Возвращает введённое значение (или default, если пусто), либо None при Ctrl-C / EOF.
"""
prompt = Text()
prompt.append(f"{_CURSOR} ", style="bold cyan")
prompt.append(question, style="bold")
if default:
prompt.append(f" [{default}]", style="dim")
console.print(prompt)
if note:
console.print(Text(f" {note}", style="dim"))
try:
raw = input(" > ").strip()
except (EOFError, KeyboardInterrupt):
console.print()
_print_cancelled(question)
return None
value = raw or default
return value
def confirm(question: str, default: bool = True) -> bool:
"""Yes/No selection block. Returns True for yes, False for no or cancel.
Блок выбора Да/Нет. Возвращает True для да, False для нет или отмены.
"""
yes, no = "Да", "Нет"
choice = select(question, [yes, no], default=yes if default else no)
return choice == yes
+11
View File
@@ -0,0 +1,11 @@
build:
base-paths:
- src
list:
base-paths:
- src
test:
base-paths:
- src
+16
View File
@@ -0,0 +1,16 @@
FROM squidfunk/mkdocs-material
RUN apk add --no-cache \
cairo \
pango \
gdk-pixbuf \
libffi \
fontconfig \
ttf-dejavu \
gcc \
g++ \
musl-dev \
python3-dev \
&& pip install \
mkdocs-static-i18n==1.3.1 \
mkdocs-to-pdf \
&& apk del --no-cache gcc g++ musl-dev python3-dev
+16
View File
@@ -0,0 +1,16 @@
/* Центрирование изображений */
.md-content img {
display: block;
margin: 1em auto;
}
/* Центрирование таблиц */
.md-typeset table {
display: table;
margin: 1em auto;
}
/* Скрываем встроенную кнопку PDF от плагина to-pdf */
a.md-header-nav__button.md-icon[href$=".pdf"] {
display: none !important;
}
+32
View File
@@ -0,0 +1,32 @@
document.addEventListener("DOMContentLoaded", function () {
const siteRoot = document.querySelector('meta[name="site-root"]')?.content ?? "";
const isEnglish = document.documentElement.lang.toLowerCase().startsWith("en");
const btn = document.createElement("a");
btn.href = siteRoot + "/pdf/documentation.pdf";
btn.download = "lwc-documentation.pdf";
btn.title = isEnglish
? "Download all documentation as PDF"
: "Скачать всю документацию в PDF";
btn.style.cssText = [
"position: fixed",
"bottom: 80px",
"right: 24px",
"z-index: 9999",
"background: var(--md-primary-fg-color, #1976d2)",
"color: #fff",
"padding: 12px 18px",
"border-radius: 24px",
"text-decoration: none",
"font-weight: 600",
"font-size: 14px",
"box-shadow: 0 3px 10px rgba(0,0,0,0.25)",
"display: flex",
"align-items: center",
"gap: 8px",
"transition: opacity .2s",
].join(";");
btn.innerHTML = isEnglish ? "&#128196; Download PDF" : "&#128196; Скачать PDF";
btn.onmouseenter = () => (btn.style.opacity = "0.85");
btn.onmouseleave = () => (btn.style.opacity = "1");
document.body.appendChild(btn);
});
@@ -0,0 +1,169 @@
# cobot CLI commands
`cobot` is the single entry point for managing the entire project. Use it for operations involving the robot, simulator, Docker containers, and documentation.
## Help
```bash
cobot -h
```
The help output is divided into four command groups:
- **Setup commands** — system configuration;
- **Run commands** — starting the project;
- **Build commands** — building ROS 2;
- **Management commands** — package management.
Some commands have their own subcommands. For example:
```bash
cobot doc-setup rebuild # rebuild subcommand of doc-setup
cobot doc-setup --help # help for a command's subcommands
```
---
## Setup commands
Commands for initial and repeated system setup.
### `cobot setup`
First-run setup wizard. It guides you through three steps:
1. Configure the documentation server.
2. Configure robot parameters in `cobot-setting.yaml`: IP address, FRI port, and tool.
3. Select a build environment: native ROS 2 Jazzy or a Docker image.
```bash
cobot setup
```
Use this command for the first installation instead of running each setup command manually.
---
### `cobot local-setup`
Installs ROS 2 Jazzy locally without Docker: downloads dependencies with `rosdep` and builds the workspace with `colcon`.
```bash
cobot local-setup
```
!!! note
After the command finishes, run `source ~/.bashrc` or open a new terminal.
---
### `cobot docker-setup`
Builds or downloads the Docker images used to run the project in isolation. Two options are available:
- **Build from the Dockerfile** — slower, but produces an up-to-date image;
- **Download a prebuilt image** — faster, using a published image.
```bash
cobot docker-setup
```
---
### `cobot doc-setup`
Deploys a local MkDocs documentation server containing a full copy of the [online documentation](https://daniel-robotics.gitverse.site/lightweight-cobot/).
```bash
cobot doc-setup # start/build the documentation
cobot doc-setup rebuild # rebuild the documentation image
```
After startup, the documentation is available at `http://localhost:8000`.
---
### `cobot robot-setup`
Interactive wizard for configuring `cobot-setting.yaml`. It asks for the robot IP address, FRI port, active tool, and other parameters.
```bash
cobot robot-setup
```
!!! tip
Use this command to change the configuration. It validates the entered values and prevents YAML syntax errors. See [System configuration](configuration.md) for parameter details.
---
## Run commands
### `cobot run`
Starts the full stack: hardware interface, MoveIt 2, RViz, and optional components such as Foxglove and the REST API. At startup, it asks you to select:
- **Docker or local execution**;
- **Webots simulation or the physical robot**.
```bash
cobot run # select the mode interactively
cobot run --simulate # force simulation mode
```
---
## Build commands
### `cobot rebuild`
Rebuilds the ROS 2 workspace with `colcon`. Use it after changing package source code.
```bash
cobot rebuild
```
!!! note
This command is available only for a local installation, not Docker. It is equivalent to `colcon build --mixin release`.
---
### `cobot clean`
Removes generated build directories. It prompts you to select which directories to remove:
- `build/` — compilation artifacts;
- `install/` — installed package files;
- `log/` — build logs.
```bash
cobot clean
```
---
## Management commands
### `cobot update`
Downloads the latest project version from GitVerse and reinstalls the `cobot` CLI.
```bash
cobot update
```
---
### `cobot delete`
Removes project components from the system. It lets you remove only the project, the Docker images and containers, or ROS 2 as well.
```bash
cobot delete
```
!!! danger
This operation is irreversible. Removed files and Docker images must be installed again.
---
**Robot control:** [Control via the REST API](control/rest-api.md)
@@ -0,0 +1,169 @@
# CLI-команды cobot
`cobot` — единая точка входа для управления всем проектом. Все операции с роботом, симулятором, Docker-контейнерами и документацией выполняются через эту команду.
## Справка
```bash
cobot -h
```
Вывод справки разделён на 4 группы команд:
- **Setup commands** — настройка системы
- **Run commands** — запуск проекта
- **Build commands** — сборка ROS 2
- **Management commands** — управление пакетом
Некоторые команды имеют собственные подкоманды. Пример:
```bash
cobot doc-setup rebuild # подкоманда rebuild для doc-setup
cobot doc-setup --help # справка по подкомандам конкретной команды
```
---
## Setup commands
Команды первичной и повторной настройки системы.
### `cobot setup`
Мастер-команда первого запуска. Проводит через три шага:
1. Настройка сервера документации
2. Параметры робота (`cobot-setting.yaml`) — IP, порт FRI, инструмент
3. Выбор среды сборки: ROS2 Jazzy нативно или Docker-образ
```bash
cobot setup
```
Используйте эту команду при первой установке вместо ручного запуска каждой setup-команды.
---
### `cobot local-setup`
Локальная установка ROS 2 Jazzy без Docker: скачивает зависимости через `rosdep`, собирает workspace через `colcon`.
```bash
cobot local-setup
```
!!! note
После выполнения обязательно выполните `source ~/.bashrc` или откройте новый терминал.
---
### `cobot docker-setup`
Сборка или скачивание готовых Docker-образов для запуска проекта в изоляции. Доступны два варианта:
- **Сборка из Dockerfile** — дольше, но даёт актуальную версию
- **Скачивание готового образа** — быстрее, использует pre-built образ
```bash
cobot docker-setup
```
---
### `cobot doc-setup`
Разворачивает локальный MkDocs-сервер документации — полную копию [онлайн-документации](https://daniel-robotics.gitverse.site/lightweight-cobot/).
```bash
cobot doc-setup # запустить / собрать документацию
cobot doc-setup rebuild # пересобрать документацию
```
После запуска документация будет доступна по адресу `http://localhost:8000`.
---
### `cobot robot-setup`
Интерактивный мастер настройки файла `cobot-setting.yaml`. Запрашивает IP-адрес робота, порт FRI, активный инструмент и другие параметры.
```bash
cobot robot-setup
```
!!! tip
Используйте именно эту команду для изменения конфигурации — она валидирует введённые значения и исключает синтаксические ошибки. Подробнее о параметрах — в разделе [Конфигурация системы](configuration.md).
---
## Run commands
### `cobot run`
Запускает весь стек: hardware interface, MoveIt 2, RViz и опциональные компоненты (Foxglove, REST API). При запуске предлагает выбор:
- **Docker или локально**
- **Симулятор (Webots) или реальный робот**
```bash
cobot run # интерактивный выбор режима
cobot run --simulate # принудительно запустить симулятор
```
---
## Build commands
### `cobot rebuild`
Пересборка ROS 2 workspace через `colcon`. Используется при изменении исходного кода пакетов.
```bash
cobot rebuild
```
!!! note
Работает только для локальной установки (не Docker). Эквивалент `colcon build --mixin release`.
---
### `cobot clean`
Удаляет сгенерированные папки сборки. Предлагает выбор, какие именно удалить:
- `build/` — артефакты компиляции
- `install/` — установленные файлы пакетов
- `log/` — логи сборки
```bash
cobot clean
```
---
## Management commands
### `cobot update`
Скачивает последнюю версию проекта с GitVerse и переустанавливает CLI `cobot`.
```bash
cobot update
```
---
### `cobot delete`
Удаляет компоненты проекта с системы. Предложит выбор: удалить только проект, Docker-образы и контейнеры, или также ROS 2.
```bash
cobot delete
```
!!! danger
Операция необратима. Удалённые файлы и Docker-образы потребуют повторной установки.
---
**Управление роботом:** [Управление через REST API](control/rest-api.md)
@@ -0,0 +1,15 @@
# System architecture
!!! info "Work in progress"
A detailed description of the system architecture is being prepared.
LWC is built as a set of interconnected ROS 2 packages. Key components:
- **iiwa_bringup** — launch files and the entry point for starting the system
- **iiwa_controller** — hardware interface connecting to the KUKA controller over FRI
- **iiwa_planning** — MoveIt 2-based motion planning
- **iiwa_web** — REST API and MCP server for external control
- **iiwa_description** — URDF robot description and Webots worlds
- **iiwa_config** — configuration files for MoveIt, controllers, and cameras
- **iiwa_utils** — helper Python utilities and configuration loading
- **iiwa_msgs** — custom ROS 2 message types (action and srv)
@@ -0,0 +1,15 @@
# Архитектура системы
!!! info "Раздел в разработке"
Подробное описание архитектуры системы готовится.
Система LWC построена как набор взаимосвязанных ROS 2 пакетов. Ключевые компоненты:
- **iiwa_bringup** — launch-файлы, точка входа для запуска всей системы
- **iiwa_controller** — hardware interface, реализует связь с контроллером KUKA по протоколу FRI
- **iiwa_planning** — планирование движений на базе MoveIt 2
- **iiwa_web** — REST API и MCP-сервер для внешнего управления
- **iiwa_description** — URDF-описание робота и миры Webots
- **iiwa_config** — все конфигурационные файлы (MoveIt, контроллеры, камеры)
- **iiwa_utils** — вспомогательные Python-утилиты, загрузка конфигов
- **iiwa_msgs** — кастомные ROS 2 типы сообщений (action, srv)
@@ -0,0 +1,23 @@
# FRI protocol
!!! info "Work in progress"
A detailed description of the FRI protocol is being prepared.
**FRI (Fast Robot Interface)** is a UDP protocol for low-level real-time control of a KUKA robot. It runs over Ethernet and provides a deterministic data exchange cycle between an external PC and the KUKA controller.
## Main characteristics
- **Transport:** UDP (no delivery guarantee, which is important for real-time operation)
- **Cycle period:** 5 ms (200 Hz) or 10 ms (100 Hz), configured in `cobot-setting.yaml``robot.fri_cycle_ms`
- **Control modes:** position, torque, and impedance
## Network requirements
!!! warning "Important: a 5 ms cycle requires KONI"
A **5 ms (200 Hz)** cycle requires the **KONI** port (KUKA Optional Network Interface).
The KLI port supports only a 10 ms cycle. Set `fri_cycle_ms: 10` when using KLI.
| Port | Minimum cycle | Purpose |
|---|---|---|
| **KONI** | 5 ms | High-frequency control, recommended for FRI |
| **KLI** | 10 ms | Standard control and programming |
@@ -0,0 +1,24 @@
# FRI-протокол
!!! info "Раздел в разработке"
Подробное описание FRI-протокола готовится.
**FRI (Fast Robot Interface)** — UDP-протокол низкоуровневого управления роботом KUKA в реальном времени. Работает поверх Ethernet и обеспечивает детерминированный цикл обмена данными между внешним ПК и контроллером KUKA.
## Основные характеристики
- **Транспорт:** UDP (без гарантии доставки — критично для RT)
- **Период цикла:** 5 мс (200 Гц) или 10 мс (100 Гц), задаётся в `cobot-setting.yaml``robot.fri_cycle_ms`
- **Режимы управления:** позиция, момент (крутящий момент), импеданс
## Требования к сетевому подключению
!!! warning "Важно: цикл 5 мс требует KONI"
Для работы с периодом цикла **5 мс (200 Гц)** необходимо подключение через порт **KONI**
(KUKA Optional Network Interface). Порт KLI поддерживает только 10 мс цикл.
При использовании KLI устанавливайте `fri_cycle_ms: 10`.
| Порт | Мин. цикл | Назначение |
|---|---|---|
| **KONI** | 5 мс | Высокочастотное управление, рекомендуется для FRI |
| **KLI** | 10 мс | Стандартное управление и программирование |
@@ -0,0 +1,23 @@
# Motion planning
!!! info "Work in progress"
A detailed description of motion planning is being prepared.
LWC uses **MoveIt 2**, the standard motion-planning framework for ROS 2.
## Key concepts
- **Planning group** (`iiwa_arm`) — the set of joints for which a plan is generated. Defined in SRDF.
- **Planner** — the trajectory-generation algorithm. Available planners:
- `ompl` — general-purpose probabilistic planner (default)
- `pilz_industrial_motion_planner` — deterministic PTP, LIN, and CIRC trajectories
- **TCP (Tool Center Point)** — the tool point for which the target pose is specified. Set in `cobot-setting.yaml``planning.pose_link`.
- **Reference frame** — the coordinate system for targets. Default: `base_link`.
## `cobot-setting.yaml` settings
| Parameter | Description |
|---|---|
| `planning.default_planner` | Default planner: `ompl` or `pilz_industrial_motion_planner` |
| `planning.planning_attempts` | Number of attempts after a planning failure |
| `planning.pose_link` | TCP link for Cartesian targets |
@@ -0,0 +1,23 @@
# Планирование движений
!!! info "Раздел в разработке"
Подробное описание планирования движений готовится.
LWC использует **MoveIt 2** — стандартный фреймворк планирования движений для ROS 2.
## Основные понятия
- **Группа планирования** (`iiwa_arm`) — набор суставов, для которых строится план. Задаётся в SRDF.
- **Планировщик** — алгоритм построения траектории. Доступны:
- `ompl` — универсальный вероятностный планировщик (по умолчанию)
- `pilz_industrial_motion_planner` — детерминированные траектории типа PTP, LIN, CIRC
- **TCP (Tool Center Point)** — точка инструмента, для которой задаётся целевая поза. Настраивается в `cobot-setting.yaml``planning.pose_link`
- **Система отсчёта** — координатная система целей. По умолчанию: `base_link`
## Настройки в `cobot-setting.yaml`
| Параметр | Описание |
|---|---|
| `planning.default_planner` | Планировщик по умолчанию: `ompl` или `pilz_industrial_motion_planner` |
| `planning.planning_attempts` | Число попыток при неудаче планирования |
| `planning.pose_link` | TCP-линк для декартовых целей |
@@ -0,0 +1,18 @@
# Simulation (Webots)
!!! info "Work in progress"
A detailed simulator guide is being prepared.
**Webots** is an open-source robot simulator. LWC uses it as a digital twin of the KUKA LBR IIWA 7, allowing control algorithms to be developed and debugged without a physical robot.
## Key features
- The simulator uses the same ROS 2 topics and interfaces as the real robot.
- The simulation world is set in `cobot-setting.yaml``digital_twin.webots.world`.
- Start it with `cobot run --simulate`.
## Differences from the real robot
- There are no real safety constraints, so motion can be faster.
- Physics is approximate, including inertia, friction, and elasticity.
- FRI is not used; communication goes through the Webots ROS 2 driver.
@@ -0,0 +1,18 @@
# Симуляция (Webots)
!!! info "Раздел в разработке"
Подробное описание работы в симуляторе готовится.
**Webots** — симулятор роботов с открытым исходным кодом. В LWC используется как цифровой двойник робота KUKA LBR IIWA 7: позволяет разрабатывать и отлаживать алгоритмы управления без доступа к физическому роботу.
## Ключевые особенности
- Симулятор использует те же ROS 2 топики и интерфейсы, что и реальный робот
- Мир симуляции задаётся в `cobot-setting.yaml``digital_twin.webots.world`
- Для запуска: `cobot run --simulate`
## Отличия от реального робота
- Нет ограничений по безопасности (можно двигаться быстрее)
- Физика не идеальна — инерция, трение и упругость приближённые
- FRI-протокол не задействован — связь идёт через Webots-драйвер ROS 2
@@ -0,0 +1,176 @@
# System configuration
## Main configuration file
All system parameters are stored in a single file: **`cobot-setting.yaml`** in the project root. It is the single source of truth for the robot IP address, ports, configuration paths, planner settings, and web server settings.
!!! info "No manual configuration is needed before installation"
When you run `cobot setup`, the wizard offers to configure this file automatically in **step 2**. Return to this section when you want to change parameters after the initial installation.
!!! danger "Do not edit the file manually"
Use only `cobot robot-setup`. The interactive wizard validates values and prevents syntax errors. Editing the YAML manually may cause parsing errors and prevent the system from starting.
```bash
cobot robot-setup
```
---
## `robot` section — robot parameters
Controls the connection to the physical KUKA controller through FRI.
```yaml
robot:
name: "iiwa7"
ip: "192.170.10.2"
port: 30200
fri_cycle_ms: 10
joint_position_tau: 0.04
joint_velocity_tau: 0.01
active_controller: "jtc"
description: pkg://iiwa_description/urdf/iiwa7.urdf.xacro
```
| Parameter | Description | Recommendation |
|---|---|---|
| `name` | Robot model | Do not change: `iiwa7` |
| `ip` | KUKA controller IP address | **Change** to the actual controller address |
| `port` | FRI UDP port | Default: `30200`; change only if the port conflicts |
| `fri_cycle_ms` | FRI cycle: `5` ms = 200 Hz, `10` ms = 100 Hz | Use `10` for stable operation or `5` for high-precision tasks |
| `joint_position_tau` | Position EMA filter [s], smoothing commands before transmission | Decrease for a faster response; increase if vibration occurs |
| `joint_velocity_tau` | Velocity EMA filter [s], removing finite-difference spikes | Tune in the same way as `joint_position_tau` |
| `active_controller` | Control mode: `jtc` (MoveIt / JointTrajectory) or `forward` (direct control) | Use `jtc` for most tasks |
| `description` | Path to the robot URDF | Do not change |
---
## `digital_twin` section — simulator
Configures the Webots environment and RViz visualization.
```yaml
digital_twin:
webots:
world: pkg://iiwa_description/worlds/iiwa.wbt
transform: "-0.25 0 0.79"
rotation: "0 0 1 0"
controller_timer: "50"
cameras:
- pkg://iiwa_config/config/cameras/d455_top.yaml
rviz:
config: pkg://iiwa_config/config/rviz/rviz_moveit.rviz
```
| Parameter | Description |
|---|---|
| `webots.world` | Path to the simulator `.wbt` world |
| `webots.transform` | Robot base offset in the world `[x y z]`, in meters |
| `webots.rotation` | Base orientation `[x y z angle]`, in radians |
| `webots.cameras` | List of YAML configurations for connected cameras |
| `rviz.config` | Path to the RViz configuration |
---
## `tool` section — active tool
Specifies which gripper or tool is attached to the robot.
```yaml
tool:
active: "patron"
```
| Value | Description |
|---|---|
| `none` | No tool |
| `patron` | Patron chuck/gripper |
Available tools are defined in `src/iiwa_config/config/tools.yaml`. To add a tool, describe it there and then set its name in `tool.active`.
---
## `planning` section — motion planning
Configures MoveIt 2 and the trajectory planner.
```yaml
planning:
pose_link: "tcp"
planning_group: "iiwa_arm"
default_frame: "base_link"
default_planner: "ompl"
planning_attempts: 3
```
| Parameter | Description | Recommendation |
|---|---|---|
| `pose_link` | TCP link used for Cartesian targets | Must match the URDF frame; do not change without updating the URDF |
| `planning_group` | Planning group from the SRDF | Do not change: `iiwa_arm` |
| `default_frame` | Default reference frame | Do not change: `base_link` |
| `default_planner` | Planner: `ompl` or `pilz_industrial_motion_planner` | `ompl` is general purpose; `pilz` produces predictable trajectories |
| `planning_attempts` | Number of planning attempts after failure | Increase for difficult trajectories |
---
## `web` section — REST API and MCP server
Configures the FastAPI server used to control the robot over HTTP and MCP for AI-agent integration.
```yaml
web:
enabled: true
host: "0.0.0.0"
port: 8007
endpoints: pkg://iiwa_config/config/api_endpoints.yaml
joint_limits: pkg://iiwa_config/config/moveit/joint_limits.yaml
```
| Parameter | Description |
|---|---|
| `enabled` | Enable (`true`) or disable (`false`) the web server |
| `host` | Listening address: `0.0.0.0` for all interfaces or `127.0.0.1` for local access only |
| `port` | HTTP API port; default: `8007` |
| `endpoints` | Path to the REST endpoint description |
| `joint_limits` | Path to joint limits used for command validation |
After startup, the REST API is available at `http://<host>:8007`, and MCP is available at `/mcp`.
---
## `foxglove` section — Foxglove Studio monitoring
[Foxglove Studio](https://foxglove.dev/) visualizes and monitors ROS 2 topics in real time.
```yaml
foxglove:
enabled: true
port: 8765
debug: false
address: 0.0.0.0
```
| Parameter | Description |
|---|---|
| `enabled` | Enable or disable Foxglove Bridge |
| `port` | WebSocket port used by Foxglove Studio; default: `8765` |
| `debug` | Detailed logging for the bridge process |
| `address` | WebSocket listening address |
The remaining parameters (`tls`, `topic_whitelist`, `min_qos_depth`, and others) are intended for advanced configuration and normally do not need to be changed.
---
## What to change and what to keep
| | Parameter | Action |
|---|---|---|
| ✅ | `robot.ip` | **Must be changed** to the controller IP address |
| ✅ | `robot.fri_cycle_ms` | Select `10` (standard) or `5` (high frequency) |
| ✅ | `tool.active` | Set the active tool |
| ✅ | `web.enabled` | Set to `false` if the web interface is not needed |
| ⚠️ | `robot.active_controller` | Change only when intentionally switching the control mode |
| ⚠️ | `planning.*` | Change only when another planner or other parameters are required |
| ❌ | `robot.description` | Do not change; this is the URDF path |
| ❌ | `controller.moveit.*` | Do not change; these are package-internal MoveIt configuration paths |
| ❌ | `digital_twin.webots.world` | Do not change unless you understand the Webots world structure |
@@ -0,0 +1,178 @@
# Конфигурация системы
## Главный конфигурационный файл
Все параметры системы хранятся в одном файле — **`cobot-setting.yaml`** в корне проекта.
Это единственный источник истины для IP-адреса робота, портов, путей к конфигам, настроек планировщика и веб-сервера.
!!! info "Не нужно настраивать вручную до установки"
При выполнении `cobot setup` мастер автоматически предложит настроить этот файл на **шаге 2** — вам не нужно делать это заранее.
Возвращайтесь к этому разделу когда захотите изменить параметры после первоначальной установки.
!!! danger "Не редактируйте файл вручную"
Используйте только команду `cobot robot-setup` — интерактивный мастер валидирует значения и не допускает синтаксических ошибок. Ручное редактирование YAML может привести к ошибкам парсинга и невозможности запуска системы.
```bash
cobot robot-setup
```
---
## Блок `robot` — параметры робота
Отвечает за соединение с физическим контроллером KUKA по протоколу FRI.
```yaml
robot:
name: "iiwa7"
ip: "192.170.10.2"
port: 30200
fri_cycle_ms: 10
joint_position_tau: 0.04
joint_velocity_tau: 0.01
active_controller: "jtc"
description: pkg://iiwa_description/urdf/iiwa7.urdf.xacro
```
| Параметр | Описание | Рекомендации |
|---|---|---|
| `name` | Модель робота | Не менять — `iiwa7` |
| `ip` | IP-адрес контроллера KUKA | **Изменить** на реальный IP вашего контроллера |
| `port` | UDP-порт FRI | По умолчанию `30200` — менять только при конфликте портов |
| `fri_cycle_ms` | Период цикла FRI: `5` мс = 200 Гц, `10` мс = 100 Гц | `10` для стабильной работы, `5` для высокоточных задач |
| `joint_position_tau` | EMA-фильтр позиций [с] — сглаживает команды перед отправкой | Уменьшать для более быстрой реакции, увеличивать при вибрациях |
| `joint_velocity_tau` | EMA-фильтр скорости [с] — убирает выбросы конечных разностей | Аналогично `joint_position_tau` |
| `active_controller` | Режим управления: `jtc` (MoveIt / JointTrajectory) или `forward` (прямое управление) | `jtc` для большинства задач |
| `description` | Путь к URDF-описанию робота | Не менять |
---
## Блок `digital_twin` — симулятор
Настройки виртуальной среды Webots и визуализации в RViz.
```yaml
digital_twin:
webots:
world: pkg://iiwa_description/worlds/iiwa.wbt
transform: "-0.25 0 0.79"
rotation: "0 0 1 0"
controller_timer: "50"
cameras:
- pkg://iiwa_config/config/cameras/d455_top.yaml
rviz:
config: pkg://iiwa_config/config/rviz/rviz_moveit.rviz
```
| Параметр | Описание |
|---|---|
| `webots.world` | Путь к `.wbt`-миру симулятора |
| `webots.transform` | Смещение базы робота в мире `[x y z]` в метрах |
| `webots.rotation` | Ориентация базы `[x y z угол]` в радианах |
| `webots.cameras` | Список YAML-конфигов подключённых камер |
| `rviz.config` | Путь к конфигурации RViz |
---
## Блок `tool` — активный инструмент
Указывает, какой захват или инструмент закреплён на роботе.
```yaml
tool:
active: "patron"
```
| Значение | Описание |
|---|---|
| `none` | Без инструмента |
| `patron` | Захват «Patron» (патрон) |
Список доступных инструментов находится в файле `src/iiwa_config/config/tools.yaml`. Для добавления нового инструмента необходимо описать его там, после чего указать имя в `tool.active`.
---
## Блок `planning` — планирование движений
Параметры MoveIt 2 и конфигурации траекторного планировщика.
```yaml
planning:
pose_link: "tcp"
planning_group: "iiwa_arm"
default_frame: "base_link"
default_planner: "ompl"
planning_attempts: 3
```
| Параметр | Описание | Рекомендации |
|---|---|---|
| `pose_link` | TCP-линк для декартовых целей | Соответствует фрейму в URDF — не менять без изменения URDF |
| `planning_group` | Группа планирования из SRDF | Не менять — `iiwa_arm` |
| `default_frame` | Система отсчёта по умолчанию | Не менять — `base_link` |
| `default_planner` | Планировщик: `ompl`, `pilz_industrial_motion_planner` | `ompl` — универсальный; `pilz` — для предсказуемых траекторий |
| `planning_attempts` | Число попыток планирования при неудаче | Увеличивать при сложных траекториях |
---
## Блок `web` — REST API и MCP-сервер
FastAPI-сервер для управления роботом через HTTP и MCP (интеграция с AI-агентами).
```yaml
web:
enabled: true
host: "0.0.0.0"
port: 8007
endpoints: pkg://iiwa_config/config/api_endpoints.yaml
joint_limits: pkg://iiwa_config/config/moveit/joint_limits.yaml
```
| Параметр | Описание |
|---|---|
| `enabled` | Включить (`true`) или отключить (`false`) веб-сервер |
| `host` | Адрес прослушивания: `0.0.0.0` — все интерфейсы, `127.0.0.1` — только локально |
| `port` | Порт HTTP API (по умолчанию `8007`) |
| `endpoints` | Путь к описанию REST-эндпоинтов |
| `joint_limits` | Путь к файлу ограничений суставов для валидации команд |
После запуска REST API доступен по адресу `http://<host>:8007`, MCP — по пути `/mcp`.
---
## Блок `foxglove` — мониторинг через Foxglove Studio
[Foxglove Studio](https://foxglove.dev/) — инструмент визуализации и мониторинга ROS 2 топиков в реальном времени.
```yaml
foxglove:
enabled: true
port: 8765
debug: false
address: 0.0.0.0
```
| Параметр | Описание |
|---|---|
| `enabled` | Включить или отключить Foxglove Bridge |
| `port` | WebSocket-порт для подключения Foxglove Studio (по умолчанию `8765`) |
| `debug` | Подробное логирование bridge-процесса |
| `address` | Адрес прослушивания WebSocket |
Остальные параметры блока (`tls`, `topic_whitelist`, `min_qos_depth` и др.) относятся к продвинутой конфигурации и в большинстве случаев менять их не требуется.
---
## Что менять, что оставить
| | Параметр | Действие |
|---|---|---|
| ✅ | `robot.ip` | **Обязательно изменить** на IP вашего контроллера |
| ✅ | `robot.fri_cycle_ms` | Выбрать `10` (стандарт) или `5` (высокая частота) |
| ✅ | `tool.active` | Указать активный инструмент |
| ✅ | `web.enabled` | Выключить (`false`), если веб-интерфейс не нужен |
| ⚠️ | `robot.active_controller` | Менять только при намеренном переключении режима управления |
| ⚠️ | `planning.*` | Менять при необходимости другого планировщика или параметров |
| ❌ | `robot.description` | Не трогать — путь к URDF |
| ❌ | `controller.moveit.*` | Не трогать — пути к конфигам MoveIt внутри пакетов |
| ❌ | `digital_twin.webots.world` | Не трогать без знания структуры Webots-миров |
@@ -0,0 +1,10 @@
# Control via Foxglove Studio
!!! info "Work in progress"
Detailed control and monitoring instructions for Foxglove Studio are being prepared.
[Foxglove Studio](https://foxglove.dev/home) is a tool for visualizing and monitoring ROS 2 data in real time. It connects to the running stack through a WebSocket bridge (port `8765` by default, configured in the `foxglove` section of `cobot-setting.yaml`).
## Download Foxglove Studio
Visit the [official Foxglove website](https://foxglove.dev/home) and download the application for your operating system.
@@ -0,0 +1,10 @@
# Управление через Foxglove Studio
!!! info "Раздел в разработке"
Подробная документация по управлению и мониторингу через Foxglove Studio готовится.
[Foxglove Studio](https://foxglove.dev/home) — инструмент визуализации и мониторинга ROS2-данных в реальном времени. Подключается к запущенному стеку через WebSocket-bridge (порт `8765` по умолчанию, настраивается в `cobot-setting.yaml` → блок `foxglove`).
## Скачать Foxglove Studio
Перейдите на [официальный сайт Foxglove](https://foxglove.dev/home) и скачайте приложение для своей ОС.
@@ -0,0 +1,651 @@
# Control via the REST API
The REST API reads robot state and sends commands over HTTP. It is intended for application scripts, integrations with other systems, and quick checks through Swagger UI.
Motion requests are synchronous: the response is returned after planning and execution finish or an internal timeout occurs. The API has no command queue. Wait for the current request to finish before sending another one.
!!! warning "Safety"
The REST API does not replace the standard KUKA safety system or emergency stop. Before the first run on a physical robot, check the Sunrise program, safety zones, tool, and workspace. Begin using the API in simulation.
## Starting and accessing the server
The web server starts with the robot stack when the **web** section is enabled in the root **cobot-setting.yaml** file:
~~~ yaml
web:
enabled: true
host: 0.0.0.0
port: 8007
endpoints: pkg://iiwa_config/config/api_endpoints.yaml
joint_limits: pkg://iiwa_config/config/moveit/joint_limits.yaml
~~~
After starting the stack with **cobot run**, the server is available at **http://server-address:8007**. Swagger UI shows the actual request schema and lets you run individual tests:
- locally: [http://localhost:8007/docs](http://localhost:8007/docs);
- from another computer: `http://server-address:8007/docs`;
- OpenAPI JSON schema: `http://server-address:8007/openapi.json`.
There is no separate health-check endpoint. If Swagger UI opens, the HTTP server is running. Readiness of ROS components is checked when a specific endpoint is called.
By default, the server listens on all network interfaces and does not use authentication. Do not expose port 8007 to an untrusted network. For local access, set **host: 127.0.0.1**. For remote access, restrict the network with firewall rules or a VPN.
## Preparing the examples
The tabs on this page are synchronized. Select a language once and the same tab will be selected in subsequent examples.
=== "curl"
~~~ bash
HOST=http://localhost:8007
~~~
=== "Python"
~~~ python
import httpx
HOST = "http://localhost:8007"
T_READ = 10
T_MOVE = 60
~~~
=== "MATLAB"
~~~ matlab
HOST = 'http://localhost:8007';
T_READ = 10;
T_MOVE = 60;
readOpts = weboptions('Timeout', T_READ);
moveOpts = weboptions('MediaType', 'application/json', 'Timeout', T_MOVE);
~~~
MATLAB uses the built-in `webwrite` function for JSON requests. Uploading CSV and JSON files requires `matlab.net.http`, available in modern desktop versions of MATLAB.
## API overview
| Method | Endpoint | Purpose |
|---|---|---|
| GET | /robot/joint_states | Current joint state |
| GET | /robot/pose | TCP pose relative to base_link |
| GET | /robot/positions | Named positions from the SRDF |
| POST | /robot/move/named | Move to a named position |
| POST | /robot/move/pose | Cartesian TCP motion |
| POST | /robot/move/joints | Move the seven joints to specified angles |
| POST | /trajectory/send | Publish a trajectory from JSON |
| POST | /trajectory/send_csv | Upload and publish a trajectory from CSV |
| GET | /trajectory/logs | Latest trajectory module log entries |
| POST | /sequences/start | Start a sequence from a JSON file |
| GET | /sequences/status | Running sequence status |
| GET | /sequences/logs | Sequence process output |
| POST | /stop | Stop API commands and the planner |
## Reading robot state
### Joint state
GET **/robot/joint_states** returns the latest message from the ROS **/joint_states** topic. The **position**, **velocity**, and **effort** fields use the same order as the **name** array. Angles in **position** are in radians.
=== "curl"
~~~ bash
curl -sS --max-time 10 $HOST/robot/joint_states | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.get(f"{HOST}/robot/joint_states", timeout=T_READ)
response.raise_for_status()
state = response.json()
print(dict(zip(state["name"], state["position"])))
~~~
=== "MATLAB"
~~~ matlab
jointState = webread([HOST '/robot/joint_states'], readOpts);
disp(jointState.position)
~~~
Typical response:
~~~ json
{
"name": ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6", "joint7"],
"position": [0.0, 0.0, 0.0, -1.57, 0.0, 1.57, 0.0],
"velocity": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
"effort": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
}
~~~
If no controller messages arrive within two seconds, the API returns 503. This usually means that the controller or robot has not started yet.
### TCP pose
GET **/robot/pose** computes forward kinematics with the MoveIt **/compute_fk** service. Position is specified in meters. Orientation is returned as both a quaternion and Euler angles:
- **euler_rad** — radians;
- **euler_deg** — degrees;
- **A, B, C** follow the KUKA ABC convention: rotation around Z, then Y, then X.
=== "curl"
~~~ bash
curl -sS --max-time 10 $HOST/robot/pose | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.get(f"{HOST}/robot/pose", timeout=T_READ)
response.raise_for_status()
pose = response.json()
print(pose["position"])
~~~
=== "MATLAB"
~~~ matlab
pose = webread([HOST '/robot/pose'], readOpts);
fprintf('TCP: x=%.3f, y=%.3f, z=%.3f m\n', ...
pose.position.x, pose.position.y, pose.position.z);
fprintf('ABC: A=%.1f, B=%.1f, C=%.1f deg\n', ...
pose.orientation.euler_deg.a, ...
pose.orientation.euler_deg.b, ...
pose.orientation.euler_deg.c);
~~~
This endpoint depends on both **/joint_states** and MoveIt. If either is unavailable, it returns 503.
### Named positions
GET **/robot/positions** reads `group_state` positions from the SRDF. The list is not hardcoded in the API; it reflects the current robot configuration. The standard configuration includes **home**, **work**, and **transport**.
=== "curl"
~~~ bash
curl -sS $HOST/robot/positions | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.get(f"{HOST}/robot/positions", timeout=T_READ)
response.raise_for_status()
for position in response.json():
print(position["name"], "—", position["description"])
~~~
=== "MATLAB"
~~~ matlab
namedPositions = webread([HOST '/robot/positions'], readOpts);
for i = 1:numel(namedPositions)
fprintf('%s — %s\n', namedPositions(i).name, ...
namedPositions(i).description);
end
~~~
Call this endpoint before **/robot/move/named** to obtain the exact name, planning group, and target joint angles.
## Motion commands
All three commands below use MoveIt. A response has this form:
~~~ json
{"success": true, "message": "Motion completed successfully"}
~~~
**success: false** means that the planner could not plan or execute the trajectory. The HTTP status may still be 200, so application code must check both the HTTP status and the **success** field.
### Moving to a named position
POST **/robot/move/named** moves the manipulator to a position from the SRDF.
| Field | Required | Value |
|---|---:|---|
| name | yes | Position name from /robot/positions |
| speed | no | Speed scale from 0.01 to 1.0; default: 0.1 |
| accel_scale | no | Acceleration scale from 0 to 1.0; 0 uses speed |
=== "curl"
~~~ bash
curl -sS --max-time 60 -X POST $HOST/robot/move/named \
-H "Content-Type: application/json" \
-d '{"name": "home", "speed": 0.1, "accel_scale": 0.0}'
~~~
=== "Python"
~~~ python
response = httpx.post(
f"{HOST}/robot/move/named",
json={"name": "home", "speed": 0.1, "accel_scale": 0.0},
timeout=T_MOVE,
)
response.raise_for_status()
result = response.json()
if not result["success"]:
raise RuntimeError(result["message"])
~~~
=== "MATLAB"
~~~ matlab
body = struct('name', 'home', 'speed', 0.1, 'accel_scale', 0.0);
reply = webwrite([HOST '/robot/move/named'], body, moveOpts);
assert(reply.success, reply.message)
~~~
### Cartesian TCP motion
POST **/robot/move/pose** accepts a TCP position in meters and an ABC orientation in radians. If **frame_id** is empty, the frame from the planning settings is used; in the standard configuration this is **base_link**.
| Field | Required | Value |
|---|---:|---|
| x, y, z | yes | TCP coordinates, m |
| a, b, c | no | KUKA ABC angles, rad; default: 0 |
| speed | no | Speed scale from 0.01 to 1.0; default: 0.1 |
| planner | no | ompl, ptp, lin, circ, or chomp; default: ptp |
| frame_id | no | Target pose frame; an empty string uses the default frame |
The **planner** value is converted to lowercase. PTP is suitable for transitions between points; LIN produces straight-line tool motion. CIRC is appropriate only when it is supported by the planner and target pose.
=== "curl"
~~~ bash
curl -sS --max-time 60 -X POST $HOST/robot/move/pose \
-H "Content-Type: application/json" \
-d '{
"x": 0.40, "y": 0.00, "z": 0.50,
"a": 0.0, "b": 3.14159, "c": 0.0,
"speed": 0.1, "planner": "ptp", "frame_id": ""
}'
~~~
=== "Python"
~~~ python
target = {
"x": 0.40, "y": 0.00, "z": 0.50,
"a": 0.0, "b": 3.14159, "c": 0.0,
"speed": 0.1, "planner": "ptp", "frame_id": "",
}
response = httpx.post(f"{HOST}/robot/move/pose", json=target, timeout=T_MOVE)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
body = struct( ...
'x', 0.40, 'y', 0.00, 'z', 0.50, ...
'a', 0.0, 'b', pi, 'c', 0.0, ...
'speed', 0.1, 'planner', 'ptp', 'frame_id', '');
reply = webwrite([HOST '/robot/move/pose'], body, moveOpts);
assert(reply.success, reply.message)
~~~
### Moving by joint angles
POST **/robot/move/joints** accepts exactly seven angles in J1J7 order. The API validates the number of values and the current limits from **joint_limits.yaml**.
| Joint | Allowed angle, rad |
|---|---:|
| J1 | -2.97 to 2.97 |
| J2 | -2.10 to 2.10 |
| J3 | -2.97 to 2.97 |
| J4 | -2.10 to 2.10 |
| J5 | -2.97 to 2.97 |
| J6 | -2.10 to 2.10 |
| J7 | -3.05 to 3.05 |
If the limits file changes, use Swagger UI as the reference. The table above describes the supplied configuration.
=== "curl"
~~~ bash
curl -sS --max-time 60 -X POST $HOST/robot/move/joints \
-H "Content-Type: application/json" \
-d '{"joints": [0.0, 0.5, 0.0, -1.57, 0.0, 1.57, 0.0], "speed": 0.1}'
~~~
=== "Python"
~~~ python
response = httpx.post(
f"{HOST}/robot/move/joints",
json={
"joints": [0.0, 0.5, 0.0, -1.57, 0.0, 1.57, 0.0],
"speed": 0.1,
},
timeout=T_MOVE,
)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
body = struct( ...
'joints', [0.0, 0.5, 0.0, -1.57, 0.0, 1.57, 0.0], ...
'speed', 0.1);
reply = webwrite([HOST '/robot/move/joints'], body, moveOpts);
assert(reply.success, reply.message)
~~~
## Joint trajectories
Endpoints under **/trajectory** publish a `JointTrajectory` message directly to **/iiwa_arm_controller/joint_trajectory**. A **status: sent** response confirms publication, not completion of motion or absence of controller errors. Monitor **/robot/joint_states** and inspect **/trajectory/logs** when necessary.
### JSON trajectory
POST **/trajectory/send** accepts one or more points.
| Field | Value |
|---|---|
| points | Non-empty point list |
| points[].positions | Exactly 7 J1J7 angles in radians |
| points[].time_from_start | Time from trajectory start in seconds, at least 0 |
| validate_limits | Validate joint limits; default: true |
The server does not check that time increases between points. Set increasing values yourself to make controller behavior predictable.
=== "curl"
~~~ bash
curl -sS --max-time 20 -X POST $HOST/trajectory/send \
-H "Content-Type: application/json" \
-d '{
"points": [
{"positions": [0, 0, 0, 0, 0, 0, 0], "time_from_start": 0.0},
{"positions": [0, 0.5, 0, -1.0, 0, 1.0, 0], "time_from_start": 3.0},
{"positions": [0, 0, 0, 0, 0, 0, 0], "time_from_start": 6.0}
],
"validate_limits": true
}'
~~~
=== "Python"
~~~ python
trajectory = {
"points": [
{"positions": [0.0] * 7, "time_from_start": 0.0},
{"positions": [0.0, 0.5, 0.0, -1.0, 0.0, 1.0, 0.0], "time_from_start": 3.0},
{"positions": [0.0] * 7, "time_from_start": 6.0},
],
"validate_limits": True,
}
response = httpx.post(f"{HOST}/trajectory/send", json=trajectory, timeout=T_READ)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
p1 = struct('positions', [0, 0, 0, 0, 0, 0, 0], ...
'time_from_start', 0.0);
p2 = struct('positions', [0, 0.5, 0, -1.0, 0, 1.0, 0], ...
'time_from_start', 3.0);
trajectory.points = [p1, p2];
trajectory.validate_limits = true;
opts = weboptions('MediaType', 'application/json', 'Timeout', T_READ);
reply = webwrite([HOST '/trajectory/send'], trajectory, opts);
disp(reply)
~~~
### Uploading CSV
POST **/trajectory/send_csv** accepts a CSV file in the multipart **file** field. The first row must be a header. Joint columns may be named **joint1** or **joint_1**, case-insensitively. The time column may be named **t**, **time**, or **time_from_start**. Columns may appear in any order.
Example file:
~~~ csv
joint1,joint2,joint3,joint4,joint5,joint6,joint7,t
0,0,0,0,0,0,0,0.0
0,0.5,0,-1.0,0,1.0,0,3.0
~~~
Pass **separator** and **validate_limits** in the query string, not as form fields. The default separator is a comma and limit validation is enabled.
=== "curl"
~~~ bash
curl -sS --max-time 20 -X POST \
"$HOST/trajectory/send_csv?separator=%2C&validate_limits=true" \
-F "file=@trajectory.csv;type=text/csv"
~~~
=== "Python"
~~~ python
with open("trajectory.csv", "rb") as csv_file:
response = httpx.post(
f"{HOST}/trajectory/send_csv",
params={"separator": ",", "validate_limits": True},
files={"file": ("trajectory.csv", csv_file, "text/csv")},
timeout=T_READ,
)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
import matlab.net.http.*
import matlab.net.http.io.*
uri = URI([HOST '/trajectory/send_csv?separator=%2C&validate_limits=true']);
form = MultipartFormProvider('file', FileProvider('trajectory.csv'));
request = RequestMessage('post', [], form);
httpOpts = HTTPOptions('ConnectTimeout', T_READ, 'ResponseTimeout', T_READ);
response = request.send(uri, httpOpts);
disp(response.Body.Data)
~~~
For a semicolon-delimited file, replace `%2C` with `%3B`.
### Trajectory module log
GET **/trajectory/logs?n=50** returns up to 300 latest entries. The **n** parameter must be between 1 and 300.
=== "curl"
~~~ bash
curl -sS "$HOST/trajectory/logs?n=20" | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.get(f"{HOST}/trajectory/logs", params={"n": 20}, timeout=T_READ)
response.raise_for_status()
for line in response.json()["lines"]:
print(line)
~~~
=== "MATLAB"
~~~ matlab
logs = webread([HOST '/trajectory/logs?n=20'], readOpts);
disp(logs.lines)
~~~
Use the common **POST /stop** endpoint to interrupt a trajectory. The API has no **/trajectory/stop** endpoint.
## Motion sequences
POST **/sequences/start** launches a separate `motion_sequence_runner` process. It reads the uploaded JSON file and sends `MoveToJoints` or `MoveToPose` targets in sequence.
| Form field | Default | Purpose |
|---|---:|---|
| config | — | Sequence JSON file; required |
| n_iterations | 3 | Number of repetitions; at least 1 |
| delay_between_iterations | 5.0 | Delay between iterations, s |
| bag_path | empty | rosbag output path; an empty string disables recording |
| topics | empty | Comma-separated rosbag topics; empty means all discovered topics |
| joints_action | cobot/move_to_joints | Action name for joint targets |
| pose_action | cobot/move_to_pose | Action name for Cartesian targets |
Minimal configuration:
~~~ json
{
"home": {
"joints": [0, 0, 0, -1.57, 0, 1.57, 0],
"speed": 0.1
},
"waypoints": [
{
"x": 0.6, "y": 0.1, "z": 0.55,
"a": 3.14, "b": 0.31, "c": 2.79,
"speed": 0.2, "planner": "lin"
},
{
"joints": [0.5, 0.3, 0, -1.2, 0, 1.4, 0],
"speed": 0.2
}
]
}
~~~
A point containing **joints** is treated as a joint target. Otherwise, the runner expects Cartesian fields **x**, **y**, **z**, **a**, **b**, and **c**.
### Starting a sequence
=== "curl"
~~~ bash
curl -sS --max-time 10 -X POST $HOST/sequences/start \
-F "config=@motion_sequence_config.json;type=application/json" \
-F "n_iterations=3" \
-F "delay_between_iterations=5.0"
~~~
=== "Python"
~~~ python
with open("motion_sequence_config.json", "rb") as config:
response = httpx.post(
f"{HOST}/sequences/start",
files={"config": ("motion_sequence_config.json", config, "application/json")},
data={"n_iterations": "3", "delay_between_iterations": "5.0"},
timeout=T_READ,
)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
import matlab.net.http.*
import matlab.net.http.io.*
form = MultipartFormProvider( ...
'config', FileProvider('motion_sequence_config.json'), ...
'n_iterations', '3', ...
'delay_between_iterations', '5.0');
request = RequestMessage('post', [], form);
httpOpts = HTTPOptions('ConnectTimeout', T_READ, 'ResponseTimeout', T_READ);
response = request.send(URI([HOST '/sequences/start']), httpOpts);
disp(response.Body.Data)
~~~
A **status: started** response confirms that the process started, not that the JSON is valid or that every motion succeeds. If the runner exits with an error, inspect its status and log.
### Sequence status and log
=== "curl"
~~~ bash
curl -sS $HOST/sequences/status | python3 -m json.tool
curl -sS "$HOST/sequences/logs?n=50" | python3 -m json.tool
~~~
=== "Python"
~~~ python
status = httpx.get(f"{HOST}/sequences/status", timeout=T_READ)
status.raise_for_status()
print(status.json())
logs = httpx.get(f"{HOST}/sequences/logs", params={"n": 50}, timeout=T_READ)
logs.raise_for_status()
for line in logs.json()["lines"]:
print(line)
~~~
=== "MATLAB"
~~~ matlab
status = webread([HOST '/sequences/status'], readOpts);
logs = webread([HOST '/sequences/logs?n=50'], readOpts);
disp(status)
disp(logs.lines)
~~~
Statuses:
- **idle** — no sequence has been started;
- **running** — the process is running;
- **finished** — the process has exited; the response includes **returncode**.
Only one sequence can run at a time. A second POST to **/sequences/start** while one is running returns 409. Use **POST /stop** to stop it; there is no separate **/sequences/stop** endpoint.
## Common stop command
POST **/stop** stops the running sequence runner, publishes a hold point at the current position to the trajectory controller, and calls the MoveIt **cobot/stop** service. If current joint states are unavailable, it publishes an empty trajectory instead.
=== "curl"
~~~ bash
curl -sS --max-time 10 -X POST $HOST/stop | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.post(f"{HOST}/stop", timeout=T_READ)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
reply = webwrite([HOST '/stop'], struct(), ...
weboptions('MediaType', 'application/json', 'Timeout', T_READ));
disp(reply)
~~~
This command cancels software operations, but does not remove robot power or replace the standard emergency stop. After calling it, verify both the response message and the physical robot state.
## Errors and diagnostics
| Code | When it occurs |
|---:|---|
| 200 | The request was processed; for motion commands, also check the success field |
| 409 | A motion sequence is already running |
| 422 | Invalid request structure, joint count, speed, planner, or joint limits |
| 503 | A ROS topic, service, action server, or MoveIt is unavailable; a wait timeout may also have occurred |
When troubleshooting, proceed from simple checks to more complex ones:
1. Open **/docs** and verify that the server is running and the endpoint appears in the schema.
2. Check **/robot/joint_states**. Without it, pose retrieval does not work and trajectory stopping cannot generate a hold point.
3. Make sure that the complete stack is running: `controller_manager`, MoveIt, and `iiwa_motion_server`.
4. After starting a sequence, inspect **/sequences/logs**. After publishing a trajectory, inspect **/trajectory/logs**.
The MCP server runs in the same process but provides a separate interface at **http://server-address:8007/mcp/mcp**. For ordinary HTTP integrations, use the endpoints documented on this page.
@@ -0,0 +1,651 @@
# Управление через REST API
REST API позволяет читать состояние робота и отправлять ему команды по HTTP. Он рассчитан на прикладные скрипты, интеграции с другими системами и быстрые проверки через Swagger UI.
Запросы к перемещению выполняются синхронно: ответ приходит после завершения планирования и выполнения команды либо после внутреннего тайм-аута. Очереди команд в API нет — дождитесь ответа на текущий запрос, прежде чем отправлять следующий.
!!! warning "Безопасность"
REST API не заменяет штатную систему безопасности KUKA и кнопку аварийного останова. Перед первым запуском на реальном роботе проверьте программу Sunrise, зоны безопасности, инструмент и рабочую область. Начинать знакомство с API лучше в симуляции.
## Запуск и доступ
Веб-сервер запускается вместе со стеком робота, если в корневом файле **cobot-setting.yaml** включён блок **web**:
~~~ yaml
web:
enabled: true
host: 0.0.0.0
port: 8007
endpoints: pkg://iiwa_config/config/api_endpoints.yaml
joint_limits: pkg://iiwa_config/config/moveit/joint_limits.yaml
~~~
После запуска через **cobot run** сервер будет доступен по адресу **http://адрес-сервера:8007**. Swagger UI помогает посмотреть фактическую схему запросов и выполнить одиночный тест:
- локально: [http://localhost:8007/docs](http://localhost:8007/docs);
- с другой машины: http://адрес-сервера:8007/docs;
- JSON-схема OpenAPI: http://адрес-сервера:8007/openapi.json.
Отдельного health-check в сервере нет. Если открывается Swagger UI, HTTP-сервер запущен. Готовность ROS-компонентов проверяется при обращении к конкретному маршруту.
По умолчанию сервер слушает все сетевые интерфейсы и не использует аутентификацию. Не публикуйте порт 8007 в недоверенную сеть. Для локальной работы укажите **host: 127.0.0.1**, а для удалённого доступа ограничьте сеть правилами firewall или VPN.
## Подготовка к примерам
Вкладки на этой странице синхронизированы: выберите удобный язык один раз, и тот же вариант будет открыт у следующих примеров.
=== "curl"
~~~ bash
HOST=http://localhost:8007
~~~
=== "Python"
~~~ python
import httpx
HOST = "http://localhost:8007"
T_READ = 10
T_MOVE = 60
~~~
=== "MATLAB"
~~~ matlab
HOST = 'http://localhost:8007';
T_READ = 10;
T_MOVE = 60;
readOpts = weboptions('Timeout', T_READ);
moveOpts = weboptions('MediaType', 'application/json', 'Timeout', T_MOVE);
~~~
Для JSON-запросов MATLAB использует встроенный webwrite. Загрузка CSV и JSON-файлов требует интерфейса matlab.net.http, который есть в современных desktop-версиях MATLAB.
## Состав API
| Метод | Маршрут | Назначение |
|---|---|---|
| GET | /robot/joint_states | Текущее состояние суставов |
| GET | /robot/pose | Поза TCP относительно base_link |
| GET | /robot/positions | Именованные положения из SRDF |
| POST | /robot/move/named | Переход в именованное положение |
| POST | /robot/move/pose | Декартово перемещение TCP |
| POST | /robot/move/joints | Перемещение по углам семи суставов |
| POST | /trajectory/send | Публикация траектории из JSON |
| POST | /trajectory/send_csv | Загрузка и публикация траектории из CSV |
| GET | /trajectory/logs | Последние записи траекторного модуля |
| POST | /sequences/start | Запуск последовательности из JSON-файла |
| GET | /sequences/status | Статус запущенной последовательности |
| GET | /sequences/logs | Вывод процесса последовательности |
| POST | /stop | Остановка команд API и планировщика |
## Получение состояния
### Состояние суставов
GET **/robot/joint_states** возвращает последнее сообщение ROS-топика **/joint_states**. Поля **position**, **velocity** и **effort** расположены в том же порядке, что и соответствующий массив **name**. Углы в **position** заданы в радианах.
=== "curl"
~~~ bash
curl -sS --max-time 10 $HOST/robot/joint_states | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.get(f"{HOST}/robot/joint_states", timeout=T_READ)
response.raise_for_status()
state = response.json()
print(dict(zip(state["name"], state["position"])))
~~~
=== "MATLAB"
~~~ matlab
jointState = webread([HOST '/robot/joint_states'], readOpts);
disp(jointState.position)
~~~
Типичный ответ:
~~~ json
{
"name": ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6", "joint7"],
"position": [0.0, 0.0, 0.0, -1.57, 0.0, 1.57, 0.0],
"velocity": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
"effort": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
}
~~~
Если сообщения от контроллера не поступают в течение двух секунд, API вернёт 503. Обычно это означает, что контроллер или робот ещё не запущен.
### Поза TCP
GET **/robot/pose** вычисляет прямую кинематику через сервис MoveIt **/compute_fk**. Положение задаётся в метрах, а ориентация возвращается одновременно кватернионом и углами Эйлера:
- **euler_rad** — радианы;
- **euler_deg** — градусы;
- углы **A, B, C** соответствуют конвенции KUKA ABC: поворот вокруг Z, затем Y и затем X.
=== "curl"
~~~ bash
curl -sS --max-time 10 $HOST/robot/pose | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.get(f"{HOST}/robot/pose", timeout=T_READ)
response.raise_for_status()
pose = response.json()
print(pose["position"])
~~~
=== "MATLAB"
~~~ matlab
pose = webread([HOST '/robot/pose'], readOpts);
fprintf('TCP: x=%.3f, y=%.3f, z=%.3f м\n', ...
pose.position.x, pose.position.y, pose.position.z);
fprintf('ABC: A=%.1f, B=%.1f, C=%.1f град\n', ...
pose.orientation.euler_deg.a, ...
pose.orientation.euler_deg.b, ...
pose.orientation.euler_deg.c);
~~~
Маршрут зависит и от **/joint_states**, и от работающего MoveIt. При недоступности любого из них будет возвращён 503.
### Именованные положения
GET **/robot/positions** читает положения group_state из SRDF. Список не зашит в API: он отражает текущую конфигурацию робота. В стандартной конфигурации есть положения **home**, **work** и **transport**.
=== "curl"
~~~ bash
curl -sS $HOST/robot/positions | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.get(f"{HOST}/robot/positions", timeout=T_READ)
response.raise_for_status()
for position in response.json():
print(position["name"], "—", position["description"])
~~~
=== "MATLAB"
~~~ matlab
namedPositions = webread([HOST '/robot/positions'], readOpts);
for i = 1:numel(namedPositions)
fprintf('%s — %s\n', namedPositions(i).name, ...
namedPositions(i).description);
end
~~~
Перед вызовом **/robot/move/named** всегда полезно получить этот список: он показывает точное имя, группу планирования и целевые углы суставов.
## Команды перемещения
Все три команды ниже используют MoveIt. Ответ имеет вид:
~~~ json
{"success": true, "message": "Движение выполнено успешно"}
~~~
Поле **success: false** означает, что планировщик не смог построить или выполнить траекторию. HTTP-статус при этом может остаться 200, поэтому в прикладном коде проверяйте и статус HTTP, и поле **success**.
### Переход в именованное положение
POST **/robot/move/named** перемещает манипулятор в положение из SRDF.
| Поле | Обязательное | Значение |
|---|---:|---|
| name | да | Имя положения из /robot/positions |
| speed | нет | Масштаб скорости от 0.01 до 1.0; по умолчанию 0.1 |
| accel_scale | нет | Масштаб ускорения от 0 до 1.0; 0 означает использовать speed |
=== "curl"
~~~ bash
curl -sS --max-time 60 -X POST $HOST/robot/move/named \
-H "Content-Type: application/json" \
-d '{"name": "home", "speed": 0.1, "accel_scale": 0.0}'
~~~
=== "Python"
~~~ python
response = httpx.post(
f"{HOST}/robot/move/named",
json={"name": "home", "speed": 0.1, "accel_scale": 0.0},
timeout=T_MOVE,
)
response.raise_for_status()
result = response.json()
if not result["success"]:
raise RuntimeError(result["message"])
~~~
=== "MATLAB"
~~~ matlab
body = struct('name', 'home', 'speed', 0.1, 'accel_scale', 0.0);
reply = webwrite([HOST '/robot/move/named'], body, moveOpts);
assert(reply.success, reply.message)
~~~
### Декартово перемещение TCP
POST **/robot/move/pose** принимает положение TCP в метрах и ориентацию ABC в радианах. Если **frame_id** пуст, используется фрейм, заданный в настройках планирования; в стандартной конфигурации это **base_link**.
| Поле | Обязательное | Значение |
|---|---:|---|
| x, y, z | да | Координаты TCP, м |
| a, b, c | нет | Углы KUKA ABC, рад; по умолчанию 0 |
| speed | нет | Масштаб скорости от 0.01 до 1.0; по умолчанию 0.1 |
| planner | нет | ompl, ptp, lin, circ или chomp; по умолчанию ptp |
| frame_id | нет | Фрейм целевой позы; пустая строка использует фрейм по умолчанию |
Значение **planner** приводится к нижнему регистру. PTP подходит для переходов между точками, LIN — для прямолинейного движения инструмента. Выбор CIRC имеет смысл только для задач, где он поддерживается вашим планировщиком и целевой позой.
=== "curl"
~~~ bash
curl -sS --max-time 60 -X POST $HOST/robot/move/pose \
-H "Content-Type: application/json" \
-d '{
"x": 0.40, "y": 0.00, "z": 0.50,
"a": 0.0, "b": 3.14159, "c": 0.0,
"speed": 0.1, "planner": "ptp", "frame_id": ""
}'
~~~
=== "Python"
~~~ python
target = {
"x": 0.40, "y": 0.00, "z": 0.50,
"a": 0.0, "b": 3.14159, "c": 0.0,
"speed": 0.1, "planner": "ptp", "frame_id": "",
}
response = httpx.post(f"{HOST}/robot/move/pose", json=target, timeout=T_MOVE)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
body = struct( ...
'x', 0.40, 'y', 0.00, 'z', 0.50, ...
'a', 0.0, 'b', pi, 'c', 0.0, ...
'speed', 0.1, 'planner', 'ptp', 'frame_id', '');
reply = webwrite([HOST '/robot/move/pose'], body, moveOpts);
assert(reply.success, reply.message)
~~~
### Перемещение по углам суставов
POST **/robot/move/joints** принимает ровно семь углов в порядке J1–J7. API проверяет количество значений и текущие границы из файла **joint_limits.yaml**.
| Сустав | Допустимый угол, рад |
|---|---:|
| J1 | от -2.97 до 2.97 |
| J2 | от -2.10 до 2.10 |
| J3 | от -2.97 до 2.97 |
| J4 | от -2.10 до 2.10 |
| J5 | от -2.97 до 2.97 |
| J6 | от -2.10 до 2.10 |
| J7 | от -3.05 до 3.05 |
При изменении файла ограничений ориентируйтесь на Swagger UI: значения в этой таблице относятся к поставляемой конфигурации.
=== "curl"
~~~ bash
curl -sS --max-time 60 -X POST $HOST/robot/move/joints \
-H "Content-Type: application/json" \
-d '{"joints": [0.0, 0.5, 0.0, -1.57, 0.0, 1.57, 0.0], "speed": 0.1}'
~~~
=== "Python"
~~~ python
response = httpx.post(
f"{HOST}/robot/move/joints",
json={
"joints": [0.0, 0.5, 0.0, -1.57, 0.0, 1.57, 0.0],
"speed": 0.1,
},
timeout=T_MOVE,
)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
body = struct( ...
'joints', [0.0, 0.5, 0.0, -1.57, 0.0, 1.57, 0.0], ...
'speed', 0.1);
reply = webwrite([HOST '/robot/move/joints'], body, moveOpts);
assert(reply.success, reply.message)
~~~
## Траектории по суставам
Маршруты раздела **/trajectory** публикуют сообщение JointTrajectory напрямую в контроллер **/iiwa_arm_controller/joint_trajectory**. Ответ **status: sent** подтверждает публикацию сообщения, но не завершение движения и не отсутствие ошибок контроллера. Отслеживайте состояние робота через **/robot/joint_states** и при необходимости смотрите **/trajectory/logs**.
### Траектория в JSON
POST **/trajectory/send** принимает одну или несколько точек.
| Поле | Значение |
|---|---|
| points | Непустой список точек |
| points[].positions | Ровно 7 углов J1–J7 в радианах |
| points[].time_from_start | Время от начала траектории в секундах, не меньше 0 |
| validate_limits | Проверять границы суставов; по умолчанию true |
Сервер не проверяет возрастание времени между точками, поэтому задавайте его самостоятельно. Для контроллера траектория с возрастающими значениями времени предсказуемее.
=== "curl"
~~~ bash
curl -sS --max-time 20 -X POST $HOST/trajectory/send \
-H "Content-Type: application/json" \
-d '{
"points": [
{"positions": [0, 0, 0, 0, 0, 0, 0], "time_from_start": 0.0},
{"positions": [0, 0.5, 0, -1.0, 0, 1.0, 0], "time_from_start": 3.0},
{"positions": [0, 0, 0, 0, 0, 0, 0], "time_from_start": 6.0}
],
"validate_limits": true
}'
~~~
=== "Python"
~~~ python
trajectory = {
"points": [
{"positions": [0.0] * 7, "time_from_start": 0.0},
{"positions": [0.0, 0.5, 0.0, -1.0, 0.0, 1.0, 0.0], "time_from_start": 3.0},
{"positions": [0.0] * 7, "time_from_start": 6.0},
],
"validate_limits": True,
}
response = httpx.post(f"{HOST}/trajectory/send", json=trajectory, timeout=T_READ)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
p1 = struct('positions', [0, 0, 0, 0, 0, 0, 0], ...
'time_from_start', 0.0);
p2 = struct('positions', [0, 0.5, 0, -1.0, 0, 1.0, 0], ...
'time_from_start', 3.0);
trajectory.points = [p1, p2];
trajectory.validate_limits = true;
opts = weboptions('MediaType', 'application/json', 'Timeout', T_READ);
reply = webwrite([HOST '/trajectory/send'], trajectory, opts);
disp(reply)
~~~
### Загрузка CSV
POST **/trajectory/send_csv** принимает CSV-файл в multipart-поле **file**. Первая строка должна быть заголовком. Имена колонок суставов могут быть записаны как **joint1** или **joint_1**, регистр не важен; колонка времени называется **t**, **time** или **time_from_start**. Порядок колонок произвольный.
Пример файла:
~~~ csv
joint1,joint2,joint3,joint4,joint5,joint6,joint7,t
0,0,0,0,0,0,0,0.0
0,0.5,0,-1.0,0,1.0,0,3.0
~~~
Параметры **separator** и **validate_limits** передаются в строке запроса, а не как поля формы. По умолчанию разделитель — запятая, проверка ограничений включена.
=== "curl"
~~~ bash
curl -sS --max-time 20 -X POST \
"$HOST/trajectory/send_csv?separator=%2C&validate_limits=true" \
-F "file=@trajectory.csv;type=text/csv"
~~~
=== "Python"
~~~ python
with open("trajectory.csv", "rb") as csv_file:
response = httpx.post(
f"{HOST}/trajectory/send_csv",
params={"separator": ",", "validate_limits": True},
files={"file": ("trajectory.csv", csv_file, "text/csv")},
timeout=T_READ,
)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
import matlab.net.http.*
import matlab.net.http.io.*
uri = URI([HOST '/trajectory/send_csv?separator=%2C&validate_limits=true']);
form = MultipartFormProvider('file', FileProvider('trajectory.csv'));
request = RequestMessage('post', [], form);
httpOpts = HTTPOptions('ConnectTimeout', T_READ, 'ResponseTimeout', T_READ);
response = request.send(uri, httpOpts);
disp(response.Body.Data)
~~~
Для файла с точкой с запятой замените %2C на %3B.
### Лог траекторного модуля
GET **/trajectory/logs?n=50** возвращает до 300 последних записей. Параметр **n** должен быть в диапазоне от 1 до 300.
=== "curl"
~~~ bash
curl -sS "$HOST/trajectory/logs?n=20" | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.get(f"{HOST}/trajectory/logs", params={"n": 20}, timeout=T_READ)
response.raise_for_status()
for line in response.json()["lines"]:
print(line)
~~~
=== "MATLAB"
~~~ matlab
logs = webread([HOST '/trajectory/logs?n=20'], readOpts);
disp(logs.lines)
~~~
Чтобы прервать траекторию, используйте общий маршрут **POST /stop**. Отдельного маршрута **/trajectory/stop** в API нет.
## Последовательности движений
POST **/sequences/start** запускает отдельный процесс motion_sequence_runner. Он читает загруженный JSON-файл и поочерёдно отправляет цели MoveToJoints или MoveToPose.
| Поле формы | Значение по умолчанию | Назначение |
|---|---:|---|
| config | — | JSON-файл последовательности, обязательное поле |
| n_iterations | 3 | Число повторений, не меньше 1 |
| delay_between_iterations | 5.0 | Пауза между итерациями, с |
| bag_path | пусто | Путь для записи rosbag; пустая строка отключает запись |
| topics | пусто | Топики для rosbag через запятую; пусто означает все обнаруженные топики |
| joints_action | cobot/move_to_joints | Имя action для суставных целей |
| pose_action | cobot/move_to_pose | Имя action для декартовых целей |
Минимальная структура конфигурации:
~~~ json
{
"home": {
"joints": [0, 0, 0, -1.57, 0, 1.57, 0],
"speed": 0.1
},
"waypoints": [
{
"x": 0.6, "y": 0.1, "z": 0.55,
"a": 3.14, "b": 0.31, "c": 2.79,
"speed": 0.2, "planner": "lin"
},
{
"joints": [0.5, 0.3, 0, -1.2, 0, 1.4, 0],
"speed": 0.2
}
]
}
~~~
Если в точке есть поле **joints**, она считается суставной. Иначе runner ожидает декартовы поля **x**, **y**, **z**, **a**, **b** и **c**.
### Запуск последовательности
=== "curl"
~~~ bash
curl -sS --max-time 10 -X POST $HOST/sequences/start \
-F "config=@motion_sequence_config.json;type=application/json" \
-F "n_iterations=3" \
-F "delay_between_iterations=5.0"
~~~
=== "Python"
~~~ python
with open("motion_sequence_config.json", "rb") as config:
response = httpx.post(
f"{HOST}/sequences/start",
files={"config": ("motion_sequence_config.json", config, "application/json")},
data={"n_iterations": "3", "delay_between_iterations": "5.0"},
timeout=T_READ,
)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
import matlab.net.http.*
import matlab.net.http.io.*
form = MultipartFormProvider( ...
'config', FileProvider('motion_sequence_config.json'), ...
'n_iterations', '3', ...
'delay_between_iterations', '5.0');
request = RequestMessage('post', [], form);
httpOpts = HTTPOptions('ConnectTimeout', T_READ, 'ResponseTimeout', T_READ);
response = request.send(URI([HOST '/sequences/start']), httpOpts);
disp(response.Body.Data)
~~~
Ответ **status: started** подтверждает запуск процесса, но не корректность содержимого JSON и не успешность каждого движения. Если runner завершится с ошибкой, проверьте его состояние и лог.
### Статус и журнал последовательности
=== "curl"
~~~ bash
curl -sS $HOST/sequences/status | python3 -m json.tool
curl -sS "$HOST/sequences/logs?n=50" | python3 -m json.tool
~~~
=== "Python"
~~~ python
status = httpx.get(f"{HOST}/sequences/status", timeout=T_READ)
status.raise_for_status()
print(status.json())
logs = httpx.get(f"{HOST}/sequences/logs", params={"n": 50}, timeout=T_READ)
logs.raise_for_status()
for line in logs.json()["lines"]:
print(line)
~~~
=== "MATLAB"
~~~ matlab
status = webread([HOST '/sequences/status'], readOpts);
logs = webread([HOST '/sequences/logs?n=50'], readOpts);
disp(status)
disp(logs.lines)
~~~
Статусы:
- **idle** — последовательность ещё не запускалась;
- **running** — процесс выполняется;
- **finished** — процесс завершён; в ответе будет код **returncode**.
Одновременно может работать только одна последовательность. Повторный POST **/sequences/start** во время её выполнения вернёт 409. Для остановки используйте **POST /stop**: отдельного **/sequences/stop** нет.
## Общая остановка
POST **/stop** останавливает запущенный runner, публикует точку удержания текущей позиции для траекторного контроллера и вызывает сервис MoveIt **cobot/stop**. Если текущие состояния суставов недоступны, вместо точки удержания публикуется пустая траектория.
=== "curl"
~~~ bash
curl -sS --max-time 10 -X POST $HOST/stop | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.post(f"{HOST}/stop", timeout=T_READ)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
reply = webwrite([HOST '/stop'], struct(), ...
weboptions('MediaType', 'application/json', 'Timeout', T_READ));
disp(reply)
~~~
Команда отменяет программные операции, но не снимает питание с робота и не заменяет штатную аварийную остановку. После её вызова проверьте сообщение в ответе и реальное состояние робота.
## Ошибки и диагностика
| Код | Когда возникает |
|---:|---|
| 200 | Запрос обработан; для команд движения дополнительно проверьте поле success |
| 409 | Уже запущена последовательность движений |
| 422 | Некорректная структура запроса, число суставов, скорость, планировщик или лимиты суставов |
| 503 | ROS-топик, сервис, action-сервер или MoveIt недоступен; также возможен тайм-аут ожидания |
При проблемах идите от простого к сложному:
1. Откройте **/docs** и убедитесь, что сервер запущен и маршрут присутствует в схеме.
2. Проверьте **/robot/joint_states**. Без него не будет работать получение позы, а остановка траектории не сможет сформировать точку удержания.
3. Убедитесь, что стек запущен полностью: controller_manager, MoveIt и iiwa_motion_server.
4. После запуска последовательности посмотрите **/sequences/logs**; после публикации траектории — **/trajectory/logs**.
MCP-сервер работает в том же процессе, но это отдельный интерфейс: его адрес — **http://адрес-сервера:8007/mcp/mcp**. Для обычных HTTP-интеграций используйте маршруты из этой страницы.
@@ -0,0 +1,11 @@
# Control via ROS 2
!!! info "Work in progress"
Detailed instructions for control through ROS 2 topics and action servers are being prepared.
This method sends commands directly to ROS 2 using CLI tools (`ros2 topic pub`, `ros2 action send_goal`) or custom ROS 2 nodes written in Python or C++.
## Additional resources
- [ROS 2 Jazzy documentation](https://docs.ros.org/en/jazzy/index.html) — official documentation for topics, services, action servers, and node development
- [MATLAB Robotics System Toolbox](https://www.mathworks.com/help/ros/index.html?s_tid=CRUX_lftnav) — control the robot through ROS 2 from MATLAB
@@ -0,0 +1,11 @@
# Управление через ROS2
!!! info "Раздел в разработке"
Подробная документация по управлению через ROS2-топики и action-серверы готовится.
Этот способ предполагает прямую отправку команд в ROS2 через CLI-инструменты (`ros2 topic pub`, `ros2 action send_goal`) или написание собственных ROS2-нод на Python/C++.
## Дополнительные ресурсы
- [Документация ROS2 Jazzy](https://docs.ros.org/en/jazzy/index.html) — официальная документация: топики, сервисы, action-серверы, написание нод
- [MATLAB Robotics System Toolbox](https://www.mathworks.com/help/ros/index.html?s_tid=CRUX_lftnav) — управление роботом через ROS2 из MATLAB
@@ -0,0 +1,24 @@
# Getting started
This section explains how to prepare the environment, connect to the controller, install the project, and start controlling the robot.
## Quick start
1. [**Sunrise Workbench setup**](sunrise-setup.md) — prepare the KUKA controller, upload `ServerFriRos2`, and configure the network. *(Physical robot only.)*
2. [**Connect to the server**](remote-access.md) — choose local or remote deployment and connect to the control server over SSH.
3. [**Install the project**](installation.md) — install LWC using `curl`, `git`, or manually.
4. [**Configure the system**](configuration.md) — configure `cobot-setting.yaml` with the robot IP, ports, and tools.
5. [**cobot CLI**](cli-reference.md) — learn the commands for running, building, and updating the project.
!!! tip "Simulation only?"
Skip the physical-controller setup and run `cobot run --simulate` after installation.
## Concepts and control
- [System architecture](concepts/architecture.md)
- [FRI protocol](concepts/fri-protocol.md)
- [Webots simulation](concepts/simulation.md)
- [Motion planning](concepts/motion-planning.md)
- [ROS 2 Control](control/ros2-control.md)
- [Foxglove](control/foxglove.md)
- [REST API](control/rest-api.md)
+48
View File
@@ -0,0 +1,48 @@
# Обзор
**Lightweight Cobot (LWC)** — открытая система управления коллаборативным роботом **KUKA LBR IIWA 7 R800** на базе **ROS 2 Jazzy**. Поддерживает работу как с физическим роботом (через протокол FRI), так и в виртуальной среде (симулятор Webots). В состав проекта входят CLI-инструмент `cobot`, аппаратный интерфейс ROS 2 Control, планировщик движений MoveIt 2 и REST/MCP API для интеграции с AI-агентами.
---
## Репозитории
| Платформа | Ссылка | Статус |
|---|---|---|
| **GitVerse** (предпочтительный) | [daniel-robotics/lightweight-cobot](https://gitverse.ru/daniel-robotics/lightweight-cobot) | основной |
| GitHub | [Daniel-Robotic/lightweight-cobot](https://github.com/Daniel-Robotic/lightweight-cobot) | зеркало |
## Онлайн документация
- [GitVerse Pages](https://daniel-robotics.gitverse.site/lightweight-cobot) — основная
- [GitHub Pages](https://daniel-robotic.github.io/lightweight-cobot/) — зеркало
---
## Предпосылки
- Физический робот **KUKA LBR IIWA 7 R800** — если планируете работу с реальным оборудованием
- Либо желание работать только в симуляторе **Webots** — физический робот не нужен
- ПК или сервер с **Ubuntu 24.04** (или подключение к существующему серверу по SSH)
- Доступ к сети, в которой находится контроллер робота
---
## Порядок шагов
1. [**Настройка SunriseWorkbench**](sunrise-setup.md) — подготовка контроллера KUKA: подключение кабелей, загрузка программы `ServerFriRos2`, настройка сетевых параметров. *(Только для физического робота)*
2. [**Подключение к серверу**](remote-access.md) — выбор варианта развёртывания (локально или удалённо), SSH-подключение к серверу управления.
3. [**Установка проекта**](installation.md) — скачивание и установка LWC через `curl`, `git` или вручную. После установки запустите `cobot setup` — мастер проведёт по оставшимся шагам автоматически.
4. [**Конфигурация системы**](configuration.md) — настройка `cobot-setting.yaml`: IP робота, порты, инструменты. Выполняется на шаге 2 мастера `cobot setup`, либо в любой момент позже через `cobot robot-setup`.
5. [**CLI-инструмент cobot**](cli-reference.md) — все команды управления проектом: запуск, сборка, обновление.
---
!!! tip "Только симуляция?"
Если физический робот недоступен, пропустите шаг 1 и начните сразу с [установки проекта](installation.md). Запустите симулятор командой `cobot run --simulate`.
!!! info "`cobot setup` сделает шаги 3–4 автоматически"
После установки проекта достаточно выполнить `cobot setup` — мастер последовательно предложит: настройку документации, параметры робота (`cobot-setting.yaml`) и выбор среды сборки (ROS2 или Docker).
@@ -0,0 +1,114 @@
# Project installation
## Quick installation
The easiest option is to install the project with a single `curl` command. Make sure that `curl` is installed:
```bash
sudo apt update && sudo apt upgrade -y && sudo apt install curl
```
Go to your home directory and run the installation script:
=== "Stable version (master)"
```bash
cd ~
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/install.sh | bash
```
=== "Development version (dev)"
```bash
cd ~
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/dev/install.sh | bash -s dev
```
---
## Installation with Git
The project is available on both [GitVerse](https://gitverse.ru/daniel-robotics/lightweight-cobot) (preferred) and [GitHub](https://github.com/Daniel-Robotic/lightweight-cobot).
!!! tip "New to Git?"
If this is your first time using Git and GitHub, see the [GitHub getting-started guide](https://docs.github.com/en/get-started/start-your-journey/hello-world).
Clone the repository and run the installation script:
=== "GitVerse"
```bash
cd ~
git clone https://gitverse.ru/daniel-robotics/lightweight-cobot.git
cd ~/lightweight-cobot
sudo chmod +x ./install.sh
./install.sh
```
=== "GitHub"
```bash
cd ~
git clone https://github.com/Daniel-Robotic/lightweight-cobot.git
cd ~/lightweight-cobot
sudo chmod +x ./install.sh
./install.sh
```
---
## Manual installation
If neither `curl` nor `git` is available, download the project archive manually from the repository page using the **Download ZIP** button, extract it, and run:
```bash
cd ~/lightweight-cobot
sudo chmod +x ./install.sh
./install.sh
```
---
## Installation process
The [`install.sh`](https://gitverse.ru/daniel-robotics/lightweight-cobot/raw/branch/master/install.sh) script automatically installs:
- **Git** — version control system;
- **Docker** — containerization for isolated execution;
- **`cobot` CLI** — the main project management tool;
- Ubuntu system dependencies.
### Restarting after installation
After the script finishes, a restart may be required for Docker to work:
```bash
sudo reboot now
```
Watch the terminal output: the script will indicate whether a restart is required.
### If the log is empty
If the script produces no output, reload the Bash environment and continue setup manually:
```bash
source ~/.bashrc # refresh environment variables
cobot setup # continue system setup
```
---
## Verifying the installation
After installation, make sure that `cobot` is available:
```bash
cobot -h
```
If the command displays the list of available subcommands, installation was successful.
---
**Next step:** [System configuration](configuration.md)
@@ -0,0 +1,114 @@
# Установка проекта
## Быстрая установка
Самый простой способ — установить через `curl` одной командой. Убедитесь, что `curl` установлен:
```bash
sudo apt update && sudo apt upgrade -y && sudo apt install curl
```
Перейдите в домашнюю директорию и запустите скрипт установки:
=== "Стабильная версия (master)"
```bash
cd ~
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/install.sh | bash
```
=== "Dev-версия (dev)"
```bash
cd ~
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/dev/install.sh | bash -s dev
```
---
## Установка через Git
Проект доступен как на [GitVerse](https://gitverse.ru/daniel-robotics/lightweight-cobot) (предпочтительно), так и на [GitHub](https://github.com/Daniel-Robotic/lightweight-cobot).
!!! tip "Не знакомы с Git?"
Если вы впервые работаете с Git и GitHub, рекомендуем [прочитать эту статью на Хабре](https://habr.com/ru/companies/yandex_praktikum/articles/700708/) — там всё объясняется с нуля.
Клонируйте репозиторий и запустите скрипт установки:
=== "GitVerse"
```bash
cd ~
git clone https://gitverse.ru/daniel-robotics/lightweight-cobot.git
cd ~/lightweight-cobot
sudo chmod +x ./install.sh
./install.sh
```
=== "GitHub"
```bash
cd ~
git clone https://github.com/Daniel-Robotic/lightweight-cobot.git
cd ~/lightweight-cobot
sudo chmod +x ./install.sh
./install.sh
```
---
## Ручная установка
Если ни `curl`, ни `git` недоступны — скачайте архив проекта вручную со страницы репозитория (кнопка «Скачать ZIP»), разархивируйте и выполните:
```bash
cd ~/lightweight-cobot
sudo chmod +x ./install.sh
./install.sh
```
---
## Процесс установки
Скрипт [`install.sh`](https://gitverse.ru/daniel-robotics/lightweight-cobot/raw/branch/master/install.sh) автоматически установит:
- **Git** — система контроля версий
- **Docker** — контейнеризация для изолированного запуска
- **CLI-инструмент `cobot`** — основной инструмент управления проектом
- Системные зависимости Ubuntu
### Перезагрузка после установки
После завершения скрипта может потребоваться перезагрузка, чтобы заработал Docker:
```bash
sudo reboot now
```
Следите за выводом в терминале — скрипт сам сообщит, нужна ли перезагрузка.
### Если лог пуст
Если после запуска скрипта не выводится никакой информации, обновите среду bash и продолжите настройку вручную:
```bash
source ~/.bashrc # обновление переменных окружения
cobot setup # продолжение настройки системы
```
---
## Проверка установки
После завершения убедитесь, что `cobot` доступен:
```bash
cobot -h
```
Если команда выводит список доступных подкоманд — установка прошла успешно.
---
**Следующий шаг:** [Конфигурация системы](configuration.md)
@@ -0,0 +1,76 @@
# Connecting to the server
## Deployment options
The project can be deployed in two ways:
| Option | Description | When to use it |
|---|---|---|
| **Local** | Install on your PC | Development, simulation, and debugging |
| **Remote (server)** | Install on a dedicated server connected to the KUKA controller | Working with the physical robot |
With remote deployment, you control the server from your PC over an **SSH connection**.
---
## SSH clients
Choose any of the following applications:
- [**Termius**](https://termius.com/) — cross-platform SSH client with a convenient GUI;
- [**MobaXterm**](https://mobaxterm.mobatek.net/) — multifunctional terminal for Windows;
- [**PuTTY**](https://putty.software/) — classic SSH client for Windows;
- the **built-in terminal or command prompt**, as described below.
For instructions on configuring Termius, MobaXterm, or PuTTY, refer to their official documentation.
---
## Connection details
```
IP address: 192.168.21.1
Username: cobot
Password: 12345678
```
!!! warning "Network requirement"
Your PC must be on the **same network/subnet as the robot** (for example, the KnASU network). Otherwise, the connection cannot be established.
---
## Connecting from the built-in terminal
=== "Linux"
Any distribution can be used. Open a terminal and run:
```bash
ssh cobot@192.168.21.1
```
=== "Windows"
**Windows 10** or later is required for the built-in SSH client. Open **Command Prompt** or **PowerShell** and run:
```powershell
ssh cobot@192.168.21.1
```
The command will prompt for a password:
```
cobot@192.168.21.1's password:
```
Enter `12345678`. Characters are not displayed while you type; this is normal security behavior. Press ++enter++.
After a successful connection, the server command prompt appears:
```
cobot@server:~$
```
---
**Next step:** [Project installation](installation.md)
@@ -0,0 +1,78 @@
# Подключение к серверу
## Варианты развёртывания
Проект можно развернуть двумя способами:
| Вариант | Описание | Когда использовать |
|---|---|---|
| **Локально** | Установка на вашем ПК | Разработка, симуляция, отладка |
| **Удалённо (сервер)** | Установка на выделенном сервере, подключённом к контроллеру KUKA | Работа с реальным роботом |
При удалённом варианте вы управляете сервером через **SSH-соединение** со своего ПК.
---
## Программы для SSH-подключения
Выберите любую из программ:
- [**Termius**](https://termius.com/) — кроссплатформенный SSH-клиент с удобным GUI
- [**MobaXterm**](https://mobaxterm.mobatek.net/) — многофункциональный терминал для Windows
- [**PuTTY**](https://putty.software/) — классический SSH-клиент для Windows
- **Встроенный терминал / командная строка** — описано ниже
Инструкции по настройке Termius, MobaXterm и PuTTY смотрите в их официальной документации.
---
## Данные для подключения
```
IP-адрес: 192.168.21.1
Имя пользователя: cobot
Пароль: 12345678
```
!!! warning "Требование к сети"
Ваш ПК должен находиться в **одной сети/подсети с роботом** (например, в сети КнАГУ).
Без этого соединение установить не удастся.
---
## Подключение через встроенный терминал
=== "Linux"
Подойдёт любой дистрибутив. Откройте терминал и выполните:
```bash
ssh cobot@192.168.21.1
```
=== "Windows"
Требуется **Windows 10** или новее (встроенный SSH-клиент).
Откройте **Командную строку** или **PowerShell** и выполните:
```powershell
ssh cobot@192.168.21.1
```
После выполнения команды появится запрос пароля:
```
cobot@192.168.21.1's password:
```
Введите пароль `12345678` — символы не отображаются во время набора, это нормальное поведение из соображений безопасности. Нажмите ++enter++.
При успешном подключении вы увидите приглашение командной строки сервера:
```
cobot@server:~$
```
---
**Следующий шаг:** [Установка проекта](installation.md)
@@ -0,0 +1,85 @@
# SunriseWorkbench setup
!!! info "Physical robot only"
This section applies only when working with a physical KUKA LBR IIWA 7. For simulation, proceed to [Project installation](installation.md).
---
## Physical hardware setup
### Ethernet connection
Connect an Ethernet cable from your PC or control server to one of the KUKA controller's network ports:
- **KLI** (KUKA Line Interface) — the primary port used for control and programming;
- **KONI** (KUKA Optional Network Interface) — the additional port used for FRI.
Both ports can be connected at the same time. You can select the interface when configuring the server.
> Connect the KLI and KONI ports according to the KUKA controller wiring diagram.
---
## Synchronizing the SunriseWorkbench project
### Checking for ServerFriRos2
Make sure that your Sunrise project contains `ServerFriRos2.java`. If the file is missing, download it from the repository. Its path is `src/iiwa_sunrise/src/ServerFriRos2.java`.
=== "curl"
```bash
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/src/iiwa_sunrise/src/ServerFriRos2.java \
-o ServerFriRos2.java
```
=== "wget"
```bash
wget -O ServerFriRos2.java \
https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/src/iiwa_sunrise/src/ServerFriRos2.java
```
After downloading it, add the file to the Sunrise project and synchronize the project with the controller.
### Synchronizing with the controller
Open **SunriseWorkbench** and click the project synchronization button:
> In SunriseWorkbench, use the project synchronization button.
Before synchronizing, make sure that the PC and KUKA controller are on the same network. The current controller network settings can be checked directly in SunriseWorkbench:
> The controller network parameters are available in the SunriseWorkbench settings window.
---
## Configuring ServerFriRos2
Open `ServerFriRos2.java` in SunriseWorkbench and change the following parameters to match your network configuration:
```java
// IP address of the KONI interface
KONI_IP = "192.170.10.10";
// IP address of the KLI interface
KLI_IP = "192.168.21.31";
// Zero position (all joints at 0°)
ZERO_POSITION = {0, 0, 0, 0, 0, 0, 0};
// Working position for monitoring
MONITOR_WORKING_POSITION = {0, 0, 0, -1.57, 0, 1.57, 0};
// Tool used by default
@Named("tool1")
```
!!! warning "Important"
`KONI_IP` and `KLI_IP` in the Java program are addresses of the ROS 2 computer that the controller can reach through the corresponding networks. Conversely, `robot.ip` in `cobot-setting.yaml` is the address of the KUKA controller as seen from the computer. Incorrect or swapped addresses prevent the FRI connection from being established.
After making the changes, synchronize the project with the controller again.
---
**Next step:** [Connecting to the control server](remote-access.md)
@@ -0,0 +1,87 @@
# Настройка SunriseWorkbench
!!! info "Только для физического робота"
Этот раздел актуален только при работе с реальным роботом KUKA LBR IIWA 7.
Для симуляции переходите к [Установке проекта](installation.md).
---
## Настройка физического оборудования
### Подключение Ethernet
Подключите кабель Ethernet от вашего ПК (или сервера управления) к одному из сетевых портов контроллера KUKA:
- **KLI** (KUKA Line Interface) — основной порт, используется для управления и программирования
- **KONI** (KUKA Optional Network Interface) — дополнительный порт, используется для FRI
Вы можете подключить оба порта одновременно — при конфигурации сервера будет выбор, какой интерфейс использовать.
> Подключите порты KLI и KONI согласно схеме подключения контроллера KUKA.
---
## Синхронизация проекта в SunriseWorkbench
### Проверка наличия ServerFriRos2
Убедитесь, что в вашем Sunrise-проекте присутствует файл `ServerFriRos2.java`.
Если файл отсутствует — скачайте его из репозитория. Он находится по пути `src/iiwa_sunrise/src/ServerFriRos2.java`.
=== "curl"
```bash
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/src/iiwa_sunrise/src/ServerFriRos2.java \
-o ServerFriRos2.java
```
=== "wget"
```bash
wget -O ServerFriRos2.java \
https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/src/iiwa_sunrise/src/ServerFriRos2.java
```
После скачивания добавьте файл в Sunrise-проект и выполните синхронизацию с контроллером.
### Синхронизация с контроллером
Откройте **SunriseWorkbench** и нажмите кнопку синхронизации проекта:
> В SunriseWorkbench используйте кнопку синхронизации проекта.
Перед синхронизацией убедитесь, что ПК и контроллер KUKA находятся в одной сети. Текущие сетевые параметры контроллера можно быстро проверить прямо в SunriseWorkbench:
> Сетевые параметры контроллера доступны в окне настроек SunriseWorkbench.
---
## Настройка ServerFriRos2
Откройте файл `ServerFriRos2.java` в SunriseWorkbench и измените следующие параметры в соответствии с вашей сетевой конфигурацией:
```java
// IP-адрес интерфейса KONI
KONI_IP = "192.170.10.10";
// IP-адрес интерфейса KLI
KLI_IP = "192.168.21.31";
// Нулевая позиция (все суставы в 0°)
ZERO_POSITION = {0, 0, 0, 0, 0, 0, 0};
// Рабочая позиция для мониторинга
MONITOR_WORKING_POSITION = {0, 0, 0, -1.57, 0, 1.57, 0};
// Инструмент, используемый по умолчанию
@Named("tool1")
```
!!! warning "Важно"
`KONI_IP` и `KLI_IP` в Java-программе — это адреса компьютера с ROS 2, доступные контроллеру через соответствующие сети. Параметр `robot.ip` в `cobot-setting.yaml`, наоборот, содержит адрес контроллера KUKA со стороны компьютера. Неверные или перепутанные адреса не позволят установить FRI-соединение.
После внесения изменений повторно выполните синхронизацию проекта с контроллером.
---
**Следующий шаг:** [Подключение к серверу управления](remote-access.md)
+44
View File
@@ -0,0 +1,44 @@
---
hide:
- navigation
- toc
- footer
---
<meta http-equiv="refresh" content="0; url=./getting-started/">
# Overview
**Lightweight Cobot (LWC)** is an open system for controlling the **KUKA LBR IIWA 7 R800** collaborative robot based on **ROS 2 Jazzy**. It supports both a physical robot through the FRI protocol and a virtual Webots simulation. The project includes the `cobot` CLI, a ROS 2 Control hardware interface, MoveIt 2 motion planning, and REST/MCP APIs for AI-agent integration.
## Repositories
| Platform | Link | Status |
|---|---|---|
| **GitVerse** (preferred) | [daniel-robotics/lightweight-cobot](https://gitverse.ru/daniel-robotics/lightweight-cobot) | primary |
| GitHub | [Daniel-Robotic/lightweight-cobot](https://github.com/Daniel-Robotic/lightweight-cobot) | mirror |
## Online documentation
- [GitVerse Pages](https://daniel-robotics.gitverse.site/lightweight-cobot) — primary
- [GitHub Pages](https://daniel-robotic.github.io/lightweight-cobot/) — mirror
## Requirements
- A physical **KUKA LBR IIWA 7 R800** for real-robot operation, or
- **Webots** if you only want to use simulation;
- A PC or server running **Ubuntu 24.04**, or SSH access to an existing server;
- Network access to the robot controller.
## Recommended order
1. [**Sunrise Workbench setup**](getting-started/sunrise-setup.md) — prepare the KUKA controller. *(Physical robot only.)*
2. [**Connect to the server**](getting-started/remote-access.md) — choose local or remote deployment and connect over SSH.
3. [**Install the project**](getting-started/installation.md) — install LWC using `curl`, `git`, or manually, then run `cobot setup`.
4. [**Configure the system**](getting-started/configuration.md) — set the robot IP, ports, and tools in `cobot-setting.yaml`.
5. [**cobot CLI**](getting-started/cli-reference.md) — review commands for running, building, and updating the project.
!!! tip "Simulation only?"
If a physical robot is unavailable, skip step 1 and start with the [project installation](getting-started/installation.md). Launch the simulator with `cobot run --simulate`.
!!! info "`cobot setup` automates steps 34"
After installing the project, run `cobot setup`. The wizard will configure the documentation, robot parameters, and the ROS 2 or Docker build environment.
+8
View File
@@ -0,0 +1,8 @@
---
hide:
- navigation
- toc
- footer
---
<meta http-equiv="refresh" content="0; url=./getting-started/">
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 161 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 KiB

Some files were not shown because too many files have changed in this diff Show More