Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
229de6d686 | ||
|
|
80c87682ea | ||
|
|
910afce714 | ||
|
|
79d88db930 | ||
|
|
08ebd40671 | ||
|
|
4547b786a3 | ||
|
|
b318cb3311 | ||
|
|
c5cbf234cb | ||
|
|
2478e9956b | ||
|
|
5134fadf31 | ||
|
|
41f516bb58 | ||
|
|
9e3ee7ebc8 | ||
|
|
4fc9622ee9 | ||
|
|
1c47b3f6f5 | ||
|
|
d26d60def4 | ||
|
|
a983a06e41 | ||
|
|
ed02b59177 | ||
|
|
6df4ab49ec | ||
|
|
7d73ab32dd | ||
|
|
76db47d989 | ||
|
|
3a9f1f5150 | ||
|
|
a3394db8fe | ||
|
|
f4e2765e69 | ||
|
|
b7db2e991c | ||
|
|
07edc4faf6 | ||
|
|
b441590dd8 | ||
|
|
5a8b1c44ff | ||
|
|
dca056064a | ||
|
|
ec4e1d87ad | ||
|
|
de0117af94 | ||
|
|
16cb4dc6e7 | ||
|
|
985425b866 | ||
|
|
4a2e23ffef | ||
|
|
a172ffe038 | ||
|
|
78405dfa8a | ||
|
|
6768d12fd7 | ||
|
|
78c5be2fa5 | ||
|
|
8ab341f60a | ||
|
|
1a1ee6f027 | ||
|
|
ddfbbda7db | ||
|
|
eb8db5c6c0 | ||
|
|
7ff5616870 | ||
|
|
c540733ace | ||
|
|
33ebbf8fad | ||
|
|
030e975d59 | ||
|
|
7d508765d0 | ||
|
|
0fe84a907f | ||
|
|
ee047618cd | ||
|
|
e76a07c8f6 | ||
|
|
36fa33b032 | ||
|
|
9f9fb24dc3 | ||
|
|
91eefe1eea | ||
|
|
e9e3163ce6 | ||
|
|
75d2c499b2 | ||
|
|
02e0c25847 | ||
|
|
4916648f03 | ||
|
|
f365cd491f | ||
|
|
d3912a5a12 | ||
|
|
30d7785d8c | ||
|
|
ec5fb3ccdb | ||
|
|
a4d318fceb | ||
|
|
a84cfde96c | ||
|
|
2f079df087 | ||
|
|
fff46f0ade | ||
|
|
e4b8daf754 | ||
|
|
b560fcf229 | ||
|
|
c66de51526 | ||
|
|
e60402c8f2 | ||
|
|
cbd05effd2 | ||
|
|
0b0ef36428 | ||
|
|
50d248eb0c | ||
|
|
490f8823a5 | ||
|
|
3da290a4f3 | ||
|
|
9f59868cec | ||
|
|
ddb6015bfd | ||
|
|
19d50d2c09 | ||
|
|
cc97e2a854 | ||
|
|
0c677176b0 | ||
|
|
14a5e6d90a | ||
|
|
fc6c08aff3 | ||
|
|
c57e94dcc4 | ||
|
|
b9c7f14a23 | ||
|
|
0dda077e7f | ||
|
|
a7dace79ad | ||
|
|
e3ef99d1f0 | ||
|
|
2a70cdbe75 | ||
|
|
7cadd1d673 | ||
|
|
463a1e1423 | ||
|
|
a7590cc93f | ||
|
|
c595365c2b | ||
|
|
58da9c0814 | ||
|
|
a1b9a21352 | ||
|
|
074896b2dd | ||
|
|
dc31589ae0 | ||
|
|
523961d432 | ||
|
|
1af22bf2ac | ||
|
|
a0be3bcd56 | ||
|
|
2bdfb139bf | ||
|
|
e154a41d33 | ||
|
|
6360023e6f | ||
|
|
4202421d5b | ||
|
|
14337aa4e7 | ||
|
|
e24f97b12d | ||
|
|
17b1425c78 | ||
|
|
8b71870d2b | ||
|
|
5f2d45f63c | ||
|
|
bdb5fb2418 | ||
|
|
fd576dc27a | ||
|
|
6be6032838 | ||
|
|
e18ff53532 | ||
|
|
2903b8825d | ||
|
|
11f24172cb | ||
|
|
615a955767 | ||
|
|
6c10d072de | ||
|
|
9ab76160f0 | ||
|
|
c8b121958d | ||
|
|
e153de0bb7 | ||
|
|
a50ff4e2e6 | ||
|
|
5f16825cf7 | ||
|
|
bbfec17876 | ||
|
|
86e6e801e9 | ||
|
|
dedf3e3467 | ||
|
|
a06470c0c9 | ||
|
|
5315767638 | ||
|
|
d1c250e6b9 | ||
|
|
6228501581 | ||
|
|
836b03a7ee | ||
|
|
24bc5f3aba | ||
|
|
06c50616b4 | ||
|
|
8d27c01b92 | ||
|
|
9bff33608e | ||
|
|
c5d8ecc4c5 | ||
|
|
aa000c0b02 | ||
|
|
04b5c99ec8 | ||
|
|
ace4d02b8a | ||
|
|
efaec9b442 | ||
|
|
86cf252a87 | ||
|
|
99215c0b20 | ||
|
|
d6b4641d9b | ||
|
|
7eefdd66d5 | ||
|
|
c3d1de7b01 | ||
|
|
302eb3d8d7 | ||
|
|
1f37a07770 | ||
|
|
68198ed2f8 | ||
|
|
6744f1963f | ||
|
|
2dfe967ca1 | ||
|
|
225ae50f10 | ||
|
|
3c8d157cbe | ||
|
|
9f30b9ff5d | ||
|
|
cd4dcf97ac | ||
|
|
e4d6bdc1af | ||
|
|
b3f4bc458b | ||
|
|
748f30b1d1 | ||
|
|
6b4ff4f8b6 | ||
|
|
8e2cf07303 | ||
|
|
ce143ff2dd | ||
|
|
f6d5d546d1 | ||
|
|
0445776d48 | ||
|
|
5eefd2fc90 | ||
|
|
bd66f314fc | ||
|
|
036ac35685 | ||
|
|
b4ceedd043 | ||
|
|
c95c94f67b | ||
|
|
1156c768bb | ||
|
|
a913d512b9 | ||
|
|
7736c71760 | ||
|
|
cd450a3476 | ||
|
|
2dfa8f1c94 | ||
|
|
d585c4f0b9 | ||
|
|
bfa16be526 | ||
|
|
9e643f756a | ||
|
|
deb646c7a9 | ||
|
|
6d8d15ba5d | ||
|
|
2eb87077dd | ||
|
|
47cafe7ea1 | ||
|
|
845f4ca89c | ||
|
|
58f246e1f2 | ||
|
|
f474d330ad | ||
|
|
45e134e116 | ||
|
|
9fae773856 | ||
|
|
e182f5b7bd | ||
|
|
9fb3477466 | ||
|
|
48c0913108 | ||
|
|
a269ef3a76 | ||
|
|
44dd2505ca | ||
|
|
1dc17d5949 | ||
|
|
032935dec9 | ||
|
|
bce4dd6067 | ||
|
|
fe89d626d3 | ||
|
|
caa9984abe | ||
|
|
fa39991bcf | ||
|
|
1a65f48c03 | ||
|
|
7637a215d3 | ||
|
|
084d4c0aa7 | ||
|
|
6acbd7ca6f | ||
|
|
37da67abe5 | ||
|
|
b36bd0e98b | ||
|
|
3852340a58 |
@@ -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
|
||||||
@@ -1,5 +1,21 @@
|
|||||||
|
# Generated MkDocs site and PDF output
|
||||||
|
doc/lwc-doc/site/
|
||||||
|
|
||||||
log/
|
log/
|
||||||
install/
|
/install/
|
||||||
build/
|
/build/
|
||||||
.vscode
|
.vscode
|
||||||
.idea
|
.idea
|
||||||
|
venv
|
||||||
|
.venv
|
||||||
|
.claude
|
||||||
|
.codex
|
||||||
|
.agents
|
||||||
|
__pycache__
|
||||||
|
.pytest_cache
|
||||||
|
|
||||||
|
*.egg-info
|
||||||
|
**.FCBak
|
||||||
|
|
||||||
|
CLAUDE.md
|
||||||
|
AGENTS.md
|
||||||
@@ -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.
|
||||||
@@ -1,13 +1,221 @@
|
|||||||
Подмена файла по пути обязательна: `/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.044 LTS;
|
||||||
|
- доступ в интернет;
|
||||||
|
- права `sudo`;
|
||||||
|
- физический KUKA LBR iiwa 7 R800 либо компьютер для работы только с симулятором.
|
||||||
|
|
||||||
|
### Установка CLI
|
||||||
|
|
||||||
|
Запустите установщик:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/install.sh | bash
|
||||||
|
```
|
||||||
|
|
||||||
|
Установщик проверит базовые инструменты, установит Docker, `uv` и Python 3.11 при необходимости, склонирует проект в `~/.lwc` и установит CLI `cobot`. Каталог можно изменить переменной `COBOT_INSTALL_DIR`.
|
||||||
|
|
||||||
|
Откройте новый терминал или обновите окружение оболочки, затем запустите мастер первоначальной настройки:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cobot setup
|
||||||
|
```
|
||||||
|
|
||||||
|
Мастер последовательно предложит запустить локальную документацию, настроить `cobot-setting.yaml` и выбрать среду сборки: нативный ROS 2 или Docker.
|
||||||
|
|
||||||
|
### Только симуляция
|
||||||
|
|
||||||
|
Для работы в 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/) | Работа выполнена при поддержке Российского научного фонда |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- ============================================================ -->
|
||||||
|
<!-- Черновые команды — будут удалены в следующих версиях -->
|
||||||
|
<!-- ============================================================ -->
|
||||||
|
|
||||||
|
## Черновые команды
|
||||||
|
|
||||||
|
> Вроде уже не обязательно
|
||||||
|
Подмена файла по пути обязательна: `/opt/ros/rolling/lib/webots_ros2_driver/ros2_supervisor.py`
|
||||||
|
необходимо `warn` заменить на `warning` в логере
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|
||||||
sudo apt install -y ros-${ROS_DISTRO}-webots-ros2 \
|
sudo apt install -y ros-${ROS_DISTRO}-webots-ros2 \
|
||||||
ros-${ROS_DISTRO}-ros2-control \
|
ros-${ROS_DISTRO}-ros2-control \
|
||||||
ros-${ROS_DISTRO}-ros2-controllers \
|
ros-${ROS_DISTRO}-ros2-controllers \
|
||||||
ros-${ROS_DISTRO}-moveit-* \
|
ros-${ROS_DISTRO}-moveit \
|
||||||
|
ros-${ROS_DISTRO}-moveit-py \
|
||||||
|
ros-${ROS_DISTRO}-rmw-cyclonedds-cpp \
|
||||||
|
ros-${ROS_DISTRO}-ament-cmake-clang-format \
|
||||||
|
ros-${ROS_DISTRO}-rosbag2-storage-mcap \
|
||||||
|
ros-${ROS_DISTRO}-librealsense2 \
|
||||||
|
ros-${ROS_DISTRO}-realsense2* \
|
||||||
|
libportaudio2 \
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Установка moveit2 (внимательно проверяй)
|
Установка moveit2 (внимательно проверяй)
|
||||||
@@ -22,10 +230,123 @@ sudo apt install -y build-essential \
|
|||||||
python3-vcstool \
|
python3-vcstool \
|
||||||
wget
|
wget
|
||||||
|
|
||||||
git clone https://github.com/moveit/moveit2.git
|
# Not Using
|
||||||
vcs import --recursive < moveit2/moveit2.repos
|
LC_ALL=C ros2 launch iiwa_moveit demo...
|
||||||
sudo apt remove ros-$ROS_DISTRO-moveit*
|
|
||||||
rosdep install -r --from-paths ./src/ --ignore-src --rosdistro $ROS_DISTRO --os=ubuntu:noble -y
|
|
||||||
|
|
||||||
colcon build --mixin release
|
sudo pip3 install transforms3d --break-system-packages
|
||||||
```
|
```
|
||||||
|
Отправка робота в точку:
|
||||||
|
```bash
|
||||||
|
ros2 action send_goal /iiwa/move_to_pose iiwa_msgs/action/MoveToPose \
|
||||||
|
"{x: 0.5, y: 0.0, z: 0.5, a: 3.14, b: 0, c: 0, speed: 0.1, planner: 'ptp'}"
|
||||||
|
|
||||||
|
ros2 action send_goal --feedback /iiwa/move_to_joints iiwa_msgs/action/MoveToJoints \
|
||||||
|
"{joints: [0.0, 0.0, 0.0, -1.57, 0.0, 1.57, 0.0], speed: 0.4}"
|
||||||
|
|
||||||
|
ros2 service call /iiwa/move_to_named iiwa_msgs/srv/MoveToNamedPose \
|
||||||
|
"{name: 'home', speed: 0.5}"
|
||||||
|
|
||||||
|
ros2 service call /iiwa/move_to_named iiwa_msgs/srv/MoveToNamedPose \
|
||||||
|
"{name: 'work', speed: 0.3}"
|
||||||
|
|
||||||
|
ros2 service call /iiwa/stop std_srvs/srv/Trigger "{}"
|
||||||
|
```
|
||||||
|
|
||||||
|
Примеры использования `test_motion_sequence`:
|
||||||
|
```bash
|
||||||
|
ros2 run iiwa_planning motion_sequence_runner \
|
||||||
|
--ros-args \
|
||||||
|
-p config_path:=/path/to/config.json \
|
||||||
|
-p n_iterations:=3 \
|
||||||
|
-p delay_between_iterations:=5.0 \
|
||||||
|
-p bag_path:=/tmp/my_bag \
|
||||||
|
-p joints_action:=my_ns/move_to_joints \
|
||||||
|
-p pose_action:=my_ns/move_to_pose
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Спавн объекта:
|
||||||
|
```bash
|
||||||
|
{
|
||||||
|
"data": "Solid { name \"test_box2\" translation 0 1 0.5 children [ Shape { appearance PBRAppearance { baseColor 0.901961 0.380392 0 } geometry Box { size 0.1 0.1 0.1 } } ] boundingObject Box { size 0.1 0.1 0.1 } physics Physics { } }"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Спавн `.proto`:
|
||||||
|
|
||||||
|
|
||||||
|
Можно заготовить готовые `.proto` файлы, и потом случайно спавнить объект по такому принципу + создать Node который будет вызываться и спавнить этот объекты. Может быть шаблон куда потом подставятся данные через `.format()`. По такому же принципу спавн человека. Остается понять, только задать область спавна относительно робта
|
||||||
|
|
||||||
|
Установка зависимостей для сборки пакетов:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
rosdep install --from-paths src --ignore-src -r -y --os=ubuntu:jammy
|
||||||
|
```
|
||||||
|
|
||||||
|
Запись данных в rosbag:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ sudo apt-get install ros-$ROS_DISTRO-rosbag2-storage-mcap
|
||||||
|
|
||||||
|
# Record all topics
|
||||||
|
ros2 bag record -a --storage mcap -o my_session
|
||||||
|
|
||||||
|
# Record specific topics
|
||||||
|
ros2 bag record \
|
||||||
|
/camera/image_raw \
|
||||||
|
/lidar/points \
|
||||||
|
/imu/data \
|
||||||
|
--storage mcap \
|
||||||
|
-o robot_drive_session
|
||||||
|
|
||||||
|
|
||||||
|
# LZ4 = faster write, moderate compression (good for real-time recording)
|
||||||
|
ros2 bag record -a --storage mcap \
|
||||||
|
--compression-mode file \
|
||||||
|
--compression-format lz4 \
|
||||||
|
-o compressed_session
|
||||||
|
|
||||||
|
# Zstandard = slower write, better compression (good for post-processing)
|
||||||
|
ros2 bag record -a --storage mcap \
|
||||||
|
--compression-mode file \
|
||||||
|
--compression-format zstd \
|
||||||
|
-o compressed_zstd_session
|
||||||
|
|
||||||
|
# convert existing rosbag2 to mcap format
|
||||||
|
ros2 bag convert \
|
||||||
|
-i robot_drive_old/ \
|
||||||
|
-o robot_drive_mcap/ \
|
||||||
|
--output-options '{"storage_id": "mcap"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
<!-- Generate Doc -->
|
||||||
|
```bash
|
||||||
|
chmod +x doc/build_docs.sh
|
||||||
|
|
||||||
|
./build_docs.sh #Собирает статику в mkdocs/site/
|
||||||
|
./build_docs.sh build # То же самое явно
|
||||||
|
./build_docs.sh serve # Live-preview с авто-перезагрузкой
|
||||||
|
```
|
||||||
|
|
||||||
|
<!-- iiwa controller - docker -->
|
||||||
|
<!-- Lightweight cobot -->
|
||||||
|
```bash
|
||||||
|
docker build -t evilfisru/lwc:... -f docker/jazzy/.../Dockerfile .
|
||||||
|
|
||||||
|
docker run -it --rm --network host evilfisru/lwa:jazzy-lwa7-noble
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# release - src/build/log удаляются (по умолчанию)
|
||||||
|
`docker build -t my-image .`
|
||||||
|
|
||||||
|
# dev - src остаётся для отладки
|
||||||
|
`docker build --build-arg BUILD_TYPE=dev -t my-image .`
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
# URL для доступа к MCP LLM
|
||||||
|
http://localhost:8007/mcp/mcp
|
||||||
|
|
||||||
|
```
|
||||||
|
|||||||
@@ -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 |
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
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
|
||||||
|
token: "ysXOyL_p3-f2YH2WqQ808KgQUA32qACziKdfqbhsJsPI0GGkoRbGn9eU22FV8mdS"
|
||||||
|
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 # Не падать, если нода не отвечает на запросы параметров (защита от зависания при старте)
|
||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
@@ -0,0 +1,336 @@
|
|||||||
|
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)"),
|
||||||
|
_Field("token", "Токен Bearer для REST API и MCP:", "",
|
||||||
|
note="Длинный секрет. Хранится в cobot-setting.yaml и нужен при внешнем host; пустое значение отключает авторизацию"),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
_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}")
|
||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
build:
|
||||||
|
base-paths:
|
||||||
|
- src
|
||||||
|
|
||||||
|
list:
|
||||||
|
base-paths:
|
||||||
|
- src
|
||||||
|
|
||||||
|
test:
|
||||||
|
base-paths:
|
||||||
|
- src
|
||||||
@@ -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
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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 ? "📄 Download PDF" : "📄 Скачать 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,185 @@
|
|||||||
|
# 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
|
||||||
|
token: "replace-with-a-long-secret-token"
|
||||||
|
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` |
|
||||||
|
| `token` | Bearer token for the REST API and MCP; required for an external `host` |
|
||||||
|
| `endpoints` | Path to the REST endpoint description |
|
||||||
|
| `joint_limits` | Path to joint limits used for command validation |
|
||||||
|
|
||||||
|
When `token` is set, every request to a protected REST or MCP route must include
|
||||||
|
the `Authorization: Bearer <token>` header. The `/docs`, `/redoc`, and
|
||||||
|
`/openapi.json` resources are public only to load Swagger UI. An empty `token`
|
||||||
|
is allowed only for local access (`127.0.0.1` or `localhost`); the server
|
||||||
|
refuses to start with an external `host`. Protect the settings file and do not
|
||||||
|
publish the token.
|
||||||
|
|
||||||
|
After startup, the REST API is available at `http://<host>:8007`, and MCP is available at `/mcp/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,187 @@
|
|||||||
|
# Конфигурация системы
|
||||||
|
|
||||||
|
## Главный конфигурационный файл
|
||||||
|
|
||||||
|
Все параметры системы хранятся в одном файле — **`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
|
||||||
|
token: "замените-на-длинный-секретный-токен"
|
||||||
|
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`) |
|
||||||
|
| `token` | Bearer-токен для REST API и MCP; обязателен для внешнего `host` |
|
||||||
|
| `endpoints` | Путь к описанию REST-эндпоинтов |
|
||||||
|
| `joint_limits` | Путь к файлу ограничений суставов для валидации команд |
|
||||||
|
|
||||||
|
Если `token` заполнен, каждый запрос к защищённому REST- или MCP-маршруту
|
||||||
|
должен содержать заголовок `Authorization: Bearer <token>`. Страницы
|
||||||
|
`/docs`, `/redoc` и `/openapi.json` доступны без токена только для загрузки
|
||||||
|
Swagger UI. Пустой `token` допустим только для локального доступа
|
||||||
|
(`127.0.0.1` или `localhost`); при внешнем `host` сервер не запустится.
|
||||||
|
Храните файл настроек с ограниченными правами доступа и не публикуйте токен.
|
||||||
|
|
||||||
|
После запуска REST API доступен по адресу `http://<host>:8007`, MCP — по пути `/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,710 @@
|
|||||||
|
# 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
|
||||||
|
token: "replace-with-a-long-secret-token"
|
||||||
|
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.
|
||||||
|
|
||||||
|
When `host` is not `localhost`, `127.0.0.1`, or another loopback address, the
|
||||||
|
`token` field is required; otherwise the server exits during startup. When
|
||||||
|
`token` is set, Bearer authentication applies to every REST route and to the
|
||||||
|
MCP route `/mcp/mcp`, including with a local `host`.
|
||||||
|
|
||||||
|
The `/docs`, `/redoc`, and `/openapi.json` resources are available without a
|
||||||
|
header so the browser can load Swagger UI. This does not expose control
|
||||||
|
commands. Open `/docs`, click **Authorize**, paste the `web.token` value without
|
||||||
|
the word `Bearer`, and confirm. Swagger adds the header to API requests.
|
||||||
|
|
||||||
|
The token is stored in **cobot-setting.yaml**. Do not add it to documentation,
|
||||||
|
scripts, or public repositories. If it is exposed, replace it and restart the
|
||||||
|
stack. For remote access, also restrict port 8007 with a firewall or VPN.
|
||||||
|
|
||||||
|
### REST and MCP authentication
|
||||||
|
|
||||||
|
Every request to a protected REST route or MCP must include the following header
|
||||||
|
when `web.token` is set:
|
||||||
|
|
||||||
|
~~~ http
|
||||||
|
Authorization: Bearer <web.token value>
|
||||||
|
~~~
|
||||||
|
|
||||||
|
Client setup examples:
|
||||||
|
|
||||||
|
=== "curl"
|
||||||
|
|
||||||
|
~~~ bash
|
||||||
|
HOST=http://localhost:8007
|
||||||
|
API_TOKEN='copy web.token from cobot-setting.yaml'
|
||||||
|
AUTH_HEADER="Authorization: Bearer ${API_TOKEN}"
|
||||||
|
curl -sS -H "${AUTH_HEADER}" $HOST/robot/joint_states
|
||||||
|
~~~
|
||||||
|
|
||||||
|
=== "Python"
|
||||||
|
|
||||||
|
~~~ python
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
HOST = "http://localhost:8007"
|
||||||
|
API_TOKEN = "copy web.token from cobot-setting.yaml"
|
||||||
|
HEADERS = {"Authorization": f"Bearer {API_TOKEN}"}
|
||||||
|
response = httpx.get(f"{HOST}/robot/joint_states", headers=HEADERS, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
~~~
|
||||||
|
|
||||||
|
=== "MATLAB"
|
||||||
|
|
||||||
|
~~~ matlab
|
||||||
|
HOST = 'http://localhost:8007';
|
||||||
|
API_TOKEN = 'copy web.token from cobot-setting.yaml';
|
||||||
|
readOpts = weboptions('Timeout', 10, ...
|
||||||
|
'HeaderFields', {'Authorization', ['Bearer ' API_TOKEN]});
|
||||||
|
jointState = webread([HOST '/robot/joint_states'], readOpts);
|
||||||
|
~~~
|
||||||
|
|
||||||
|
Pass the same header when connecting an MCP client to
|
||||||
|
`http://<host>:8007/mcp/mcp`. If the client supports custom HTTP headers, set
|
||||||
|
`Authorization: Bearer <web.token value>` in its connection settings.
|
||||||
|
|
||||||
|
## 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 J1–J7 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 J1–J7 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**. It uses the same Bearer token; pass the `Authorization` header when connecting an MCP client. For ordinary HTTP integrations, use the endpoints documented on this page.
|
||||||
@@ -0,0 +1,714 @@
|
|||||||
|
# Управление через 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
|
||||||
|
token: "замените-на-длинный-секретный-токен"
|
||||||
|
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-компонентов проверяется при обращении к конкретному маршруту.
|
||||||
|
|
||||||
|
Если `host` отличается от `localhost`, `127.0.0.1` или другого loopback-адреса,
|
||||||
|
поле `token` обязательно: без него сервер завершит запуск с ошибкой. Если
|
||||||
|
`token` заполнен, Bearer-аутентификация применяется ко всем REST-маршрутам и
|
||||||
|
к MCP-маршруту `/mcp/mcp`, в том числе при локальном `host`.
|
||||||
|
|
||||||
|
Страницы `/docs`, `/redoc` и схема `/openapi.json` доступны без заголовка,
|
||||||
|
чтобы браузер мог загрузить Swagger UI. Это не открывает команды управления.
|
||||||
|
Откройте `/docs`, нажмите **Authorize**, вставьте значение `web.token` без
|
||||||
|
слова `Bearer` и подтвердите. Swagger сам добавит нужный заголовок к запросам.
|
||||||
|
|
||||||
|
Токен хранится в **cobot-setting.yaml**. Не добавляйте его в документацию,
|
||||||
|
скрипты или публичные репозитории; после утечки замените значение и перезапустите
|
||||||
|
стек. Для удалённого доступа дополнительно ограничьте порт 8007 firewall или VPN.
|
||||||
|
|
||||||
|
### Аутентификация REST и MCP
|
||||||
|
|
||||||
|
Каждый запрос к защищённому REST-маршруту или MCP при заполненном `web.token`
|
||||||
|
должен содержать:
|
||||||
|
|
||||||
|
~~~ http
|
||||||
|
Authorization: Bearer <значение-web.token>
|
||||||
|
~~~
|
||||||
|
|
||||||
|
Примеры подготовки клиентов:
|
||||||
|
|
||||||
|
=== "curl"
|
||||||
|
|
||||||
|
~~~ bash
|
||||||
|
HOST=http://localhost:8007
|
||||||
|
API_TOKEN='скопируйте значение web.token из cobot-setting.yaml'
|
||||||
|
AUTH_HEADER="Authorization: Bearer ${API_TOKEN}"
|
||||||
|
curl -sS -H "${AUTH_HEADER}" $HOST/robot/joint_states
|
||||||
|
~~~
|
||||||
|
|
||||||
|
=== "Python"
|
||||||
|
|
||||||
|
~~~ python
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
HOST = "http://localhost:8007"
|
||||||
|
API_TOKEN = "скопируйте значение web.token из cobot-setting.yaml"
|
||||||
|
HEADERS = {"Authorization": f"Bearer {API_TOKEN}"}
|
||||||
|
response = httpx.get(f"{HOST}/robot/joint_states", headers=HEADERS, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
~~~
|
||||||
|
|
||||||
|
=== "MATLAB"
|
||||||
|
|
||||||
|
~~~ matlab
|
||||||
|
HOST = 'http://localhost:8007';
|
||||||
|
API_TOKEN = 'скопируйте значение web.token из cobot-setting.yaml';
|
||||||
|
readOpts = weboptions('Timeout', 10, ...
|
||||||
|
'HeaderFields', {'Authorization', ['Bearer ' API_TOKEN]});
|
||||||
|
jointState = webread([HOST '/robot/joint_states'], readOpts);
|
||||||
|
~~~
|
||||||
|
|
||||||
|
Тот же заголовок передаётся MCP-клиенту при подключении к
|
||||||
|
`http://<host>:8007/mcp/mcp`. Если клиент поддерживает пользовательские HTTP
|
||||||
|
заголовки, укажите `Authorization: Bearer <значение-web.token>` в его настройках.
|
||||||
|
|
||||||
|
## Подготовка к примерам
|
||||||
|
|
||||||
|
Вкладки на этой странице синхронизированы: выберите удобный язык один раз, и тот же вариант будет открыт у следующих примеров.
|
||||||
|
|
||||||
|
=== "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", headers=HEADERS, 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", headers=HEADERS, 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", headers=HEADERS, 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",
|
||||||
|
headers=HEADERS,
|
||||||
|
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", headers=HEADERS, 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",
|
||||||
|
headers=HEADERS,
|
||||||
|
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", headers=HEADERS, 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",
|
||||||
|
headers=HEADERS,
|
||||||
|
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", headers=HEADERS, 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",
|
||||||
|
headers=HEADERS,
|
||||||
|
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", headers=HEADERS, timeout=T_READ)
|
||||||
|
status.raise_for_status()
|
||||||
|
print(status.json())
|
||||||
|
|
||||||
|
logs = httpx.get(f"{HOST}/sequences/logs", headers=HEADERS, 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", headers=HEADERS, 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**. Он использует тот же Bearer-токен; передайте заголовок `Authorization` при подключении 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)
|
||||||
@@ -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)
|
||||||
@@ -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 3–4"
|
||||||
|
After installing the project, run `cobot setup`. The wizard will configure the documentation, robot parameters, and the ROS 2 or Docker build environment.
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
---
|
||||||
|
hide:
|
||||||
|
- navigation
|
||||||
|
- toc
|
||||||
|
- footer
|
||||||
|
---
|
||||||
|
|
||||||
|
<meta http-equiv="refresh" content="0; url=./getting-started/">
|
||||||
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 8.2 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 9.3 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 128 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 126 KiB |
|
After Width: | Height: | Size: 86 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 103 KiB |
|
After Width: | Height: | Size: 144 KiB |
|
After Width: | Height: | Size: 212 KiB |
|
After Width: | Height: | Size: 151 KiB |
|
After Width: | Height: | Size: 108 KiB |
|
After Width: | Height: | Size: 168 KiB |
|
After Width: | Height: | Size: 168 KiB |
|
After Width: | Height: | Size: 190 KiB |
|
After Width: | Height: | Size: 133 KiB |
|
After Width: | Height: | Size: 164 KiB |
|
After Width: | Height: | Size: 136 KiB |
|
After Width: | Height: | Size: 153 KiB |
|
After Width: | Height: | Size: 136 KiB |
|
After Width: | Height: | Size: 156 KiB |
|
After Width: | Height: | Size: 161 KiB |
|
After Width: | Height: | Size: 152 KiB |
|
After Width: | Height: | Size: 132 KiB |
|
After Width: | Height: | Size: 122 KiB |
|
After Width: | Height: | Size: 150 KiB |
|
After Width: | Height: | Size: 162 KiB |
|
After Width: | Height: | Size: 186 KiB |