AgroTechSim API
Русский
🚀 Описание
AgroTechSim API — это Python-библиотека для работы с симулятором AgroTechSim, предназначенная для получения телеметрии с дронов, обработки сенсорных данных и реализации систем автономного управления. Библиотека предоставляет как низкоуровневый доступ к сырым данным сенсоров, так и высокоуровневые абстракции для упрощённого управления дроном.
Модуль позволяет разработчикам создавать сложные алгоритмы компьютерного зрения, навигации и управления без необходимости работы с реальным оборудованием, используя полнофункциональный симулятор дронов.
📊 Совместимость
| Компонент | Версия | Статус |
|---|---|---|
| AgroTechSim API | 1.0.1-v1.0.2 | ✅ Compatible with AgroTechSim 1.0.3 |
| AgroTechSim API | 1.0.3 | ✅ Compatible with AgroTechSim 1.0.4-1.0.5 |
| Python | 3.10 | ✅ Recommended |
| InavMSPApi | 1.1.0 | ✅ Dependency |
⚡ Установка
Вариант 1: Установка из PyPi (рекомендуется)
pip install agrotechsimapi
Этот способ автоматически установит все зависимости, включая inavmspapi требуемой версии.
Вариант 2: Установка из исходников
- Клонируйте репозиторий:
git clone https://github.com/AgroTechAvia/TechSimApi.git
cd TechSimApi
- Запустите скрипт установки:
python setup_by_source.py
Скрипт автоматически установит все зависимости и настроит окружение.
Вариант 3: Ручная установка (для разработчиков)
# 1. Создайте виртуальное окружение
python -m venv .venv
# 2. Активируйте окружение
# Windows:
.venv\Scripts\activate
# Linux/Mac:
source .venv/bin/activate
# 3. Установите inavmspapi
git clone https://github.com/AgroTechAvia/InavMSPApi.git
cd InavMSPApi
git checkout v1.1.0
pip install .
# 4. Установите agrotechsimapi
cd ..
git clone https://github.com/AgroTechAvia/TechSimApi.git
cd TechSimApi
pip install .
🎯 Функционал
Низкоуровневый API (SimClient)
- 📷 Камеры: Получение цветных, тепловизионных, глубинных и спектральных изображений
- 📡 Лидар: 360° сканирование окружения с настраиваемыми параметрами
- 🎯 Радар: Обнаружение ближайших объектов с угловыми координатами
- 📏 Дальномер: Точечное измерение расстояния
- 💡 LED управление: Контроль подсветки дрона
- 📊 Кинематика: Получение позиции, ориентации и скорости дрона
Высокоуровневый API (HighLevelSimClient)
- 🚁 Управление полётом: Взлёт, посадка, удержание высоты
- 🧭 Навигация: Движение к координатам в разных системах отсчёта
- 🎯 Стабилизация: PID-регуляторы для автоматического удержания позиции
- 👁️ Обработка изображений: Детектирование ArUco маркеров и blob-объектов
- 🔄 Одометрия: Отслеживание перемещения относительно начальной точки
- Обновление автономного полета: Пакет содержит именованные PID-профили и встроенный калибратор. Готовые пресеты
edu-ext,edu-constructorиeduможно выбрать при создании клиента; отдельные регуляторы по-прежнему можно переопределять вручную.
📁 Примеры использования
В репозитории представлены готовые примеры:
examples_low_level/ - Низкоуровневые примеры
examples_high_level/ - Высокоуровневые примеры
🚀 Быстрый старт
from agrotechsimapi import SimClient, CaptureType
import cv2
# Подключение к симулятору
client = SimClient(address="127.0.0.1", port=8080)
# Получение изображения с камеры
image = client.get_camera_capture(camera_id=0, type=CaptureType.color)
# Отображение изображения
cv2.imshow("Drone Camera", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
🎛️ Калибровка автономного полёта
По умолчанию HighLevelSimClient использует встроенный профиль edu-ext.
Профиль можно выбрать по имени:
from agrotechsimapi import HighLevelSimClient
client = HighLevelSimClient(calibration="edu")
Посмотреть доступные профили и создать конфигурацию новой калибровки:
python -m agrotechsimapi calibrations list
python -m agrotechsimapi calibrations init-config --output calibration.json
Сначала рекомендуется проверить план без подключения к симулятору, а затем
запустить полёт с --fly:
python -m agrotechsimapi calibrate --name my_drone --config calibration.json
python -m agrotechsimapi calibrate --name my_drone --config calibration.json --fly
Калибратор последовательно настраивает высоту, yaw, ускорение XY, скорость XY и положение XY. Посмотреть текущий запуск или готовый профиль можно в автономном HTML-отчёте:
python -m agrotechsimapi plot --current --last 8 --open
python -m agrotechsimapi plot --calibration my_drone --open
Профили можно переносить между окружениями:
python -m agrotechsimapi calibrations export my_drone --output my_drone.json
python -m agrotechsimapi calibrations import my_drone.json --name imported_drone
Подробности находятся в практической инструкции и техническом описании.
🧪 Тестирование работоспособности
Для проверки корректной работы модуля с симулятором используйте интеграционные тесты. Файл test_sim_client_real.py содержит тесты, которые проверяют подключение к симулятору и работу всех основных функций.
📋 Предварительные требования:
- Запущенный симулятор AgroTechSim
- Дрон появился в симуляторе
- Установлен Python 3.10+ и необходимые зависимости
🚀 Запуск тестов:
# Перейдите в директорию проекта
cd TechSimApi
# Запустите тесты с симулятором
pytest test/test_sim_client_real.py --with-simulator -v
📊 Что проверяют тесты:
Тест test_sim_client_real.py последовательно проверяет:
- ✅ Подключение к симулятору - проверка соединения
- ✅ Получение изображений с камер - цветная, тепловизионная, глубинная камеры
- ✅ Кинематические данные - позиция и ориентация дрона
- ✅ Данные дальномера - измерение расстояния
- ✅ Сканирование лидаром - 360° сканирование окружения
- ✅ Радар - обнаружение ближайших объектов
- ✅ Управление LED - включение/выключение подсветки
- ✅ Обработка изображений - добавление шума и артефактов
- ✅ Несколько камер - работа с разными ID камер
- ✅ Обработка ошибок - корректная реакция на невалидные параметры
- ✅ Производительность - время отклика основных функций
⚠️ Важные замечания по тестированию:
- Симулятор должен быть запущен перед запуском тестов
- Тесты могут пропускаться, если определенный сенсор не доступен в текущей конфигурации симулятора
- Первые измерения лидара и радара могут быть некорректными (особенность симулятора)
- Для ручной проверки можно использовать скрипт:
🔧 Пример вывода успешного тестирования:
============================================================
Running SimClient Integration Tests with Real Simulator
============================================================
test_connection: ✓ PASSED
test_get_camera_capture: ✓ PASSED
test_get_kinematics_data: ✓ PASSED
test_get_range_data: ✓ PASSED
test_get_laser_scan: ✓ PASSED
test_get_radar_point: ⚠ SKIPPED (Radar not available)
test_led_control: ✓ PASSED
test_image_processing_methods: ✓ PASSED
test_multiple_camera_ids: ✓ PASSED
test_call_event_action: ✓ PASSED
test_error_handling: ✓ PASSED
test_performance: ✓ PASSED
✅ Все основные функции работают корректно!
🐛 Если тесты не проходят:
- Проверьте подключение к симулятору:
from agrotechsimapi import SimClient
client = SimClient()
print(f"Connected: {client.is_connected()}")
- Убедитесь, что порт 8080 открыт:
# Linux/Mac
nc -z localhost 8080
# Windows
Test-NetConnection -ComputerName localhost -Port 8080
- Проверьте, что дрон заспавнен в симуляторе
Тестирование позволяет убедиться, что все компоненты модуля работают корректно с текущей версией симулятора.
English
🚀 Description
AgroTechSim API is a Python library for working with the AgroTechSim simulator, designed for obtaining drone telemetry, processing sensor data, and implementing autonomous control systems. The library provides both low-level access to raw sensor data and high-level abstractions for simplified drone control.
The module enables developers to create complex computer vision, navigation, and control algorithms without the need for real hardware, using a full-featured drone simulator.
📊 Compatibility
| Component | Version | Status |
|---|---|---|
| AgroTechSim API | 1.0.1-v1.0.2 | ✅ Works with AgroTechSim 1.0.3 |
| AgroTechSim API | 1.0.3 | ✅ Works with AgroTechSim 1.0.4-1.0.5 |
| Python | 3.10 | ✅ Recommended |
| InavMSPApi | 1.1.0 | ✅ Dependency |
⚡ Installation
Option 1: Install from PyPi (recommended)
pip install agrotechsimapi
This method will automatically install all dependencies, including the required version of inavmspapi.
Option 2: Install from source
- Clone the repository:
git https://github.com/AgroTechAvia/TechSimApi.git
cd TechSimApi
- Run the installation script:
python setup_by_source.py
The script will automatically install all dependencies and set up the environment.
Option 3: Manual installation (for developers)
# 1. Create a virtual environment
python -m venv .venv
# 2. Activate the environment
# Windows:
.venv\Scripts\activate
# Linux/Mac:
source .venv/bin/activate
# 3. Install inavmspapi
git clone https://github.com/AgroTechAvia/InavMSPApi.git
cd InavMSPApi
git checkout v1.1.0
pip install .
# 4. Install agrotechsimapi
cd ..
git clone https://github.com/AgroTechAvia/TechSimApi.git
cd TechSimApi
pip install .
🎯 Features
Low-Level API (SimClient)
- 📷 Cameras: Capture color, thermal, depth, and spectral images
- 📡 Lidar: 360° environment scanning with configurable parameters
- 🎯 Radar: Nearest object detection with angular coordinates
- 📏 Rangefinder: Point distance measurement
- 💡 LED Control: Drone lighting control
- 📊 Kinematics: Get drone position, orientation, and velocity
High-Level API (HighLevelSimClient)
- 🚁 Flight Control: Takeoff, landing, altitude hold
- 🧭 Navigation: Movement to coordinates in different reference frames
- 🎯 Stabilization: PID controllers for automatic position hold
- 👁️ Image Processing: ArUco marker and blob object detection
- 🔄 Odometry: Track movement relative to starting point
- Autonomous flight update: The package provides named PID profiles and a built-in calibration workflow. Select
edu-ext,edu-constructor, oreduwhen creating the client; individual controllers can still be overridden manually.
📁 Usage Examples
The repository includes ready-to-use examples:
examples_low_level/ - Low-level examples
examples_high_level/ - High-level examples
🚀 Quick Start
from agrotechsimapi import SimClient, CaptureType
import cv2
# Connect to simulator
client = SimClient(address="127.0.0.1", port=8080)
# Get camera image
image = client.get_camera_capture(camera_id=0, type=CaptureType.color)
# Display image
cv2.imshow("Drone Camera", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
🎛️ Autonomous Flight Calibration
HighLevelSimClient uses the bundled edu-ext profile by default. Select a
different profile by name:
from agrotechsimapi import HighLevelSimClient
client = HighLevelSimClient(calibration="edu")
List available profiles and create an editable calibration configuration:
python -m agrotechsimapi calibrations list
python -m agrotechsimapi calibrations init-config --output calibration.json
Preview the plan first, then add --fly to connect to the simulator:
python -m agrotechsimapi calibrate --name my_drone --config calibration.json
python -m agrotechsimapi calibrate --name my_drone --config calibration.json --fly
The workflow tunes altitude, yaw, XY acceleration, XY velocity and XY position in sequence. Generate a one-time HTML snapshot of the active run or a completed profile with:
python -m agrotechsimapi plot --current --last 8 --open
python -m agrotechsimapi plot --calibration my_drone --lang en --open
Export and import profiles between environments or computers:
python -m agrotechsimapi calibrations export my_drone --output my_drone.json
python -m agrotechsimapi calibrations import my_drone.json --name imported_drone
See the practical calibration guide and the technical reference for details.
🧪 Functionality Testing
To verify that the module works correctly with the simulator, use the integration tests. The test_sim_client_real.py file contains tests that check the connection to the simulator and the operation of all main functions.
📋 Prerequisites:
- Running AgroTechSim simulator on
localhost:8080 - Drone spawned in the simulator
- Python 3.10+ installed with necessary dependencies
🚀 Running tests:
# Go to the project directory
cd TechSimApi
# Run tests with simulator
pytest tests/test_sim_client_real.py --with-simulator -v
📊 What the tests check:
The test_sim_client_real.py test sequentially verifies:
- ✅ Connection to simulator - connection check
- ✅ Camera image capture - color, thermal, depth cameras
- ✅ Kinematic data - drone position and orientation
- ✅ Rangefinder data - distance measurement
- ✅ Lidar scanning - 360° environment scanning
- ✅ Radar - nearest object detection
- ✅ LED control - turning lights on/off
- ✅ Image processing - adding noise and artifacts
- ✅ Multiple cameras - working with different camera IDs
- ✅ Error handling - correct response to invalid parameters
- ✅ Performance - response time of main functions
⚠️ Important testing notes:
- Simulator must be running before starting tests
- Tests may be skipped if a particular sensor is not available in the current simulator configuration
- First lidar and radar measurements may be incorrect (simulator feature)
- For manual checking you can use the script:
🔧 Example of successful test output:
============================================================
Running SimClient Integration Tests with Real Simulator
============================================================
test_connection: ✓ PASSED
test_get_camera_capture: ✓ PASSED
test_get_kinematics_data: ✓ PASSED
test_get_range_data: ✓ PASSED
test_get_laser_scan: ✓ PASSED
test_get_radar_point: ⚠ SKIPPED (Radar not available)
test_led_control: ✓ PASSED
test_image_processing_methods: ✓ PASSED
test_multiple_camera_ids: ✓ PASSED
test_call_event_action: ✓ PASSED
test_error_handling: ✓ PASSED
test_performance: ✓ PASSED
✅ All main functions work correctly!
🐛 If tests fail:
- Check connection to simulator:
from agrotechsimapi import SimClient
client = SimClient()
print(f"Connected: {client.is_connected()}")
- Make sure port 8080 is open:
# Linux/Mac
nc -z localhost 8080
# Windows
Test-NetConnection -ComputerName localhost -Port 8080
- Verify that drone is spawned in simulator
Testing allows you to ensure that all module components work correctly with the current simulator version.
Metadata
Release files for agrotechsimapi 1.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| agrotechsimapi-1.1.0.tar.gz | 2.8 MB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| agrotechsimapi-1.1.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 5.7 MB
Release files / agrotechsimapi-1.1.0.tar.gz
| Download URL | agrotechsimapi-1.1.0.tar.gz |
|---|---|
| Size | 2.8 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a11fb31aa45128e4573594b060ac9145b89b55dea7fb3b4a1300ba87de89652c
|
|
BLAKE2b-256 checksum How to use checksums |
dd32eeb934c52fc2dad666773f8134f5b33e5800b1540cfe3a5b684c4a6a3c6b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.9
|
Release files / agrotechsimapi-1.1.0-py3-none-any.whl
| Download URL | agrotechsimapi-1.1.0-py3-none-any.whl |
|---|---|
| Size | 2.9 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
bfc1fa3e720711a22a99b5b0ebc6ab72d049bbea807f68360f53217928fb163a
|
|
BLAKE2b-256 checksum How to use checksums |
53fa38c1164f95eb1157585f1893c7afe8b0eb86cc86a722e0b6d08afe48fedc
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.9
|