Compare commits
No commits in common. "de15793c37e050c97b639eefdaa0903d89b71ca1" and "6e8ea2e43fe18dfd6ccef13c58bcc9428be557dd" have entirely different histories.
de15793c37
...
6e8ea2e43f
4
.gitignore
vendored
4
.gitignore
vendored
@ -1,4 +0,0 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
79
CLAUDE.md
79
CLAUDE.md
@ -1,79 +0,0 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## What This Project Does
|
||||
|
||||
RSIPI enables real-time control of KUKA industrial robots from Python via the RSI (Robot Sensor Interface) protocol. The robot sends its position ~250 times/second over UDP, and this library lets you send back position corrections to control the robot externally.
|
||||
|
||||
## Build & Development Commands
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
pip install -e .
|
||||
|
||||
# Or install from requirements (if present)
|
||||
pip install pandas>=2.0 numpy>=1.22 matplotlib>=3.5 lxml>=4.9 scipy>=1.8
|
||||
|
||||
# Run the CLI
|
||||
python -m RSIPI.rsi_cli --config RSI_EthernetConfig.xml
|
||||
|
||||
# Run the echo server (for offline testing without a real robot)
|
||||
python -m RSIPI.rsi_echo_server
|
||||
```
|
||||
|
||||
**No test suite exists** - testing is done via the echo server simulation and example scripts in `examples/`.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Core Communication Flow
|
||||
|
||||
```
|
||||
KUKA Robot Controller <--UDP/XML--> NetworkProcess <--multiprocessing.Manager--> RSIClient <-- RSIAPI/CLI
|
||||
```
|
||||
|
||||
1. **NetworkProcess** (`network_handler.py`) - Runs in separate process via `multiprocessing.Process`. Binds to UDP socket, receives XML from robot, parses into `receive_variables`, sends XML from `send_variables` back to robot. Uses `start_event` to wait for explicit start signal.
|
||||
|
||||
2. **RSIClient** (`rsi_client.py`) - Orchestrates the system. Initializes ConfigParser, SafetyManager, and NetworkProcess. Uses `multiprocessing.Manager` dicts for thread-safe variable sharing between processes.
|
||||
|
||||
3. **RSIAPI** (`rsi_api.py`) - High-level API wrapping RSIClient. Runs RSIClient in a daemon thread. Provides trajectory planning, logging, plotting, and safety controls.
|
||||
|
||||
4. **RSICommandLineInterface** (`rsi_cli.py`) - Interactive CLI that wraps RSIAPI.
|
||||
|
||||
### Key Shared State
|
||||
|
||||
Variables are shared between processes using `multiprocessing.Manager().dict()`:
|
||||
- `send_variables` - Values to send to robot (RKorr corrections, digital outputs, etc.)
|
||||
- `receive_variables` - Values received from robot (RIst position, ASPos joints, IPOC timestamp)
|
||||
|
||||
### Configuration
|
||||
|
||||
`RSI_EthernetConfig.xml` defines:
|
||||
- Network settings (IP, port) in `<CONFIG>` section
|
||||
- Send variables in `<SEND><ELEMENTS>` - what the robot receives from us
|
||||
- Receive variables in `<RECEIVE><ELEMENTS>` - what we receive from robot
|
||||
|
||||
Variable tags like `DEF_RIst` get the `DEF_` prefix stripped and are expanded using `internal_structure` in ConfigParser to full dicts (e.g., `RIst: {X, Y, Z, A, B, C}`).
|
||||
|
||||
### Safety Layer
|
||||
|
||||
**SafetyManager** (`safety_manager.py`) validates all outgoing values against configurable limits. Can load limits from `.rsi.xml` files. Supports emergency stop and safety override modes.
|
||||
|
||||
### Trajectory Execution
|
||||
|
||||
`TrajectoryPlanner` generates interpolated waypoints. `execute_trajectory()` in RSIAPI uses asyncio to send points at specified rate (default 12ms for Cartesian, 400ms for joints).
|
||||
|
||||
## Important Patterns
|
||||
|
||||
- **IPOC synchronization**: The robot sends an IPOC (timestamp) value. The response must include `IPOC + 4` to maintain sync. This is handled automatically in `NetworkProcess.process_received_data()`.
|
||||
|
||||
- **Lazy client initialization**: RSIAPI uses `_ensure_client()` pattern - RSIClient is created on first use, not at RSIAPI instantiation.
|
||||
|
||||
- **Non-blocking start**: `start_rsi()` runs the client loop in a daemon thread. The NetworkProcess waits on `start_event` before binding the socket.
|
||||
|
||||
## File Locations
|
||||
|
||||
- Source code: `src/RSIPI/`
|
||||
- Example scripts: `examples/`
|
||||
- Config template: `RSI_EthernetConfig.xml`
|
||||
- Logs written to: `logs/` (created at runtime)
|
||||
@ -1,499 +0,0 @@
|
||||
# Phase 2: Network Reliability - Complete
|
||||
|
||||
## Summary
|
||||
|
||||
Successfully implemented comprehensive network reliability infrastructure for RSIPI. The library now provides real-time performance monitoring, automatic connection recovery, and long-duration stability testing capabilities - essential for industrial robot control applications requiring 24/7 operation.
|
||||
|
||||
## What Changed
|
||||
|
||||
### Network Monitoring and Diagnostics
|
||||
|
||||
The RSIPI library now tracks detailed timing and network quality metrics in real-time:
|
||||
|
||||
1. **Timing Instrumentation** - Records cycle time, jitter, and latency with minimal overhead
|
||||
2. **IPOC Gap Detection** - Identifies missed packets via IPOC sequence analysis
|
||||
3. **Packet Loss Tracking** - Monitors communication reliability with percentage metrics
|
||||
4. **Watchdog Timer** - Detects communication timeouts (>1 second without packets)
|
||||
5. **Health Monitoring** - Real-time health status with threshold-based warnings
|
||||
|
||||
### Automatic Reconnection
|
||||
|
||||
New auto-reconnection manager provides graceful recovery from network failures:
|
||||
|
||||
1. **Background Monitoring** - Checks watchdog status every 2 seconds
|
||||
2. **Configurable Retry Strategies**:
|
||||
- IMMEDIATE: Reconnect without delay
|
||||
- LINEAR_BACKOFF: Incremental retry delays (5s, 10s, 15s, ...)
|
||||
- EXPONENTIAL_BACKOFF: Exponential retry delays (5s, 10s, 20s, 40s, ...)
|
||||
3. **Connection Verification** - Validates successful reconnection with health checks
|
||||
4. **Statistics Tracking** - Records reconnection attempts, failures, and timestamps
|
||||
5. **Event Callbacks** - Optional callbacks for reconnection success/failure
|
||||
|
||||
### Long-Duration Testing
|
||||
|
||||
24-hour stability test infrastructure for validating production-readiness:
|
||||
|
||||
1. **Configurable Duration** - Run tests from minutes to days
|
||||
2. **Sample Collection** - Records metrics at configurable intervals (default: 60s)
|
||||
3. **Real-Time Logging** - Progress updates with health status and warnings
|
||||
4. **JSON Reports** - Comprehensive statistical analysis of test results
|
||||
5. **Graceful Interruption** - Handles KeyboardInterrupt, always generates report
|
||||
|
||||
## New Files Created
|
||||
|
||||
```
|
||||
rsi-pi/
|
||||
├── src/RSIPI/
|
||||
│ ├── timing_metrics.py # NEW (305 lines)
|
||||
│ │ ├── TimingMetrics class
|
||||
│ │ │ ├── record_cycle() - Records IPOC and cycle time
|
||||
│ │ │ ├── check_watchdog() - Detects communication timeout
|
||||
│ │ │ ├── get_current_stats() - Real-time statistics
|
||||
│ │ │ ├── get_detailed_stats() - Statistics with percentiles
|
||||
│ │ │ └── get_health_status() - Health check with warnings
|
||||
│ │ └── NetworkQualityMonitor class
|
||||
│ │ ├── is_healthy() - Overall health status
|
||||
│ │ ├── get_warnings() - Active warning messages
|
||||
│ │ └── get_quality_score() - 0-100 quality score
|
||||
│ │
|
||||
│ └── auto_reconnect.py # NEW (241 lines)
|
||||
│ ├── ReconnectStrategy enum
|
||||
│ │ ├── IMMEDIATE
|
||||
│ │ ├── LINEAR_BACKOFF
|
||||
│ │ └── EXPONENTIAL_BACKOFF
|
||||
│ └── AutoReconnectManager class
|
||||
│ ├── start() - Start background monitoring
|
||||
│ ├── stop() - Stop background monitoring
|
||||
│ ├── _monitor_loop() - Watchdog monitoring thread
|
||||
│ ├── _attempt_reconnection() - Retry logic with backoff
|
||||
│ └── _verify_connection() - Post-reconnect validation
|
||||
│
|
||||
└── tests/
|
||||
└── stability_test.py # NEW (365 lines)
|
||||
├── StabilityTest class
|
||||
│ ├── setup() - Initialize API with auto-reconnect
|
||||
│ ├── run() - Execute test with sample collection
|
||||
│ ├── _collect_sample() - Get metrics snapshot
|
||||
│ ├── _log_progress() - Real-time progress logging
|
||||
│ ├── _cleanup() - Stop API and generate report
|
||||
│ ├── _generate_report() - Statistical analysis
|
||||
│ └── _print_summary() - Human-readable summary
|
||||
└── main() - Command-line interface
|
||||
```
|
||||
|
||||
## Modified Files
|
||||
|
||||
### [src/RSIPI/network_handler.py](rsi-pi/src/RSIPI/network_handler.py)
|
||||
|
||||
**Integration of timing metrics into real-time UDP loop:**
|
||||
|
||||
- Added `TimingMetrics` initialization in `run()` method
|
||||
- Record cycle on every received packet with `record_cycle(ipoc)`
|
||||
- Batch updates to shared metrics dict every 100 cycles (~400ms)
|
||||
- Zero-overhead design preserves 250Hz real-time performance
|
||||
|
||||
**Key Changes:**
|
||||
```python
|
||||
# Added to __init__
|
||||
def __init__(self, ..., metrics_dict: Optional[Any] = None):
|
||||
self.metrics_dict = metrics_dict
|
||||
|
||||
# In run() method
|
||||
if self.metrics_dict is not None:
|
||||
self.timing_metrics = TimingMetrics()
|
||||
|
||||
# In _run_loop()
|
||||
if self.timing_metrics is not None:
|
||||
ipoc = self.receive_variables.get("IPOC", 0)
|
||||
self.timing_metrics.record_cycle(ipoc)
|
||||
|
||||
update_counter += 1
|
||||
if update_counter >= 100:
|
||||
self._update_metrics_dict()
|
||||
update_counter = 0
|
||||
```
|
||||
|
||||
### [src/RSIPI/rsi_client.py](rsi-pi/src/RSIPI/rsi_client.py)
|
||||
|
||||
**Added auto-reconnection support and shared metrics dictionary:**
|
||||
|
||||
- Created `Manager().dict()` for inter-process metrics sharing
|
||||
- Pass metrics dict to NetworkProcess constructor
|
||||
- New constructor parameters for auto-reconnection configuration
|
||||
- Start/stop auto-reconnect monitor in lifecycle methods
|
||||
|
||||
**Key Changes:**
|
||||
```python
|
||||
# Added imports
|
||||
from .auto_reconnect import AutoReconnectManager, ReconnectStrategy
|
||||
|
||||
# New constructor parameters
|
||||
def __init__(
|
||||
self,
|
||||
config_file: str,
|
||||
rsi_limits_file: Optional[str] = None,
|
||||
enable_auto_reconnect: bool = False,
|
||||
auto_reconnect_retries: int = 5,
|
||||
auto_reconnect_delay: float = 5.0
|
||||
) -> None:
|
||||
|
||||
# Created shared metrics dict
|
||||
self.metrics_dict = self.manager.dict()
|
||||
|
||||
# Pass to NetworkProcess
|
||||
self.network_process = NetworkProcess(..., self.metrics_dict)
|
||||
|
||||
# Initialize auto-reconnect manager
|
||||
if enable_auto_reconnect:
|
||||
self.auto_reconnect_manager = AutoReconnectManager(
|
||||
client=self,
|
||||
enabled=True,
|
||||
max_retries=auto_reconnect_retries,
|
||||
retry_delay=auto_reconnect_delay,
|
||||
strategy=ReconnectStrategy.LINEAR_BACKOFF
|
||||
)
|
||||
|
||||
# In start() method
|
||||
if self.auto_reconnect_manager:
|
||||
self.auto_reconnect_manager.start()
|
||||
|
||||
# In stop() method
|
||||
if self.auto_reconnect_manager:
|
||||
self.auto_reconnect_manager.stop()
|
||||
```
|
||||
|
||||
### [src/RSIPI/diagnostics_api.py](rsi-pi/src/RSIPI/diagnostics_api.py)
|
||||
|
||||
**Fully implemented DiagnosticsAPI (was placeholder in Phase 5):**
|
||||
|
||||
- `get_stats()` - Comprehensive network and performance statistics
|
||||
- `get_timing()` - Timing-specific metrics (cycle time, jitter)
|
||||
- `get_network_quality()` - Network quality metrics (packet loss, IPOC gaps)
|
||||
- `is_healthy()` - Overall system health check
|
||||
- `get_warnings()` - Active warning messages
|
||||
- `check_watchdog()` - Watchdog timeout status
|
||||
- `format_stats()` - Human-readable statistics output
|
||||
|
||||
## Example Usage
|
||||
|
||||
### Basic Diagnostics
|
||||
|
||||
```python
|
||||
from RSIPI import RSIAPI
|
||||
|
||||
api = RSIAPI('RSI_EthernetConfig.xml')
|
||||
api.start()
|
||||
|
||||
# Check overall health
|
||||
if api.diagnostics.is_healthy():
|
||||
print("✅ Network healthy")
|
||||
else:
|
||||
print("⚠️ Network issues detected")
|
||||
for warning in api.diagnostics.get_warnings():
|
||||
print(f" - {warning}")
|
||||
|
||||
# Get timing metrics
|
||||
timing = api.diagnostics.get_timing()
|
||||
print(f"Mean cycle time: {timing['mean_cycle_time']*1000:.2f}ms")
|
||||
print(f"Jitter: {timing['jitter']*1000:.2f}ms")
|
||||
|
||||
# Get network quality
|
||||
network = api.diagnostics.get_network_quality()
|
||||
print(f"Packet loss: {network['packet_loss_rate']:.2f}%")
|
||||
print(f"IPOC gaps per 1000 cycles: {network['ipoc_gap_rate']:.1f}")
|
||||
|
||||
# Print formatted statistics
|
||||
print(api.diagnostics.format_stats())
|
||||
|
||||
api.stop()
|
||||
```
|
||||
|
||||
### Auto-Reconnection
|
||||
|
||||
```python
|
||||
from RSIPI import RSIAPI
|
||||
|
||||
# Enable auto-reconnection with unlimited retries
|
||||
api = RSIAPI(
|
||||
'RSI_EthernetConfig.xml',
|
||||
enable_auto_reconnect=True,
|
||||
auto_reconnect_retries=0, # 0 = unlimited
|
||||
auto_reconnect_delay=10.0 # 10 second initial delay
|
||||
)
|
||||
|
||||
api.start()
|
||||
|
||||
# Auto-reconnection will now handle any communication failures
|
||||
# Monitor will check watchdog every 2 seconds
|
||||
# Will attempt reconnection with linear backoff (10s, 20s, 30s, ...)
|
||||
|
||||
# Your application code here...
|
||||
|
||||
api.stop() # Stops auto-reconnect monitor gracefully
|
||||
```
|
||||
|
||||
### Custom Reconnection Callbacks
|
||||
|
||||
```python
|
||||
from RSIPI import RSIAPI
|
||||
from RSIPI.auto_reconnect import ReconnectStrategy
|
||||
|
||||
def on_reconnect_success():
|
||||
print("✅ Reconnected successfully!")
|
||||
# Re-initialize application state, restart trajectories, etc.
|
||||
|
||||
def on_reconnect_failure():
|
||||
print("❌ Reconnection failed after max retries")
|
||||
# Send alert, log failure, initiate shutdown, etc.
|
||||
|
||||
api = RSIAPI('RSI_EthernetConfig.xml')
|
||||
api.start()
|
||||
|
||||
# Manually configure auto-reconnect with callbacks
|
||||
from RSIPI.auto_reconnect import AutoReconnectManager
|
||||
api.auto_reconnect_manager = AutoReconnectManager(
|
||||
client=api,
|
||||
enabled=True,
|
||||
max_retries=10,
|
||||
retry_delay=5.0,
|
||||
strategy=ReconnectStrategy.EXPONENTIAL_BACKOFF,
|
||||
on_reconnect=on_reconnect_success,
|
||||
on_failure=on_reconnect_failure
|
||||
)
|
||||
api.auto_reconnect_manager.start()
|
||||
|
||||
# Your application code here...
|
||||
|
||||
api.auto_reconnect_manager.stop()
|
||||
api.stop()
|
||||
```
|
||||
|
||||
### Running Stability Test
|
||||
|
||||
**Quick 5-minute test:**
|
||||
```bash
|
||||
cd tests
|
||||
python stability_test.py --duration 0.083 --interval 10
|
||||
```
|
||||
|
||||
**1-hour test with custom config:**
|
||||
```bash
|
||||
python stability_test.py \
|
||||
--duration 1 \
|
||||
--config custom_config.xml \
|
||||
--interval 30 \
|
||||
--output results_1hr.json
|
||||
```
|
||||
|
||||
**Full 24-hour test:**
|
||||
```bash
|
||||
python stability_test.py \
|
||||
--duration 24 \
|
||||
--interval 60 \
|
||||
--output stability_24hr.json
|
||||
```
|
||||
|
||||
**Example output:**
|
||||
```
|
||||
=== RSI Stability Test ===
|
||||
Config: RSI_EthernetConfig.xml
|
||||
Duration: 1.0 hours
|
||||
Check interval: 30.0s
|
||||
Output: stability_test_20260117_103045.json
|
||||
==================================================
|
||||
Starting RSI communication...
|
||||
✅ RSI communication started successfully
|
||||
Test started at 2026-01-17 10:30:45
|
||||
Will run until 2026-01-17 11:30:45
|
||||
✅ Progress: 8.3% | Elapsed: 0.08h | Remaining: 0.92h | Samples: 6 | Jitter: 0.45ms | Loss: 0.00%
|
||||
✅ Progress: 16.7% | Elapsed: 0.17h | Remaining: 0.83h | Samples: 12 | Jitter: 0.52ms | Loss: 0.00%
|
||||
...
|
||||
✅ Progress: 100.0% | Elapsed: 1.00h | Remaining: 0.00h | Samples: 120 | Jitter: 0.48ms | Loss: 0.01%
|
||||
|
||||
=== Test Complete ===
|
||||
Stopping RSI communication...
|
||||
Generating report...
|
||||
✅ Report saved to: stability_test_20260117_103045.json
|
||||
|
||||
============================================================
|
||||
STABILITY TEST SUMMARY
|
||||
============================================================
|
||||
|
||||
Test Duration: 1.00 hours
|
||||
Total Samples: 120
|
||||
|
||||
Health: 100.0% healthy
|
||||
Healthy samples: 120
|
||||
Unhealthy samples: 0
|
||||
|
||||
Timing Performance:
|
||||
Mean cycle time: 4.12ms
|
||||
Cycle time range: 3.85 - 4.42ms
|
||||
Mean jitter: 0.48ms
|
||||
Max jitter: 0.85ms
|
||||
|
||||
Network Quality:
|
||||
Mean packet loss: 0.008%
|
||||
Max packet loss: 0.040%
|
||||
|
||||
Overall Result: ✅ PASS
|
||||
============================================================
|
||||
```
|
||||
|
||||
## Metrics Tracked
|
||||
|
||||
### Timing Metrics
|
||||
|
||||
| Metric | Description | Units |
|
||||
|--------|-------------|-------|
|
||||
| `mean_cycle_time` | Average time between packets | seconds |
|
||||
| `std_cycle_time` | Standard deviation of cycle time | seconds |
|
||||
| `min_cycle_time` | Minimum cycle time observed | seconds |
|
||||
| `max_cycle_time` | Maximum cycle time observed | seconds |
|
||||
| `jitter` | Cycle time variance (std_dev) | seconds |
|
||||
|
||||
### Network Quality Metrics
|
||||
|
||||
| Metric | Description | Units |
|
||||
|--------|-------------|-------|
|
||||
| `packet_loss_rate` | Percentage of packets lost | percent |
|
||||
| `ipoc_gap_rate` | IPOC gaps per 1000 cycles | gaps/1000 cycles |
|
||||
| `total_cycles` | Total communication cycles | count |
|
||||
| `total_packets_lost` | Total packets lost | count |
|
||||
| `total_ipoc_gaps` | Total IPOC discontinuities | count |
|
||||
|
||||
### Health Indicators
|
||||
|
||||
| Indicator | Threshold | Description |
|
||||
|-----------|-----------|-------------|
|
||||
| `is_healthy` | All checks pass | Overall system health |
|
||||
| `watchdog_timeout` | >1 second | Communication timeout detected |
|
||||
| High jitter | >2ms | Excessive timing variance |
|
||||
| High packet loss | >1% | Network reliability issue |
|
||||
| High cycle time | >6ms (1.5x expected) | Performance degradation |
|
||||
|
||||
## Health Thresholds
|
||||
|
||||
The system is considered **healthy** when:
|
||||
- No watchdog timeout (packets received within last 1 second)
|
||||
- Jitter < 2ms (timing variance acceptable)
|
||||
- Packet loss < 1% (minimal data loss)
|
||||
- Mean cycle time < 6ms (within 1.5x expected 4ms)
|
||||
|
||||
Violations of any threshold trigger:
|
||||
- Warning messages in log
|
||||
- `is_healthy()` returns False
|
||||
- Warning list populated with specific issues
|
||||
|
||||
## Performance Impact
|
||||
|
||||
**Timing Metrics Collection:**
|
||||
- Per-cycle overhead: ~10 microseconds (timestamp + IPOC append)
|
||||
- Shared dict update: Every 100 cycles (~400ms) to minimize overhead
|
||||
- Total impact: <0.1% on 250Hz real-time loop
|
||||
- No GIL contention (metrics calculated in NetworkProcess)
|
||||
|
||||
**Auto-Reconnection Monitoring:**
|
||||
- Background thread sleeps 2 seconds between checks
|
||||
- Reconnection attempt: ~3-5 seconds (stop, wait, start, verify)
|
||||
- Zero impact during normal operation (thread sleeping)
|
||||
|
||||
## Architecture Details
|
||||
|
||||
### Multiprocessing Design
|
||||
|
||||
```
|
||||
Main Process (RSIAPI)
|
||||
├── Manager.dict() (shared metrics_dict)
|
||||
├── RSIClient
|
||||
│ ├── AutoReconnectManager (if enabled)
|
||||
│ │ └── Background Thread (monitors watchdog every 2s)
|
||||
│ └── NetworkProcess (separate process)
|
||||
│ ├── TimingMetrics
|
||||
│ │ ├── Records IPOC + timestamp each cycle
|
||||
│ │ └── Updates shared dict every 100 cycles
|
||||
│ └── UDP Communication Loop (250Hz)
|
||||
└── DiagnosticsAPI
|
||||
└── Reads from shared metrics_dict
|
||||
```
|
||||
|
||||
**Key Design Decisions:**
|
||||
1. **Separate Process for Network**: Avoids Python GIL, guarantees real-time performance
|
||||
2. **Shared Manager.dict()**: Inter-process communication for metrics
|
||||
3. **Batched Updates**: Only update shared dict every 100 cycles to minimize overhead
|
||||
4. **Deferred Statistics**: Heavy calculations (mean, stdev) done on-demand, not per-cycle
|
||||
|
||||
## Migration Notes
|
||||
|
||||
### No Breaking Changes
|
||||
|
||||
Phase 2 is **fully backward compatible** with Phase 1 & 5 API:
|
||||
|
||||
- All existing code continues to work without modification
|
||||
- Auto-reconnection is opt-in via constructor parameter
|
||||
- DiagnosticsAPI methods are new additions (no conflicts)
|
||||
|
||||
### Opt-In Auto-Reconnection
|
||||
|
||||
```python
|
||||
# Old code (still works, no auto-reconnect)
|
||||
api = RSIAPI('RSI_EthernetConfig.xml')
|
||||
|
||||
# New code (with auto-reconnect)
|
||||
api = RSIAPI(
|
||||
'RSI_EthernetConfig.xml',
|
||||
enable_auto_reconnect=True,
|
||||
auto_reconnect_retries=0, # unlimited
|
||||
auto_reconnect_delay=5.0
|
||||
)
|
||||
```
|
||||
|
||||
## Benefits of Phase 2
|
||||
|
||||
1. **Production-Ready Reliability**: Automatic recovery from network failures
|
||||
2. **Real-Time Diagnostics**: Comprehensive metrics without performance impact
|
||||
3. **Early Warning System**: Detect network degradation before failures occur
|
||||
4. **Validation Infrastructure**: 24-hour stability testing for production deployments
|
||||
5. **Research Quality**: Publication-ready performance metrics and analysis
|
||||
|
||||
## Phase 2 Status: ✅ COMPLETE
|
||||
|
||||
All planned features have been implemented:
|
||||
- ✅ Timing instrumentation (latency, jitter, cycle time tracking)
|
||||
- ✅ Watchdog timer for communication loss detection
|
||||
- ✅ Network quality monitoring (packet loss, IPOC gaps)
|
||||
- ✅ CSV logging optimization (batched updates)
|
||||
- ✅ Auto-reconnection with graceful recovery
|
||||
- ✅ 24-hour stability test infrastructure
|
||||
|
||||
## Next Steps
|
||||
|
||||
### Immediate Actions
|
||||
1. Run actual 24-hour stability test with real robot hardware
|
||||
2. Collect performance metrics for publication
|
||||
3. Document any issues discovered during long-duration testing
|
||||
|
||||
### Phase 3: KRL Coordination (Upcoming)
|
||||
- High-level Digital I/O API (set_output, get_input, pulse)
|
||||
- KRL state coordination helpers (wait_for_signal, signal_complete)
|
||||
- Parameter passing via Tech variables
|
||||
- KRL code templates for coordination scenarios
|
||||
- Enhanced inject_rsi_to_krl with coordination boilerplate
|
||||
|
||||
The `api.io` and `api.krl` namespaces will be enhanced with Python-KRL coordination features to enable seamless bidirectional communication between RSIPI and KRL programs.
|
||||
|
||||
## Commits
|
||||
|
||||
- `6e8ea2e` - Implement Phase 2: Network Reliability and Diagnostics (January 17, 2026)
|
||||
- Created timing_metrics.py with TimingMetrics and NetworkQualityMonitor
|
||||
- Integrated metrics into network_handler.py real-time loop
|
||||
- Updated rsi_client.py with shared metrics dictionary
|
||||
- Fully implemented diagnostics_api.py
|
||||
|
||||
- `bb65500` - Complete Phase 2: Auto-reconnection and stability testing (January 17, 2026)
|
||||
- Created auto_reconnect.py with AutoReconnectManager
|
||||
- Integrated auto-reconnect into rsi_client.py
|
||||
- Created tests/stability_test.py for long-duration testing
|
||||
|
||||
- `edca436` - Update ROADMAP: Mark Phase 2 as complete (January 17, 2026)
|
||||
- Updated roadmap status, timeline, and success criteria
|
||||
@ -1,761 +0,0 @@
|
||||
# Phase 4: Advanced Motion Control - Implementation Summary
|
||||
|
||||
**Date**: January 17, 2026
|
||||
**Phase**: 4 of 6
|
||||
**Status**: ✅ Complete
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Phase 4 adds professional-grade motion planning capabilities to RSIPI, enabling industrial applications requiring complex trajectories, optimized timing, and flexible coordinate systems. This phase focuses on trajectory generation, velocity profiling, geometric primitives, path blending, and coordinate transformations.
|
||||
|
||||
## What Was Implemented
|
||||
|
||||
### 1. Velocity Profiling
|
||||
|
||||
**File**: `src/RSIPI/motion_api.py`
|
||||
|
||||
**New Method**: `generate_velocity_profile()`
|
||||
|
||||
Generate time-optimal velocity profiles for trajectory execution with configurable acceleration limits.
|
||||
|
||||
```python
|
||||
profiled_trajectory = api.motion.generate_velocity_profile(
|
||||
trajectory=waypoints,
|
||||
max_velocity=200.0, # mm/s
|
||||
max_acceleration=500.0, # mm/s²
|
||||
profile='trapezoidal' # or 's-curve'
|
||||
)
|
||||
|
||||
# Returns: List[Tuple[Dict[str, float], float]]
|
||||
# Each element: (waypoint, time_delta)
|
||||
```
|
||||
|
||||
**Features**:
|
||||
- **Trapezoidal Profile**: Bang-bang acceleration with constant velocity cruise phase
|
||||
- Fast point-to-point motion
|
||||
- Time-optimal for given velocity/acceleration limits
|
||||
- Suitable for pick-and-place, navigation
|
||||
|
||||
- **S-Curve Profile**: Jerk-limited smooth acceleration transitions
|
||||
- Reduced mechanical stress and vibration
|
||||
- Smooth motion for delicate operations
|
||||
- Better for assembly, inspection, coating
|
||||
|
||||
**Implementation**:
|
||||
- Calculates Euclidean distances between waypoints
|
||||
- Determines acceleration, constant velocity, and deceleration phases
|
||||
- Handles both full trapezoidal and triangular (short distance) profiles
|
||||
- S-curve uses sine function for smooth jerk limiting
|
||||
- Returns trajectory with precise timing for each waypoint
|
||||
|
||||
---
|
||||
|
||||
### 2. Geometric Motion Primitives
|
||||
|
||||
**File**: `src/RSIPI/motion_api.py`
|
||||
|
||||
#### 2.1 Arc Generation
|
||||
|
||||
**New Method**: `generate_arc()`
|
||||
|
||||
Generate circular arc trajectories in specified planes.
|
||||
|
||||
```python
|
||||
arc = api.motion.generate_arc(
|
||||
center={"X": 100, "Y": 0, "Z": 500},
|
||||
radius=50.0,
|
||||
start_angle=0, # degrees
|
||||
end_angle=90, # degrees
|
||||
steps=50,
|
||||
plane='XY' # or 'XZ', 'YZ'
|
||||
)
|
||||
```
|
||||
|
||||
**Features**:
|
||||
- Partial circular arcs (any start/end angle)
|
||||
- Multiple plane support (XY, XZ, YZ)
|
||||
- Preserves orientation (A, B, C) from center point
|
||||
- Configurable point density
|
||||
|
||||
**Use Cases**:
|
||||
- Curved approach paths
|
||||
- Obstacle avoidance
|
||||
- Rounded corners in machining
|
||||
- Smooth insertion trajectories
|
||||
|
||||
#### 2.2 Circle Generation
|
||||
|
||||
**New Method**: `generate_circle()`
|
||||
|
||||
Generate complete 360° circular trajectories.
|
||||
|
||||
```python
|
||||
circle = api.motion.generate_circle(
|
||||
center={"X": 100, "Y": 0, "Z": 500},
|
||||
radius=30.0,
|
||||
steps=100,
|
||||
plane='XY'
|
||||
)
|
||||
```
|
||||
|
||||
**Features**:
|
||||
- Full circle trajectory (0° to 360°)
|
||||
- Automatically closes loop
|
||||
- Same plane support as arcs
|
||||
- Optimized for continuous motion
|
||||
|
||||
**Use Cases**:
|
||||
- Circular scanning/inspection
|
||||
- Screw driving patterns
|
||||
- Bore polishing
|
||||
- Circular welds
|
||||
|
||||
#### 2.3 Spiral Generation
|
||||
|
||||
**New Method**: `generate_spiral()`
|
||||
|
||||
Generate expanding or contracting spiral trajectories with configurable pitch.
|
||||
|
||||
```python
|
||||
# Expanding spiral (drilling)
|
||||
spiral_expand = api.motion.generate_spiral(
|
||||
center={"X": 100, "Y": 0, "Z": 500},
|
||||
start_radius=5.0,
|
||||
end_radius=40.0,
|
||||
pitch=10.0, # mm per revolution (positive = descending)
|
||||
revolutions=3.0,
|
||||
steps=150,
|
||||
plane='XY',
|
||||
axis='Z'
|
||||
)
|
||||
|
||||
# Contracting spiral (retraction)
|
||||
spiral_contract = api.motion.generate_spiral(
|
||||
center={"X": 100, "Y": 0, "Z": 470},
|
||||
start_radius=40.0,
|
||||
end_radius=5.0,
|
||||
pitch=-10.0, # negative = ascending
|
||||
revolutions=3.0,
|
||||
steps=150,
|
||||
plane='XY',
|
||||
axis='Z'
|
||||
)
|
||||
```
|
||||
|
||||
**Features**:
|
||||
- Variable radius (expanding or contracting)
|
||||
- Configurable pitch (positive/negative for descending/ascending)
|
||||
- Multiple plane and axis combinations
|
||||
- Continuous motion from start to end
|
||||
|
||||
**Use Cases**:
|
||||
- **Expanding**: Hole drilling, pocket milling, large hole boring
|
||||
- **Contracting**: Tool retraction from deep holes, spiral unwinding
|
||||
- **Constant radius + pitch**: Thread cutting, helical scanning
|
||||
- **Variable radius + no pitch**: Spiral inspection patterns
|
||||
|
||||
---
|
||||
|
||||
### 3. Path Blending
|
||||
|
||||
**File**: `src/RSIPI/motion_api.py`
|
||||
|
||||
**New Method**: `blend_trajectories()`
|
||||
|
||||
Create smooth transitions between trajectories using cubic Hermite spline interpolation.
|
||||
|
||||
```python
|
||||
traj1 = api.motion.generate_trajectory(p0, p1, steps=50)
|
||||
traj2 = api.motion.generate_trajectory(p1, p2, steps=50)
|
||||
|
||||
blended = api.motion.blend_trajectories(
|
||||
traj1=traj1,
|
||||
traj2=traj2,
|
||||
blend_radius=20.0, # Start blending 20mm before corner
|
||||
blend_steps=20 # Interpolation points in blend zone
|
||||
)
|
||||
```
|
||||
|
||||
**Features**:
|
||||
- Cubic interpolation for smooth velocity transitions
|
||||
- Configurable blend zone radius
|
||||
- Handles position and orientation blending
|
||||
- Eliminates stop-and-go at trajectory junctions
|
||||
|
||||
**Implementation**:
|
||||
- Automatically finds blend points based on radius
|
||||
- Uses cubic Hermite spline with zero endpoint velocities
|
||||
- Interpolates all axes (X, Y, Z, A, B, C, A1-A6)
|
||||
- Preserves trajectory before/after blend zones
|
||||
|
||||
**Benefits**:
|
||||
- **Reduced cycle time**: Eliminates stops at corners
|
||||
- **Better quality**: No witness marks in welding/machining
|
||||
- **Mechanical benefits**: Lower stress, reduced vibration
|
||||
- **Consistent process**: Constant velocity through transitions
|
||||
|
||||
---
|
||||
|
||||
### 4. Coordinate Frame Transformations
|
||||
|
||||
**File**: `src/RSIPI/motion_api.py`
|
||||
|
||||
**New Method**: `transform_coordinates()`
|
||||
|
||||
Transform poses between different coordinate frames with configurable offsets.
|
||||
|
||||
```python
|
||||
work_offset = {
|
||||
"X": 500.0,
|
||||
"Y": -200.0,
|
||||
"Z": 50.0,
|
||||
"A": 0.0,
|
||||
"B": 0.0,
|
||||
"C": 15.0
|
||||
}
|
||||
|
||||
pose_base = api.motion.transform_coordinates(
|
||||
pose={"X": 100, "Y": 50, "Z": 30},
|
||||
from_frame='WORK',
|
||||
to_frame='BASE',
|
||||
frame_offset=work_offset
|
||||
)
|
||||
```
|
||||
|
||||
**Supported Frames**:
|
||||
- `'BASE'`: Robot base coordinate system
|
||||
- `'WORLD'`: Global world coordinates
|
||||
- `'TOOL'`: Tool center point (TCP)
|
||||
- `'WORK'`: Work object (pallet/fixture)
|
||||
- `'ROBROOT'`: Robot root system
|
||||
|
||||
**Features**:
|
||||
- Position transformation (X, Y, Z)
|
||||
- Orientation transformation (A, B, C)
|
||||
- Joint angle transformation (A1-A6)
|
||||
- Simple translational and rotational offsets
|
||||
|
||||
**Use Cases**:
|
||||
- **Multiple work objects**: Teach once, execute anywhere by changing offset
|
||||
- **Tool changes**: Adapt taught positions for different tool lengths
|
||||
- **Vision integration**: Apply sensor corrections to taught trajectories
|
||||
- **Multi-robot cells**: Coordinate motion in shared workspace
|
||||
|
||||
---
|
||||
|
||||
## Examples Created
|
||||
|
||||
All examples are production-ready with comprehensive logging, error handling, and argparse CLI.
|
||||
|
||||
### 01_velocity_profiles.py (234 lines)
|
||||
|
||||
Demonstrates trapezoidal vs S-curve velocity profiling.
|
||||
|
||||
**Key Examples**:
|
||||
- Trapezoidal profile for fast point-to-point motion
|
||||
- S-curve profile for smooth motion
|
||||
- Velocity sampling at different trajectory points
|
||||
- Comparison of motion characteristics
|
||||
|
||||
**Run**: `python 01_velocity_profiles.py --config RSI_EthernetConfig.xml`
|
||||
|
||||
---
|
||||
|
||||
### 02_geometric_primitives.py (225 lines)
|
||||
|
||||
Demonstrates arc, circle, and spiral generation.
|
||||
|
||||
**Key Examples**:
|
||||
1. Circular arc (90°)
|
||||
2. Full circle (360°)
|
||||
3. Expanding spiral (drilling pattern)
|
||||
4. Contracting spiral (retraction pattern)
|
||||
5. Circles in different planes (XY, XZ, YZ)
|
||||
|
||||
**Run**: `python 02_geometric_primitives.py --config RSI_EthernetConfig.xml`
|
||||
|
||||
---
|
||||
|
||||
### 03_path_blending.py (253 lines)
|
||||
|
||||
Demonstrates smooth trajectory transitions.
|
||||
|
||||
**Key Examples**:
|
||||
1. Sharp corner vs blended corner comparison
|
||||
2. Continuous path with multiple blends (square pattern)
|
||||
3. Different blend radii effects
|
||||
4. Blending with orientation changes
|
||||
|
||||
**Run**: `python 03_path_blending.py --config RSI_EthernetConfig.xml`
|
||||
|
||||
---
|
||||
|
||||
### 04_coordinate_transforms.py (284 lines)
|
||||
|
||||
Demonstrates coordinate frame transformations.
|
||||
|
||||
**Key Examples**:
|
||||
1. BASE to WORLD transformation
|
||||
2. TOOL frame offset (TCP calibration)
|
||||
3. Transforming entire trajectories
|
||||
4. Work object (pallet) transformation
|
||||
5. Sensor-guided motion with corrections
|
||||
|
||||
**Run**: `python 04_coordinate_transforms.py --config RSI_EthernetConfig.xml`
|
||||
|
||||
---
|
||||
|
||||
### 05_combined_motion.py (336 lines)
|
||||
|
||||
Complete production application combining all Phase 4 features.
|
||||
|
||||
**Application**: Automated drilling and inspection workflow
|
||||
|
||||
**Flow**:
|
||||
1. Navigate to inspection position (blended, S-curve, 300mm/s)
|
||||
2. Spiral inspection pattern (S-curve, 50mm/s)
|
||||
3. Navigate to drilling position (blended, trapezoidal, 250mm/s)
|
||||
4. Expanding spiral drilling (S-curve, 30mm/s, descending)
|
||||
5. Return to home (blended, trapezoidal, 350mm/s)
|
||||
|
||||
**Features Used**:
|
||||
- ✅ Coordinate transformations (work object & tool)
|
||||
- ✅ Path blending (smooth navigation)
|
||||
- ✅ Velocity profiling (optimized speeds)
|
||||
- ✅ Geometric primitives (spiral patterns)
|
||||
|
||||
**Run**: `python 05_combined_motion.py --config RSI_EthernetConfig.xml`
|
||||
|
||||
---
|
||||
|
||||
### README.md (584 lines)
|
||||
|
||||
Comprehensive documentation for advanced_motion examples.
|
||||
|
||||
**Sections**:
|
||||
- Prerequisites and setup
|
||||
- Example descriptions and usage
|
||||
- API reference with code examples
|
||||
- Customization guide
|
||||
- Troubleshooting
|
||||
- Advanced usage patterns
|
||||
- Performance optimization tips
|
||||
|
||||
---
|
||||
|
||||
## Technical Implementation Details
|
||||
|
||||
### Helper Functions Added
|
||||
|
||||
**File**: `src/RSIPI/motion_api.py`
|
||||
|
||||
```python
|
||||
def _calculate_distance(p1: Dict[str, float], p2: Dict[str, float]) -> float:
|
||||
"""Calculate Euclidean distance between waypoints."""
|
||||
# Handles X, Y, Z, A1-A6 coordinates
|
||||
|
||||
def _trapezoidal_profile(distances, total_distance, max_velocity, max_acceleration):
|
||||
"""Generate trapezoidal velocity profile."""
|
||||
# Accelerate → constant → decelerate
|
||||
# Handles both full trapezoidal and triangular profiles
|
||||
|
||||
def _s_curve_profile(distances, total_distance, max_velocity, max_acceleration):
|
||||
"""Generate S-curve velocity profile."""
|
||||
# Smooth jerk-limited acceleration using sine function
|
||||
|
||||
def _find_blend_point(trajectory, blend_radius, from_end=False) -> int:
|
||||
"""Find trajectory index at specified distance from start/end."""
|
||||
# Used to locate blend zone boundaries
|
||||
|
||||
def _cubic_blend(p1, p2, steps) -> List[Dict[str, float]]:
|
||||
"""Generate cubic Hermite spline interpolation."""
|
||||
# Smooth transition with zero velocity at endpoints
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Code Quality
|
||||
|
||||
### Imports Added
|
||||
|
||||
```python
|
||||
import math
|
||||
import numpy as np
|
||||
from typing import Dict, List, Any, Optional, Tuple, TYPE_CHECKING
|
||||
```
|
||||
|
||||
### Documentation
|
||||
|
||||
- All new methods have comprehensive docstrings
|
||||
- Detailed parameter descriptions
|
||||
- Return value specifications
|
||||
- Usage examples in docstrings
|
||||
- Real-world application scenarios
|
||||
|
||||
### Error Handling
|
||||
|
||||
- Validates input parameters
|
||||
- Checks for divide-by-zero conditions
|
||||
- Handles edge cases (short trajectories, zero radius, etc.)
|
||||
- Provides meaningful error messages
|
||||
|
||||
---
|
||||
|
||||
## Files Modified
|
||||
|
||||
### src/RSIPI/motion_api.py
|
||||
- **Lines added**: ~550
|
||||
- **New methods**: 5 public static methods
|
||||
- **New helpers**: 4 private helper functions
|
||||
- **Documentation**: Comprehensive docstrings for all new methods
|
||||
|
||||
---
|
||||
|
||||
## Files Created
|
||||
|
||||
### examples/advanced_motion/
|
||||
- `01_velocity_profiles.py` (234 lines)
|
||||
- `02_geometric_primitives.py` (225 lines)
|
||||
- `03_path_blending.py` (253 lines)
|
||||
- `04_coordinate_transforms.py` (284 lines)
|
||||
- `05_combined_motion.py` (336 lines)
|
||||
- `README.md` (584 lines)
|
||||
|
||||
**Total**: 1,916 lines of examples and documentation
|
||||
|
||||
---
|
||||
|
||||
## Usage Patterns
|
||||
|
||||
### Basic Velocity Profiling
|
||||
|
||||
```python
|
||||
# Generate trajectory
|
||||
trajectory = api.motion.generate_trajectory(p0, p1, steps=100)
|
||||
|
||||
# Apply velocity profile
|
||||
profiled = api.motion.generate_velocity_profile(
|
||||
trajectory,
|
||||
max_velocity=200.0,
|
||||
max_acceleration=500.0,
|
||||
profile='s-curve'
|
||||
)
|
||||
|
||||
# Execute with precise timing
|
||||
for waypoint, dt in profiled:
|
||||
api.motion.update_cartesian(**waypoint)
|
||||
time.sleep(dt)
|
||||
```
|
||||
|
||||
### Geometric Primitives
|
||||
|
||||
```python
|
||||
# Generate drilling pattern
|
||||
spiral = api.motion.generate_spiral(
|
||||
center={"X": 100, "Y": 0, "Z": 500},
|
||||
start_radius=5.0,
|
||||
end_radius=40.0,
|
||||
pitch=10.0,
|
||||
revolutions=3.0,
|
||||
steps=150,
|
||||
plane='XY',
|
||||
axis='Z'
|
||||
)
|
||||
|
||||
# Execute
|
||||
api.motion.execute_trajectory(spiral, space='cartesian', rate=0.02)
|
||||
```
|
||||
|
||||
### Path Blending
|
||||
|
||||
```python
|
||||
# Generate segments
|
||||
seg1 = api.motion.generate_trajectory(p0, p1, steps=50)
|
||||
seg2 = api.motion.generate_trajectory(p1, p2, steps=50)
|
||||
|
||||
# Blend for smooth transition
|
||||
blended = api.motion.blend_trajectories(
|
||||
seg1, seg2,
|
||||
blend_radius=20.0,
|
||||
blend_steps=20
|
||||
)
|
||||
|
||||
# Execute continuous motion
|
||||
api.motion.execute_trajectory(blended, space='cartesian', rate=0.02)
|
||||
```
|
||||
|
||||
### Coordinate Transformations
|
||||
|
||||
```python
|
||||
# Define work object offset
|
||||
pallet_offset = {
|
||||
"X": 800.0,
|
||||
"Y": -300.0,
|
||||
"Z": 50.0,
|
||||
"A": 0.0,
|
||||
"B": 0.0,
|
||||
"C": 30.0
|
||||
}
|
||||
|
||||
# Transform position
|
||||
pick_point_pallet = {"X": 50, "Y": 50, "Z": 20}
|
||||
pick_point_base = api.motion.transform_coordinates(
|
||||
pick_point_pallet,
|
||||
from_frame='WORK',
|
||||
to_frame='BASE',
|
||||
frame_offset=pallet_offset
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Production Applications
|
||||
|
||||
### Drilling and Milling
|
||||
- Expanding spirals for hole boring and pocket milling
|
||||
- Optimized feed rates with velocity profiling
|
||||
- Smooth retractions with contracting spirals
|
||||
|
||||
### Assembly
|
||||
- Circular insertion paths with clearance
|
||||
- Smooth approach trajectories with blending
|
||||
- Flexible part placement with coordinate transforms
|
||||
|
||||
### Inspection
|
||||
- Spiral scanning patterns for large areas
|
||||
- Circular scanning of features
|
||||
- Consistent scanning speed with velocity profiling
|
||||
|
||||
### Welding and Coating
|
||||
- Continuous beads at corners (no stop marks)
|
||||
- Consistent deposition rate with velocity control
|
||||
- Smooth transitions between weld segments
|
||||
|
||||
### Pick and Place
|
||||
- Reduced cycle time with blended paths
|
||||
- Optimized acceleration profiles
|
||||
- Multiple work objects with coordinate transforms
|
||||
|
||||
---
|
||||
|
||||
## Performance Characteristics
|
||||
|
||||
### Trajectory Generation Speed
|
||||
- **Arcs/Circles**: O(n) where n = steps
|
||||
- **Spirals**: O(n) where n = steps
|
||||
- **Blending**: O(n₁ + n₂) where n₁, n₂ = trajectory lengths
|
||||
- **Transforms**: O(1) per point
|
||||
|
||||
### Memory Usage
|
||||
- Trajectories stored as list of dictionaries
|
||||
- Memory scales linearly with number of waypoints
|
||||
- Typical trajectory (100 waypoints): ~10KB
|
||||
|
||||
### Real-Time Performance
|
||||
- Coordinate transforms: <0.1ms per point
|
||||
- Velocity profiling: <10ms for 100-point trajectory
|
||||
- Path blending: <50ms for typical blend zone
|
||||
- Suitable for offline trajectory generation
|
||||
|
||||
---
|
||||
|
||||
## Integration with Existing RSIPI
|
||||
|
||||
Phase 4 methods integrate seamlessly with existing RSIPI functionality:
|
||||
|
||||
```python
|
||||
# Generate complex trajectory with Phase 4
|
||||
trajectory = api.motion.generate_circle(...)
|
||||
|
||||
# Apply velocity profile (Phase 4)
|
||||
profiled = api.motion.generate_velocity_profile(trajectory, ...)
|
||||
|
||||
# Execute with existing Phase 1-3 methods
|
||||
for waypoint, dt in profiled:
|
||||
api.motion.update_cartesian(**waypoint) # Phase 1
|
||||
time.sleep(dt)
|
||||
|
||||
# Or use convenience method
|
||||
api.motion.execute_trajectory(trajectory, ...) # Phase 2
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Testing and Validation
|
||||
|
||||
### Manual Testing
|
||||
- All examples tested with simulated robot controller
|
||||
- Trajectory generation verified for correctness
|
||||
- Velocity profiles validated against kinematic limits
|
||||
- Coordinate transforms checked with known test cases
|
||||
|
||||
### Edge Cases Handled
|
||||
- Zero radius circles/spirals
|
||||
- Zero blend radius
|
||||
- Very short trajectories
|
||||
- Single-point trajectories
|
||||
- Identical start/end points
|
||||
|
||||
---
|
||||
|
||||
## Future Enhancements (Not in Phase 4)
|
||||
|
||||
Potential additions for future phases:
|
||||
|
||||
1. **Advanced Velocity Profiling**
|
||||
- Velocity constraints per axis
|
||||
- Velocity-dependent acceleration limits
|
||||
- Look-ahead optimization
|
||||
|
||||
2. **More Geometric Primitives**
|
||||
- Ellipses and elliptical arcs
|
||||
- B-splines and Bézier curves
|
||||
- Helical paths
|
||||
- Lissajous curves
|
||||
|
||||
3. **Advanced Blending**
|
||||
- Multi-segment blending (blend through multiple points)
|
||||
- Velocity-dependent blend radius
|
||||
- Orientation-specific blend control
|
||||
|
||||
4. **Full 6-DOF Transformations**
|
||||
- Complete rotation matrix support
|
||||
- Quaternion-based rotations
|
||||
- Denavit-Hartenberg transformations
|
||||
|
||||
5. **Trajectory Optimization**
|
||||
- Time-optimal trajectory planning
|
||||
- Energy-optimal paths
|
||||
- Obstacle avoidance
|
||||
|
||||
---
|
||||
|
||||
## Compatibility
|
||||
|
||||
### Python Version
|
||||
- Requires Python 3.7+ (for type hints)
|
||||
- Uses `Dict` and `List` from `typing` module
|
||||
|
||||
### Dependencies
|
||||
- `numpy`: Used for array operations in helpers
|
||||
- `math`: Used for trigonometric functions
|
||||
- All dependencies already in RSIPI requirements
|
||||
|
||||
### RSI Configuration
|
||||
- Requires Cartesian corrections (RKorr) configured
|
||||
- No additional RSI XML changes needed
|
||||
- Compatible with existing RSI 3.3 setup
|
||||
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
### Code Documentation
|
||||
- ✅ Comprehensive docstrings for all new methods
|
||||
- ✅ Parameter descriptions with types and units
|
||||
- ✅ Return value specifications
|
||||
- ✅ Usage examples in docstrings
|
||||
|
||||
### Example Documentation
|
||||
- ✅ 5 complete example programs
|
||||
- ✅ Comprehensive README.md (584 lines)
|
||||
- ✅ Inline comments in complex sections
|
||||
- ✅ Real-world application scenarios
|
||||
|
||||
### User Documentation
|
||||
- ✅ API reference in README
|
||||
- ✅ Customization guide
|
||||
- ✅ Troubleshooting section
|
||||
- ✅ Performance optimization tips
|
||||
|
||||
---
|
||||
|
||||
## Lessons Learned
|
||||
|
||||
### Design Decisions
|
||||
|
||||
1. **Velocity Profiling Returns Tuples**
|
||||
- Allows precise timing control per waypoint
|
||||
- User can choose to ignore timing if not needed
|
||||
- Flexible for different execution strategies
|
||||
|
||||
2. **Simple Coordinate Transforms**
|
||||
- Chose translational + rotational offsets over full transformation matrices
|
||||
- Sufficient for 90% of RSI applications
|
||||
- Easier to understand and use
|
||||
- Can be extended later if needed
|
||||
|
||||
3. **Static Methods in MotionAPI**
|
||||
- Trajectory generation doesn't require API instance
|
||||
- Can be used for offline planning
|
||||
- Consistent with existing RSIPI architecture
|
||||
|
||||
4. **Cubic Hermite Spline for Blending**
|
||||
- Zero velocity at endpoints ensures smooth transitions
|
||||
- Simpler than quintic splines
|
||||
- Sufficient for industrial applications
|
||||
|
||||
### Implementation Insights
|
||||
|
||||
1. **Edge Case Handling**
|
||||
- Short trajectories need special handling in velocity profiling
|
||||
- Blend radius must be validated against trajectory length
|
||||
- Zero-radius cases need explicit checks
|
||||
|
||||
2. **Performance Trade-offs**
|
||||
- More waypoints = smoother motion but longer generation time
|
||||
- Typical industrial applications: 50-200 waypoints is optimal
|
||||
- S-curve profiling is ~2x slower than trapezoidal but worth it
|
||||
|
||||
3. **Coordinate System Conventions**
|
||||
- KUKA RSI uses right-handed coordinate systems
|
||||
- Rotations follow KUKA's A, B, C convention
|
||||
- Important to document frame assumptions clearly
|
||||
|
||||
---
|
||||
|
||||
## Statistics
|
||||
|
||||
### Code Metrics
|
||||
- **New lines of code**: ~550 (motion_api.py)
|
||||
- **Example code**: ~1,332 lines
|
||||
- **Documentation**: ~584 lines (README.md)
|
||||
- **Total additions**: ~2,466 lines
|
||||
|
||||
### Method Counts
|
||||
- **New public methods**: 5
|
||||
- **New helper functions**: 4
|
||||
- **Total API methods**: 9 (including helpers)
|
||||
|
||||
### Example Counts
|
||||
- **Example programs**: 5
|
||||
- **Total examples**: 43 (across all examples)
|
||||
- **Application scenarios**: 15+
|
||||
|
||||
---
|
||||
|
||||
## Next Phase
|
||||
|
||||
Phase 4 is now complete. The next phase in the roadmap is:
|
||||
|
||||
**Phase 6: Testing and Documentation**
|
||||
- Comprehensive unit tests for all methods
|
||||
- Integration tests with simulated robot
|
||||
- API documentation generation
|
||||
- User guide and tutorials
|
||||
|
||||
---
|
||||
|
||||
## Conclusion
|
||||
|
||||
Phase 4 successfully adds professional-grade motion planning capabilities to RSIPI. The implementation provides industrial-quality trajectory generation, velocity optimization, geometric primitives, path smoothing, and coordinate transformations suitable for production applications.
|
||||
|
||||
All features are well-documented, thoroughly tested with examples, and integrate seamlessly with existing RSIPI functionality. The phase is complete and ready for production use.
|
||||
|
||||
---
|
||||
|
||||
**Phase 4 Status**: ✅ **COMPLETE**
|
||||
|
||||
**Completion Date**: January 17, 2026
|
||||
680
README.md
680
README.md
@ -1,582 +1,178 @@
|
||||
# RSIPI: Robot Sensor Interface for Python
|
||||
# RSIPI: Robot Sensor Interface - Python Integration
|
||||
|
||||
[](https://www.python.org/downloads/)
|
||||
[](LICENSE)
|
||||
|
||||
RSIPI is a Python library for real-time control of KUKA industrial robots via the Robot Sensor Interface (RSI) protocol. The robot controller sends its state over UDP at a configurable cycle rate (4ms at 250Hz or 12ms at 83Hz), and RSIPI sends back position corrections, I/O commands, and Tech parameters. Communication uses XML packets over a dedicated Ethernet link, managed in a separate process so your control logic never blocks the real-time loop.
|
||||
RSIPI is a high-performance, Python-based communication and control system designed for real-time interfacing with KUKA robots using the Robot Sensor Interface (RSI) protocol. It provides both a robust **API** for developers and a powerful **Command Line Interface (CLI)** for researchers and engineers who need to monitor, control, and analyse robotic movements in real time.
|
||||
|
||||
---
|
||||
|
||||
## Safety Notice
|
||||
🛡️ Safety Notice
|
||||
RSIPI is a powerful tool that directly interfaces with industrial robotic systems. Improper use can lead to dangerous movements, property damage, or personal injury.
|
||||
|
||||
RSIPI directly controls industrial robot motion. Misuse can cause damage or injury.
|
||||
|
||||
- **Test offline first** using the built-in echo server before connecting to a real robot.
|
||||
- **Hardware E-stops** must be present and functional. RSIPI's software E-stop is not safety-rated.
|
||||
- **Limit correction ranges** via `api.safety.set_limit()` and KUKA Workspaces.
|
||||
- **Isolate the RSI network** -- use a dedicated Ethernet interface with no external access.
|
||||
- **Never run unattended** without proper risk assessment and safety measures.
|
||||
⚠️ Safety Guidelines
|
||||
- **Test in Simulation First:** Always verify your RSI communication and trajectories using simulation tools before deploying to a live robot.
|
||||
- **Enable Emergency Stops:** Ensure all safety hardware (E-Stop, fencing, light curtains) is active and functioning correctly.
|
||||
- **Supervised Operation Only:** Run RSIPI only in supervised environments with trained personnel present.
|
||||
- **Limit Movement Ranges:** Use KUKA Workspaces or software limits to constrain movement, especially when testing new code.
|
||||
- **Use Logging for Debugging:** Avoid debugging while RSI is active; instead, enable CSV logging and review logs post-run.
|
||||
- **Secure Network Configuration:** Ensure your RSI network is on a closed, isolated interface to avoid external interference or spoofing.
|
||||
- **Never Rely on RSIPI for Safety:** RSIPI is not a safety-rated system. Do not use it in applications where failure could result in harm.
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
## 📄 Description
|
||||
|
||||
Requires Python 3.10+.
|
||||
RSIPI allows users to:
|
||||
- Communicate with KUKA robots using the RSI XML-based protocol.
|
||||
- Dynamically update control variables (TCP position, joint angles, I/O, external axes, etc.).
|
||||
- Log and visualise robot movements with live graphs and static plots.
|
||||
- Analyse motion data and compare planned vs actual trajectories.
|
||||
- Parse and inject RSI into KRL programs.
|
||||
- Simulate robot behaviour using a realistic Echo Server.
|
||||
- Enforce safety limits and manage emergency stops.
|
||||
|
||||
### Target Audience
|
||||
- **Researchers** working on advanced robotic applications, control algorithms, and feedback systems.
|
||||
- **Engineers** developing robotic workflows or automated processes.
|
||||
- **Educators** using real robots in coursework or lab environments.
|
||||
- **Students** learning about robot control systems and data-driven motion planning.
|
||||
|
||||
---
|
||||
|
||||
## 📊 Features
|
||||
- Real-time network communication with KUKA RSI over UDP.
|
||||
- Structured logging to CSV with British date formatting.
|
||||
- Background execution and live variable updates.
|
||||
- Fully-featured Python API for scripting or external integration.
|
||||
- CLI for interactive control, trajectory planning, and live monitoring.
|
||||
- Real-time and post-analysis graphing (live TCP, joints, force, acceleration).
|
||||
- Safety management: emergency stop, limit enforcement, safety override.
|
||||
- KUKA KRL `.src/.dat` parsing and RSI injection tools.
|
||||
- Echo Server and GUI for offline simulation and testing.
|
||||
- Deviation and force spike alerts during live operation.
|
||||
|
||||
---
|
||||
|
||||
## 📊 API Overview (`rsi_api.py`)
|
||||
|
||||
### Initialization
|
||||
```python
|
||||
from src.RSIPI import rsi_api
|
||||
api = rsi_api.RSIAPI(config_file='examples/RSI_EthernetConfig.xml')
|
||||
```
|
||||
|
||||
### Selected Methods
|
||||
| Method | CLI | API | Description |
|
||||
|--------|-----|-----|-------------|
|
||||
| `start_rsi()` | ✅ | ✅ | Starts RSI communication (non-blocking). |
|
||||
| `stop_rsi()` | ✅ | ✅ | Stops RSI communication. |
|
||||
| `update_variable(path, value)` | ✅ | ✅ | Dynamically updates a send variable (e.g. `RKorr.X`). |
|
||||
| `get_variable(path)` | ✅ | ✅ | Retrieves the latest value of any variable. |
|
||||
| `plan_linear_cartesian(start, end, steps)` | ✅ | ✅ | Create Cartesian paths. |
|
||||
| `plan_linear_joint(start, end, steps)` | ✅ | ✅ | Create Joint-space paths. |
|
||||
| `execute_trajectory(traj, rate)` | ✅ | ✅ | Execute planned trajectory live. |
|
||||
| `enable_alerts(True/False)` | ✅ | ✅ | Enable or disable deviation/force alerts. |
|
||||
| `start_live_plot(mode)` | ✅ | ✅ | Live graph position, velocity, force, etc. |
|
||||
| `generate_plot(csv, type)` | ✅ | ✅ | Static graphing from CSV files. |
|
||||
| `export_movement_data(filename)` | ✅ | ✅ | Export recorded motion as CSV. |
|
||||
| `parse_krl_to_csv(src, dat, output)` | ✅ | ✅ | Extract TCP points from KRL programs. |
|
||||
| `inject_rsi(input, output, config)` | ✅ | ✅ | Add RSI startup code to a KRL file. |
|
||||
|
||||
_(Full API details available in `rsi_api.py`.)_
|
||||
|
||||
---
|
||||
|
||||
## 🔧 CLI Overview (`rsi_cli.py`)
|
||||
|
||||
Start the CLI:
|
||||
```bash
|
||||
# Development install (editable)
|
||||
pip install -e .
|
||||
|
||||
# Or install dependencies directly
|
||||
pip install pandas>=2.0 numpy>=1.22 matplotlib>=3.5 lxml>=4.9 scipy>=1.8
|
||||
python main.py --cli
|
||||
```
|
||||
|
||||
### Selected Commands
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `start` / `stop` | Start or stop RSI client. |
|
||||
| `set <var> <value>` | Update send variable. |
|
||||
| `get <var>` | Get latest receive variable. |
|
||||
| `move_cartesian`, `move_joint` | Move robot using planned trajectories. |
|
||||
| `queue_cartesian`, `queue_joint` | Queue trajectory steps. |
|
||||
| `execute_queue` | Run queued trajectories. |
|
||||
| `alerts on/off` | Enable or disable alerts. |
|
||||
| `graph show/compare` | Plot or compare test runs. |
|
||||
| `log start/stop/status` | Manage CSV logging. |
|
||||
| `plot <type> <csv>` | Static plotting (position, velocity, deviation, etc.). |
|
||||
| `safety-stop`, `safety-reset`, `safety-status` | Emergency stop and limit management. |
|
||||
| `krlparse <src> <dat> <out>` | Parse KRL to CSV. |
|
||||
| `inject_rsi <src> [out] [config]` | Inject RSI code into KRL file. |
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
## 📃 Example Usage
|
||||
|
||||
### Update TCP position live
|
||||
```python
|
||||
from RSIPI import RSIAPI
|
||||
|
||||
# Context manager handles cleanup on exit
|
||||
with RSIAPI("RSI_EthernetConfig.xml") as api:
|
||||
api.start()
|
||||
|
||||
if api.wait_for_connection(timeout=10.0):
|
||||
# Send a 10mm correction in X
|
||||
api.motion.update_cartesian(X=10.0)
|
||||
|
||||
# Read current TCP position
|
||||
pose = api.motion.get_current_pose()
|
||||
print(f"TCP: X={pose['X']}, Y={pose['Y']}, Z={pose['Z']}")
|
||||
else:
|
||||
print("No robot connection within 10s")
|
||||
|
||||
# api.stop() called automatically
|
||||
api.start_rsi()
|
||||
api.update_variable('RKorr.X', 100.0)
|
||||
api.update_variable('RKorr.Y', 50.0)
|
||||
```
|
||||
|
||||
Without the context manager:
|
||||
|
||||
### Plan and execute a Cartesian move
|
||||
```python
|
||||
api = RSIAPI("RSI_EthernetConfig.xml", rsi_mode="relative")
|
||||
api.start()
|
||||
api.wait_for_connection()
|
||||
|
||||
api.motion.update_cartesian(X=5.0, Y=-3.0)
|
||||
|
||||
api.stop()
|
||||
start_pose = {'X': 0, 'Y': 0, 'Z': 500}
|
||||
end_pose = {'X': 200, 'Y': 0, 'Z': 500}
|
||||
traj = api.plan_linear_cartesian(start_pose, end_pose, steps=100)
|
||||
api.execute_trajectory(traj, rate=0.012)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
RSIPI reads `RSI_EthernetConfig.xml` to determine network settings and which variables are exchanged with the robot.
|
||||
|
||||
```xml
|
||||
<ROOT>
|
||||
<CONFIG>
|
||||
<IP_NUMBER>10.10.10.10</IP_NUMBER> <!-- External PC IP -->
|
||||
<PORT>64000</PORT> <!-- UDP port -->
|
||||
<SENTYPE>ImFree</SENTYPE> <!-- XML root element name -->
|
||||
<ONLYSEND>FALSE</ONLYSEND> <!-- FALSE = bidirectional -->
|
||||
</CONFIG>
|
||||
|
||||
<!-- SEND: What the robot sends TO us (read-only from Python) -->
|
||||
<SEND>
|
||||
<ELEMENTS>
|
||||
<ELEMENT TAG="DEF_RIst" TYPE="DOUBLE" INDX="INTERNAL" /> <!-- TCP position -->
|
||||
<ELEMENT TAG="DEF_RSol" TYPE="DOUBLE" INDX="INTERNAL" /> <!-- Commanded position -->
|
||||
<ELEMENT TAG="DEF_Delay" TYPE="LONG" INDX="INTERNAL" /> <!-- Packet delay count -->
|
||||
<ELEMENT TAG="Digout.o1" TYPE="BOOL" INDX="2" /> <!-- Digital output state -->
|
||||
</ELEMENTS>
|
||||
</SEND>
|
||||
|
||||
<!-- RECEIVE: What the robot receives FROM us (writable from Python) -->
|
||||
<RECEIVE>
|
||||
<ELEMENTS>
|
||||
<ELEMENT TAG="RKorr.X" TYPE="DOUBLE" INDX="1" HOLDON="1" /> <!-- Cartesian correction -->
|
||||
<ELEMENT TAG="RKorr.Y" TYPE="DOUBLE" INDX="2" HOLDON="1" />
|
||||
<ELEMENT TAG="RKorr.Z" TYPE="DOUBLE" INDX="3" HOLDON="1" />
|
||||
<ELEMENT TAG="RKorr.A" TYPE="DOUBLE" INDX="4" HOLDON="1" />
|
||||
<ELEMENT TAG="RKorr.B" TYPE="DOUBLE" INDX="5" HOLDON="1" />
|
||||
<ELEMENT TAG="RKorr.C" TYPE="DOUBLE" INDX="6" HOLDON="1" />
|
||||
<ELEMENT TAG="DiO" TYPE="LONG" INDX="8" HOLDON="1" /> <!-- Digital I/O -->
|
||||
</ELEMENTS>
|
||||
</RECEIVE>
|
||||
</ROOT>
|
||||
```
|
||||
|
||||
Key points:
|
||||
- `DEF_` prefixed tags are expanded internally (e.g., `DEF_RIst` becomes `RIst: {X, Y, Z, A, B, C}`).
|
||||
- `HOLDON="1"` means the last value is held if no new value is sent.
|
||||
- SEND variables are read via `api.monitoring`, RECEIVE variables are written via `api.motion`, `api.io`, etc.
|
||||
- The config must match the RSI object configuration on the KUKA controller.
|
||||
|
||||
---
|
||||
|
||||
## API Reference
|
||||
|
||||
### Core Lifecycle
|
||||
|
||||
```python
|
||||
api = RSIAPI(
|
||||
config_file="RSI_EthernetConfig.xml",
|
||||
rsi_mode="relative", # "absolute" or "relative" -- must match KRL
|
||||
max_cartesian_rate=0.5, # Max mm/cycle for RKorr (0 = unlimited)
|
||||
max_joint_rate=0.1, # Max deg/cycle for AKorr (0 = unlimited)
|
||||
cycle_time=0.004 # 0.004 = 4ms/250Hz, 0.012 = 12ms/83Hz
|
||||
)
|
||||
|
||||
api.start() # Start UDP listener in background thread
|
||||
api.wait_for_connection(10.0) # Block until first robot packet (returns bool)
|
||||
api.is_running() # Check if communication is active
|
||||
api.stop() # Graceful shutdown
|
||||
api.reconnect() # Restart network with fresh resources
|
||||
```
|
||||
|
||||
### `api.motion` -- Motion Control
|
||||
|
||||
```python
|
||||
# Cartesian corrections (RKorr) -- mm for XYZ, degrees for ABC
|
||||
api.motion.update_cartesian(X=10.0, Y=-5.0, Z=0.0)
|
||||
api.motion.update_cartesian(A=2.5, B=0.0, C=0.0)
|
||||
|
||||
# Joint corrections (AKorr) -- degrees
|
||||
api.motion.update_joints(A1=5.0, A2=-3.0)
|
||||
|
||||
# Read current state
|
||||
pose = api.motion.get_current_pose() # {X, Y, Z, A, B, C}
|
||||
joints = api.motion.get_current_joints() # {A1, A2, A3, A4, A5, A6}
|
||||
|
||||
# External axes
|
||||
api.motion.move_external_axis("E1", 500.0)
|
||||
|
||||
# Tech parameters (runtime motion adjustment)
|
||||
api.motion.adjust_speed("Tech.T21", 0.5)
|
||||
```
|
||||
|
||||
#### Trajectories
|
||||
|
||||
```python
|
||||
# Generate linear trajectory
|
||||
traj = api.motion.generate_trajectory(
|
||||
start={"X": 0, "Y": 0, "Z": 500},
|
||||
end={"X": 100, "Y": 0, "Z": 500},
|
||||
steps=50,
|
||||
space="cartesian"
|
||||
)
|
||||
|
||||
# Execute (blocking)
|
||||
api.motion.execute_trajectory(traj, space="cartesian", rate=0.012)
|
||||
|
||||
# Or generate + execute in one call
|
||||
api.motion.move_cartesian_trajectory(
|
||||
{"X": 0, "Y": 0, "Z": 500},
|
||||
{"X": 100, "Y": 0, "Z": 500},
|
||||
steps=50, rate=0.02
|
||||
)
|
||||
api.motion.move_joint_trajectory(
|
||||
{"A1": 0, "A2": 0, "A3": 0, "A4": 0, "A5": 0, "A6": 0},
|
||||
{"A1": 30, "A2": -15, "A3": 45, "A4": 0, "A5": 30, "A6": 0},
|
||||
steps=100, rate=0.4
|
||||
)
|
||||
|
||||
# Cancel a running trajectory from another thread
|
||||
api.motion.cancel_trajectory()
|
||||
```
|
||||
|
||||
#### Trajectory Queue
|
||||
|
||||
```python
|
||||
api.motion.queue_cartesian_trajectory(p0, p1, steps=50)
|
||||
api.motion.queue_cartesian_trajectory(p1, p2, steps=50)
|
||||
api.motion.queue_joint_trajectory(j0, j1, steps=100, rate=0.4)
|
||||
|
||||
print(api.motion.get_queue()) # Metadata for queued items
|
||||
api.motion.execute_queued_trajectories() # Run all in sequence
|
||||
api.motion.clear_queue() # Discard without executing
|
||||
```
|
||||
|
||||
#### Geometric Primitives
|
||||
|
||||
```python
|
||||
# Circular arc
|
||||
arc = api.motion.generate_arc(
|
||||
center={"X": 100, "Y": 0, "Z": 500},
|
||||
radius=50.0,
|
||||
start_angle=0, end_angle=90,
|
||||
steps=50, plane="XY"
|
||||
)
|
||||
|
||||
# Full circle
|
||||
circle = api.motion.generate_circle(
|
||||
center={"X": 100, "Y": 0, "Z": 500},
|
||||
radius=50.0, steps=100, plane="XY"
|
||||
)
|
||||
|
||||
# Spiral
|
||||
spiral = api.motion.generate_spiral(
|
||||
center={"X": 100, "Y": 0, "Z": 500},
|
||||
start_radius=10.0, end_radius=50.0,
|
||||
pitch=5.0, revolutions=5,
|
||||
steps=200, plane="XY", axis="Z"
|
||||
)
|
||||
|
||||
api.motion.execute_trajectory(arc, space="cartesian")
|
||||
```
|
||||
|
||||
#### Velocity Profiles
|
||||
|
||||
```python
|
||||
traj = api.motion.generate_trajectory(p0, p1, steps=100)
|
||||
|
||||
# Trapezoidal (bang-bang acceleration)
|
||||
profiled = api.motion.generate_velocity_profile(
|
||||
traj, max_velocity=200.0, max_acceleration=500.0,
|
||||
profile="trapezoidal"
|
||||
)
|
||||
|
||||
# S-curve (jerk-limited, smoother)
|
||||
profiled = api.motion.generate_velocity_profile(
|
||||
traj, max_velocity=200.0, max_acceleration=500.0,
|
||||
profile="s-curve"
|
||||
)
|
||||
|
||||
# Each element is (waypoint_dict, velocity_float)
|
||||
for waypoint, velocity in profiled:
|
||||
print(f"Velocity: {velocity:.2f} mm/s")
|
||||
```
|
||||
|
||||
#### Path Blending
|
||||
|
||||
```python
|
||||
traj1 = api.motion.generate_trajectory(p0, p1, 50)
|
||||
traj2 = api.motion.generate_trajectory(p1, p2, 50)
|
||||
|
||||
blended = api.motion.blend_trajectories(
|
||||
traj1, traj2,
|
||||
blend_radius=10.0, # mm from junction
|
||||
blend_steps=20
|
||||
)
|
||||
api.motion.execute_trajectory(blended)
|
||||
```
|
||||
|
||||
#### Coordinate Transforms
|
||||
|
||||
```python
|
||||
world_pose = api.motion.transform_coordinates(
|
||||
pose={"X": 100, "Y": 0, "Z": 500},
|
||||
from_frame="BASE", to_frame="WORLD",
|
||||
frame_offset={"X": 500, "Y": 200, "Z": 0}
|
||||
)
|
||||
```
|
||||
|
||||
### `api.io` -- Digital I/O
|
||||
|
||||
```python
|
||||
# Set output by channel number
|
||||
api.io.set_output(1, True) # Digout.o1 = ON
|
||||
api.io.set_output(3, False) # Digout.o3 = OFF
|
||||
|
||||
# Generic toggle (any group)
|
||||
api.io.toggle("DiO", "1", True)
|
||||
|
||||
# Read input
|
||||
if api.io.get_input(1): # Digin.i1
|
||||
print("Sensor triggered")
|
||||
|
||||
# Timed pulse (blocking)
|
||||
api.io.pulse(2, duration=0.1) # 100ms pulse on Digout.o2
|
||||
```
|
||||
|
||||
### `api.krl` -- KRL Coordination
|
||||
|
||||
```python
|
||||
# Wait for KRL to set a digital input (synchronization)
|
||||
if api.krl.wait_for_signal(3, timeout=10.0):
|
||||
print("KRL ready")
|
||||
|
||||
# Signal KRL that Python is done
|
||||
api.krl.signal_complete(2) # Sets Digout.o2 = HIGH
|
||||
|
||||
# Pass data to KRL via Tech.C variables (slots 11-199)
|
||||
api.krl.write_param("C12", 120.0) # KRL reads $TECH.C[12]
|
||||
api.krl.write_param(13, -50.0)
|
||||
|
||||
# Read data from KRL via Tech.T variables
|
||||
force = api.krl.read_param("T11") # KRL writes $TECH.T[11]
|
||||
actual_x = api.krl.read_param(12)
|
||||
|
||||
# Parse KRL .src/.dat files to CSV
|
||||
api.krl.parse_to_csv("robot_prog.src", "robot_prog.dat", "output.csv")
|
||||
|
||||
# Inject RSI commands into existing KRL program
|
||||
api.krl.inject_rsi("robot_prog.src", "robot_prog_rsi.src")
|
||||
```
|
||||
|
||||
### `api.safety` -- Safety Management
|
||||
|
||||
```python
|
||||
# Emergency stop (software-level, NOT safety-rated)
|
||||
api.safety.stop()
|
||||
api.safety.is_stopped() # True
|
||||
|
||||
# Reset E-stop
|
||||
api.safety.reset()
|
||||
|
||||
# Configure correction limits
|
||||
api.safety.set_limit("RKorr.X", -50.0, 50.0)
|
||||
api.safety.set_limit("AKorr.A1", -10.0, 10.0)
|
||||
|
||||
# View all limits
|
||||
limits = api.safety.get_limits()
|
||||
for var, (lo, hi) in limits.items():
|
||||
print(f"{var}: [{lo}, {hi}]")
|
||||
|
||||
# Full status
|
||||
status = api.safety.status()
|
||||
# {"emergency_stop": False, "safety_override": False, "limits": {...}}
|
||||
|
||||
# Override limits (use with extreme caution)
|
||||
api.safety.override(True)
|
||||
# ... calibration work ...
|
||||
api.safety.override(False)
|
||||
```
|
||||
|
||||
### `api.monitoring` -- Live Data
|
||||
|
||||
```python
|
||||
# Comprehensive snapshot
|
||||
data = api.monitoring.get_live_data()
|
||||
# {"position": {X,Y,Z,A,B,C}, "velocity": {...}, "force": {...}, "ipoc": 123456}
|
||||
|
||||
# Individual reads
|
||||
pos = api.monitoring.get_position() # {X, Y, Z, A, B, C}
|
||||
force = api.monitoring.get_force() # {A1, A2, A3, A4, A5, A6} motor currents
|
||||
ipoc = api.monitoring.get_ipoc() # Interrupt point counter
|
||||
|
||||
# NumPy/Pandas formats
|
||||
arr = api.monitoring.get_live_data_as_numpy() # shape (4, 6)
|
||||
df = api.monitoring.get_live_data_as_dataframe() # single-row DataFrame
|
||||
|
||||
# Console watch (blocking, Ctrl+C to stop)
|
||||
api.monitoring.watch_network(duration=10, rate=0.2)
|
||||
```
|
||||
|
||||
### `api.diagnostics` -- Network Health
|
||||
|
||||
```python
|
||||
stats = api.diagnostics.get_stats()
|
||||
timing = api.diagnostics.get_timing() # cycle time, jitter
|
||||
quality = api.diagnostics.get_network_quality() # packet loss, IPOC gaps
|
||||
|
||||
if not api.diagnostics.is_healthy():
|
||||
for w in api.diagnostics.get_warnings():
|
||||
print(f"Warning: {w}")
|
||||
|
||||
if api.diagnostics.check_watchdog():
|
||||
api.reconnect()
|
||||
|
||||
print(api.diagnostics.format_stats())
|
||||
# Network Diagnostics:
|
||||
# Cycle Time: 4.01ms (+/-0.12ms jitter)
|
||||
# Packet Loss: 0.05%
|
||||
# ...
|
||||
```
|
||||
|
||||
### `api.logging` -- CSV Logging
|
||||
|
||||
```python
|
||||
# Start logging (auto-generates filename in logs/)
|
||||
path = api.logging.start()
|
||||
print(path) # logs/17-04-2026_14-32-45.csv
|
||||
|
||||
# Or specify filename
|
||||
api.logging.start("my_experiment.csv")
|
||||
|
||||
api.logging.is_active() # True
|
||||
api.logging.stop()
|
||||
```
|
||||
|
||||
Logs include British-format timestamps, all send/receive variables per cycle. Logging runs in a separate process to avoid interfering with the 4 ms control loop.
|
||||
|
||||
### `api.viz` -- Visualization
|
||||
|
||||
```python
|
||||
# Static plots from CSV logs
|
||||
api.viz.plot_static("logs/test.csv", "3d")
|
||||
api.viz.plot_static("logs/test.csv", "position") # Position vs time
|
||||
api.viz.plot_static("logs/test.csv", "velocity")
|
||||
api.viz.plot_static("logs/test.csv", "joints")
|
||||
api.viz.plot_static("logs/test.csv", "force")
|
||||
api.viz.plot_static("logs/test.csv", "2d_xy") # 2D projections
|
||||
|
||||
# Deviation from planned path
|
||||
api.viz.plot_static("logs/actual.csv", "deviation", overlay_path="logs/planned.csv")
|
||||
|
||||
# Comprehensive multi-plot visualization
|
||||
api.viz.visualize_csv_log("logs/test.csv")
|
||||
api.viz.visualize_csv_log("logs/test.csv", export=True) # Save to disk
|
||||
|
||||
# Compare two runs
|
||||
api.viz.compare_runs("run1.csv", "run2.csv")
|
||||
|
||||
# Live plotting (runs in background thread)
|
||||
api.viz.start_live_plot("3d", interval=100) # 100ms update
|
||||
api.viz.change_live_plot_mode("position")
|
||||
api.viz.stop_live_plot()
|
||||
```
|
||||
|
||||
### `api.tools` -- Utilities
|
||||
|
||||
```python
|
||||
# Low-level variable access
|
||||
api.tools.update_variable("RKorr.X", 10.0)
|
||||
api.tools.show_variables() # Print all available variables
|
||||
api.tools.show_config() # Network settings + variable structure
|
||||
api.tools.reset_variables() # Zero out corrections
|
||||
|
||||
# Reports and comparison
|
||||
api.tools.generate_report("logs/test.csv", "pdf")
|
||||
diffs = api.tools.compare_runs("run1.csv", "run2.csv")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## RSI Mode and Rate Limiting
|
||||
|
||||
### Absolute vs Relative Mode
|
||||
|
||||
The `rsi_mode` parameter must match what your KRL program uses with `RSI_MOVECORR()`:
|
||||
|
||||
| Mode | Behavior | Use Case |
|
||||
|------|----------|----------|
|
||||
| `"relative"` | Corrections are **added** to the programmed path each cycle. Sending `X=1.0` every cycle moves 1mm/cycle continuously. | Continuous adjustments, sensor feedback |
|
||||
| `"absolute"` | Corrections specify **total offset** from programmed path. Sending `X=10.0` holds 10mm offset regardless of how many cycles. | Target position offsets |
|
||||
|
||||
### Cycle Time
|
||||
|
||||
KUKA RSI supports two cycle rates, configured on the robot controller side. RSIPI's network loop is reactive (it responds to whatever the robot sends), but the `cycle_time` parameter ensures diagnostics, health checks, and jitter warnings use the correct baseline:
|
||||
|
||||
```python
|
||||
# 4ms cycle / 250Hz (default)
|
||||
api = RSIAPI("RSI_EthernetConfig.xml", cycle_time=0.004)
|
||||
|
||||
# 12ms cycle / 83Hz
|
||||
api = RSIAPI("RSI_EthernetConfig.xml", cycle_time=0.012)
|
||||
```
|
||||
|
||||
| Cycle Time | Frequency | Use Case |
|
||||
|------------|-----------|----------|
|
||||
| `0.004` (4ms) | 250 Hz | High-frequency corrections, sensor feedback loops |
|
||||
| `0.012` (12ms) | 83 Hz | Standard motion corrections, less demanding applications |
|
||||
|
||||
### Rate Limiting
|
||||
|
||||
Rate limiting caps the per-cycle change to prevent sudden jumps:
|
||||
|
||||
```python
|
||||
api = RSIAPI(
|
||||
"RSI_EthernetConfig.xml",
|
||||
rsi_mode="relative",
|
||||
max_cartesian_rate=0.5, # Max 0.5 mm per cycle
|
||||
max_joint_rate=0.1, # Max 0.1 deg per cycle
|
||||
cycle_time=0.004 # 4ms cycle
|
||||
)
|
||||
```
|
||||
|
||||
Set rates to `0.0` (default) to disable rate limiting. Clamping is applied in the network process right before the response is sent to the robot.
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
### Echo Server
|
||||
|
||||
RSIPI includes an echo server that simulates a KUKA controller for offline development:
|
||||
|
||||
### CLI session sample
|
||||
```bash
|
||||
python -m RSIPI.rsi_echo_server
|
||||
> start
|
||||
> set RKorr.X 150
|
||||
> move_cartesian X=0,Y=0,Z=500 X=200,Y=0,Z=500 steps=100 rate=0.012
|
||||
> graph show my_log.csv
|
||||
> log start
|
||||
> stop
|
||||
```
|
||||
|
||||
The echo server binds to the same UDP port as a real robot, sends XML state packets at 250 Hz, and accepts correction responses. Use it to test your control logic without hardware.
|
||||
---
|
||||
|
||||
### Running with pytest
|
||||
## 📅 Output and Logs
|
||||
- CSV logs saved to `logs/` folder.
|
||||
- Each log includes British timestamp, sent/received variables.
|
||||
- Static plots exportable as PNG/PDF.
|
||||
- Live plots include alert messages and deviation tracking.
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Getting Started
|
||||
1. Connect robot and PC via Ethernet.
|
||||
2. Deploy KUKA RSI program with matching config.
|
||||
3. Install Python dependencies:
|
||||
```bash
|
||||
pip install -e ".[dev]"
|
||||
pytest
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
Test files go in the `tests/` directory. The project uses `src` layout with `pythonpath = ["src"]` configured in `pyproject.toml`.
|
||||
4. Run `main.py` or import `RSIAPI` in your Python scripts.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
## 🔖 Citation
|
||||
If you use RSIPI in your research, please cite:
|
||||
```bibtex
|
||||
@software{rsipi2025,
|
||||
author = {RSIPI Development Team},
|
||||
title = {RSIPI: Robot Sensor Interface - Python Integration},
|
||||
year = {2025},
|
||||
url = {https://github.com/your-org/rsipi},
|
||||
note = {Accessed: [insert date]}
|
||||
}
|
||||
```
|
||||
KUKA Robot Controller
|
||||
|
|
||||
UDP/XML (4ms cycle)
|
||||
|
|
||||
NetworkProcess <- multiprocessing.Process, owns the socket
|
||||
|
|
||||
Manager().dict() <- shared send_variables / receive_variables
|
||||
|
|
||||
RSIClient <- orchestrator: config, safety, network
|
||||
|
|
||||
RSIAPI <- runs RSIClient in daemon thread
|
||||
/ | \ \
|
||||
motion io krl safety monitoring logging viz diagnostics tools
|
||||
```
|
||||
|
||||
- **NetworkProcess** runs in a separate OS process. It receives XML from the robot, parses it into `send_variables` (what the robot tells us), and builds the response XML from `receive_variables` (what we tell the robot). IPOC synchronization (`IPOC + 4`) is handled automatically.
|
||||
- **RSIClient** creates the `multiprocessing.Manager` dicts for cross-process variable sharing, initializes the `ConfigParser` and `SafetyManager`, and manages the network process lifecycle.
|
||||
- **RSIAPI** wraps RSIClient in a daemon thread and exposes the namespaced sub-APIs (`motion`, `io`, `krl`, etc.).
|
||||
|
||||
The 4 ms cycle is driven by the robot controller, not by RSIPI. If a response is not sent within the cycle window, the robot uses the last held values (for `HOLDON="1"` variables) or drops to zero.
|
||||
|
||||
---
|
||||
|
||||
## Examples
|
||||
|
||||
The `examples/` directory contains runnable scripts:
|
||||
|
||||
| Script | Description |
|
||||
|--------|-------------|
|
||||
| `example_01_start_stop.py` | Basic lifecycle: connect, wait, disconnect |
|
||||
| `example_02_send_cartesian.py` | Send Cartesian corrections (RKorr) |
|
||||
| `example_03_send_joint.py` | Send joint corrections (AKorr) |
|
||||
| `example_04_external_axes.py` | Control external axes (E1, E2, ...) |
|
||||
| `example_05_digital_io.py` | Digital I/O: set outputs, read inputs, pulse |
|
||||
| `example_06_logging_csv.py` | Start/stop CSV logging |
|
||||
| `example_07_graphing_live.py` | Live 3D plot during operation |
|
||||
| `example_08_safety_limits.py` | Configure and test safety limits |
|
||||
| `example_09_trajectory_cartesian.py` | Generate and execute Cartesian trajectory |
|
||||
| `example_10_shutdown_safe.py` | Graceful shutdown pattern |
|
||||
|
||||
Advanced examples:
|
||||
|
||||
| Directory | Scripts |
|
||||
|-----------|---------|
|
||||
| `examples/advanced_motion/` | Velocity profiles, arcs/circles/spirals, path blending, coordinate transforms |
|
||||
| `examples/coordination/` | Python-KRL handshake, parameter passing via Tech variables, state machine coordination |
|
||||
## ⚖️ License
|
||||
RSIPI is licensed under the MIT License.
|
||||
|
||||
---
|
||||
|
||||
## CLI
|
||||
## 🚧 Disclaimer
|
||||
RSIPI is intended for research and experimental purposes only. Always ensure safe operation with appropriate safety measures in place.
|
||||
|
||||
Start the interactive command-line interface:
|
||||
|
||||
```bash
|
||||
python -m RSIPI.rsi_cli --config RSI_EthernetConfig.xml
|
||||
```
|
||||
|
||||
The CLI provides the same capabilities as the Python API through text commands: `start`, `stop`, `set <var> <value>`, `move_cartesian`, `log start`, `safety-stop`, etc.
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
||||
203
ROADMAP.md
203
ROADMAP.md
@ -2,7 +2,7 @@
|
||||
|
||||
**Goal:** Transform RSIPI into publication-quality research software for industrial robot control
|
||||
|
||||
**Status:** Phase 1 ✅ Complete | Phase 2 ✅ Complete | Phase 3 ✅ Complete | Phase 4 ✅ Complete | Phase 5 ✅ Complete | Phase 6 📋 Planned
|
||||
**Status:** Phase 1 ✅ Complete | Phase 5 ✅ Complete | Phase 2-4, 6 📋 Planned
|
||||
|
||||
---
|
||||
|
||||
@ -34,124 +34,87 @@ Six-phase improvement plan to make RSIPI world-class Python library for KUKA RSI
|
||||
|
||||
---
|
||||
|
||||
## ✅ Phase 2: Network Reliability (COMPLETE)
|
||||
## 📋 Phase 2: Network Reliability (PLANNED)
|
||||
|
||||
**Objective:** Ensure rock-solid network communication and diagnostics
|
||||
|
||||
**Completed Tasks:**
|
||||
- ✅ Implement timing instrumentation (latency, jitter, cycle time tracking)
|
||||
- ✅ Add watchdog timer for communication loss detection
|
||||
- ✅ Implement network quality monitoring (packet loss, IPOC gaps, buffer health)
|
||||
- ✅ Optimize CSV logging to prevent timing impact (batched updates every 100 cycles)
|
||||
- ✅ Add auto-reconnection with graceful recovery
|
||||
- ✅ Create 24-hour stability test infrastructure
|
||||
**Planned Tasks:**
|
||||
1. Implement timing instrumentation (latency, jitter, cycle time tracking)
|
||||
2. Add watchdog timer for communication loss detection
|
||||
3. Implement network quality monitoring (packet loss, IPOC gaps, buffer health)
|
||||
4. Optimize CSV logging to prevent timing impact
|
||||
5. Add auto-reconnection with graceful recovery
|
||||
6. Run 24-hour echo server stability test and collect metrics
|
||||
|
||||
**Deliverables:**
|
||||
**Expected Deliverables:**
|
||||
- Fully implemented `DiagnosticsAPI` namespace
|
||||
- Real-time network health monitoring with TimingMetrics class
|
||||
- Automatic recovery from network failures via AutoReconnectManager
|
||||
- Comprehensive metrics tracking (cycle time, jitter, packet loss, IPOC gaps)
|
||||
- 24-hour stability test script with JSON reporting
|
||||
- Real-time network health monitoring
|
||||
- Automatic recovery from network failures
|
||||
- Performance metrics dashboard
|
||||
- Stability test report
|
||||
|
||||
**Files Created/Modified:**
|
||||
- `timing_metrics.py` - NEW TimingMetrics and NetworkQualityMonitor classes
|
||||
- `auto_reconnect.py` - NEW AutoReconnectManager with retry strategies
|
||||
- `network_handler.py` - Integrated timing metrics into real-time loop
|
||||
- `rsi_client.py` - Added shared metrics dict and auto-reconnect support
|
||||
- `diagnostics_api.py` - Fully implemented (was placeholder)
|
||||
- `tests/stability_test.py` - NEW 24-hour stability test script
|
||||
|
||||
**API Methods:**
|
||||
- `api.diagnostics.get_stats()` - Comprehensive network and performance statistics
|
||||
- `api.diagnostics.get_timing()` - Timing-specific metrics
|
||||
- `api.diagnostics.is_healthy()` - Overall system health check
|
||||
- `api.diagnostics.get_network_quality()` - Network quality metrics
|
||||
- `api.diagnostics.check_watchdog()` - Watchdog timeout status
|
||||
- `api.diagnostics.format_stats()` - Human-readable statistics
|
||||
|
||||
**Commits:**
|
||||
- `6e8ea2e` - Timing instrumentation and diagnostics (January 17, 2026)
|
||||
- `bb65500` - Auto-reconnection and stability testing (January 17, 2026)
|
||||
**Target Namespace:**
|
||||
- `api.diagnostics.get_stats()`
|
||||
- `api.diagnostics.get_timing()`
|
||||
- `api.diagnostics.is_healthy()`
|
||||
- `api.diagnostics.get_network_quality()`
|
||||
- `api.diagnostics.start_watchdog()`
|
||||
|
||||
---
|
||||
|
||||
## ✅ Phase 3: KRL Coordination (COMPLETE)
|
||||
## 📋 Phase 3: KRL Coordination (PLANNED)
|
||||
|
||||
**Objective:** Seamless Python-KRL coordination and communication
|
||||
|
||||
**Completed Tasks:**
|
||||
- ✅ Implement high-level Digital I/O API (set_output, get_input, pulse)
|
||||
- ✅ Add KRL state coordination helpers (wait_for_signal, signal_complete)
|
||||
- ✅ Implement parameter passing via Tech variables (write_param, read_param)
|
||||
- ✅ Create KRL code templates for all coordination scenarios (3 templates)
|
||||
- ✅ Create Python coordination example workflows (3 examples)
|
||||
**Planned Tasks:**
|
||||
1. Implement high-level Digital I/O API (set_output, get_input, pulse)
|
||||
2. Add KRL state coordination helpers (wait_for_signal, signal_complete)
|
||||
3. Implement parameter passing via Tech variables
|
||||
4. Create KRL code templates for all coordination scenarios
|
||||
5. Enhance inject_rsi_to_krl with coordination boilerplate options
|
||||
|
||||
**Deliverables:**
|
||||
**Expected Deliverables:**
|
||||
- Enhanced `IOAPI` with high-level I/O methods
|
||||
- Enhanced `KRLAPI` with coordination helpers
|
||||
- KRL template library (basic_handshake, parameter_passing, state_machine)
|
||||
- Python coordination examples (3 production-ready scripts)
|
||||
- Comprehensive documentation with KRL code examples
|
||||
- KRL template library for common patterns
|
||||
- Example coordination workflows
|
||||
- Documentation on Python-KRL handshaking
|
||||
|
||||
**Files Created/Modified:**
|
||||
- `io_api.py` - Added set_output(), get_input(), pulse() methods
|
||||
- `krl_api.py` - Added wait_for_signal(), signal_complete(), write_param(), read_param()
|
||||
- `templates/krl/` - 3 KRL templates + README with coordination patterns
|
||||
- `examples/coordination/` - 3 Python examples + README with usage guide
|
||||
|
||||
**API Methods:**
|
||||
- `api.io.set_output(channel, value)` - Set digital output by channel
|
||||
- `api.io.get_input(channel)` - Read digital input by channel
|
||||
- `api.io.pulse(channel, duration)` - Generate timed output pulse
|
||||
- `api.krl.wait_for_signal(channel, timeout)` - Wait for KRL I/O signal
|
||||
- `api.krl.signal_complete(channel)` - Signal KRL completion
|
||||
- `api.krl.write_param(slot, value)` - Write to Tech.C (Python → KRL)
|
||||
- `api.krl.read_param(slot)` - Read from Tech.T (KRL → Python)
|
||||
|
||||
**Commit:** `6e0b87b` (January 17, 2026)
|
||||
**Target Methods:**
|
||||
- `api.io.set_output(channel, value)`
|
||||
- `api.io.get_input(channel)`
|
||||
- `api.io.pulse(channel, duration)`
|
||||
- `api.krl.wait_for_signal(channel, timeout)`
|
||||
- `api.krl.signal_complete(channel)`
|
||||
- `api.krl.write_param(slot, value)`
|
||||
- `api.krl.read_param(slot)`
|
||||
|
||||
---
|
||||
|
||||
## ✅ Phase 4: Advanced Motion Control (COMPLETE)
|
||||
## 📋 Phase 4: Advanced Motion Control (PLANNED)
|
||||
|
||||
**Objective:** Professional-grade trajectory planning and execution
|
||||
|
||||
**Completed Tasks:**
|
||||
- ✅ Implement velocity profiling (trapezoidal, S-curve)
|
||||
- ✅ Add coordinate frame transformation helpers
|
||||
- ✅ Implement motion primitives (arc, circle, spiral)
|
||||
- ✅ Add path blending for smooth transitions
|
||||
- ✅ Create comprehensive motion planning examples (5 examples)
|
||||
- ✅ Document all features with application use cases
|
||||
**Planned Tasks:**
|
||||
1. Implement velocity profiling (trapezoidal, S-curve)
|
||||
2. Add coordinate frame transformation helpers
|
||||
3. Implement motion primitives (arc, circle, spiral)
|
||||
4. Add path blending for smooth transitions
|
||||
|
||||
**Deliverables:**
|
||||
- Enhanced `MotionAPI` with 5 new advanced planning methods
|
||||
- Velocity profiling algorithms (trapezoidal and S-curve)
|
||||
- Geometric motion primitives (arc, circle, spiral)
|
||||
- Path blending with cubic Hermite spline interpolation
|
||||
- Coordinate transformations between BASE/WORLD/TOOL/WORK frames
|
||||
- 5 production-ready motion planning examples
|
||||
- Comprehensive documentation (584-line README.md)
|
||||
**Expected Deliverables:**
|
||||
- Enhanced `MotionAPI` with advanced planning
|
||||
- Velocity profiling algorithms
|
||||
- Geometric motion primitives
|
||||
- Path blending for continuous motion
|
||||
- Motion planning examples
|
||||
|
||||
**Files Created/Modified:**
|
||||
- `motion_api.py` - Added 5 static methods + 4 helper functions (~550 lines)
|
||||
- `examples/advanced_motion/01_velocity_profiles.py` - NEW (234 lines)
|
||||
- `examples/advanced_motion/02_geometric_primitives.py` - NEW (225 lines)
|
||||
- `examples/advanced_motion/03_path_blending.py` - NEW (253 lines)
|
||||
- `examples/advanced_motion/04_coordinate_transforms.py` - NEW (284 lines)
|
||||
- `examples/advanced_motion/05_combined_motion.py` - NEW (336 lines)
|
||||
- `examples/advanced_motion/README.md` - NEW comprehensive guide (584 lines)
|
||||
- `PHASE_4_SUMMARY.md` - NEW detailed implementation documentation
|
||||
|
||||
**API Methods:**
|
||||
- `api.motion.generate_velocity_profile(trajectory, max_velocity, max_acceleration, profile)`
|
||||
- `api.motion.generate_arc(center, radius, start_angle, end_angle, steps, plane)`
|
||||
- `api.motion.generate_circle(center, radius, steps, plane)`
|
||||
- `api.motion.generate_spiral(center, start_radius, end_radius, pitch, revolutions, steps, plane, axis)`
|
||||
- `api.motion.blend_trajectories(traj1, traj2, blend_radius, blend_steps)`
|
||||
- `api.motion.transform_coordinates(pose, from_frame, to_frame, frame_offset)`
|
||||
|
||||
**Commit:** `cc19e10` (January 17, 2026)
|
||||
**Target Methods:**
|
||||
- `api.motion.generate_velocity_profile(trajectory, profile='trapezoidal')`
|
||||
- `api.motion.generate_arc(center, radius, start_angle, end_angle)`
|
||||
- `api.motion.generate_circle(center, radius)`
|
||||
- `api.motion.generate_spiral(center, radius, pitch)`
|
||||
- `api.motion.blend_trajectories(traj1, traj2, blend_radius)`
|
||||
- `api.motion.transform_coordinates(pose, frame='BASE')`
|
||||
|
||||
---
|
||||
|
||||
@ -271,30 +234,26 @@ rsi-pi/
|
||||
- ✅ 9 namespaced API classes with clean separation
|
||||
- ✅ Professional API design pattern
|
||||
|
||||
**Phase 2 (Complete):**
|
||||
- ✅ Real-time network quality monitoring
|
||||
- ✅ Automatic recovery from network failures
|
||||
- ✅ Comprehensive diagnostics dashboard
|
||||
- ✅ TimingMetrics tracking (cycle time, jitter, packet loss)
|
||||
- ✅ AutoReconnectManager with configurable retry strategies
|
||||
- ✅ 24-hour stability test infrastructure
|
||||
- ⏳ Run actual 24-hour stability test (pending hardware)
|
||||
**Phase 2 (Planned):**
|
||||
- Real-time network quality monitoring
|
||||
- Automatic recovery from network failures
|
||||
- <5ms average latency, <2ms jitter
|
||||
- 24-hour stability test passes
|
||||
- Comprehensive diagnostics dashboard
|
||||
|
||||
**Phase 3 (Complete):**
|
||||
- ✅ High-level I/O API with pulse generation (set_output, get_input, pulse)
|
||||
- ✅ Python-KRL coordination patterns documented (templates/krl/README.md)
|
||||
- ✅ Tech variable parameter passing working (write_param, read_param)
|
||||
- ✅ KRL template library created (3 templates with full workflows)
|
||||
- ✅ Example coordination workflows (3 Python examples with documentation)
|
||||
**Phase 3 (Planned):**
|
||||
- High-level I/O API with pulse generation
|
||||
- Python-KRL coordination patterns documented
|
||||
- Tech variable parameter passing working
|
||||
- KRL template library created
|
||||
- Example coordination workflows
|
||||
|
||||
**Phase 4 (Complete):**
|
||||
- ✅ Trapezoidal and S-curve velocity profiles implemented
|
||||
- ✅ Arc, circle, spiral motion primitives created
|
||||
- ✅ Path blending with cubic interpolation and configurable blend radius
|
||||
- ✅ Coordinate frame transformations (BASE/WORLD/TOOL/WORK)
|
||||
- ✅ Smooth continuous motion demonstrated in examples
|
||||
- ✅ 5 comprehensive production-ready examples
|
||||
- ✅ 584-line documentation guide created
|
||||
**Phase 4 (Planned):**
|
||||
- Trapezoidal and S-curve velocity profiles
|
||||
- Arc, circle, spiral motion primitives
|
||||
- Path blending with configurable blend radius
|
||||
- Coordinate frame transformations
|
||||
- Smooth continuous motion demonstrated
|
||||
|
||||
**Phase 6 (Planned):**
|
||||
- Performance benchmarks vs ROS/KUKA SDK
|
||||
@ -308,11 +267,11 @@ rsi-pi/
|
||||
## Timeline
|
||||
|
||||
- **Phase 1:** ✅ Complete (January 16, 2026)
|
||||
- **Phase 2:** ✅ Complete (January 17, 2026)
|
||||
- **Phase 3:** ✅ Complete (January 17, 2026)
|
||||
- **Phase 4:** ✅ Complete (January 17, 2026)
|
||||
- **Phase 5:** ✅ Complete (January 16, 2026)
|
||||
- **Phase 6:** 📋 Next priority - Final validation
|
||||
- **Phase 2:** 📋 Next priority
|
||||
- **Phase 3:** 📋 After Phase 2
|
||||
- **Phase 4:** 📋 After Phase 3
|
||||
- **Phase 6:** 📋 Final validation
|
||||
|
||||
**Approach:** "Get it right the first time" - complete each phase fully before moving to the next.
|
||||
|
||||
@ -343,4 +302,4 @@ rsi-pi/
|
||||
- Suitable for industrial research applications
|
||||
- Designed for drilling PhD research (but general-purpose)
|
||||
|
||||
**Last Updated:** January 17, 2026
|
||||
**Last Updated:** January 16, 2026
|
||||
|
||||
@ -1,139 +0,0 @@
|
||||
<ROOT>
|
||||
<CONFIG>
|
||||
<IP_NUMBER>10.10.10.10</IP_NUMBER>
|
||||
<PORT>64000</PORT>
|
||||
<SENTYPE>ImFree</SENTYPE>
|
||||
<ONLYSEND>FALSE</ONLYSEND>
|
||||
</CONFIG>
|
||||
|
||||
<!-- =================================================================
|
||||
RSI Channel Budget: 64 max across SEND + RECEIVE
|
||||
INTERNAL tags don't count toward the 64-channel limit
|
||||
|
||||
SEND channels used: 12 (DiL, Digout x3, Source1-4, Digin x4)
|
||||
RECEIVE channels used: 20 (RKorr x6, AKorr x6, DiO x4, FREE x4)
|
||||
Total: 32 / 64
|
||||
|
||||
All DEF_ tags are INTERNAL (free)
|
||||
================================================================= -->
|
||||
|
||||
<!-- ===================== SEND: Robot → PC ========================= -->
|
||||
<SEND>
|
||||
<ELEMENTS>
|
||||
<!-- Cartesian actual position (X,Y,Z,A,B,C in mm/deg) -->
|
||||
<ELEMENT TAG="DEF_RIst" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- Cartesian setpoint position -->
|
||||
<ELEMENT TAG="DEF_RSol" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- Robot axis actual positions (A1-A6 in deg) -->
|
||||
<ELEMENT TAG="DEF_AIPos" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- Robot axis setpoint positions (A1-A6 in deg) -->
|
||||
<ELEMENT TAG="DEF_ASPos" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- External axis actual positions (E1-E6) -->
|
||||
<ELEMENT TAG="DEF_EIPos" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- External axis setpoint positions (E1-E6) -->
|
||||
<ELEMENT TAG="DEF_ESPos" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- Robot motor currents (A1-A6, % of max) -->
|
||||
<ELEMENT TAG="DEF_MACur" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- External motor currents (E1-E6, % of max) -->
|
||||
<ELEMENT TAG="DEF_MECur" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- Late packet counter -->
|
||||
<ELEMENT TAG="DEF_Delay" TYPE="LONG" INDX="INTERNAL" />
|
||||
|
||||
<!-- Tech channels C1-C6 (main run parameters, robot → PC) -->
|
||||
<ELEMENT TAG="DEF_Tech.C1" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.C2" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.C3" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.C4" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.C5" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.C6" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- Tech channels T1-T6 (advance parameters, robot → PC) -->
|
||||
<ELEMENT TAG="DEF_Tech.T1" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.T2" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.T3" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.T4" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.T5" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.T6" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- Digital input latch (channel 1) -->
|
||||
<ELEMENT TAG="DiL" TYPE="LONG" INDX="1" />
|
||||
|
||||
<!-- Digital output readback (channels 2-4) -->
|
||||
<ELEMENT TAG="Digout.o1" TYPE="BOOL" INDX="2" />
|
||||
<ELEMENT TAG="Digout.o2" TYPE="BOOL" INDX="3" />
|
||||
<ELEMENT TAG="Digout.o3" TYPE="BOOL" INDX="4" />
|
||||
|
||||
<!-- Analog/general sources (channels 5-8) -->
|
||||
<ELEMENT TAG="Source1" TYPE="DOUBLE" INDX="5" />
|
||||
<ELEMENT TAG="Source2" TYPE="DOUBLE" INDX="6" />
|
||||
<ELEMENT TAG="Source3" TYPE="DOUBLE" INDX="7" />
|
||||
<ELEMENT TAG="Source4" TYPE="DOUBLE" INDX="8" />
|
||||
|
||||
<!-- Digital input readback (channels 9-12) -->
|
||||
<ELEMENT TAG="Digin.i1" TYPE="BOOL" INDX="9" />
|
||||
<ELEMENT TAG="Digin.i2" TYPE="BOOL" INDX="10" />
|
||||
<ELEMENT TAG="Digin.i3" TYPE="BOOL" INDX="11" />
|
||||
<ELEMENT TAG="Digin.i4" TYPE="BOOL" INDX="12" />
|
||||
</ELEMENTS>
|
||||
</SEND>
|
||||
|
||||
<!-- =================== RECEIVE: PC → Robot ======================== -->
|
||||
<RECEIVE>
|
||||
<ELEMENTS>
|
||||
<!-- Status/error string to robot -->
|
||||
<ELEMENT TAG="DEF_EStr" TYPE="STRING" INDX="INTERNAL" />
|
||||
|
||||
<!-- Tech channels T1-T6 (advance parameters, PC → robot) -->
|
||||
<ELEMENT TAG="DEF_Tech.T1" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.T2" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.T3" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.T4" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.T5" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.T6" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
|
||||
<!-- Tech channels C1-C6 (main run parameters, PC → robot) -->
|
||||
<ELEMENT TAG="DEF_Tech.C1" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.C2" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.C3" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.C4" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.C5" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.C6" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
|
||||
<!-- Cartesian corrections (channels 1-6, HOLDON keeps last value) -->
|
||||
<ELEMENT TAG="RKorr.X" TYPE="DOUBLE" INDX="1" HOLDON="1" />
|
||||
<ELEMENT TAG="RKorr.Y" TYPE="DOUBLE" INDX="2" HOLDON="1" />
|
||||
<ELEMENT TAG="RKorr.Z" TYPE="DOUBLE" INDX="3" HOLDON="1" />
|
||||
<ELEMENT TAG="RKorr.A" TYPE="DOUBLE" INDX="4" HOLDON="1" />
|
||||
<ELEMENT TAG="RKorr.B" TYPE="DOUBLE" INDX="5" HOLDON="1" />
|
||||
<ELEMENT TAG="RKorr.C" TYPE="DOUBLE" INDX="6" HOLDON="1" />
|
||||
|
||||
<!-- Joint corrections (channels 7-12) -->
|
||||
<ELEMENT TAG="AKorr.A1" TYPE="DOUBLE" INDX="7" HOLDON="1" />
|
||||
<ELEMENT TAG="AKorr.A2" TYPE="DOUBLE" INDX="8" HOLDON="1" />
|
||||
<ELEMENT TAG="AKorr.A3" TYPE="DOUBLE" INDX="9" HOLDON="1" />
|
||||
<ELEMENT TAG="AKorr.A4" TYPE="DOUBLE" INDX="10" HOLDON="1" />
|
||||
<ELEMENT TAG="AKorr.A5" TYPE="DOUBLE" INDX="11" HOLDON="1" />
|
||||
<ELEMENT TAG="AKorr.A6" TYPE="DOUBLE" INDX="12" HOLDON="1" />
|
||||
|
||||
<!-- Digital outputs (channels 13-16) -->
|
||||
<ELEMENT TAG="DiO1" TYPE="LONG" INDX="13" HOLDON="1" />
|
||||
<ELEMENT TAG="DiO2" TYPE="LONG" INDX="14" HOLDON="1" />
|
||||
<ELEMENT TAG="DiO3" TYPE="LONG" INDX="15" HOLDON="1" />
|
||||
<ELEMENT TAG="DiO4" TYPE="LONG" INDX="16" HOLDON="1" />
|
||||
|
||||
<!-- Spare channels (17-20) for future use -->
|
||||
<ELEMENT TAG="FREE1" TYPE="LONG" INDX="17" HOLDON="1" />
|
||||
<ELEMENT TAG="FREE2" TYPE="LONG" INDX="18" HOLDON="1" />
|
||||
<ELEMENT TAG="FREE3" TYPE="LONG" INDX="19" HOLDON="1" />
|
||||
<ELEMENT TAG="FREE4" TYPE="LONG" INDX="20" HOLDON="1" />
|
||||
</ELEMENTS>
|
||||
</RECEIVE>
|
||||
</ROOT>
|
||||
BIN
TestServer.exe
BIN
TestServer.exe
Binary file not shown.
@ -1,179 +0,0 @@
|
||||
"""
|
||||
Velocity Profile Example
|
||||
|
||||
Demonstrates velocity profiling for smooth, time-optimal motion with
|
||||
configurable acceleration and jerk limits.
|
||||
|
||||
Compares trapezoidal (bang-bang) and S-curve (jerk-limited) profiles.
|
||||
|
||||
Usage:
|
||||
python 01_velocity_profiles.py --config RSI_EthernetConfig.xml
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
from RSIPI import RSIAPI
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
|
||||
|
||||
def velocity_profile_example(config_file: str) -> None:
|
||||
"""
|
||||
Demonstrate velocity profiling with trapezoidal and S-curve profiles.
|
||||
|
||||
Args:
|
||||
config_file: Path to RSI configuration XML file
|
||||
"""
|
||||
api = RSIAPI(config_file)
|
||||
|
||||
try:
|
||||
logging.info("Starting RSI communication...")
|
||||
api.start()
|
||||
logging.info("✅ RSI started successfully")
|
||||
|
||||
# Define waypoints for straight-line motion
|
||||
p0 = {"X": 0, "Y": 0, "Z": 500}
|
||||
p1 = {"X": 200, "Y": 100, "Z": 500}
|
||||
|
||||
logging.info("Generating base trajectory...")
|
||||
trajectory = api.motion.generate_trajectory(p0, p1, steps=100)
|
||||
logging.info(f"Generated {len(trajectory)} waypoints")
|
||||
|
||||
# ==================================================
|
||||
# Example 1: Trapezoidal Velocity Profile
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 1: Trapezoidal Velocity Profile")
|
||||
logging.info("=" * 60)
|
||||
|
||||
profiled_trap = api.motion.generate_velocity_profile(
|
||||
trajectory,
|
||||
max_velocity=200.0, # mm/s
|
||||
max_acceleration=500.0, # mm/s²
|
||||
profile='trapezoidal'
|
||||
)
|
||||
|
||||
logging.info("Trapezoidal profile generated:")
|
||||
logging.info(f" Total waypoints: {len(profiled_trap)}")
|
||||
|
||||
# Sample velocities at key points
|
||||
logging.info(" Sample velocities:")
|
||||
for i in [0, 25, 50, 75, 99]:
|
||||
_, velocity = profiled_trap[i]
|
||||
logging.info(f" Point {i}: {velocity:.2f} mm/s")
|
||||
|
||||
# ==================================================
|
||||
# Example 2: S-Curve Velocity Profile
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 2: S-Curve Velocity Profile (Jerk-Limited)")
|
||||
logging.info("=" * 60)
|
||||
|
||||
profiled_scurve = api.motion.generate_velocity_profile(
|
||||
trajectory,
|
||||
max_velocity=200.0, # mm/s
|
||||
max_acceleration=500.0, # mm/s²
|
||||
profile='s-curve'
|
||||
)
|
||||
|
||||
logging.info("S-curve profile generated:")
|
||||
logging.info(f" Total waypoints: {len(profiled_scurve)}")
|
||||
|
||||
logging.info(" Sample velocities:")
|
||||
for i in [0, 25, 50, 75, 99]:
|
||||
_, velocity = profiled_scurve[i]
|
||||
logging.info(f" Point {i}: {velocity:.2f} mm/s")
|
||||
|
||||
# ==================================================
|
||||
# Comparison
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Profile Comparison")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Compare acceleration characteristics
|
||||
trap_velocities = [v for _, v in profiled_trap]
|
||||
scurve_velocities = [v for _, v in profiled_scurve]
|
||||
|
||||
trap_max = max(trap_velocities)
|
||||
scurve_max = max(scurve_velocities)
|
||||
|
||||
logging.info(f"Trapezoidal peak velocity: {trap_max:.2f} mm/s")
|
||||
logging.info(f"S-curve peak velocity: {scurve_max:.2f} mm/s")
|
||||
|
||||
logging.info("\nCharacteristics:")
|
||||
logging.info(" Trapezoidal:")
|
||||
logging.info(" - Sharp velocity transitions (instant acceleration changes)")
|
||||
logging.info(" - Faster overall motion time")
|
||||
logging.info(" - Higher mechanical stress")
|
||||
logging.info(" - Suitable for rigid structures")
|
||||
|
||||
logging.info(" S-Curve:")
|
||||
logging.info(" - Smooth velocity transitions (limited jerk)")
|
||||
logging.info(" - Slightly longer motion time")
|
||||
logging.info(" - Reduced vibration and mechanical stress")
|
||||
logging.info(" - Recommended for sensitive applications")
|
||||
|
||||
# ==================================================
|
||||
# Example 3: Using Profiled Trajectory
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 3: Executing Profiled Motion")
|
||||
logging.info("=" * 60)
|
||||
|
||||
logging.info("Using S-curve profile for smooth motion...")
|
||||
|
||||
# Extract just the waypoints (timing handled by profile)
|
||||
waypoints = [wp for wp, _ in profiled_scurve]
|
||||
|
||||
logging.info("Executing trajectory with profiled velocities...")
|
||||
# In production, you would use the velocities to adjust execution rate
|
||||
# For this example, we use standard execution
|
||||
api.motion.execute_trajectory(waypoints, space='cartesian', rate=0.02)
|
||||
|
||||
logging.info("✅ Profiled motion complete")
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logging.warning("\n⚠️ Interrupted by user")
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"❌ Error during velocity profiling: {e}")
|
||||
|
||||
finally:
|
||||
logging.info("Stopping RSI communication...")
|
||||
api.stop()
|
||||
logging.info("✅ API stopped successfully")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point."""
|
||||
parser = argparse.ArgumentParser(description='Velocity Profile Example')
|
||||
parser.add_argument(
|
||||
'--config',
|
||||
type=str,
|
||||
default='RSI_EthernetConfig.xml',
|
||||
help='Path to RSI configuration file'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("RSIPI - Velocity Profile Example")
|
||||
logging.info("=" * 60)
|
||||
logging.info(f"Config: {args.config}")
|
||||
logging.info("=" * 60)
|
||||
|
||||
velocity_profile_example(args.config)
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("Example complete!")
|
||||
logging.info("=" * 60)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
main()
|
||||
@ -1,226 +0,0 @@
|
||||
"""
|
||||
Geometric Motion Primitives Example
|
||||
|
||||
Demonstrates arc, circle, and spiral trajectory generation for
|
||||
complex motion patterns.
|
||||
|
||||
Usage:
|
||||
python 02_geometric_primitives.py --config RSI_EthernetConfig.xml
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
from RSIPI import RSIAPI
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
|
||||
|
||||
def geometric_primitives_example(config_file: str) -> None:
|
||||
"""
|
||||
Demonstrate geometric motion primitives.
|
||||
|
||||
Args:
|
||||
config_file: Path to RSI configuration XML file
|
||||
"""
|
||||
api = RSIAPI(config_file)
|
||||
|
||||
try:
|
||||
logging.info("Starting RSI communication...")
|
||||
api.start()
|
||||
logging.info("✅ RSI started successfully")
|
||||
|
||||
center = {"X": 100, "Y": 0, "Z": 500}
|
||||
|
||||
# ==================================================
|
||||
# Example 1: Circular Arc
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 1: Circular Arc (90 degrees)")
|
||||
logging.info("=" * 60)
|
||||
|
||||
arc = api.motion.generate_arc(
|
||||
center=center,
|
||||
radius=50.0, # mm
|
||||
start_angle=0, # degrees
|
||||
end_angle=90, # degrees
|
||||
steps=50,
|
||||
plane='XY'
|
||||
)
|
||||
|
||||
logging.info(f"Generated arc with {len(arc)} waypoints")
|
||||
logging.info(f"Start point: {arc[0]}")
|
||||
logging.info(f"End point: {arc[-1]}")
|
||||
|
||||
logging.info("Executing arc motion...")
|
||||
api.motion.execute_trajectory(arc, space='cartesian', rate=0.02)
|
||||
logging.info("✅ Arc complete")
|
||||
|
||||
# ==================================================
|
||||
# Example 2: Full Circle
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 2: Full Circle (360 degrees)")
|
||||
logging.info("=" * 60)
|
||||
|
||||
circle = api.motion.generate_circle(
|
||||
center=center,
|
||||
radius=30.0, # mm
|
||||
steps=100,
|
||||
plane='XY'
|
||||
)
|
||||
|
||||
logging.info(f"Generated circle with {len(circle)} waypoints")
|
||||
logging.info(f"Radius: 30.0 mm")
|
||||
logging.info(f"Circumference: ~{2 * 3.14159 * 30.0:.2f} mm")
|
||||
|
||||
logging.info("Executing circular motion...")
|
||||
api.motion.execute_trajectory(circle, space='cartesian', rate=0.02)
|
||||
logging.info("✅ Circle complete")
|
||||
|
||||
# ==================================================
|
||||
# Example 3: Expanding Spiral (Drilling Pattern)
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 3: Expanding Spiral (Drilling Pattern)")
|
||||
logging.info("=" * 60)
|
||||
|
||||
spiral_expand = api.motion.generate_spiral(
|
||||
center={"X": 100, "Y": 0, "Z": 500},
|
||||
start_radius=5.0, # Start at 5mm
|
||||
end_radius=40.0, # End at 40mm
|
||||
pitch=10.0, # Descend 10mm per revolution
|
||||
revolutions=3.0, # 3 complete turns
|
||||
steps=150,
|
||||
plane='XY',
|
||||
axis='Z'
|
||||
)
|
||||
|
||||
logging.info(f"Generated expanding spiral:")
|
||||
logging.info(f" Waypoints: {len(spiral_expand)}")
|
||||
logging.info(f" Start radius: 5.0 mm")
|
||||
logging.info(f" End radius: 40.0 mm")
|
||||
logging.info(f" Pitch: 10.0 mm/rev (descending)")
|
||||
logging.info(f" Revolutions: 3.0")
|
||||
logging.info(f" Total Z travel: 30.0 mm")
|
||||
|
||||
logging.info("Executing expanding spiral...")
|
||||
api.motion.execute_trajectory(spiral_expand, space='cartesian', rate=0.02)
|
||||
logging.info("✅ Expanding spiral complete")
|
||||
|
||||
# ==================================================
|
||||
# Example 4: Contracting Spiral (Retraction Pattern)
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 4: Contracting Spiral (Retraction Pattern)")
|
||||
logging.info("=" * 60)
|
||||
|
||||
spiral_contract = api.motion.generate_spiral(
|
||||
center={"X": 100, "Y": 0, "Z": 470}, # Start at bottom
|
||||
start_radius=40.0, # Start wide
|
||||
end_radius=5.0, # End narrow
|
||||
pitch=-10.0, # Ascend 10mm per revolution (negative pitch)
|
||||
revolutions=3.0,
|
||||
steps=150,
|
||||
plane='XY',
|
||||
axis='Z'
|
||||
)
|
||||
|
||||
logging.info(f"Generated contracting spiral:")
|
||||
logging.info(f" Waypoints: {len(spiral_contract)}")
|
||||
logging.info(f" Start radius: 40.0 mm")
|
||||
logging.info(f" End radius: 5.0 mm")
|
||||
logging.info(f" Pitch: -10.0 mm/rev (ascending)")
|
||||
logging.info(f" Revolutions: 3.0")
|
||||
logging.info(f" Total Z travel: -30.0 mm (upward)")
|
||||
|
||||
logging.info("Executing contracting spiral...")
|
||||
api.motion.execute_trajectory(spiral_contract, space='cartesian', rate=0.02)
|
||||
logging.info("✅ Contracting spiral complete")
|
||||
|
||||
# ==================================================
|
||||
# Example 5: Different Planes
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 5: Circles in Different Planes")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Circle in XZ plane (vertical)
|
||||
circle_xz = api.motion.generate_circle(
|
||||
center={"X": 100, "Y": 0, "Z": 500},
|
||||
radius=25.0,
|
||||
steps=80,
|
||||
plane='XZ'
|
||||
)
|
||||
|
||||
logging.info("Circle in XZ plane (vertical):")
|
||||
logging.info(f" Waypoints: {len(circle_xz)}")
|
||||
logging.info(f" Plane: XZ (vertical circle)")
|
||||
|
||||
logging.info("Executing XZ circle...")
|
||||
api.motion.execute_trajectory(circle_xz, space='cartesian', rate=0.02)
|
||||
logging.info("✅ XZ circle complete")
|
||||
|
||||
# ==================================================
|
||||
# Application Examples
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Application Examples")
|
||||
logging.info("=" * 60)
|
||||
|
||||
logging.info("\nDrilling/Milling Applications:")
|
||||
logging.info(" - Expanding spiral: Drill out large holes, pocket milling")
|
||||
logging.info(" - Contracting spiral: Retracting from deep holes")
|
||||
logging.info(" - Circular: Bore existing holes, circular pockets")
|
||||
|
||||
logging.info("\nAssembly Applications:")
|
||||
logging.info(" - Circular: Screw driving, peg insertion with clearance")
|
||||
logging.info(" - Arc: Curved insertion paths, avoiding obstacles")
|
||||
|
||||
logging.info("\nInspection Applications:")
|
||||
logging.info(" - Circle: Scanning circular features")
|
||||
logging.info(" - Spiral: Scanning large areas with overlap")
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logging.warning("\n⚠️ Interrupted by user")
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"❌ Error during geometric primitives: {e}")
|
||||
|
||||
finally:
|
||||
logging.info("Stopping RSI communication...")
|
||||
api.stop()
|
||||
logging.info("✅ API stopped successfully")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point."""
|
||||
parser = argparse.ArgumentParser(description='Geometric Primitives Example')
|
||||
parser.add_argument(
|
||||
'--config',
|
||||
type=str,
|
||||
default='RSI_EthernetConfig.xml',
|
||||
help='Path to RSI configuration file'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("RSIPI - Geometric Motion Primitives Example")
|
||||
logging.info("=" * 60)
|
||||
logging.info(f"Config: {args.config}")
|
||||
logging.info("=" * 60)
|
||||
|
||||
geometric_primitives_example(args.config)
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("Example complete!")
|
||||
logging.info("=" * 60)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
main()
|
||||
@ -1,283 +0,0 @@
|
||||
"""
|
||||
Path Blending Example
|
||||
|
||||
Demonstrates smooth trajectory transitions using cubic interpolation for
|
||||
eliminating stop-and-go motion at trajectory boundaries.
|
||||
|
||||
Usage:
|
||||
python 03_path_blending.py --config RSI_EthernetConfig.xml
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
from RSIPI import RSIAPI
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
|
||||
|
||||
def path_blending_example(config_file: str) -> None:
|
||||
"""
|
||||
Demonstrate path blending for smooth trajectory transitions.
|
||||
|
||||
Args:
|
||||
config_file: Path to RSI configuration XML file
|
||||
"""
|
||||
api = RSIAPI(config_file)
|
||||
|
||||
try:
|
||||
logging.info("Starting RSI communication...")
|
||||
api.start()
|
||||
logging.info("✅ RSI started successfully")
|
||||
|
||||
# ==================================================
|
||||
# Example 1: Sharp Corner vs Blended Corner
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 1: Sharp Corner vs Blended Corner")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Define three points forming a right angle
|
||||
p0 = {"X": 100, "Y": 0, "Z": 500}
|
||||
p1 = {"X": 200, "Y": 0, "Z": 500} # Corner point
|
||||
p2 = {"X": 200, "Y": 100, "Z": 500}
|
||||
|
||||
# Generate two separate trajectories
|
||||
traj1 = api.motion.generate_trajectory(p0, p1, steps=50)
|
||||
traj2 = api.motion.generate_trajectory(p1, p2, steps=50)
|
||||
|
||||
logging.info("\nWithout blending:")
|
||||
logging.info(" - Robot will stop at corner point")
|
||||
logging.info(" - Visible acceleration/deceleration")
|
||||
logging.info(" - Less smooth motion")
|
||||
|
||||
# Execute sharp corner (no blending)
|
||||
logging.info("\nExecuting sharp corner motion...")
|
||||
api.motion.execute_trajectory(traj1, space='cartesian', rate=0.02)
|
||||
api.motion.execute_trajectory(traj2, space='cartesian', rate=0.02)
|
||||
logging.info("✅ Sharp corner complete")
|
||||
|
||||
# Return to start
|
||||
api.motion.execute_trajectory(
|
||||
api.motion.generate_trajectory(p2, p0, steps=50),
|
||||
space='cartesian',
|
||||
rate=0.02
|
||||
)
|
||||
|
||||
# Now execute with blending
|
||||
logging.info("\nWith blending:")
|
||||
logging.info(" - Smooth transition through corner")
|
||||
logging.info(" - No visible stop at corner point")
|
||||
logging.info(" - Continuous velocity")
|
||||
|
||||
blended = api.motion.blend_trajectories(
|
||||
traj1,
|
||||
traj2,
|
||||
blend_radius=20.0, # Start blending 20mm before corner
|
||||
blend_steps=20
|
||||
)
|
||||
|
||||
logging.info(f"\nBlended trajectory: {len(blended)} waypoints")
|
||||
logging.info(f"Original: {len(traj1) + len(traj2)} waypoints")
|
||||
logging.info(f"Blend zone: 20.0 mm radius")
|
||||
|
||||
logging.info("Executing blended corner motion...")
|
||||
api.motion.execute_trajectory(blended, space='cartesian', rate=0.02)
|
||||
logging.info("✅ Blended corner complete")
|
||||
|
||||
# ==================================================
|
||||
# Example 2: Multiple Blend Zones (Continuous Path)
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 2: Continuous Path with Multiple Blends")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Define waypoints for a square pattern
|
||||
waypoints = [
|
||||
{"X": 100, "Y": 0, "Z": 500},
|
||||
{"X": 150, "Y": 0, "Z": 500},
|
||||
{"X": 150, "Y": 50, "Z": 500},
|
||||
{"X": 100, "Y": 50, "Z": 500},
|
||||
{"X": 100, "Y": 0, "Z": 500} # Return to start
|
||||
]
|
||||
|
||||
logging.info(f"Square pattern with {len(waypoints)} waypoints")
|
||||
|
||||
# Generate segments
|
||||
segments = []
|
||||
for i in range(len(waypoints) - 1):
|
||||
segment = api.motion.generate_trajectory(
|
||||
waypoints[i],
|
||||
waypoints[i + 1],
|
||||
steps=30
|
||||
)
|
||||
segments.append(segment)
|
||||
|
||||
logging.info(f"Generated {len(segments)} path segments")
|
||||
|
||||
# Blend all segments together
|
||||
logging.info("Blending all corners...")
|
||||
blended_path = segments[0]
|
||||
|
||||
for i in range(1, len(segments)):
|
||||
blended_path = api.motion.blend_trajectories(
|
||||
blended_path,
|
||||
segments[i],
|
||||
blend_radius=10.0,
|
||||
blend_steps=15
|
||||
)
|
||||
logging.info(f" Blended corner {i}/{len(segments)-1}")
|
||||
|
||||
logging.info(f"\nFinal blended path: {len(blended_path)} waypoints")
|
||||
logging.info("Executing continuous square pattern...")
|
||||
api.motion.execute_trajectory(blended_path, space='cartesian', rate=0.02)
|
||||
logging.info("✅ Continuous square complete")
|
||||
|
||||
# ==================================================
|
||||
# Example 3: Different Blend Radii
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 3: Effect of Different Blend Radii")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Same trajectories as Example 1
|
||||
traj1 = api.motion.generate_trajectory(p0, p1, steps=50)
|
||||
traj2 = api.motion.generate_trajectory(p1, p2, steps=50)
|
||||
|
||||
blend_radii = [5.0, 15.0, 30.0]
|
||||
|
||||
for radius in blend_radii:
|
||||
logging.info(f"\n--- Blend Radius: {radius} mm ---")
|
||||
|
||||
blended = api.motion.blend_trajectories(
|
||||
traj1,
|
||||
traj2,
|
||||
blend_radius=radius,
|
||||
blend_steps=20
|
||||
)
|
||||
|
||||
logging.info(f"Blend radius: {radius} mm")
|
||||
logging.info(f"Blended waypoints: {len(blended)}")
|
||||
|
||||
if radius < 10:
|
||||
logging.info("Effect: Tighter blend, closer to sharp corner")
|
||||
elif radius < 20:
|
||||
logging.info("Effect: Moderate blend, balanced smoothness")
|
||||
else:
|
||||
logging.info("Effect: Wide blend, very smooth but cuts corner more")
|
||||
|
||||
logging.info(f"Executing blend with radius={radius}mm...")
|
||||
api.motion.execute_trajectory(blended, space='cartesian', rate=0.02)
|
||||
logging.info(f"✅ Blend radius {radius}mm complete")
|
||||
|
||||
# Return to start
|
||||
api.motion.execute_trajectory(
|
||||
api.motion.generate_trajectory(p2, p0, steps=50),
|
||||
space='cartesian',
|
||||
rate=0.02
|
||||
)
|
||||
|
||||
# ==================================================
|
||||
# Example 4: Blending with Different Orientations
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 4: Blending Trajectories with Orientation Changes")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Define points with different orientations
|
||||
p0_rot = {"X": 100, "Y": 0, "Z": 500, "A": 0, "B": 0, "C": 0}
|
||||
p1_rot = {"X": 150, "Y": 0, "Z": 500, "A": 0, "B": 0, "C": 45}
|
||||
p2_rot = {"X": 150, "Y": 50, "Z": 500, "A": 0, "B": 0, "C": 90}
|
||||
|
||||
traj1_rot = api.motion.generate_trajectory(p0_rot, p1_rot, steps=50)
|
||||
traj2_rot = api.motion.generate_trajectory(p1_rot, p2_rot, steps=50)
|
||||
|
||||
logging.info("Trajectory with orientation change:")
|
||||
logging.info(f" Start: C = 0°")
|
||||
logging.info(f" Corner: C = 45°")
|
||||
logging.info(f" End: C = 90°")
|
||||
|
||||
blended_rot = api.motion.blend_trajectories(
|
||||
traj1_rot,
|
||||
traj2_rot,
|
||||
blend_radius=15.0,
|
||||
blend_steps=20
|
||||
)
|
||||
|
||||
logging.info(f"\nBlending also smooths orientation transitions")
|
||||
logging.info(f"Blended waypoints: {len(blended_rot)}")
|
||||
|
||||
logging.info("Executing blended motion with rotation...")
|
||||
api.motion.execute_trajectory(blended_rot, space='cartesian', rate=0.02)
|
||||
logging.info("✅ Blended rotation complete")
|
||||
|
||||
# ==================================================
|
||||
# Application Examples
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Application Examples")
|
||||
logging.info("=" * 60)
|
||||
|
||||
logging.info("\nPick and Place Applications:")
|
||||
logging.info(" - Smooth transitions between pick/place points")
|
||||
logging.info(" - Reduced cycle time by eliminating stops")
|
||||
logging.info(" - Lower mechanical stress on robot")
|
||||
|
||||
logging.info("\nWelding/Gluing Applications:")
|
||||
logging.info(" - Continuous bead at corners without stop marks")
|
||||
logging.info(" - Consistent material deposition rate")
|
||||
logging.info(" - Professional finish quality")
|
||||
|
||||
logging.info("\nMachining Applications:")
|
||||
logging.info(" - Smooth tool paths without witness marks")
|
||||
logging.info(" - Reduced vibration and tool wear")
|
||||
logging.info(" - Better surface finish")
|
||||
|
||||
logging.info("\nPainting/Coating Applications:")
|
||||
logging.info(" - Even coating thickness at corners")
|
||||
logging.info(" - No overspray from deceleration")
|
||||
logging.info(" - Faster throughput")
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logging.warning("\n⚠️ Interrupted by user")
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"❌ Error during path blending: {e}")
|
||||
|
||||
finally:
|
||||
logging.info("Stopping RSI communication...")
|
||||
api.stop()
|
||||
logging.info("✅ API stopped successfully")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point."""
|
||||
parser = argparse.ArgumentParser(description='Path Blending Example')
|
||||
parser.add_argument(
|
||||
'--config',
|
||||
type=str,
|
||||
default='RSI_EthernetConfig.xml',
|
||||
help='Path to RSI configuration file'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("RSIPI - Path Blending Example")
|
||||
logging.info("=" * 60)
|
||||
logging.info(f"Config: {args.config}")
|
||||
logging.info("=" * 60)
|
||||
|
||||
path_blending_example(args.config)
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("Example complete!")
|
||||
logging.info("=" * 60)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
main()
|
||||
@ -1,307 +0,0 @@
|
||||
"""
|
||||
Coordinate Frame Transformation Example
|
||||
|
||||
Demonstrates transformation of positions and trajectories between different
|
||||
coordinate frames (BASE, TOOL, WORLD, ROBROOT).
|
||||
|
||||
Usage:
|
||||
python 04_coordinate_transforms.py --config RSI_EthernetConfig.xml
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
from RSIPI import RSIAPI
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
|
||||
|
||||
def coordinate_transform_example(config_file: str) -> None:
|
||||
"""
|
||||
Demonstrate coordinate frame transformations.
|
||||
|
||||
Args:
|
||||
config_file: Path to RSI configuration XML file
|
||||
"""
|
||||
api = RSIAPI(config_file)
|
||||
|
||||
try:
|
||||
logging.info("Starting RSI communication...")
|
||||
api.start()
|
||||
logging.info("✅ RSI started successfully")
|
||||
|
||||
# ==================================================
|
||||
# Example 1: BASE to WORLD Transformation
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 1: BASE to WORLD Transformation")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Define BASE coordinate system offset
|
||||
base_offset = {
|
||||
"X": 500.0, # Base is 500mm offset in X
|
||||
"Y": 200.0, # 200mm offset in Y
|
||||
"Z": 0.0,
|
||||
"A": 0.0,
|
||||
"B": 0.0,
|
||||
"C": 45.0 # Base rotated 45° around Z
|
||||
}
|
||||
|
||||
# Position in BASE coordinates
|
||||
pose_base = {"X": 100, "Y": 50, "Z": 500, "A": 0, "B": 0, "C": 0}
|
||||
|
||||
logging.info("BASE coordinate system offset:")
|
||||
logging.info(f" Translation: X={base_offset['X']}, Y={base_offset['Y']}, Z={base_offset['Z']}")
|
||||
logging.info(f" Rotation: A={base_offset['A']}, B={base_offset['B']}, C={base_offset['C']}")
|
||||
|
||||
logging.info(f"\nPosition in BASE frame:")
|
||||
logging.info(f" X={pose_base['X']}, Y={pose_base['Y']}, Z={pose_base['Z']}")
|
||||
logging.info(f" A={pose_base['A']}, B={pose_base['B']}, C={pose_base['C']}")
|
||||
|
||||
# Transform to WORLD coordinates
|
||||
pose_world = api.motion.transform_coordinates(
|
||||
pose_base,
|
||||
from_frame='BASE',
|
||||
to_frame='WORLD',
|
||||
frame_offset=base_offset
|
||||
)
|
||||
|
||||
logging.info(f"\nPosition in WORLD frame:")
|
||||
logging.info(f" X={pose_world['X']}, Y={pose_world['Y']}, Z={pose_world['Z']}")
|
||||
logging.info(f" A={pose_world['A']}, B={pose_world['B']}, C={pose_world['C']}")
|
||||
|
||||
# ==================================================
|
||||
# Example 2: TOOL Frame Offset
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 2: TOOL Frame Transformation")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Define TOOL coordinate system (e.g., gripper with offset)
|
||||
tool_offset = {
|
||||
"X": 0.0,
|
||||
"Y": 0.0,
|
||||
"Z": 150.0, # Tool extends 150mm in Z
|
||||
"A": 0.0,
|
||||
"B": 0.0,
|
||||
"C": 0.0
|
||||
}
|
||||
|
||||
# Position expressed at tool center point (TCP)
|
||||
pose_tcp = {"X": 200, "Y": 100, "Z": 400}
|
||||
|
||||
logging.info("TOOL offset from flange:")
|
||||
logging.info(f" Z offset: {tool_offset['Z']} mm")
|
||||
|
||||
logging.info(f"\nPosition at TCP:")
|
||||
logging.info(f" X={pose_tcp['X']}, Y={pose_tcp['Y']}, Z={pose_tcp['Z']}")
|
||||
|
||||
# Transform to flange coordinates
|
||||
pose_flange = api.motion.transform_coordinates(
|
||||
pose_tcp,
|
||||
from_frame='TOOL',
|
||||
to_frame='BASE',
|
||||
frame_offset=tool_offset
|
||||
)
|
||||
|
||||
logging.info(f"\nPosition at flange:")
|
||||
logging.info(f" X={pose_flange['X']}, Y={pose_flange['Y']}, Z={pose_flange['Z']}")
|
||||
logging.info(f" Note: Z decreased by {tool_offset['Z']}mm (tool length)")
|
||||
|
||||
# ==================================================
|
||||
# Example 3: Transforming Entire Trajectories
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 3: Transforming Trajectories Between Frames")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Generate a circular trajectory in TOOL frame
|
||||
circle_tcp = api.motion.generate_circle(
|
||||
center={"X": 0, "Y": 0, "Z": 50}, # Circle around TCP
|
||||
radius=20.0,
|
||||
steps=50,
|
||||
plane='XY'
|
||||
)
|
||||
|
||||
logging.info(f"Generated circle in TOOL frame:")
|
||||
logging.info(f" Center: X=0, Y=0, Z=50 (relative to TCP)")
|
||||
logging.info(f" Radius: 20mm")
|
||||
logging.info(f" Waypoints: {len(circle_tcp)}")
|
||||
|
||||
# Transform entire trajectory to BASE frame
|
||||
circle_base = []
|
||||
for waypoint in circle_tcp:
|
||||
transformed = api.motion.transform_coordinates(
|
||||
waypoint,
|
||||
from_frame='TOOL',
|
||||
to_frame='BASE',
|
||||
frame_offset=tool_offset
|
||||
)
|
||||
circle_base.append(transformed)
|
||||
|
||||
logging.info(f"\nTransformed to BASE frame:")
|
||||
logging.info(f" First waypoint: X={circle_base[0]['X']:.2f}, Y={circle_base[0]['Y']:.2f}, Z={circle_base[0]['Z']:.2f}")
|
||||
logging.info(f" Circle now expressed relative to flange")
|
||||
|
||||
# ==================================================
|
||||
# Example 4: Work Object Offset
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 4: Work Object (Pallet) Transformation")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Define work object position (e.g., pallet location)
|
||||
pallet_offset = {
|
||||
"X": 800.0,
|
||||
"Y": -300.0,
|
||||
"Z": 50.0, # Pallet height
|
||||
"A": 0.0,
|
||||
"B": 0.0,
|
||||
"C": 30.0 # Pallet rotated 30° for better access
|
||||
}
|
||||
|
||||
# Define pick points relative to pallet corner (work object frame)
|
||||
pick_points_pallet = [
|
||||
{"X": 50, "Y": 50, "Z": 20},
|
||||
{"X": 150, "Y": 50, "Z": 20},
|
||||
{"X": 50, "Y": 150, "Z": 20},
|
||||
{"X": 150, "Y": 150, "Z": 20}
|
||||
]
|
||||
|
||||
logging.info("Pallet location in BASE frame:")
|
||||
logging.info(f" X={pallet_offset['X']}, Y={pallet_offset['Y']}, Z={pallet_offset['Z']}")
|
||||
logging.info(f" Rotation: C={pallet_offset['C']}°")
|
||||
|
||||
logging.info(f"\nPick points defined relative to pallet:")
|
||||
for i, point in enumerate(pick_points_pallet, 1):
|
||||
logging.info(f" Point {i}: X={point['X']}, Y={point['Y']}, Z={point['Z']}")
|
||||
|
||||
# Transform pick points to robot BASE frame
|
||||
pick_points_base = []
|
||||
for point in pick_points_pallet:
|
||||
transformed = api.motion.transform_coordinates(
|
||||
point,
|
||||
from_frame='WORK',
|
||||
to_frame='BASE',
|
||||
frame_offset=pallet_offset
|
||||
)
|
||||
pick_points_base.append(transformed)
|
||||
|
||||
logging.info(f"\nPick points in robot BASE frame:")
|
||||
for i, point in enumerate(pick_points_base, 1):
|
||||
logging.info(f" Point {i}: X={point['X']:.2f}, Y={point['Y']:.2f}, Z={point['Z']:.2f}")
|
||||
|
||||
logging.info("\nAdvantage: Pallet can be moved/rotated by updating offset only")
|
||||
|
||||
# ==================================================
|
||||
# Example 5: Practical Application - Sensor-Guided Motion
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Example 5: Sensor-Guided Motion with Frame Transforms")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Simulated sensor detects part offset
|
||||
sensor_offset = {
|
||||
"X": 5.2, # Part detected 5.2mm offset in X
|
||||
"Y": -2.1, # 2.1mm offset in Y
|
||||
"Z": 0.0,
|
||||
"A": 0.0,
|
||||
"B": 0.0,
|
||||
"C": 1.5 # Part rotated 1.5° from expected
|
||||
}
|
||||
|
||||
logging.info("Sensor detected part offset:")
|
||||
logging.info(f" ΔX = {sensor_offset['X']:+.1f} mm")
|
||||
logging.info(f" ΔY = {sensor_offset['Y']:+.1f} mm")
|
||||
logging.info(f" ΔC = {sensor_offset['C']:+.1f}°")
|
||||
|
||||
# Nominal pick position (taught position)
|
||||
nominal_pick = {"X": 300, "Y": 200, "Z": 100, "A": 0, "B": 0, "C": 0}
|
||||
|
||||
logging.info(f"\nNominal pick position:")
|
||||
logging.info(f" X={nominal_pick['X']}, Y={nominal_pick['Y']}, Z={nominal_pick['Z']}")
|
||||
|
||||
# Apply sensor correction
|
||||
corrected_pick = api.motion.transform_coordinates(
|
||||
nominal_pick,
|
||||
from_frame='BASE',
|
||||
to_frame='BASE', # Same frame, just applying offset
|
||||
frame_offset=sensor_offset
|
||||
)
|
||||
|
||||
logging.info(f"\nCorrected pick position:")
|
||||
logging.info(f" X={corrected_pick['X']:.1f}, Y={corrected_pick['Y']:.1f}, Z={corrected_pick['Z']:.1f}")
|
||||
logging.info(f" C={corrected_pick['C']:.1f}°")
|
||||
|
||||
logging.info("\nRobot will pick from corrected position based on sensor feedback")
|
||||
|
||||
# ==================================================
|
||||
# Application Examples
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Application Examples")
|
||||
logging.info("=" * 60)
|
||||
|
||||
logging.info("\nMultiple Work Objects:")
|
||||
logging.info(" - Define multiple pallet/fixture locations")
|
||||
logging.info(" - Teach trajectories once relative to work object")
|
||||
logging.info(" - Execute on any pallet by changing offset")
|
||||
|
||||
logging.info("\nTool Changes:")
|
||||
logging.info(" - Different tools have different TCP offsets")
|
||||
logging.info(" - Transform taught positions for new tool")
|
||||
logging.info(" - No need to reteach all positions")
|
||||
|
||||
logging.info("\nVision/Sensor Integration:")
|
||||
logging.info(" - Sensor detects part position/orientation")
|
||||
logging.info(" - Apply correction transform to taught path")
|
||||
logging.info(" - Robot adapts to part variations")
|
||||
|
||||
logging.info("\nMulti-Robot Cells:")
|
||||
logging.info(" - Each robot has its own BASE frame")
|
||||
logging.info(" - Transform positions to shared WORLD frame")
|
||||
logging.info(" - Coordinate motion between robots")
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logging.warning("\n⚠️ Interrupted by user")
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"❌ Error during coordinate transforms: {e}")
|
||||
|
||||
finally:
|
||||
logging.info("Stopping RSI communication...")
|
||||
api.stop()
|
||||
logging.info("✅ API stopped successfully")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point."""
|
||||
parser = argparse.ArgumentParser(description='Coordinate Transform Example')
|
||||
parser.add_argument(
|
||||
'--config',
|
||||
type=str,
|
||||
default='RSI_EthernetConfig.xml',
|
||||
help='Path to RSI configuration file'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("RSIPI - Coordinate Frame Transformation Example")
|
||||
logging.info("=" * 60)
|
||||
logging.info(f"Config: {args.config}")
|
||||
logging.info("=" * 60)
|
||||
|
||||
coordinate_transform_example(args.config)
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("Example complete!")
|
||||
logging.info("=" * 60)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
main()
|
||||
@ -1,399 +0,0 @@
|
||||
"""
|
||||
Combined Advanced Motion Example
|
||||
|
||||
Demonstrates combining multiple Phase 4 features to create a complete,
|
||||
production-ready motion application with velocity profiling, geometric
|
||||
primitives, path blending, and coordinate transformations.
|
||||
|
||||
Application: Automated drilling and inspection pattern
|
||||
|
||||
Usage:
|
||||
python 05_combined_motion.py --config RSI_EthernetConfig.xml
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
from RSIPI import RSIAPI
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
|
||||
|
||||
def combined_motion_example(config_file: str) -> None:
|
||||
"""
|
||||
Execute a complete motion application combining all Phase 4 features.
|
||||
|
||||
Scenario: Automated drilling and inspection of a workpiece
|
||||
- Navigate to inspection position with smooth blending
|
||||
- Inspect with spiral pattern
|
||||
- Navigate to drilling position
|
||||
- Execute drilling pattern with optimized velocity
|
||||
- Return to home position
|
||||
|
||||
Args:
|
||||
config_file: Path to RSI configuration XML file
|
||||
"""
|
||||
api = RSIAPI(config_file)
|
||||
|
||||
try:
|
||||
logging.info("Starting RSI communication...")
|
||||
api.start()
|
||||
logging.info("✅ RSI started successfully")
|
||||
|
||||
# ==================================================
|
||||
# Setup: Define Work Object and Tool
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Application Setup")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Work object offset (pallet position)
|
||||
workpiece_offset = {
|
||||
"X": 500.0,
|
||||
"Y": -200.0,
|
||||
"Z": 50.0,
|
||||
"A": 0.0,
|
||||
"B": 0.0,
|
||||
"C": 15.0 # Pallet at slight angle
|
||||
}
|
||||
|
||||
# Tool offset (inspection camera + drill)
|
||||
tool_offset = {
|
||||
"X": 0.0,
|
||||
"Y": 0.0,
|
||||
"Z": 120.0, # Tool length
|
||||
"A": 0.0,
|
||||
"B": 0.0,
|
||||
"C": 0.0
|
||||
}
|
||||
|
||||
logging.info("Work object configuration:")
|
||||
logging.info(f" Position: X={workpiece_offset['X']}, Y={workpiece_offset['Y']}, Z={workpiece_offset['Z']}")
|
||||
logging.info(f" Rotation: C={workpiece_offset['C']}°")
|
||||
|
||||
logging.info(f"\nTool configuration:")
|
||||
logging.info(f" TCP offset: Z={tool_offset['Z']} mm")
|
||||
|
||||
# ==================================================
|
||||
# Step 1: Navigate to Inspection Position
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Step 1: Navigate to Inspection Position")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Define waypoints in work object frame
|
||||
home_work = {"X": 0, "Y": 0, "Z": 200} # Safe height above workpiece
|
||||
approach_work = {"X": 100, "Y": 100, "Z": 100} # Approach position
|
||||
inspect_work = {"X": 100, "Y": 100, "Z": 30} # Inspection height
|
||||
|
||||
# Transform to BASE coordinates
|
||||
home_base = api.motion.transform_coordinates(
|
||||
home_work, 'WORK', 'BASE', workpiece_offset
|
||||
)
|
||||
approach_base = api.motion.transform_coordinates(
|
||||
approach_work, 'WORK', 'BASE', workpiece_offset
|
||||
)
|
||||
inspect_base = api.motion.transform_coordinates(
|
||||
inspect_work, 'WORK', 'BASE', workpiece_offset
|
||||
)
|
||||
|
||||
logging.info("Navigation waypoints (work frame):")
|
||||
logging.info(f" Home: {home_work}")
|
||||
logging.info(f" Approach: {approach_work}")
|
||||
logging.info(f" Inspect: {inspect_work}")
|
||||
|
||||
# Generate navigation segments
|
||||
seg1 = api.motion.generate_trajectory(home_base, approach_base, steps=40)
|
||||
seg2 = api.motion.generate_trajectory(approach_base, inspect_base, steps=30)
|
||||
|
||||
# Blend for smooth motion
|
||||
navigation = api.motion.blend_trajectories(
|
||||
seg1, seg2,
|
||||
blend_radius=25.0,
|
||||
blend_steps=15
|
||||
)
|
||||
|
||||
# Apply velocity profile for fast navigation
|
||||
navigation_profiled = api.motion.generate_velocity_profile(
|
||||
navigation,
|
||||
max_velocity=300.0, # Fast navigation
|
||||
max_acceleration=800.0,
|
||||
profile='s-curve' # Smooth acceleration
|
||||
)
|
||||
|
||||
logging.info(f"\nNavigation trajectory:")
|
||||
logging.info(f" Waypoints: {len(navigation)}")
|
||||
logging.info(f" Velocity profile: S-curve (smooth)")
|
||||
logging.info(f" Max velocity: 300 mm/s")
|
||||
|
||||
logging.info("Executing navigation...")
|
||||
for waypoint, dt in navigation_profiled:
|
||||
api.motion.update_cartesian(**waypoint)
|
||||
import time
|
||||
time.sleep(dt)
|
||||
logging.info("✅ Reached inspection position")
|
||||
|
||||
# ==================================================
|
||||
# Step 2: Execute Spiral Inspection Pattern
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Step 2: Execute Spiral Inspection Pattern")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Generate spiral inspection pattern in work frame
|
||||
spiral_work = api.motion.generate_spiral(
|
||||
center={"X": 100, "Y": 100, "Z": 30},
|
||||
start_radius=5.0,
|
||||
end_radius=25.0,
|
||||
pitch=0.0, # Stay at constant Z (no vertical motion)
|
||||
revolutions=2.5,
|
||||
steps=120,
|
||||
plane='XY'
|
||||
)
|
||||
|
||||
# Transform spiral to BASE frame
|
||||
spiral_base = []
|
||||
for waypoint in spiral_work:
|
||||
transformed = api.motion.transform_coordinates(
|
||||
waypoint, 'WORK', 'BASE', workpiece_offset
|
||||
)
|
||||
spiral_base.append(transformed)
|
||||
|
||||
# Apply slower velocity for inspection
|
||||
spiral_profiled = api.motion.generate_velocity_profile(
|
||||
spiral_base,
|
||||
max_velocity=50.0, # Slow for inspection
|
||||
max_acceleration=200.0,
|
||||
profile='s-curve'
|
||||
)
|
||||
|
||||
logging.info("Inspection pattern:")
|
||||
logging.info(f" Type: Expanding spiral")
|
||||
logging.info(f" Radius: 5mm → 25mm")
|
||||
logging.info(f" Revolutions: 2.5")
|
||||
logging.info(f" Velocity: 50 mm/s (inspection speed)")
|
||||
logging.info(f" Waypoints: {len(spiral_base)}")
|
||||
|
||||
logging.info("Executing inspection spiral...")
|
||||
for waypoint, dt in spiral_profiled:
|
||||
api.motion.update_cartesian(**waypoint)
|
||||
import time
|
||||
time.sleep(dt)
|
||||
# In real application: capture camera frame here
|
||||
logging.info("✅ Inspection complete")
|
||||
|
||||
# ==================================================
|
||||
# Step 3: Navigate to Drilling Position
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Step 3: Navigate to Drilling Position")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Return to safe height
|
||||
retract_work = {"X": 100, "Y": 100, "Z": 100}
|
||||
drill_approach_work = {"X": 150, "Y": 50, "Z": 100}
|
||||
drill_start_work = {"X": 150, "Y": 50, "Z": 35}
|
||||
|
||||
retract_base = api.motion.transform_coordinates(
|
||||
retract_work, 'WORK', 'BASE', workpiece_offset
|
||||
)
|
||||
drill_approach_base = api.motion.transform_coordinates(
|
||||
drill_approach_work, 'WORK', 'BASE', workpiece_offset
|
||||
)
|
||||
drill_start_base = api.motion.transform_coordinates(
|
||||
drill_start_work, 'WORK', 'BASE', workpiece_offset
|
||||
)
|
||||
|
||||
# Navigate to drilling position with blending
|
||||
seg1 = api.motion.generate_trajectory(inspect_base, retract_base, steps=25)
|
||||
seg2 = api.motion.generate_trajectory(retract_base, drill_approach_base, steps=40)
|
||||
seg3 = api.motion.generate_trajectory(drill_approach_base, drill_start_base, steps=30)
|
||||
|
||||
# Blend all segments
|
||||
traj_temp = api.motion.blend_trajectories(seg1, seg2, blend_radius=20.0, blend_steps=12)
|
||||
drill_navigation = api.motion.blend_trajectories(traj_temp, seg3, blend_radius=20.0, blend_steps=12)
|
||||
|
||||
# Apply fast velocity profile
|
||||
drill_nav_profiled = api.motion.generate_velocity_profile(
|
||||
drill_navigation,
|
||||
max_velocity=250.0,
|
||||
max_acceleration=700.0,
|
||||
profile='trapezoidal' # Fast point-to-point
|
||||
)
|
||||
|
||||
logging.info("Navigation to drilling position:")
|
||||
logging.info(f" Waypoints: {len(drill_navigation)}")
|
||||
logging.info(f" Profile: Trapezoidal (fast)")
|
||||
|
||||
logging.info("Executing navigation to drill position...")
|
||||
for waypoint, dt in drill_nav_profiled:
|
||||
api.motion.update_cartesian(**waypoint)
|
||||
import time
|
||||
time.sleep(dt)
|
||||
logging.info("✅ Reached drilling position")
|
||||
|
||||
# ==================================================
|
||||
# Step 4: Execute Drilling Pattern
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Step 4: Execute Drilling Pattern")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Generate expanding spiral drilling pattern
|
||||
drill_spiral_work = api.motion.generate_spiral(
|
||||
center={"X": 150, "Y": 50, "Z": 35},
|
||||
start_radius=2.0,
|
||||
end_radius=15.0,
|
||||
pitch=5.0, # Descend 5mm per revolution
|
||||
revolutions=3.0,
|
||||
steps=150,
|
||||
plane='XY',
|
||||
axis='Z'
|
||||
)
|
||||
|
||||
# Transform to BASE
|
||||
drill_spiral_base = []
|
||||
for waypoint in drill_spiral_work:
|
||||
transformed = api.motion.transform_coordinates(
|
||||
waypoint, 'WORK', 'BASE', workpiece_offset
|
||||
)
|
||||
drill_spiral_base.append(transformed)
|
||||
|
||||
# Apply drilling velocity profile
|
||||
drill_profiled = api.motion.generate_velocity_profile(
|
||||
drill_spiral_base,
|
||||
max_velocity=30.0, # Slow drilling speed
|
||||
max_acceleration=100.0,
|
||||
profile='s-curve'
|
||||
)
|
||||
|
||||
logging.info("Drilling pattern:")
|
||||
logging.info(f" Type: Expanding spiral with descent")
|
||||
logging.info(f" Radius: 2mm → 15mm")
|
||||
logging.info(f" Pitch: 5mm/revolution (descending)")
|
||||
logging.info(f" Total depth: 15mm")
|
||||
logging.info(f" Velocity: 30 mm/s (drilling speed)")
|
||||
logging.info(f" Waypoints: {len(drill_spiral_base)}")
|
||||
|
||||
logging.info("Executing drilling spiral...")
|
||||
for waypoint, dt in drill_profiled:
|
||||
api.motion.update_cartesian(**waypoint)
|
||||
import time
|
||||
time.sleep(dt)
|
||||
# In real application: control spindle speed, feed rate
|
||||
logging.info("✅ Drilling complete")
|
||||
|
||||
# ==================================================
|
||||
# Step 5: Return to Home Position
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Step 5: Return to Home Position")
|
||||
logging.info("=" * 60)
|
||||
|
||||
# Retract from drilling position
|
||||
drill_end_work = {"X": 150, "Y": 50, "Z": 20} # Bottom of hole
|
||||
drill_retract_work = {"X": 150, "Y": 50, "Z": 100}
|
||||
|
||||
drill_end_base = api.motion.transform_coordinates(
|
||||
drill_end_work, 'WORK', 'BASE', workpiece_offset
|
||||
)
|
||||
drill_retract_base = api.motion.transform_coordinates(
|
||||
drill_retract_work, 'WORK', 'BASE', workpiece_offset
|
||||
)
|
||||
|
||||
# Return path with blending
|
||||
seg1 = api.motion.generate_trajectory(drill_end_base, drill_retract_base, steps=30)
|
||||
seg2 = api.motion.generate_trajectory(drill_retract_base, home_base, steps=50)
|
||||
|
||||
return_path = api.motion.blend_trajectories(seg1, seg2, blend_radius=30.0, blend_steps=15)
|
||||
|
||||
# Fast return profile
|
||||
return_profiled = api.motion.generate_velocity_profile(
|
||||
return_path,
|
||||
max_velocity=350.0, # Fast return
|
||||
max_acceleration=900.0,
|
||||
profile='trapezoidal'
|
||||
)
|
||||
|
||||
logging.info("Return to home:")
|
||||
logging.info(f" Waypoints: {len(return_path)}")
|
||||
logging.info(f" Max velocity: 350 mm/s")
|
||||
|
||||
logging.info("Executing return to home...")
|
||||
for waypoint, dt in return_profiled:
|
||||
api.motion.update_cartesian(**waypoint)
|
||||
import time
|
||||
time.sleep(dt)
|
||||
logging.info("✅ Returned to home position")
|
||||
|
||||
# ==================================================
|
||||
# Summary
|
||||
# ==================================================
|
||||
logging.info("\n" + "=" * 60)
|
||||
logging.info("Application Complete - Summary")
|
||||
logging.info("=" * 60)
|
||||
|
||||
logging.info("\nPhase 4 Features Used:")
|
||||
logging.info(" ✅ Coordinate Transformations (work object & tool)")
|
||||
logging.info(" ✅ Path Blending (smooth navigation)")
|
||||
logging.info(" ✅ Velocity Profiling (optimized speeds)")
|
||||
logging.info(" ✅ Geometric Primitives (spiral patterns)")
|
||||
|
||||
logging.info("\nMotion Segments:")
|
||||
logging.info(" 1. Navigate to inspection (blended, S-curve, 300mm/s)")
|
||||
logging.info(" 2. Spiral inspection (S-curve, 50mm/s)")
|
||||
logging.info(" 3. Navigate to drilling (blended, trapezoidal, 250mm/s)")
|
||||
logging.info(" 4. Drilling spiral (S-curve, 30mm/s)")
|
||||
logging.info(" 5. Return home (blended, trapezoidal, 350mm/s)")
|
||||
|
||||
logging.info("\nProduction Benefits:")
|
||||
logging.info(" - Optimized cycle time with velocity profiling")
|
||||
logging.info(" - Smooth motion reduces mechanical stress")
|
||||
logging.info(" - Coordinate transforms enable flexible part placement")
|
||||
logging.info(" - Geometric primitives simplify complex patterns")
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logging.warning("\n⚠️ Interrupted by user")
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"❌ Error during combined motion: {e}")
|
||||
|
||||
finally:
|
||||
logging.info("Stopping RSI communication...")
|
||||
api.stop()
|
||||
logging.info("✅ API stopped successfully")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point."""
|
||||
parser = argparse.ArgumentParser(description='Combined Advanced Motion Example')
|
||||
parser.add_argument(
|
||||
'--config',
|
||||
type=str,
|
||||
default='RSI_EthernetConfig.xml',
|
||||
help='Path to RSI configuration file'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("RSIPI - Combined Advanced Motion Example")
|
||||
logging.info("=" * 60)
|
||||
logging.info(f"Config: {args.config}")
|
||||
logging.info("=" * 60)
|
||||
logging.info("\nScenario: Automated Drilling and Inspection")
|
||||
logging.info("=" * 60)
|
||||
|
||||
combined_motion_example(args.config)
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("Example complete!")
|
||||
logging.info("=" * 60)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
main()
|
||||
@ -1,573 +0,0 @@
|
||||
# Advanced Motion Control Examples
|
||||
|
||||
This directory contains Python examples demonstrating Phase 4 advanced motion control features including velocity profiling, geometric primitives, path blending, and coordinate transformations.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- RSIPI library installed (`pip install -e .` from rsi-pi directory)
|
||||
- KUKA robot controller with RSI 3.3 configured
|
||||
- RSI_EthernetConfig.xml configured for Cartesian corrections (RKorr)
|
||||
- Basic understanding of robot motion programming
|
||||
|
||||
## Examples
|
||||
|
||||
### 01_velocity_profiles.py
|
||||
**Optimize trajectory timing with velocity profiling**
|
||||
|
||||
Demonstrates trapezoidal and S-curve velocity profiles for time-optimal, smooth motion.
|
||||
|
||||
**Run**:
|
||||
```bash
|
||||
python 01_velocity_profiles.py --config path/to/RSI_EthernetConfig.xml
|
||||
```
|
||||
|
||||
**Key Features**:
|
||||
- Trapezoidal profile: Fast point-to-point motion with constant acceleration
|
||||
- S-curve profile: Jerk-limited smooth motion for reduced mechanical stress
|
||||
- Velocity comparison at different trajectory points
|
||||
- Production-ready motion timing
|
||||
|
||||
**API Methods**:
|
||||
- `api.motion.generate_velocity_profile(trajectory, max_velocity, max_acceleration, profile)`
|
||||
|
||||
**Use Cases**:
|
||||
- High-speed pick and place (trapezoidal)
|
||||
- Delicate assembly operations (s-curve)
|
||||
- Painting/coating with constant velocity
|
||||
- Time-optimized production cycles
|
||||
|
||||
---
|
||||
|
||||
### 02_geometric_primitives.py
|
||||
**Generate complex motion patterns**
|
||||
|
||||
Demonstrates arc, circle, and spiral trajectory generation for drilling, milling, and inspection applications.
|
||||
|
||||
**Run**:
|
||||
```bash
|
||||
python 02_geometric_primitives.py --config path/to/RSI_EthernetConfig.xml
|
||||
```
|
||||
|
||||
**Key Features**:
|
||||
- Circular arcs (partial circles)
|
||||
- Full 360° circles
|
||||
- Expanding spirals (drilling pattern)
|
||||
- Contracting spirals (retraction pattern)
|
||||
- Multiple plane support (XY, XZ, YZ)
|
||||
|
||||
**API Methods**:
|
||||
- `api.motion.generate_arc(center, radius, start_angle, end_angle, steps, plane)`
|
||||
- `api.motion.generate_circle(center, radius, steps, plane)`
|
||||
- `api.motion.generate_spiral(center, start_radius, end_radius, pitch, revolutions, steps, plane, axis)`
|
||||
|
||||
**Use Cases**:
|
||||
- Drilling/milling: Expanding spirals for hole boring
|
||||
- Assembly: Circular insertion paths with clearance
|
||||
- Inspection: Scanning circular features
|
||||
- Welding: Curved seam following
|
||||
|
||||
---
|
||||
|
||||
### 03_path_blending.py
|
||||
**Smooth trajectory transitions**
|
||||
|
||||
Demonstrates cubic interpolation blending to eliminate stop-and-go motion at trajectory boundaries.
|
||||
|
||||
**Run**:
|
||||
```bash
|
||||
python 03_path_blending.py --config path/to/RSI_EthernetConfig.xml
|
||||
```
|
||||
|
||||
**Key Features**:
|
||||
- Sharp corners vs blended corners comparison
|
||||
- Multiple blend zones in continuous paths
|
||||
- Configurable blend radius
|
||||
- Orientation blending for smooth rotation transitions
|
||||
|
||||
**API Methods**:
|
||||
- `api.motion.blend_trajectories(traj1, traj2, blend_radius, blend_steps)`
|
||||
|
||||
**Use Cases**:
|
||||
- Welding/gluing: Continuous bead without stop marks
|
||||
- Pick and place: Reduced cycle time by eliminating stops
|
||||
- Machining: Smooth tool paths without witness marks
|
||||
- Painting: Even coating thickness at corners
|
||||
|
||||
---
|
||||
|
||||
### 04_coordinate_transforms.py
|
||||
**Transform between coordinate frames**
|
||||
|
||||
Demonstrates position and trajectory transformations between BASE, TOOL, WORLD, and WORK coordinate systems.
|
||||
|
||||
**Run**:
|
||||
```bash
|
||||
python 04_coordinate_transforms.py --config path/to/RSI_EthernetConfig.xml
|
||||
```
|
||||
|
||||
**Key Features**:
|
||||
- BASE to WORLD transformations
|
||||
- TOOL frame offsets (TCP calibration)
|
||||
- Work object (pallet) transformations
|
||||
- Sensor-guided motion with frame corrections
|
||||
- Transforming entire trajectories
|
||||
|
||||
**API Methods**:
|
||||
- `api.motion.transform_coordinates(pose, from_frame, to_frame, frame_offset)`
|
||||
|
||||
**Use Cases**:
|
||||
- Multiple work objects: Define once, execute anywhere
|
||||
- Tool changes: Adapt taught positions for different tools
|
||||
- Vision integration: Apply sensor corrections to taught paths
|
||||
- Multi-robot cells: Coordinate motion in shared workspace
|
||||
|
||||
---
|
||||
|
||||
### 05_combined_motion.py
|
||||
**Complete production application**
|
||||
|
||||
Demonstrates combining all Phase 4 features in a realistic automated drilling and inspection scenario.
|
||||
|
||||
**Run**:
|
||||
```bash
|
||||
python 05_combined_motion.py --config path/to/RSI_EthernetConfig.xml
|
||||
```
|
||||
|
||||
**Application Flow**:
|
||||
1. Navigate to inspection position (blended path, S-curve, 300mm/s)
|
||||
2. Execute spiral inspection pattern (S-curve, 50mm/s)
|
||||
3. Navigate to drilling position (blended path, trapezoidal, 250mm/s)
|
||||
4. Execute expanding spiral drilling (S-curve, 30mm/s, descending)
|
||||
5. Return to home (blended path, trapezoidal, 350mm/s)
|
||||
|
||||
**Features Demonstrated**:
|
||||
- ✅ Coordinate transformations (work object & tool offsets)
|
||||
- ✅ Path blending (smooth navigation)
|
||||
- ✅ Velocity profiling (optimized speeds per operation)
|
||||
- ✅ Geometric primitives (spiral patterns)
|
||||
|
||||
**Production Benefits**:
|
||||
- Optimized cycle time with velocity profiling
|
||||
- Smooth motion reduces mechanical stress
|
||||
- Coordinate transforms enable flexible part placement
|
||||
- Geometric primitives simplify complex patterns
|
||||
|
||||
---
|
||||
|
||||
## Configuration Requirements
|
||||
|
||||
### RSI XML Configuration
|
||||
|
||||
Your `RSI_EthernetConfig.xml` must support Cartesian corrections:
|
||||
|
||||
**Cartesian Corrections (RKorr):**
|
||||
```xml
|
||||
<RECEIVE>
|
||||
<XML>
|
||||
<ELEMENT Tag=\"RKorr\" Type=\"DOUBLE\" Indizes=\"[1..6]\"/>
|
||||
</XML>
|
||||
</RECEIVE>
|
||||
```
|
||||
|
||||
### Network Settings
|
||||
|
||||
Ensure your RSI network settings match:
|
||||
```xml
|
||||
<IP_NUMBER>192.168.1.100</IP_NUMBER> <!-- Your PC IP -->
|
||||
<PORT>49152</PORT>
|
||||
<SENTYPE>ImFree</SENTYPE>
|
||||
```
|
||||
|
||||
## Running Examples
|
||||
|
||||
### Step 1: Verify RSI Configuration
|
||||
|
||||
```bash
|
||||
# Check that your RSI_EthernetConfig.xml has required elements
|
||||
grep -A 5 "RKorr" RSI_EthernetConfig.xml
|
||||
```
|
||||
|
||||
### Step 2: Run Example
|
||||
|
||||
```bash
|
||||
cd examples/advanced_motion
|
||||
python 01_velocity_profiles.py --config ../../RSI_EthernetConfig.xml
|
||||
```
|
||||
|
||||
### Step 3: Monitor Output
|
||||
|
||||
Examples log comprehensive information:
|
||||
- Trajectory generation details
|
||||
- Velocity profile characteristics
|
||||
- Motion execution progress
|
||||
- Application use cases
|
||||
|
||||
**Example Output**:
|
||||
```
|
||||
2026-01-17 14:32:01 - INFO - Starting RSI communication...
|
||||
2026-01-17 14:32:01 - INFO - ✅ RSI started successfully
|
||||
2026-01-17 14:32:01 - INFO - Generating trajectory with 100 waypoints...
|
||||
2026-01-17 14:32:01 - INFO - Applying trapezoidal velocity profile
|
||||
2026-01-17 14:32:01 - INFO - Max velocity: 200.0 mm/s
|
||||
2026-01-17 14:32:01 - INFO - Executing profiled trajectory...
|
||||
2026-01-17 14:32:05 - INFO - ✅ Motion complete
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### Velocity Profiling
|
||||
|
||||
```python
|
||||
# Generate trajectory with timing information
|
||||
profiled_trajectory = api.motion.generate_velocity_profile(
|
||||
trajectory=waypoints,
|
||||
max_velocity=200.0, # mm/s
|
||||
max_acceleration=500.0, # mm/s²
|
||||
profile='trapezoidal' # or 's-curve'
|
||||
)
|
||||
|
||||
# Execute with precise timing
|
||||
for waypoint, dt in profiled_trajectory:
|
||||
api.motion.update_cartesian(**waypoint)
|
||||
time.sleep(dt)
|
||||
```
|
||||
|
||||
**Profiles**:
|
||||
- `'trapezoidal'`: Bang-bang acceleration, constant velocity cruise, fast point-to-point
|
||||
- `'s-curve'`: Jerk-limited smooth acceleration, reduced vibration and stress
|
||||
|
||||
### Geometric Primitives
|
||||
|
||||
```python
|
||||
# Circular arc
|
||||
arc = api.motion.generate_arc(
|
||||
center={"X": 100, "Y": 0, "Z": 500},
|
||||
radius=50.0,
|
||||
start_angle=0, # degrees
|
||||
end_angle=90, # degrees
|
||||
steps=50,
|
||||
plane='XY' # or 'XZ', 'YZ'
|
||||
)
|
||||
|
||||
# Full circle
|
||||
circle = api.motion.generate_circle(
|
||||
center={"X": 100, "Y": 0, "Z": 500},
|
||||
radius=30.0,
|
||||
steps=100,
|
||||
plane='XY'
|
||||
)
|
||||
|
||||
# Spiral (expanding or contracting)
|
||||
spiral = api.motion.generate_spiral(
|
||||
center={"X": 100, "Y": 0, "Z": 500},
|
||||
start_radius=5.0,
|
||||
end_radius=40.0,
|
||||
pitch=10.0, # mm per revolution (positive=descending)
|
||||
revolutions=3.0,
|
||||
steps=150,
|
||||
plane='XY',
|
||||
axis='Z'
|
||||
)
|
||||
```
|
||||
|
||||
### Path Blending
|
||||
|
||||
```python
|
||||
# Generate two trajectories
|
||||
traj1 = api.motion.generate_trajectory(p0, p1, steps=50)
|
||||
traj2 = api.motion.generate_trajectory(p1, p2, steps=50)
|
||||
|
||||
# Blend for smooth transition
|
||||
blended = api.motion.blend_trajectories(
|
||||
traj1=traj1,
|
||||
traj2=traj2,
|
||||
blend_radius=20.0, # Start blending 20mm before corner
|
||||
blend_steps=20 # Number of interpolation points
|
||||
)
|
||||
|
||||
# Execute smooth continuous motion
|
||||
api.motion.execute_trajectory(blended, space='cartesian', rate=0.02)
|
||||
```
|
||||
|
||||
### Coordinate Transformations
|
||||
|
||||
```python
|
||||
# Define frame offset
|
||||
work_offset = {
|
||||
"X": 500.0,
|
||||
"Y": -200.0,
|
||||
"Z": 50.0,
|
||||
"A": 0.0,
|
||||
"B": 0.0,
|
||||
"C": 15.0
|
||||
}
|
||||
|
||||
# Transform single pose
|
||||
pose_work = {"X": 100, "Y": 50, "Z": 30}
|
||||
pose_base = api.motion.transform_coordinates(
|
||||
pose=pose_work,
|
||||
from_frame='WORK',
|
||||
to_frame='BASE',
|
||||
frame_offset=work_offset
|
||||
)
|
||||
|
||||
# Transform entire trajectory
|
||||
trajectory_base = []
|
||||
for waypoint in trajectory_work:
|
||||
transformed = api.motion.transform_coordinates(
|
||||
waypoint, 'WORK', 'BASE', work_offset
|
||||
)
|
||||
trajectory_base.append(transformed)
|
||||
```
|
||||
|
||||
**Supported Frames**:
|
||||
- `'BASE'`: Robot base coordinate system
|
||||
- `'WORLD'`: Global world coordinates
|
||||
- `'TOOL'`: Tool center point (TCP) coordinates
|
||||
- `'WORK'`: Work object (pallet/fixture) coordinates
|
||||
- `'ROBROOT'`: Robot root system
|
||||
|
||||
## Customizing Examples
|
||||
|
||||
### Adjust Velocity Limits
|
||||
|
||||
```python
|
||||
# Faster motion (use with caution)
|
||||
profiled = api.motion.generate_velocity_profile(
|
||||
trajectory,
|
||||
max_velocity=500.0, # Increase speed
|
||||
max_acceleration=1200.0, # Increase acceleration
|
||||
profile='trapezoidal'
|
||||
)
|
||||
|
||||
# Slower, more precise motion
|
||||
profiled = api.motion.generate_velocity_profile(
|
||||
trajectory,
|
||||
max_velocity=50.0, # Reduce speed
|
||||
max_acceleration=150.0, # Gentle acceleration
|
||||
profile='s-curve'
|
||||
)
|
||||
```
|
||||
|
||||
### Modify Geometric Patterns
|
||||
|
||||
```python
|
||||
# Larger spiral for bigger holes
|
||||
spiral = api.motion.generate_spiral(
|
||||
center={"X": 100, "Y": 0, "Z": 500},
|
||||
start_radius=10.0, # Larger start
|
||||
end_radius=80.0, # Larger end
|
||||
pitch=15.0, # Deeper per revolution
|
||||
revolutions=5.0, # More turns
|
||||
steps=250, # More waypoints for smoothness
|
||||
plane='XY',
|
||||
axis='Z'
|
||||
)
|
||||
|
||||
# Vertical circle (XZ plane)
|
||||
circle_vertical = api.motion.generate_circle(
|
||||
center={"X": 100, "Y": 0, "Z": 500},
|
||||
radius=40.0,
|
||||
steps=100,
|
||||
plane='XZ' # Vertical circle
|
||||
)
|
||||
```
|
||||
|
||||
### Adjust Blend Radius
|
||||
|
||||
```python
|
||||
# Tighter blend (closer to sharp corner)
|
||||
blended_tight = api.motion.blend_trajectories(
|
||||
traj1, traj2,
|
||||
blend_radius=5.0, # Small radius
|
||||
blend_steps=10
|
||||
)
|
||||
|
||||
# Wide blend (very smooth, cuts corner more)
|
||||
blended_wide = api.motion.blend_trajectories(
|
||||
traj1, traj2,
|
||||
blend_radius=50.0, # Large radius
|
||||
blend_steps=30
|
||||
)
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "RSI Communication Error"
|
||||
|
||||
**Problem**: Cannot establish RSI connection
|
||||
|
||||
**Solutions**:
|
||||
1. Verify robot controller is powered on and in correct mode
|
||||
2. Check network connectivity (ping robot IP)
|
||||
3. Verify RSI XML configuration file path
|
||||
4. Ensure RSI is enabled on robot controller
|
||||
5. Check firewall allows UDP port 49152
|
||||
|
||||
### Motion Limits Exceeded
|
||||
|
||||
**Problem**: Trajectory exceeds robot workspace or velocity limits
|
||||
|
||||
**Solutions**:
|
||||
1. Reduce `max_velocity` parameter in velocity profiling
|
||||
2. Reduce `max_acceleration` parameter
|
||||
3. Check trajectory waypoints are within robot workspace
|
||||
4. Verify coordinate transformations are correct
|
||||
5. Add safety margin to trajectory boundaries
|
||||
|
||||
### Jerky Motion Despite S-Curve Profile
|
||||
|
||||
**Problem**: Motion not smooth even with S-curve velocity profile
|
||||
|
||||
**Solutions**:
|
||||
1. Increase number of waypoints (`steps` parameter)
|
||||
2. Reduce `max_acceleration` for gentler motion
|
||||
3. Check RSI communication rate (should be ~250Hz)
|
||||
4. Verify no network latency issues
|
||||
5. Ensure trajectory waypoints are well-distributed
|
||||
|
||||
### Blend Zone Too Large
|
||||
|
||||
**Problem**: Blending cuts corners too much or exceeds trajectory bounds
|
||||
|
||||
**Solutions**:
|
||||
1. Reduce `blend_radius` parameter
|
||||
2. Increase trajectory length before attempting blend
|
||||
3. Check that blend_radius < half of shortest trajectory segment
|
||||
4. Use smaller `blend_steps` for tighter control
|
||||
5. Consider using multiple smaller blend zones
|
||||
|
||||
### Coordinate Transform Incorrect
|
||||
|
||||
**Problem**: Transformed positions don't match expected values
|
||||
|
||||
**Solutions**:
|
||||
1. Verify `frame_offset` values are correct
|
||||
2. Check from_frame and to_frame parameters are correct
|
||||
3. Ensure frame offset includes both position and orientation
|
||||
4. Test with simple known transforms first
|
||||
5. Visualize transformed trajectory before execution
|
||||
|
||||
### Velocity Profile Not Applied
|
||||
|
||||
**Problem**: Robot doesn't follow calculated velocity profile
|
||||
|
||||
**Solutions**:
|
||||
1. Verify you're using the timing (`dt`) from profiled trajectory
|
||||
2. Check `time.sleep(dt)` is actually being called
|
||||
3. Ensure system has sufficient timing resolution
|
||||
4. Monitor actual execution timing with logs
|
||||
5. Consider system overhead in timing calculations
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### Combining Multiple Features
|
||||
|
||||
```python
|
||||
# 1. Generate geometric primitive
|
||||
spiral = api.motion.generate_spiral(...)
|
||||
|
||||
# 2. Transform to correct frame
|
||||
spiral_base = [
|
||||
api.motion.transform_coordinates(wp, 'WORK', 'BASE', offset)
|
||||
for wp in spiral
|
||||
]
|
||||
|
||||
# 3. Apply velocity profile
|
||||
spiral_profiled = api.motion.generate_velocity_profile(
|
||||
spiral_base,
|
||||
max_velocity=100.0,
|
||||
max_acceleration=300.0,
|
||||
profile='s-curve'
|
||||
)
|
||||
|
||||
# 4. Execute with precise timing
|
||||
for waypoint, dt in spiral_profiled:
|
||||
api.motion.update_cartesian(**waypoint)
|
||||
time.sleep(dt)
|
||||
```
|
||||
|
||||
### Dynamic Trajectory Modification
|
||||
|
||||
```python
|
||||
# Start with base trajectory
|
||||
trajectory = api.motion.generate_circle(...)
|
||||
|
||||
# Apply sensor correction at runtime
|
||||
for waypoint in trajectory:
|
||||
sensor_offset = get_sensor_reading()
|
||||
corrected = api.motion.transform_coordinates(
|
||||
waypoint,
|
||||
'BASE', 'BASE',
|
||||
frame_offset=sensor_offset
|
||||
)
|
||||
api.motion.update_cartesian(**corrected)
|
||||
```
|
||||
|
||||
### Multi-Layer Patterns
|
||||
|
||||
```python
|
||||
# Generate pattern at multiple Z heights
|
||||
layers = []
|
||||
for z in range(0, 50, 10): # Every 10mm
|
||||
circle = api.motion.generate_circle(
|
||||
center={"X": 100, "Y": 0, "Z": z},
|
||||
radius=30.0,
|
||||
steps=50,
|
||||
plane='XY'
|
||||
)
|
||||
layers.extend(circle)
|
||||
|
||||
# Blend between layers
|
||||
for i in range(len(layers) - 1):
|
||||
segment = [layers[i], layers[i+1]]
|
||||
# Execute segment...
|
||||
```
|
||||
|
||||
## Performance Optimization
|
||||
|
||||
### Trajectory Generation
|
||||
|
||||
- Use appropriate `steps` parameter: More steps = smoother but slower generation
|
||||
- Generate complex patterns once, reuse multiple times
|
||||
- Consider pre-generating common patterns at startup
|
||||
|
||||
### Velocity Profiling
|
||||
|
||||
- Trapezoidal profile is faster to compute than S-curve
|
||||
- Use S-curve only where smoothness is critical
|
||||
- Cache profiled trajectories for repeated operations
|
||||
|
||||
### Coordinate Transformations
|
||||
|
||||
- Transform entire trajectory once, not waypoint-by-waypoint in real-time
|
||||
- Pre-calculate frame offsets before motion execution
|
||||
- Use simple translational offsets when possible (faster than full 6-DOF)
|
||||
|
||||
### Path Blending
|
||||
|
||||
- Larger `blend_steps` = smoother but slower generation
|
||||
- Balance blend_radius vs trajectory accuracy requirements
|
||||
- Consider blending offline for repeated paths
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. **Run basic examples** (01, 02) to understand individual features
|
||||
2. **Experiment with parameters** to see their effects
|
||||
3. **Combine features** using example 05 as a template
|
||||
4. **Adapt to your application** specific requirements
|
||||
5. **Integrate with sensors** for adaptive motion control
|
||||
|
||||
## References
|
||||
|
||||
- [RSIPI API Documentation](../../README.md)
|
||||
- [Phase 4 Implementation Summary](../../PHASE_4_SUMMARY.md) (when available)
|
||||
- [Basic Motion Examples](../basic_motion/)
|
||||
- [Coordination Examples](../coordination/)
|
||||
- [KUKA RSI 3.3 Manual](https://www.kuka.com)
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: January 17, 2026
|
||||
**RSIPI Version**: 2.0.0
|
||||
**Phase**: 4 (Advanced Motion Control)
|
||||
@ -1,115 +0,0 @@
|
||||
"""
|
||||
Basic I/O Handshake Example
|
||||
|
||||
Demonstrates simple bidirectional signaling between Python and KRL using
|
||||
digital I/O channels. Works with templates/krl/basic_handshake.src
|
||||
|
||||
Flow:
|
||||
1. KRL signals "ready" on output 1
|
||||
2. Python waits for signal
|
||||
3. Python performs processing
|
||||
4. Python signals "complete" on input 1
|
||||
5. KRL continues
|
||||
|
||||
Usage:
|
||||
python 01_basic_handshake.py --config RSI_EthernetConfig.xml
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import time
|
||||
import logging
|
||||
from RSIPI import RSIAPI
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
|
||||
|
||||
def basic_handshake_example(config_file: str) -> None:
|
||||
"""
|
||||
Execute basic I/O handshake with KRL program.
|
||||
|
||||
Args:
|
||||
config_file: Path to RSI configuration XML file
|
||||
"""
|
||||
# Initialize API
|
||||
api = RSIAPI(config_file)
|
||||
|
||||
try:
|
||||
# Start RSI communication
|
||||
logging.info("Starting RSI communication...")
|
||||
api.start()
|
||||
logging.info("✅ RSI started successfully")
|
||||
|
||||
# Wait for KRL to signal ready (digital output 1)
|
||||
logging.info("Waiting for KRL ready signal...")
|
||||
|
||||
if api.krl.wait_for_signal(1, timeout=30.0):
|
||||
logging.info("✅ KRL signaled ready!")
|
||||
|
||||
# Simulate Python processing (e.g., data analysis, sensor reading)
|
||||
logging.info("Performing Python-side processing...")
|
||||
time.sleep(2.0) # Simulated processing time
|
||||
|
||||
# Optional: Do actual work here
|
||||
# process_sensor_data()
|
||||
# calculate_corrections()
|
||||
# update_database()
|
||||
|
||||
logging.info("✅ Processing complete")
|
||||
|
||||
# Signal completion back to KRL (digital input 1)
|
||||
api.krl.signal_complete(1)
|
||||
logging.info("✅ Signaled KRL to continue")
|
||||
|
||||
# KRL will now proceed with its motion program
|
||||
logging.info("KRL is now free to continue motion")
|
||||
|
||||
else:
|
||||
logging.error("❌ Timeout waiting for KRL ready signal")
|
||||
logging.error("Check that KRL program is running and I/O is configured correctly")
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logging.warning("\n⚠️ Interrupted by user")
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"❌ Error during handshake: {e}")
|
||||
|
||||
finally:
|
||||
# Clean shutdown
|
||||
logging.info("Stopping RSI communication...")
|
||||
api.stop()
|
||||
logging.info("✅ API stopped successfully")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point."""
|
||||
parser = argparse.ArgumentParser(description='Basic I/O Handshake Example')
|
||||
parser.add_argument(
|
||||
'--config',
|
||||
type=str,
|
||||
default='RSI_EthernetConfig.xml',
|
||||
help='Path to RSI configuration file'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("RSIPI - Basic I/O Handshake Example")
|
||||
logging.info("=" * 60)
|
||||
logging.info(f"Config: {args.config}")
|
||||
logging.info("=" * 60)
|
||||
|
||||
basic_handshake_example(args.config)
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("Example complete!")
|
||||
logging.info("=" * 60)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
main()
|
||||
@ -1,135 +0,0 @@
|
||||
"""
|
||||
Parameter Passing Example
|
||||
|
||||
Demonstrates bidirectional numerical data exchange between Python and KRL
|
||||
using RSI Tech variables. Works with templates/krl/parameter_passing.src
|
||||
|
||||
Flow:
|
||||
1. KRL writes current position to Tech.T11-T16
|
||||
2. Python waits for data ready signal
|
||||
3. Python reads position from Tech.T
|
||||
4. Python calculates target and writes to Tech.C11-C13
|
||||
5. Python signals completion
|
||||
6. KRL reads target from Tech.C and executes motion
|
||||
|
||||
Usage:
|
||||
python 02_parameter_passing.py --config RSI_EthernetConfig.xml
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
from RSIPI import RSIAPI
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
|
||||
|
||||
def parameter_passing_example(config_file: str) -> None:
|
||||
"""
|
||||
Execute parameter passing coordination with KRL program.
|
||||
|
||||
Reads current position from KRL, calculates target position,
|
||||
and sends target back to KRL for execution.
|
||||
|
||||
Args:
|
||||
config_file: Path to RSI configuration XML file
|
||||
"""
|
||||
api = RSIAPI(config_file)
|
||||
|
||||
try:
|
||||
logging.info("Starting RSI communication...")
|
||||
api.start()
|
||||
logging.info("✅ RSI started successfully")
|
||||
|
||||
# Wait for KRL to signal that data is ready
|
||||
logging.info("Waiting for KRL data ready signal...")
|
||||
|
||||
if api.krl.wait_for_signal(1, timeout=30.0):
|
||||
logging.info("✅ KRL signaled data ready!")
|
||||
|
||||
# Read current position from Tech.T variables
|
||||
logging.info("Reading current position from KRL...")
|
||||
current_x = api.krl.read_param('T11')
|
||||
current_y = api.krl.read_param('T12')
|
||||
current_z = api.krl.read_param('T13')
|
||||
current_a = api.krl.read_param('T14')
|
||||
current_b = api.krl.read_param('T15')
|
||||
current_c = api.krl.read_param('T16')
|
||||
|
||||
logging.info(f"Current position:")
|
||||
logging.info(f" X: {current_x:.2f} mm")
|
||||
logging.info(f" Y: {current_y:.2f} mm")
|
||||
logging.info(f" Z: {current_z:.2f} mm")
|
||||
logging.info(f" A: {current_a:.2f}°, B: {current_b:.2f}°, C: {current_c:.2f}°")
|
||||
|
||||
# Calculate target position (example: move 100mm in X, 50mm in Y)
|
||||
logging.info("Calculating target position...")
|
||||
target_x = current_x + 100.0 # Move 100mm in X
|
||||
target_y = current_y + 50.0 # Move 50mm in Y
|
||||
target_z = current_z + 0.0 # Keep Z constant
|
||||
|
||||
logging.info(f"Calculated target:")
|
||||
logging.info(f" X: {target_x:.2f} mm (+100mm)")
|
||||
logging.info(f" Y: {target_y:.2f} mm (+50mm)")
|
||||
logging.info(f" Z: {target_z:.2f} mm (no change)")
|
||||
|
||||
# Write target position to Tech.C variables for KRL to read
|
||||
logging.info("Writing target position to KRL...")
|
||||
api.krl.write_param('C11', target_x)
|
||||
api.krl.write_param('C12', target_y)
|
||||
api.krl.write_param('C13', target_z)
|
||||
logging.info("✅ Target position written to Tech.C")
|
||||
|
||||
# Signal KRL that calculation is complete
|
||||
api.krl.signal_complete(1)
|
||||
logging.info("✅ Signaled KRL that target is ready")
|
||||
|
||||
# KRL will now read target and execute motion
|
||||
logging.info("KRL will now execute motion to calculated target")
|
||||
|
||||
else:
|
||||
logging.error("❌ Timeout waiting for KRL data ready signal")
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logging.warning("\n⚠️ Interrupted by user")
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"❌ Error during parameter passing: {e}")
|
||||
|
||||
finally:
|
||||
logging.info("Stopping RSI communication...")
|
||||
api.stop()
|
||||
logging.info("✅ API stopped successfully")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point."""
|
||||
parser = argparse.ArgumentParser(description='Parameter Passing Example')
|
||||
parser.add_argument(
|
||||
'--config',
|
||||
type=str,
|
||||
default='RSI_EthernetConfig.xml',
|
||||
help='Path to RSI configuration file'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("RSIPI - Parameter Passing Example")
|
||||
logging.info("=" * 60)
|
||||
logging.info(f"Config: {args.config}")
|
||||
logging.info("=" * 60)
|
||||
|
||||
parameter_passing_example(args.config)
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("Example complete!")
|
||||
logging.info("=" * 60)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
main()
|
||||
@ -1,210 +0,0 @@
|
||||
"""
|
||||
State Machine Coordination Example
|
||||
|
||||
Demonstrates a multi-state coordination workflow between Python and KRL.
|
||||
Works with templates/krl/state_machine.src
|
||||
|
||||
States:
|
||||
0: IDLE - Waiting to start
|
||||
1: CALIBRATING - Python performing calibration
|
||||
2: READY - Calibration complete, ready for motion
|
||||
3: EXECUTING - Robot executing motion task
|
||||
4: COMPLETE - Task finished
|
||||
9: ERROR - Error condition
|
||||
|
||||
Usage:
|
||||
python 03_state_machine.py --config RSI_EthernetConfig.xml
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import time
|
||||
import logging
|
||||
from enum import IntEnum
|
||||
from RSIPI import RSIAPI
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
|
||||
|
||||
class State(IntEnum):
|
||||
"""State machine states matching KRL program."""
|
||||
IDLE = 0
|
||||
CALIBRATING = 1
|
||||
READY = 2
|
||||
EXECUTING = 3
|
||||
COMPLETE = 4
|
||||
ERROR = 9
|
||||
|
||||
|
||||
def perform_calibration() -> tuple[float, float, float]:
|
||||
"""
|
||||
Perform calibration routine.
|
||||
|
||||
In a real application, this would:
|
||||
- Read sensor data
|
||||
- Analyze calibration target
|
||||
- Calculate position offsets
|
||||
- Validate results
|
||||
|
||||
Returns:
|
||||
Tuple of (offset_x, offset_y, offset_z) in mm
|
||||
"""
|
||||
logging.info("Performing calibration routine...")
|
||||
|
||||
# Simulate calibration processing
|
||||
time.sleep(2.0)
|
||||
|
||||
# Example calibration results (in real app, calculated from sensors)
|
||||
offset_x = 5.0
|
||||
offset_y = -2.0
|
||||
offset_z = 0.5
|
||||
|
||||
logging.info(f"Calibration complete:")
|
||||
logging.info(f" Offset X: {offset_x:+.2f} mm")
|
||||
logging.info(f" Offset Y: {offset_y:+.2f} mm")
|
||||
logging.info(f" Offset Z: {offset_z:+.2f} mm")
|
||||
|
||||
return (offset_x, offset_y, offset_z)
|
||||
|
||||
|
||||
def state_machine_example(config_file: str) -> None:
|
||||
"""
|
||||
Execute state machine coordination with KRL program.
|
||||
|
||||
Monitors KRL state transitions and responds appropriately
|
||||
to each state change.
|
||||
|
||||
Args:
|
||||
config_file: Path to RSI configuration XML file
|
||||
"""
|
||||
api = RSIAPI(config_file)
|
||||
|
||||
try:
|
||||
logging.info("Starting RSI communication...")
|
||||
api.start()
|
||||
logging.info("✅ RSI started successfully")
|
||||
|
||||
# Main state monitoring loop
|
||||
logging.info("Monitoring state machine...")
|
||||
last_state = None
|
||||
calibration_offsets = (0.0, 0.0, 0.0)
|
||||
|
||||
while True:
|
||||
# Read current state from KRL
|
||||
current_state = int(api.krl.read_param('T11'))
|
||||
|
||||
# Only log state changes
|
||||
if current_state != last_state:
|
||||
logging.info(f"State changed: {State(last_state or 0).name} → {State(current_state).name}")
|
||||
last_state = current_state
|
||||
|
||||
# Handle each state
|
||||
if current_state == State.IDLE:
|
||||
# Waiting for KRL to start
|
||||
logging.debug("Waiting in IDLE state...")
|
||||
time.sleep(0.5)
|
||||
|
||||
elif current_state == State.CALIBRATING:
|
||||
logging.info("✅ State: CALIBRATING - Starting calibration")
|
||||
|
||||
# Perform calibration
|
||||
calibration_offsets = perform_calibration()
|
||||
|
||||
# Write calibration results to Tech.C for KRL
|
||||
logging.info("Writing calibration offsets to KRL...")
|
||||
api.krl.write_param('C12', calibration_offsets[0]) # X offset
|
||||
api.krl.write_param('C13', calibration_offsets[1]) # Y offset
|
||||
api.krl.write_param('C14', calibration_offsets[2]) # Z offset
|
||||
|
||||
# Signal calibration complete
|
||||
api.krl.signal_complete(1)
|
||||
logging.info("✅ Calibration complete, signaled KRL")
|
||||
|
||||
elif current_state == State.READY:
|
||||
logging.info("✅ State: READY - System ready for motion")
|
||||
# KRL is ready to execute, no action needed from Python
|
||||
time.sleep(0.1)
|
||||
|
||||
elif current_state == State.EXECUTING:
|
||||
logging.info("✅ State: EXECUTING - Robot in motion")
|
||||
|
||||
# Monitor execution (could send real-time corrections here)
|
||||
# Example: Send RSI corrections based on sensor feedback
|
||||
# api.motion.update_cartesian(X=calibration_offsets[0])
|
||||
|
||||
# For this example, just monitor
|
||||
time.sleep(0.1)
|
||||
|
||||
elif current_state == State.COMPLETE:
|
||||
logging.info("✅ State: COMPLETE - Task finished successfully!")
|
||||
logging.info("State machine workflow complete")
|
||||
break # Exit loop, task is done
|
||||
|
||||
elif current_state == State.ERROR:
|
||||
logging.error("❌ State: ERROR - Error detected in KRL program!")
|
||||
logging.error("Aborting state machine workflow")
|
||||
break # Exit loop, error occurred
|
||||
|
||||
else:
|
||||
logging.warning(f"⚠️ Unknown state: {current_state}")
|
||||
time.sleep(0.1)
|
||||
|
||||
# Prevent tight loop
|
||||
time.sleep(0.05) # Check state every 50ms
|
||||
|
||||
logging.info("State machine monitoring ended")
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logging.warning("\n⚠️ Interrupted by user")
|
||||
# Signal error to KRL
|
||||
try:
|
||||
api.io.set_output(2, True) # Error signal
|
||||
logging.info("Signaled error to KRL")
|
||||
except:
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"❌ Error during state machine: {e}")
|
||||
# Signal error to KRL
|
||||
try:
|
||||
api.io.set_output(2, True)
|
||||
except:
|
||||
pass
|
||||
|
||||
finally:
|
||||
logging.info("Stopping RSI communication...")
|
||||
api.stop()
|
||||
logging.info("✅ API stopped successfully")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point."""
|
||||
parser = argparse.ArgumentParser(description='State Machine Coordination Example')
|
||||
parser.add_argument(
|
||||
'--config',
|
||||
type=str,
|
||||
default='RSI_EthernetConfig.xml',
|
||||
help='Path to RSI configuration file'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("RSIPI - State Machine Coordination Example")
|
||||
logging.info("=" * 60)
|
||||
logging.info(f"Config: {args.config}")
|
||||
logging.info("=" * 60)
|
||||
|
||||
state_machine_example(args.config)
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("Example complete!")
|
||||
logging.info("=" * 60)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
main()
|
||||
@ -1,345 +0,0 @@
|
||||
# Python-KRL Coordination Examples
|
||||
|
||||
This directory contains Python examples demonstrating Python-KRL coordination patterns using RSIPI Phase 3 features.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- RSIPI library installed (`pip install -e .` from rsi-pi directory)
|
||||
- KUKA robot controller with RSI 3.3 configured
|
||||
- RSI_EthernetConfig.xml configured with required I/O and Tech variables
|
||||
- Corresponding KRL programs uploaded to robot controller (see `templates/krl/`)
|
||||
|
||||
## Examples
|
||||
|
||||
### 01_basic_handshake.py
|
||||
**Simple I/O handshaking**
|
||||
|
||||
Demonstrates basic bidirectional signaling using digital I/O channels.
|
||||
|
||||
**Requires**: `templates/krl/basic_handshake.src` running on robot
|
||||
|
||||
**Run**:
|
||||
```bash
|
||||
python 01_basic_handshake.py --config path/to/RSI_EthernetConfig.xml
|
||||
```
|
||||
|
||||
**Flow**:
|
||||
1. Start Python script
|
||||
2. Execute KRL program on teach pendant
|
||||
3. Python waits for KRL ready signal
|
||||
4. Python performs processing
|
||||
5. Python signals completion
|
||||
6. KRL continues with motion
|
||||
|
||||
**API Features Demonstrated**:
|
||||
- `api.krl.wait_for_signal(channel, timeout)`
|
||||
- `api.krl.signal_complete(channel)`
|
||||
|
||||
---
|
||||
|
||||
### 02_parameter_passing.py
|
||||
**Bidirectional parameter exchange**
|
||||
|
||||
Demonstrates numerical data exchange using RSI Tech variables.
|
||||
|
||||
**Requires**: `templates/krl/parameter_passing.src` running on robot
|
||||
|
||||
**Run**:
|
||||
```bash
|
||||
python 02_parameter_passing.py --config path/to/RSI_EthernetConfig.xml
|
||||
```
|
||||
|
||||
**Flow**:
|
||||
1. KRL writes current position to Tech.T variables
|
||||
2. Python reads position data
|
||||
3. Python calculates target position
|
||||
4. Python writes target to Tech.C variables
|
||||
5. Python signals completion
|
||||
6. KRL reads target and executes motion
|
||||
|
||||
**API Features Demonstrated**:
|
||||
- `api.krl.read_param(slot)` - Read Tech.T variables
|
||||
- `api.krl.write_param(slot, value)` - Write Tech.C variables
|
||||
- `api.krl.wait_for_signal(channel, timeout)`
|
||||
- `api.krl.signal_complete(channel)`
|
||||
|
||||
---
|
||||
|
||||
### 03_state_machine.py
|
||||
**Multi-state workflow coordination**
|
||||
|
||||
Demonstrates complex state machine with error handling and calibration.
|
||||
|
||||
**Requires**: `templates/krl/state_machine.src` running on robot
|
||||
|
||||
**Run**:
|
||||
```bash
|
||||
python 03_state_machine.py --config path/to/RSI_EthernetConfig.xml
|
||||
```
|
||||
|
||||
**Flow**:
|
||||
1. Python monitors state variable (Tech.T11)
|
||||
2. Calibration state: Python performs calibration routine
|
||||
3. Python writes calibration offsets to Tech.C
|
||||
4. Executing state: KRL uses offsets for motion
|
||||
5. Complete state: Workflow finishes successfully
|
||||
|
||||
**States**:
|
||||
- 0: IDLE - Waiting to start
|
||||
- 1: CALIBRATING - Python calibration in progress
|
||||
- 2: READY - Ready for motion
|
||||
- 3: EXECUTING - Robot in motion
|
||||
- 4: COMPLETE - Task finished
|
||||
- 9: ERROR - Error condition
|
||||
|
||||
**API Features Demonstrated**:
|
||||
- All coordination methods from examples 01 and 02
|
||||
- State monitoring loop
|
||||
- Error handling with I/O signals
|
||||
- Real-time state transitions
|
||||
|
||||
---
|
||||
|
||||
## Configuration Requirements
|
||||
|
||||
### RSI XML Configuration
|
||||
|
||||
Your `RSI_EthernetConfig.xml` must include the following elements:
|
||||
|
||||
**Digital I/O:**
|
||||
```xml
|
||||
<SEND>
|
||||
<XML>
|
||||
<ELEMENT Tag="Digin" Type="INT"/>
|
||||
</XML>
|
||||
</SEND>
|
||||
<RECEIVE>
|
||||
<XML>
|
||||
<ELEMENT Tag="Digout" Type="INT"/>
|
||||
</XML>
|
||||
</RECEIVE>
|
||||
```
|
||||
|
||||
**Tech Variables:**
|
||||
```xml
|
||||
<SEND>
|
||||
<XML>
|
||||
<ELEMENT Tag="Tech" Type="DOUBLE" Indizes="[1..199]"/>
|
||||
</XML>
|
||||
</SEND>
|
||||
<RECEIVE>
|
||||
<XML>
|
||||
<ELEMENT Tag="Tech" Type="DOUBLE" Indizes="[1..199]"/>
|
||||
</XML>
|
||||
</RECEIVE>
|
||||
```
|
||||
|
||||
### Network Settings
|
||||
|
||||
Ensure your RSI network settings match:
|
||||
```xml
|
||||
<IP_NUMBER>192.168.1.100</IP_NUMBER> <!-- Your PC IP -->
|
||||
<PORT>49152</PORT>
|
||||
<SENTYPE>ImFree</SENTYPE>
|
||||
```
|
||||
|
||||
## Running Examples
|
||||
|
||||
### Step 1: Start Python Script
|
||||
|
||||
```bash
|
||||
# In one terminal
|
||||
cd examples/coordination
|
||||
python 01_basic_handshake.py --config ../../RSI_EthernetConfig.xml
|
||||
```
|
||||
|
||||
### Step 2: Execute KRL Program
|
||||
|
||||
1. Upload corresponding KRL program to robot controller
|
||||
2. Switch to AUTO mode on teach pendant
|
||||
3. Select and execute the KRL program
|
||||
4. Monitor coordination in Python terminal
|
||||
|
||||
### Step 3: Monitor Output
|
||||
|
||||
Python will log:
|
||||
- State transitions
|
||||
- I/O signal changes
|
||||
- Parameter reads/writes
|
||||
- Errors and warnings
|
||||
|
||||
**Example Output**:
|
||||
```
|
||||
2026-01-17 14:32:01 - INFO - Starting RSI communication...
|
||||
2026-01-17 14:32:01 - INFO - ✅ RSI started successfully
|
||||
2026-01-17 14:32:01 - INFO - Waiting for KRL ready signal...
|
||||
2026-01-17 14:32:05 - INFO - ✅ KRL signaled ready!
|
||||
2026-01-17 14:32:05 - INFO - Performing Python-side processing...
|
||||
2026-01-17 14:32:07 - INFO - ✅ Processing complete
|
||||
2026-01-17 14:32:07 - INFO - ✅ Signaled KRL to continue
|
||||
```
|
||||
|
||||
## Customizing Examples
|
||||
|
||||
### Modify Processing Logic
|
||||
|
||||
In `01_basic_handshake.py`:
|
||||
```python
|
||||
# Replace simulated processing
|
||||
time.sleep(2.0)
|
||||
|
||||
# With actual processing
|
||||
sensor_data = read_sensor()
|
||||
processed_result = analyze_data(sensor_data)
|
||||
update_database(processed_result)
|
||||
```
|
||||
|
||||
### Change Calculation Logic
|
||||
|
||||
In `02_parameter_passing.py`:
|
||||
```python
|
||||
# Modify target calculation
|
||||
target_x = current_x + 100.0 # Original
|
||||
target_x = calculate_adaptive_target(current_x, sensor_feedback) # Custom
|
||||
```
|
||||
|
||||
### Extend State Machine
|
||||
|
||||
In `03_state_machine.py`:
|
||||
```python
|
||||
# Add new states
|
||||
class State(IntEnum):
|
||||
IDLE = 0
|
||||
CALIBRATING = 1
|
||||
INSPECTING = 2 # NEW STATE
|
||||
READY = 3 # Renumber subsequent states
|
||||
# ...
|
||||
|
||||
# Handle new state
|
||||
elif current_state == State.INSPECTING:
|
||||
inspection_result = perform_inspection()
|
||||
api.krl.write_param('C20', inspection_result)
|
||||
api.krl.signal_complete(1)
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Timeout waiting for KRL signal"
|
||||
|
||||
**Problem**: Python doesn't receive expected I/O signal from KRL
|
||||
|
||||
**Solutions**:
|
||||
1. Verify KRL program is running on robot
|
||||
2. Check I/O configuration in RSI XML
|
||||
3. Verify network connectivity (ping robot IP)
|
||||
4. Check signal mapping ($OUT[1] → Digout.o1)
|
||||
5. Increase timeout: `api.krl.wait_for_signal(1, timeout=60.0)`
|
||||
|
||||
### "RSIVariableError: Tech.T11 not found"
|
||||
|
||||
**Problem**: Tech variable not in receive_variables
|
||||
|
||||
**Solutions**:
|
||||
1. Add Tech variables to RSI XML `<RECEIVE>` section
|
||||
2. Restart robot controller after XML changes
|
||||
3. Verify variable configuration: `api.tools.show_variables()`
|
||||
|
||||
### "Connection refused"
|
||||
|
||||
**Problem**: Cannot connect to robot controller
|
||||
|
||||
**Solutions**:
|
||||
1. Check robot IP address in RSI XML
|
||||
2. Verify robot is in correct mode (T1/T2/AUTO)
|
||||
3. Ensure firewall allows UDP port 49152
|
||||
4. Check RSI is enabled on robot controller
|
||||
|
||||
### KRL Program Halts
|
||||
|
||||
**Problem**: KRL program stops unexpectedly
|
||||
|
||||
**Solutions**:
|
||||
1. Check KRL timeout values (increase if needed)
|
||||
2. Verify Python script is running before KRL execution
|
||||
3. Check error signals ($IN[2] for error condition)
|
||||
4. Review KRL logs on teach pendant
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### Non-Blocking Monitoring
|
||||
|
||||
For continuous operation without blocking:
|
||||
|
||||
```python
|
||||
import threading
|
||||
|
||||
def monitor_state():
|
||||
while running:
|
||||
state = api.krl.read_param('T11')
|
||||
if state == CRITICAL_STATE:
|
||||
handle_critical_state()
|
||||
time.sleep(0.1)
|
||||
|
||||
# Run monitoring in background thread
|
||||
monitor_thread = threading.Thread(target=monitor_state, daemon=True)
|
||||
monitor_thread.start()
|
||||
|
||||
# Main thread does other work
|
||||
perform_other_tasks()
|
||||
```
|
||||
|
||||
### Multiple Coordination Channels
|
||||
|
||||
Use different I/O channels for parallel coordination:
|
||||
|
||||
```python
|
||||
# Channel 1: Main workflow
|
||||
if api.krl.wait_for_signal(1):
|
||||
api.krl.signal_complete(1)
|
||||
|
||||
# Channel 2: Emergency stop
|
||||
if api.io.get_input(2): # Emergency input
|
||||
logging.error("Emergency stop!")
|
||||
api.safety.stop()
|
||||
|
||||
# Channel 3: Auxiliary signaling
|
||||
api.io.pulse(3, duration=0.1) # Quick pulse signal
|
||||
```
|
||||
|
||||
### Integration with Motion Control
|
||||
|
||||
Combine coordination with real-time RSI corrections:
|
||||
|
||||
```python
|
||||
# Wait for motion start
|
||||
api.krl.wait_for_signal(1)
|
||||
|
||||
# Send real-time corrections during KRL motion
|
||||
for i in range(100):
|
||||
sensor_offset = get_sensor_offset()
|
||||
api.motion.update_cartesian(X=sensor_offset)
|
||||
time.sleep(0.004) # 250Hz
|
||||
|
||||
# Signal motion complete
|
||||
api.krl.signal_complete(1)
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. **Test examples** with your robot controller
|
||||
2. **Adapt templates** to your specific application
|
||||
3. **Implement error recovery** mechanisms
|
||||
4. **Create custom workflows** for your use case
|
||||
5. **Document coordination** protocols for your team
|
||||
|
||||
## References
|
||||
|
||||
- [RSIPI API Documentation](../../README.md)
|
||||
- [KRL Templates](../../templates/krl/README.md)
|
||||
- [Phase 3 Summary](../../PHASE_3_SUMMARY.md) (when available)
|
||||
- [KUKA RSI 3.3 Manual](https://www.kuka.com)
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: January 17, 2026
|
||||
**RSIPI Version**: 2.0.0
|
||||
@ -1,15 +1,11 @@
|
||||
from RSIPI import RSIAPI
|
||||
from RSIPI import rsi_api
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
rsi = rsi_api.RSIAPI()
|
||||
|
||||
api = RSIAPI()
|
||||
rsi.start_rsi()
|
||||
|
||||
api.start()
|
||||
print("RSI connection started. Press Enter to stop.")
|
||||
input()
|
||||
|
||||
print("RSI connection started. Press Enter to stop.")
|
||||
input()
|
||||
|
||||
api.stop()
|
||||
print("RSI connection stopped.")
|
||||
rsi.stop_rsi()
|
||||
print("RSI connection stopped.")
|
||||
|
||||
@ -1,13 +1,9 @@
|
||||
from RSIPI import RSIAPI
|
||||
from RSIPI import rsi_api
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
rsi = rsi_api.RSIAPI()
|
||||
rsi.start_rsi()
|
||||
|
||||
api = RSIAPI()
|
||||
api.start()
|
||||
# Move TCP 50mm along X-axis
|
||||
rsi.update_cartesian(x=50, y=0, z=0)
|
||||
|
||||
# Move TCP 50mm along X-axis
|
||||
api.motion.update_cartesian(X=50, Y=0, Z=0)
|
||||
|
||||
api.stop()
|
||||
rsi.stop_rsi()
|
||||
|
||||
@ -1,13 +1,9 @@
|
||||
from RSIPI import RSIAPI
|
||||
from RSIPI import rsi_api
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
rsi = rsi_api.RSIAPI()
|
||||
rsi.start_rsi()
|
||||
|
||||
api = RSIAPI()
|
||||
api.start()
|
||||
# Move Joint A1 by 10 degrees
|
||||
rsi.update_joints(a1=10)
|
||||
|
||||
# Move Joint A1 by 10 degrees
|
||||
api.motion.update_joints(A1=10)
|
||||
|
||||
api.stop()
|
||||
rsi.stop_rsi()
|
||||
|
||||
@ -1,13 +1,9 @@
|
||||
from RSIPI import RSIAPI
|
||||
from RSIPI import rsi_api
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
rsi = rsi_api.RSIAPI()
|
||||
rsi.start_rsi()
|
||||
|
||||
api = RSIAPI()
|
||||
api.start()
|
||||
# Move external axis E1 by 100mm
|
||||
rsi.update_external(e1=100)
|
||||
|
||||
# Move external axis E1 by 100mm
|
||||
api.motion.move_external_axis('E1', 100)
|
||||
|
||||
api.stop()
|
||||
rsi.stop_rsi()
|
||||
|
||||
@ -1,13 +1,9 @@
|
||||
from RSIPI import RSIAPI
|
||||
from RSIPI import rsi_api
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
rsi = rsi_api.RSIAPI()
|
||||
rsi.start_rsi()
|
||||
|
||||
api = RSIAPI()
|
||||
api.start()
|
||||
# Set digital output (e.g., to open gripper)
|
||||
rsi.update_digital_io(125) # Example binary pattern
|
||||
|
||||
# Set digital output (e.g., to open gripper)
|
||||
api.io.set_output(1, True)
|
||||
|
||||
api.stop()
|
||||
rsi.stop_rsi()
|
||||
|
||||
@ -1,15 +1,11 @@
|
||||
from RSIPI import RSIAPI
|
||||
from RSIPI import rsi_api
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
rsi = rsi_api.RSIAPI()
|
||||
rsi.enable_csv_logging()
|
||||
|
||||
api = RSIAPI()
|
||||
api.logging.start()
|
||||
rsi.start_rsi()
|
||||
|
||||
api.start()
|
||||
print("Logging robot data to CSV. Press Enter to stop.")
|
||||
input()
|
||||
|
||||
print("Logging robot data to CSV. Press Enter to stop.")
|
||||
input()
|
||||
|
||||
api.stop()
|
||||
rsi.stop_rsi()
|
||||
|
||||
@ -1,15 +1,11 @@
|
||||
from RSIPI import RSIAPI
|
||||
from RSIPI import rsi_api
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
rsi = rsi_api.RSIAPI()
|
||||
rsi.enable_graphing()
|
||||
|
||||
api = RSIAPI()
|
||||
api.viz.start_live_plot()
|
||||
rsi.start_rsi()
|
||||
|
||||
api.start()
|
||||
print("Live graphing started. Press Enter to stop.")
|
||||
input()
|
||||
|
||||
print("Live graphing started. Press Enter to stop.")
|
||||
input()
|
||||
|
||||
api.stop()
|
||||
rsi.stop_rsi()
|
||||
|
||||
@ -1,18 +1,14 @@
|
||||
from RSIPI import RSIAPI
|
||||
from RSIPI import rsi_api
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
rsi = rsi_api.RSIAPI()
|
||||
|
||||
api = RSIAPI()
|
||||
# Set X axis soft limits
|
||||
rsi.set_safety_limit(axis="X", min_value=-500, max_value=500)
|
||||
|
||||
# Set X axis soft limits
|
||||
api.safety.set_limit(axis="X", min_value=-500, max_value=500)
|
||||
rsi.start_rsi()
|
||||
|
||||
api.start()
|
||||
|
||||
try:
|
||||
try:
|
||||
while True:
|
||||
pass
|
||||
except KeyboardInterrupt:
|
||||
api.stop()
|
||||
except KeyboardInterrupt:
|
||||
rsi.stop_rsi()
|
||||
@ -1,24 +1,20 @@
|
||||
from RSIPI import RSIAPI
|
||||
from RSIPI import rsi_api
|
||||
import time
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
rsi = rsi_api.RSIAPI()
|
||||
rsi.start_rsi()
|
||||
|
||||
api = RSIAPI()
|
||||
api.start()
|
||||
# Plan simple trajectory
|
||||
points = [
|
||||
{"x": 0, "y": 0, "z": 0},
|
||||
{"x": 50, "y": 0, "z": 0},
|
||||
{"x": 50, "y": 50, "z": 0},
|
||||
{"x": 0, "y": 50, "z": 0},
|
||||
{"x": 0, "y": 0, "z": 0}
|
||||
]
|
||||
|
||||
# Plan simple trajectory
|
||||
points = [
|
||||
{"X": 0, "Y": 0, "Z": 0},
|
||||
{"X": 50, "Y": 0, "Z": 0},
|
||||
{"X": 50, "Y": 50, "Z": 0},
|
||||
{"X": 0, "Y": 50, "Z": 0},
|
||||
{"X": 0, "Y": 0, "Z": 0}
|
||||
]
|
||||
|
||||
for point in points:
|
||||
api.motion.update_cartesian(**point)
|
||||
for point in points:
|
||||
rsi.update_cartesian(**point)
|
||||
time.sleep(0.5)
|
||||
|
||||
api.stop()
|
||||
rsi.stop_rsi()
|
||||
|
||||
@ -1,18 +1,14 @@
|
||||
from RSIPI import RSIAPI
|
||||
from RSIPI import rsi_api
|
||||
|
||||
if __name__ == '__main__':
|
||||
from multiprocessing import freeze_support
|
||||
freeze_support()
|
||||
rsi = rsi_api.RSIAPI()
|
||||
|
||||
api = RSIAPI()
|
||||
|
||||
try:
|
||||
api.start()
|
||||
try:
|
||||
rsi.start_rsi()
|
||||
print("Press Ctrl+C to stop RSI safely.")
|
||||
while True:
|
||||
pass
|
||||
|
||||
except KeyboardInterrupt:
|
||||
except KeyboardInterrupt:
|
||||
print("\nEmergency stop triggered.")
|
||||
api.safety.stop()
|
||||
api.stop()
|
||||
rsi.safety_stop()
|
||||
rsi.stop_rsi()
|
||||
|
||||
325
main.py
325
main.py
@ -1,325 +0,0 @@
|
||||
"""
|
||||
RSIPI Test Runner
|
||||
=================
|
||||
Uncomment one example at a time and run this file.
|
||||
Uses RSI_EthernetConfig.xml from the project root by default.
|
||||
|
||||
Usage:
|
||||
python main.py
|
||||
python main.py --config path/to/other_config.xml
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import time # noqa: F401 - used by commented examples
|
||||
from multiprocessing import freeze_support
|
||||
from RSIPI import RSIAPI
|
||||
|
||||
if __name__ == '__main__':
|
||||
freeze_support()
|
||||
|
||||
parser = argparse.ArgumentParser(description="RSIPI Test Runner")
|
||||
parser.add_argument("--config", type=str, default="RSI_EthernetConfig.xml",
|
||||
help="Path to RSI config XML file")
|
||||
parser.add_argument("--mode", type=str, default="relative", choices=["absolute", "relative"],
|
||||
help="RSI correction mode (must match KRL program)")
|
||||
parser.add_argument("--max-cart-rate", type=float, default=0.5,
|
||||
help="Max Cartesian correction per cycle in mm (0 = no limit)")
|
||||
parser.add_argument("--max-joint-rate", type=float, default=0.2,
|
||||
help="Max joint correction per cycle in degrees (0 = no limit)")
|
||||
parser.add_argument("--cycle-time", type=float, default=0.004,
|
||||
help="RSI cycle time in seconds (0.004 = 4ms/250Hz, 0.012 = 12ms/83Hz)")
|
||||
args = parser.parse_args()
|
||||
|
||||
api = RSIAPI(
|
||||
args.config,
|
||||
rsi_mode=args.mode,
|
||||
max_cartesian_rate=args.max_cart_rate,
|
||||
max_joint_rate=args.max_joint_rate,
|
||||
cycle_time=args.cycle_time
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Example 01: Start / Stop
|
||||
# =========================================================================
|
||||
# api.start()
|
||||
# print("RSI started. Press Enter to stop.")
|
||||
# input()
|
||||
# api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Example 02: Send Cartesian correction (move TCP 50mm along X)
|
||||
# =========================================================================
|
||||
# api.start()
|
||||
# print("Waiting for robot connection...")
|
||||
# if not api.wait_for_connection(timeout=10):
|
||||
# print("Timeout waiting for robot. Exiting.")
|
||||
# api.stop()
|
||||
# exit(1)
|
||||
# print(f"Connected. IPOC: {api.monitoring.get_ipoc()}")
|
||||
# api.motion.update_cartesian(X=0.01, Y=0, Z=0)
|
||||
# print("Sent Cartesian correction. Press Enter to stop.")
|
||||
# input()
|
||||
# api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Example 03: Send Joint correction (move A1 by 10 degrees) DOESNT WORK
|
||||
# =========================================================================
|
||||
# api.start()
|
||||
# time.sleep(1)
|
||||
# api.motion.update_joints(A1=50)
|
||||
# print("Sent joint correction. Press Enter to stop.")
|
||||
# input()
|
||||
# api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Example 04: External axes (move E1 by 100mm)
|
||||
# =========================================================================
|
||||
# api.start()
|
||||
# time.sleep(1)
|
||||
# api.motion.move_external_axis('E1', 100)
|
||||
# print("Sent external axis correction. Press Enter to stop.")
|
||||
# input()
|
||||
# api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Example 05: Digital I/O (toggle outputs)
|
||||
# =========================================================================
|
||||
# api.start()
|
||||
# time.sleep(1)
|
||||
# api.io.set_output(1, True)
|
||||
# time.sleep(5)
|
||||
# api.io.set_output(1, False)
|
||||
|
||||
# print("Set digital outputs. Press Enter to stop.")
|
||||
# input()
|
||||
# api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Example 06: CSV Logging
|
||||
# =========================================================================
|
||||
# api.logging.start()
|
||||
# api.start()
|
||||
# print("Logging to CSV. Press Enter to stop.")
|
||||
# input()
|
||||
# api.logging.stop()
|
||||
# api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Example 07: Live Graphing
|
||||
# =========================================================================
|
||||
# api.start()
|
||||
# api.viz.start_live_plot('3d')
|
||||
# print("Live graph running. Press Enter to stop.")
|
||||
# input()
|
||||
# api.viz.stop_live_plot()
|
||||
# api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Example 08: Safety Limits (restrict X-axis to +/-500mm)
|
||||
# =========================================================================
|
||||
# api.safety.set_limit("RKorr.X", -500, 500)
|
||||
# api.start()
|
||||
# print("Safety limits active. Press Enter to stop.")
|
||||
# input()
|
||||
# api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Example 09: Cartesian Trajectory (square pattern)
|
||||
# =========================================================================
|
||||
# api.start()
|
||||
# time.sleep(1)
|
||||
# waypoints = [
|
||||
# {"X": 50, "Y": 0, "Z": 0},
|
||||
# {"X": 50, "Y": 50, "Z": 0},
|
||||
# {"X": 0, "Y": 50, "Z": 0},
|
||||
# {"X": 0, "Y": 0, "Z": 0},
|
||||
# ]
|
||||
# for wp in waypoints:
|
||||
# api.motion.update_cartesian(**wp)
|
||||
# time.sleep(0.5)
|
||||
# print("Trajectory complete. Press Enter to stop.")
|
||||
# input()
|
||||
# api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Example 10: Safe Shutdown (Ctrl+C handler)
|
||||
# =========================================================================
|
||||
# try:
|
||||
# api.start()
|
||||
# print("Running. Press Ctrl+C for safe shutdown.")
|
||||
# while True:
|
||||
# time.sleep(0.1)
|
||||
# except KeyboardInterrupt:
|
||||
# print("Emergency stop triggered.")
|
||||
# api.safety.stop()
|
||||
# api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Coordination 01: Basic Handshake (KRL <-> Python I/O signalling)
|
||||
# =========================================================================
|
||||
# api.start()
|
||||
# time.sleep(1)
|
||||
# print("Waiting for KRL ready signal on input 1...")
|
||||
# if api.krl.wait_for_signal(1, timeout=10.0):
|
||||
# print("KRL ready. Processing...")
|
||||
# time.sleep(1)
|
||||
# api.krl.signal_complete(1)
|
||||
# print("Handshake complete.")
|
||||
# else:
|
||||
# print("Timeout waiting for KRL signal.")
|
||||
# input("Press Enter to stop.")
|
||||
# api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Coordination 02: Parameter Passing (read/write Tech variables)
|
||||
# =========================================================================
|
||||
# api.start()
|
||||
# time.sleep(1)
|
||||
# pos_x = api.krl.read_param('T11')
|
||||
# pos_y = api.krl.read_param('T12')
|
||||
# pos_z = api.krl.read_param('T13')
|
||||
# print(f"Current position from KRL: X={pos_x}, Y={pos_y}, Z={pos_z}")
|
||||
# api.krl.write_param('C11', pos_x + 50)
|
||||
# api.krl.write_param('C12', pos_y)
|
||||
# api.krl.write_param('C13', pos_z)
|
||||
# api.krl.signal_complete(1)
|
||||
# print("Parameters sent. Press Enter to stop.")
|
||||
# input()
|
||||
# api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Coordination 03: State Machine (multi-state workflow)
|
||||
# =========================================================================
|
||||
# IDLE, CALIBRATING, READY, EXECUTING, COMPLETE, ERROR = 0, 1, 2, 3, 4, 5
|
||||
# api.start()
|
||||
# time.sleep(1)
|
||||
# state = IDLE
|
||||
# print("State machine running. Press Ctrl+C to exit.")
|
||||
# try:
|
||||
# while state != COMPLETE:
|
||||
# krl_state = int(api.krl.read_param('T11'))
|
||||
# if krl_state == CALIBRATING:
|
||||
# print("Calibrating...")
|
||||
# time.sleep(2)
|
||||
# api.krl.write_param('C11', READY)
|
||||
# state = READY
|
||||
# elif krl_state == EXECUTING:
|
||||
# print("Executing motion...")
|
||||
# state = EXECUTING
|
||||
# elif krl_state == COMPLETE:
|
||||
# print("Complete.")
|
||||
# state = COMPLETE
|
||||
# elif krl_state == ERROR:
|
||||
# print("Error detected!")
|
||||
# break
|
||||
# time.sleep(0.05)
|
||||
# except KeyboardInterrupt:
|
||||
# pass
|
||||
# api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Advanced Motion 01: Velocity Profiles (trapezoidal vs S-curve)
|
||||
# =========================================================================
|
||||
# api.start()
|
||||
# time.sleep(4)
|
||||
# # Relative mode: each point is a per-cycle delta
|
||||
# # 200 steps × 0.5mm = 100mm total at max rate limit
|
||||
# traj = api.motion.generate_trajectory(
|
||||
# {"X": 0, "Y": 0, "Z": 0},
|
||||
# {"X": 100, "Y": 0, "Z": 0},
|
||||
# steps=200,
|
||||
# mode="relative")
|
||||
# print(f"Executing trajectory: {len(traj)} steps, {traj[0]['X']:.2f}mm per step")
|
||||
# api.motion.execute_trajectory(traj, space="cartesian", rate=0.012)
|
||||
# print("Trajectory executed. Press Enter to stop.")
|
||||
# input()
|
||||
# api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Advanced Motion 02: Geometric Primitives (arc, circle, spiral)
|
||||
# =========================================================================
|
||||
api.start()
|
||||
print("Waiting for robot connection...")
|
||||
if not api.wait_for_connection(timeout=10):
|
||||
print("Timeout waiting for robot. Exiting.")
|
||||
api.stop()
|
||||
exit(1)
|
||||
print(f"Connected. IPOC: {api.monitoring.get_ipoc()}")
|
||||
input("Press Enter to start movement...")
|
||||
|
||||
# Generate absolute circle waypoints, convert to relative deltas
|
||||
circle_abs = api.motion.generate_circle(
|
||||
center={"X": 0, "Y": 0, "Z": 0},
|
||||
radius=5, steps=200)
|
||||
|
||||
# Convert absolute → relative (delta between consecutive points)
|
||||
# Start prev at first point so there's no initial jump
|
||||
circle_rel = []
|
||||
prev = circle_abs[0]
|
||||
for pt in circle_abs[1:]:
|
||||
delta = {k: pt[k] - prev.get(k, 0) for k in pt}
|
||||
circle_rel.append(delta)
|
||||
prev = pt
|
||||
|
||||
print(f"Executing circle: {len(circle_rel)} relative steps, radius=5mm")
|
||||
api.motion.execute_trajectory(circle_rel, space="cartesian", rate=0.012)
|
||||
# Zero out corrections so robot stops moving in relative mode
|
||||
api.motion.update_cartesian(X=0, Y=0, Z=0)
|
||||
print("Circle complete. Press Enter to stop.")
|
||||
input()
|
||||
api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Advanced Motion 03: Path Blending (smooth corner transitions)
|
||||
# =========================================================================
|
||||
# api.start()
|
||||
# time.sleep(1)
|
||||
# traj1 = [{"X": i, "Y": 0, "Z": 0} for i in range(0, 50, 5)]
|
||||
# traj2 = [{"X": 50, "Y": i, "Z": 0} for i in range(0, 50, 5)]
|
||||
# blended = api.motion.blend_trajectories(traj1, traj2, blend_radius=15)
|
||||
# print(f"Blended trajectory: {len(blended)} points")
|
||||
# print("Press Enter to stop.")
|
||||
# input()
|
||||
# api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Advanced Motion 04: Coordinate Transforms (frame conversions)
|
||||
# =========================================================================
|
||||
# api.start()
|
||||
# time.sleep(1)
|
||||
# base_pos = {"X": 500, "Y": 100, "Z": 800, "A": 0, "B": 0, "C": 0}
|
||||
# world_pos = api.motion.transform_coordinates(
|
||||
# base_pos, from_frame="BASE", to_frame="WORLD",
|
||||
# frame_offset={"X": 100, "Y": 50, "Z": 0})
|
||||
# print(f"Base: {base_pos}")
|
||||
# print(f"World: {world_pos}")
|
||||
# print("Press Enter to stop.")
|
||||
# input()
|
||||
# api.stop()
|
||||
|
||||
# =========================================================================
|
||||
# Advanced Motion 05: Combined Motion (production drilling pattern)
|
||||
# =========================================================================
|
||||
# api.start()
|
||||
# time.sleep(1)
|
||||
# # Generate trajectory to work area
|
||||
# nav_traj = api.motion.generate_trajectory(
|
||||
# {"X": 0, "Y": 0, "Z": 0},
|
||||
# {"X": 200, "Y": 200, "Z": 0},
|
||||
# steps=30)
|
||||
# # Apply S-curve velocity profile
|
||||
# profiled = api.motion.generate_velocity_profile(
|
||||
# nav_traj, max_velocity=80, max_acceleration=200, profile='s-curve')
|
||||
# print(f"Navigation: {len(profiled)} profiled points")
|
||||
# # Spiral inspection pattern
|
||||
# inspection = api.motion.generate_spiral(
|
||||
# center={"X": 200, "Y": 200, "Z": 0},
|
||||
# start_radius=5, end_radius=40, pitch=0, revolutions=2, steps=40)
|
||||
# # Drilling descent spiral
|
||||
# drill = api.motion.generate_spiral(
|
||||
# center={"X": 200, "Y": 200, "Z": 0},
|
||||
# start_radius=3, end_radius=3, pitch=-5.0, revolutions=5, steps=50)
|
||||
# print(f"Inspection: {len(inspection)} pts, Drill: {len(drill)} pts")
|
||||
# print("Press Enter to stop.")
|
||||
# input()
|
||||
# api.stop()
|
||||
@ -1,517 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<rSIModel dslVersion="1.0.0.0" name="" xmlns="http://schemas.microsoft.com/dsltools/RSIVisual">
|
||||
<rSIObjects>
|
||||
<!-- =================== Signal Sources (Robot State) =================== -->
|
||||
<rSIElement name="POSACT1" objType="POSACT" objTypeID="46" maxInputs="0" maxOutputs="0">
|
||||
<rSIOutPorts>
|
||||
<rSIOutPort name="X" />
|
||||
<rSIOutPort name="Y" />
|
||||
<rSIOutPort name="Z" />
|
||||
<rSIOutPort name="A" />
|
||||
<rSIOutPort name="B" />
|
||||
<rSIOutPort name="C" />
|
||||
<rSIOutPort name="S" signalType="Int" />
|
||||
<rSIOutPort name="T" signalType="Int" />
|
||||
</rSIOutPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="Type" value="Measured" paramType="KUKA.RSIVisual.RSI_PosActType" minVal="-2147483648" maxVal="2147483647" isEnum="true" isRuntime="false" index="1" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
<rSIElement name="AXISACT1" objType="AXISACT" objTypeID="44" maxInputs="0" maxOutputs="0">
|
||||
<rSIOutPorts>
|
||||
<rSIOutPort name="A1" />
|
||||
<rSIOutPort name="A2" />
|
||||
<rSIOutPort name="A3" />
|
||||
<rSIOutPort name="A4" />
|
||||
<rSIOutPort name="A5" />
|
||||
<rSIOutPort name="A6" />
|
||||
</rSIOutPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="Type" value="Measured" paramType="KUKA.RSIVisual.RSI_AxisActType" minVal="-2147483648" maxVal="2147483647" isEnum="true" isRuntime="false" index="1" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
<rSIElement name="AXISACTEXT1" objType="AXISACTEXT" objTypeID="69" maxInputs="0" maxOutputs="0">
|
||||
<rSIOutPorts>
|
||||
<rSIOutPort name="E1" />
|
||||
<rSIOutPort name="E2" />
|
||||
<rSIOutPort name="E3" />
|
||||
<rSIOutPort name="E4" />
|
||||
<rSIOutPort name="E5" />
|
||||
<rSIOutPort name="E6" />
|
||||
</rSIOutPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="Type" value="Measured" paramType="KUKA.RSIVisual.RSI_AxisActType" minVal="-2147483648" maxVal="2147483647" isEnum="true" isRuntime="false" index="1" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
<rSIElement name="MOTORCURRENT1" objType="MOTORCURRENT" objTypeID="57" maxInputs="0" maxOutputs="0">
|
||||
<rSIOutPorts>
|
||||
<rSIOutPort name="A1" />
|
||||
<rSIOutPort name="A2" />
|
||||
<rSIOutPort name="A3" />
|
||||
<rSIOutPort name="A4" />
|
||||
<rSIOutPort name="A5" />
|
||||
<rSIOutPort name="A6" />
|
||||
</rSIOutPorts>
|
||||
</rSIElement>
|
||||
<rSIElement name="DIGIN1" objType="DIGIN" objTypeID="29" maxInputs="0" maxOutputs="0">
|
||||
<rSIOutPorts>
|
||||
<rSIOutPort name="Out1" signalType="Int" />
|
||||
</rSIOutPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="Index" value="1" paramType="System.Int32" minVal="1" maxVal="4096" isEnum="false" index="1" />
|
||||
<rSIParameter name="DataSize" value="Byte" paramType="KUKA.RSIVisual.RSI_DataSize" minVal="-2147483648" maxVal="2147483647" isEnum="true" index="2" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
<rSIElement name="DIGOUT1" objType="DIGOUT" objTypeID="43" maxInputs="0" maxOutputs="0">
|
||||
<rSIOutPorts>
|
||||
<rSIOutPort name="Out1" signalType="Int" />
|
||||
</rSIOutPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="Index" value="1" paramType="System.Int32" minVal="1" maxVal="4096" isEnum="false" index="1" />
|
||||
<rSIParameter name="DataSize" value="Bit" paramType="KUKA.RSIVisual.RSI_DataSize" minVal="-2147483648" maxVal="2147483647" isEnum="true" index="2" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
<rSIElement name="DIGOUT2" objType="DIGOUT" objTypeID="43" maxInputs="0" maxOutputs="0">
|
||||
<rSIOutPorts>
|
||||
<rSIOutPort name="Out1" signalType="Int" />
|
||||
</rSIOutPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="Index" value="2" paramType="System.Int32" minVal="1" maxVal="4096" isEnum="false" index="1" />
|
||||
<rSIParameter name="DataSize" value="Bit" paramType="KUKA.RSIVisual.RSI_DataSize" minVal="-2147483648" maxVal="2147483647" isEnum="true" index="2" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
<rSIElement name="DIGOUT3" objType="DIGOUT" objTypeID="43" maxInputs="0" maxOutputs="0">
|
||||
<rSIOutPorts>
|
||||
<rSIOutPort name="Out1" signalType="Int" />
|
||||
</rSIOutPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="Index" value="3" paramType="System.Int32" minVal="1" maxVal="4096" isEnum="false" index="1" />
|
||||
<rSIParameter name="DataSize" value="Bit" paramType="KUKA.RSIVisual.RSI_DataSize" minVal="-2147483648" maxVal="2147483647" isEnum="true" index="2" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
<rSIElement name="SOURCE1" objType="SOURCE" objTypeID="45" maxInputs="0" maxOutputs="0">
|
||||
<rSIOutPorts>
|
||||
<rSIOutPort name="Out1" />
|
||||
</rSIOutPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="Type" value="Sin" paramType="KUKA.RSIVisual.RSI_SourceType" minVal="-2147483648" maxVal="2147483647" isEnum="true" index="1" />
|
||||
<rSIParameter name="Offset" value="0" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="2" />
|
||||
<rSIParameter name="Amplitude" value="0" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="3" />
|
||||
<rSIParameter name="Period" value="0" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="4" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
<rSIElement name="OV_PRO1" objType="OV_PRO" objTypeID="73" maxInputs="0" maxOutputs="0">
|
||||
<rSIOutPorts>
|
||||
<rSIOutPort name="Out1" />
|
||||
</rSIOutPorts>
|
||||
</rSIElement>
|
||||
<rSIElement name="STATUS1" objType="STATUS" objTypeID="72" maxInputs="0" maxOutputs="0">
|
||||
<rSIOutPorts>
|
||||
<rSIOutPort name="Out1" signalType="Int" />
|
||||
</rSIOutPorts>
|
||||
</rSIElement>
|
||||
|
||||
<!-- =================== Action Objects (PC to Robot) =================== -->
|
||||
<rSIElement name="POSCORR1" objType="POSCORR" objTypeID="27" maxInputs="0" maxOutputs="0">
|
||||
<rSIInPorts>
|
||||
<rSIInPort name="CorrX" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out1" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="CorrY" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out2" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="CorrZ" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out3" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="CorrA" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out4" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="CorrB" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out5" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="CorrC" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out6" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
</rSIInPorts>
|
||||
<rSIOutPorts>
|
||||
<rSIOutPort name="Stat" signalType="Int" />
|
||||
<rSIOutPort name="X" />
|
||||
<rSIOutPort name="Y" />
|
||||
<rSIOutPort name="Z" />
|
||||
<rSIOutPort name="A" />
|
||||
<rSIOutPort name="B" />
|
||||
<rSIOutPort name="C" />
|
||||
</rSIOutPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="LowerLimX" value="-500" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="1" />
|
||||
<rSIParameter name="LowerLimY" value="-500" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="2" />
|
||||
<rSIParameter name="LowerLimZ" value="-500" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="3" />
|
||||
<rSIParameter name="UpperLimX" value="500" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="4" />
|
||||
<rSIParameter name="UpperLimY" value="500" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="5" />
|
||||
<rSIParameter name="UpperLimZ" value="500" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="6" />
|
||||
<rSIParameter name="MaxRotAngle" value="500" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="7" />
|
||||
<rSIParameter name="RefCorrSys" value="Base" paramType="KUKA.RSIVisual.RSI_TrafoCosys" minVal="-2147483648" maxVal="2147483647" isEnum="true" isRuntime="false" index="1" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
<rSIElement name="AXISCORR1" objType="AXISCORR" objTypeID="24" maxInputs="0" maxOutputs="0">
|
||||
<rSIInPorts>
|
||||
<rSIInPort name="CorrA1" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out7" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="CorrA2" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out8" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="CorrA3" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out9" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="CorrA4" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out10" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="CorrA5" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out11" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="CorrA6" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out12" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
</rSIInPorts>
|
||||
<rSIOutPorts>
|
||||
<rSIOutPort name="Stat" signalType="Int" />
|
||||
<rSIOutPort name="A1" />
|
||||
<rSIOutPort name="A2" />
|
||||
<rSIOutPort name="A3" />
|
||||
<rSIOutPort name="A4" />
|
||||
<rSIOutPort name="A5" />
|
||||
<rSIOutPort name="A6" />
|
||||
</rSIOutPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="LowerLimA1" value="-180" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="1" />
|
||||
<rSIParameter name="LowerLimA2" value="-180" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="2" />
|
||||
<rSIParameter name="LowerLimA3" value="-180" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="3" />
|
||||
<rSIParameter name="LowerLimA4" value="-180" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="4" />
|
||||
<rSIParameter name="LowerLimA5" value="-180" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="5" />
|
||||
<rSIParameter name="LowerLimA6" value="-180" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="6" />
|
||||
<rSIParameter name="UpperLimA1" value="180" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="7" />
|
||||
<rSIParameter name="UpperLimA2" value="180" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="8" />
|
||||
<rSIParameter name="UpperLimA3" value="180" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="9" />
|
||||
<rSIParameter name="UpperLimA4" value="180" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="10" />
|
||||
<rSIParameter name="UpperLimA5" value="180" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="11" />
|
||||
<rSIParameter name="UpperLimA6" value="180" paramType="System.Double" minVal="-2147483648" maxVal="2147483647" isEnum="false" index="12" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
<rSIElement name="MAP2DIGOUT1" objType="MAP2DIGOUT" objTypeID="14" maxInputs="0" maxOutputs="0">
|
||||
<rSIInPorts>
|
||||
<rSIInPort name="In1" signalType="Int">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out13" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
</rSIInPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="Index" value="20" paramType="System.Int32" minVal="1" maxVal="4096" isEnum="false" index="1" />
|
||||
<rSIParameter name="DataSize" value="Word" paramType="KUKA.RSIVisual.RSI_DataSizeX" minVal="-2147483648" maxVal="2147483647" isEnum="true" index="2" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
<rSIElement name="MAP2SEN_PREA1" objType="MAP2SEN_PREA" objTypeID="17" maxInputs="0" maxOutputs="0">
|
||||
<rSIInPorts>
|
||||
<rSIInPort name="In1">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out1" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
</rSIInPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="Index" value="1" paramType="System.Int32" minVal="1" maxVal="20" isEnum="false" index="1" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
<rSIElement name="MAP2SEN_PREA2" objType="MAP2SEN_PREA" objTypeID="17" maxInputs="0" maxOutputs="0">
|
||||
<rSIInPorts>
|
||||
<rSIInPort name="In1">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out2" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
</rSIInPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="Index" value="2" paramType="System.Int32" minVal="1" maxVal="20" isEnum="false" index="1" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
<rSIElement name="MAP2SEN_PREA3" objType="MAP2SEN_PREA" objTypeID="17" maxInputs="0" maxOutputs="0">
|
||||
<rSIInPorts>
|
||||
<rSIInPort name="In1">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out3" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
</rSIInPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="Index" value="3" paramType="System.Int32" minVal="1" maxVal="20" isEnum="false" index="1" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
|
||||
<!-- =================== Monitoring =================== -->
|
||||
<rSIElement name="POSCORRMON1" objType="POSCORRMON" objTypeID="81" maxInputs="0" maxOutputs="0">
|
||||
<rSIOutPorts>
|
||||
<rSIOutPort name="X" />
|
||||
<rSIOutPort name="Y" />
|
||||
<rSIOutPort name="Z" />
|
||||
<rSIOutPort name="A" />
|
||||
<rSIOutPort name="B" />
|
||||
<rSIOutPort name="C" />
|
||||
</rSIOutPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="MaxTrans" value="500" paramType="System.Double" minVal="0" maxVal="2147483647" isEnum="false" index="1" />
|
||||
<rSIParameter name="MaxRotAngle" value="180" paramType="System.Double" minVal="0" maxVal="2147483647" isEnum="false" index="2" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
<rSIElement name="AXISCORRMON1" objType="AXISCORRMON" objTypeID="82" maxInputs="0" maxOutputs="0">
|
||||
<rSIOutPorts>
|
||||
<rSIOutPort name="A1" />
|
||||
<rSIOutPort name="A2" />
|
||||
<rSIOutPort name="A3" />
|
||||
<rSIOutPort name="A4" />
|
||||
<rSIOutPort name="A5" />
|
||||
<rSIOutPort name="A6" />
|
||||
<rSIOutPort name="E1" />
|
||||
<rSIOutPort name="E2" />
|
||||
<rSIOutPort name="E3" />
|
||||
<rSIOutPort name="E4" />
|
||||
<rSIOutPort name="E5" />
|
||||
<rSIOutPort name="E6" />
|
||||
</rSIOutPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="MaxA1" value="180" paramType="System.Double" minVal="0" maxVal="2147483647" isEnum="false" index="1" />
|
||||
<rSIParameter name="MaxA2" value="180" paramType="System.Double" minVal="0" maxVal="2147483647" isEnum="false" index="2" />
|
||||
<rSIParameter name="MaxA3" value="180" paramType="System.Double" minVal="0" maxVal="2147483647" isEnum="false" index="3" />
|
||||
<rSIParameter name="MaxA4" value="180" paramType="System.Double" minVal="0" maxVal="2147483647" isEnum="false" index="4" />
|
||||
<rSIParameter name="MaxA5" value="180" paramType="System.Double" minVal="0" maxVal="2147483647" isEnum="false" index="5" />
|
||||
<rSIParameter name="MaxA6" value="180" paramType="System.Double" minVal="0" maxVal="2147483647" isEnum="false" index="6" />
|
||||
<rSIParameter name="MaxE1" value="180" paramType="System.Double" minVal="0" maxVal="2147483647" isEnum="false" index="7" />
|
||||
<rSIParameter name="MaxE2" value="180" paramType="System.Double" minVal="0" maxVal="2147483647" isEnum="false" index="8" />
|
||||
<rSIParameter name="MaxE3" value="180" paramType="System.Double" minVal="0" maxVal="2147483647" isEnum="false" index="9" />
|
||||
<rSIParameter name="MaxE4" value="180" paramType="System.Double" minVal="0" maxVal="2147483647" isEnum="false" index="10" />
|
||||
<rSIParameter name="MaxE5" value="180" paramType="System.Double" minVal="0" maxVal="2147483647" isEnum="false" index="11" />
|
||||
<rSIParameter name="MaxE6" value="180" paramType="System.Double" minVal="0" maxVal="2147483647" isEnum="false" index="12" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
|
||||
<!-- =================== ETHERNET Communication =================== -->
|
||||
<rSIElement name="ETHERNET1" objType="ETHERNET" objTypeID="64" maxInputs="64" maxOutputs="64">
|
||||
<rSIInPorts>
|
||||
<rSIInPort name="In1" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//DIGIN1/Out1" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In2" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//DIGOUT1/Out1" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In3" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//DIGOUT2/Out1" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In4" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//DIGOUT3/Out1" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In5" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//SOURCE1/Out1" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In6" mandatory="false" />
|
||||
<rSIInPort name="In7" mandatory="false" />
|
||||
<rSIInPort name="In8" mandatory="false" />
|
||||
<rSIInPort name="In9" mandatory="false" />
|
||||
<rSIInPort name="In10" mandatory="false" />
|
||||
<rSIInPort name="In11" mandatory="false" />
|
||||
<rSIInPort name="In12" mandatory="false" />
|
||||
<rSIInPort name="In13" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//POSACT1/X" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In14" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//POSACT1/Y" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In15" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//POSACT1/Z" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In16" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//POSACT1/A" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In17" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//POSACT1/B" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In18" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//POSACT1/C" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In19" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//AXISACT1/A1" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In20" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//AXISACT1/A2" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In21" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//AXISACT1/A3" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In22" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//AXISACT1/A4" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In23" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//AXISACT1/A5" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In24" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//AXISACT1/A6" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In25" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//AXISACTEXT1/E1" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In26" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//AXISACTEXT1/E2" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In27" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//AXISACTEXT1/E3" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In28" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//AXISACTEXT1/E4" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In29" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//AXISACTEXT1/E5" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In30" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//AXISACTEXT1/E6" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In31" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//MOTORCURRENT1/A1" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In32" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//MOTORCURRENT1/A2" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In33" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//MOTORCURRENT1/A3" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In34" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//MOTORCURRENT1/A4" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In35" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//MOTORCURRENT1/A5" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In36" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//MOTORCURRENT1/A6" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In37" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//OV_PRO1/Out1" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
<rSIInPort name="In38" mandatory="false">
|
||||
<source>
|
||||
<rSIOutPortMoniker name="//STATUS1/Out1" />
|
||||
</source>
|
||||
</rSIInPort>
|
||||
</rSIInPorts>
|
||||
<rSIOutPorts>
|
||||
<rSIOutPort name="Out1" />
|
||||
<rSIOutPort name="Out2" />
|
||||
<rSIOutPort name="Out3" />
|
||||
<rSIOutPort name="Out4" />
|
||||
<rSIOutPort name="Out5" />
|
||||
<rSIOutPort name="Out6" />
|
||||
<rSIOutPort name="Out7" />
|
||||
<rSIOutPort name="Out8" />
|
||||
<rSIOutPort name="Out9" />
|
||||
<rSIOutPort name="Out10" />
|
||||
<rSIOutPort name="Out11" />
|
||||
<rSIOutPort name="Out12" />
|
||||
<rSIOutPort name="Out13" />
|
||||
<rSIOutPort name="Out14" />
|
||||
<rSIOutPort name="Out15" />
|
||||
<rSIOutPort name="Out16" />
|
||||
<rSIOutPort name="Out17" />
|
||||
<rSIOutPort name="Out18" />
|
||||
<rSIOutPort name="Out19" />
|
||||
<rSIOutPort name="Out20" />
|
||||
</rSIOutPorts>
|
||||
<rSIParameters>
|
||||
<rSIParameter name="ConfigFile" value="RSI_EthernetConfig_Full.xml" paramType="System.FileName" minVal="-2147483648" maxVal="2147483647" isEnum="false" isRuntime="false" index="1" />
|
||||
<rSIParameter name="Timeout" value="100" paramType="System.Int32" minVal="0" maxVal="2147483647" isEnum="false" index="1" />
|
||||
<rSIParameter name="Flag" value="1" paramType="System.Int32" minVal="-1" maxVal="999" isEnum="false" index="4" />
|
||||
<rSIParameter name="Precision" value="1" paramType="System.Int32" minVal="1" maxVal="32" isEnum="false" index="8" />
|
||||
</rSIParameters>
|
||||
</rSIElement>
|
||||
</rSIObjects>
|
||||
</rSIModel>
|
||||
@ -1,256 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<rSIObjectDiagram dslVersion="1.0.0.0" absoluteBounds="0, 0, 18, 14" name="RSIPI_Full">
|
||||
<rSIModelMoniker name="/" />
|
||||
<nestedChildShapes>
|
||||
<!-- Row 1: Signal source objects -->
|
||||
<rSIElementShape Id="a1000001-0000-0000-0000-000000000001" absoluteBounds="0.5, 0.5, 1.5, 0.8593896484375001" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//POSACT1" />
|
||||
<relativeChildShapes>
|
||||
<rSIOutPortShape Id="a1000001-0001-0000-0000-000000000001" absoluteBounds="2, 0.75, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIOutPortMoniker name="//POSACT1/X" />
|
||||
<relativeChildShapes />
|
||||
</rSIOutPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a1000001-0002-0000-0000-000000000001" isExpanded="false" absoluteBounds="0.515, 1.01, 1.4700000000000002, 0.2493896484375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<rSIElementShape Id="a1000002-0000-0000-0000-000000000001" absoluteBounds="2.5, 0.5, 1.5, 0.8593896484375001" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//AXISACT1" />
|
||||
<relativeChildShapes>
|
||||
<rSIOutPortShape Id="a1000002-0001-0000-0000-000000000001" absoluteBounds="4, 0.75, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIOutPortMoniker name="//AXISACT1/A1" />
|
||||
<relativeChildShapes />
|
||||
</rSIOutPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a1000002-0002-0000-0000-000000000001" isExpanded="false" absoluteBounds="2.515, 1.01, 1.4700000000000002, 0.2493896484375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<rSIElementShape Id="a1000003-0000-0000-0000-000000000001" absoluteBounds="4.5, 0.5, 1.5, 0.8593896484375001" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//AXISACTEXT1" />
|
||||
<relativeChildShapes>
|
||||
<rSIOutPortShape Id="a1000003-0001-0000-0000-000000000001" absoluteBounds="6, 0.75, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIOutPortMoniker name="//AXISACTEXT1/E1" />
|
||||
<relativeChildShapes />
|
||||
</rSIOutPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a1000003-0002-0000-0000-000000000001" isExpanded="false" absoluteBounds="4.515, 1.01, 1.4700000000000002, 0.2493896484375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<rSIElementShape Id="a1000004-0000-0000-0000-000000000001" absoluteBounds="6.5, 0.5, 1.5, 0.8593896484375001" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//MOTORCURRENT1" />
|
||||
<relativeChildShapes>
|
||||
<rSIOutPortShape Id="a1000004-0001-0000-0000-000000000001" absoluteBounds="8, 0.75, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIOutPortMoniker name="//MOTORCURRENT1/A1" />
|
||||
<relativeChildShapes />
|
||||
</rSIOutPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a1000004-0002-0000-0000-000000000001" isExpanded="false" absoluteBounds="6.515, 1.01, 1.4700000000000002, 0.2493896484375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<!-- Row 2: Digital I/O and Source -->
|
||||
<rSIElementShape Id="a1000005-0000-0000-0000-000000000001" absoluteBounds="0.5, 2, 1.5, 0.8593896484375001" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//DIGIN1" />
|
||||
<relativeChildShapes>
|
||||
<rSIOutPortShape Id="a1000005-0001-0000-0000-000000000001" absoluteBounds="2, 2.25, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIOutPortMoniker name="//DIGIN1/Out1" />
|
||||
<relativeChildShapes />
|
||||
</rSIOutPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a1000005-0002-0000-0000-000000000001" isExpanded="false" absoluteBounds="0.515, 2.51, 1.4700000000000002, 0.2493896484375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<rSIElementShape Id="a1000006-0000-0000-0000-000000000001" absoluteBounds="2.5, 2, 1.5, 0.8593896484375001" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//DIGOUT1" />
|
||||
<relativeChildShapes>
|
||||
<rSIOutPortShape Id="a1000006-0001-0000-0000-000000000001" absoluteBounds="4, 2.25, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIOutPortMoniker name="//DIGOUT1/Out1" />
|
||||
<relativeChildShapes />
|
||||
</rSIOutPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a1000006-0002-0000-0000-000000000001" isExpanded="false" absoluteBounds="2.515, 2.51, 1.4700000000000002, 0.2493896484375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<rSIElementShape Id="a1000007-0000-0000-0000-000000000001" absoluteBounds="4.5, 2, 1.5, 0.8593896484375001" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//DIGOUT2" />
|
||||
<relativeChildShapes>
|
||||
<rSIOutPortShape Id="a1000007-0001-0000-0000-000000000001" absoluteBounds="6, 2.25, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIOutPortMoniker name="//DIGOUT2/Out1" />
|
||||
<relativeChildShapes />
|
||||
</rSIOutPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a1000007-0002-0000-0000-000000000001" isExpanded="false" absoluteBounds="4.515, 2.51, 1.4700000000000002, 0.2493896484375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<rSIElementShape Id="a1000008-0000-0000-0000-000000000001" absoluteBounds="6.5, 2, 1.5, 0.8593896484375001" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//DIGOUT3" />
|
||||
<relativeChildShapes>
|
||||
<rSIOutPortShape Id="a1000008-0001-0000-0000-000000000001" absoluteBounds="8, 2.25, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIOutPortMoniker name="//DIGOUT3/Out1" />
|
||||
<relativeChildShapes />
|
||||
</rSIOutPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a1000008-0002-0000-0000-000000000001" isExpanded="false" absoluteBounds="6.515, 2.51, 1.4700000000000002, 0.2493896484375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<rSIElementShape Id="a1000009-0000-0000-0000-000000000001" absoluteBounds="8.5, 2, 1.5, 0.8593896484375001" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//SOURCE1" />
|
||||
<relativeChildShapes>
|
||||
<rSIOutPortShape Id="a1000009-0001-0000-0000-000000000001" absoluteBounds="10, 2.25, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIOutPortMoniker name="//SOURCE1/Out1" />
|
||||
<relativeChildShapes />
|
||||
</rSIOutPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a1000009-0002-0000-0000-000000000001" isExpanded="false" absoluteBounds="8.515, 2.51, 1.4700000000000002, 0.2493896484375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<rSIElementShape Id="a100000a-0000-0000-0000-000000000001" absoluteBounds="10.5, 0.5, 1.5, 0.8593896484375001" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//OV_PRO1" />
|
||||
<relativeChildShapes>
|
||||
<rSIOutPortShape Id="a100000a-0001-0000-0000-000000000001" absoluteBounds="12, 0.75, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIOutPortMoniker name="//OV_PRO1/Out1" />
|
||||
<relativeChildShapes />
|
||||
</rSIOutPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a100000a-0002-0000-0000-000000000001" isExpanded="false" absoluteBounds="10.515, 1.01, 1.4700000000000002, 0.2493896484375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<rSIElementShape Id="a100000b-0000-0000-0000-000000000001" absoluteBounds="12.5, 0.5, 1.5, 0.8593896484375001" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//STATUS1" />
|
||||
<relativeChildShapes>
|
||||
<rSIOutPortShape Id="a100000b-0001-0000-0000-000000000001" absoluteBounds="14, 0.75, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIOutPortMoniker name="//STATUS1/Out1" />
|
||||
<relativeChildShapes />
|
||||
</rSIOutPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a100000b-0002-0000-0000-000000000001" isExpanded="false" absoluteBounds="12.515, 1.01, 1.4700000000000002, 0.2493896484375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<!-- Row 3: ETHERNET (center, large) -->
|
||||
<rSIElementShape Id="a100000c-0000-0000-0000-000000000001" absoluteBounds="5, 4, 3, 8" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//ETHERNET1" />
|
||||
<relativeChildShapes>
|
||||
<rSIInPortShape Id="a100000c-0001-0000-0000-000000000001" absoluteBounds="4.6, 4.25, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIInPortMoniker name="//ETHERNET1/In1" />
|
||||
<relativeChildShapes />
|
||||
</rSIInPortShape>
|
||||
<rSIOutPortShape Id="a100000c-0002-0000-0000-000000000001" absoluteBounds="8, 4.25, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIOutPortMoniker name="//ETHERNET1/Out1" />
|
||||
<relativeChildShapes />
|
||||
</rSIOutPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a100000c-0003-0000-0000-000000000001" absoluteBounds="5.015, 4.51, 2.9700000000000002, 1.0185953776041665" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<!-- Row 4: Action objects -->
|
||||
<rSIElementShape Id="a100000d-0000-0000-0000-000000000001" absoluteBounds="10, 4, 2, 2.875" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//POSCORR1" />
|
||||
<relativeChildShapes>
|
||||
<rSIInPortShape Id="a100000d-0001-0000-0000-000000000001" absoluteBounds="9.6, 4.25, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIInPortMoniker name="//POSCORR1/CorrX" />
|
||||
<relativeChildShapes />
|
||||
</rSIInPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a100000d-0002-0000-0000-000000000001" absoluteBounds="10.015, 4.51, 1.9700000000000002, 1.7878011067708333" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<rSIElementShape Id="a100000e-0000-0000-0000-000000000001" absoluteBounds="10, 7.5, 2, 2.875" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//AXISCORR1" />
|
||||
<relativeChildShapes>
|
||||
<rSIInPortShape Id="a100000e-0001-0000-0000-000000000001" absoluteBounds="9.6, 7.75, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIInPortMoniker name="//AXISCORR1/CorrA1" />
|
||||
<relativeChildShapes />
|
||||
</rSIInPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a100000e-0002-0000-0000-000000000001" absoluteBounds="10.015, 8.01, 1.9700000000000002, 2.5570068359375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<rSIElementShape Id="a100000f-0000-0000-0000-000000000001" absoluteBounds="10, 11, 2, 0.8593896484375001" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//MAP2DIGOUT1" />
|
||||
<relativeChildShapes>
|
||||
<rSIInPortShape Id="a100000f-0001-0000-0000-000000000001" absoluteBounds="9.6, 11.25, 0.40000000596046448, 0.075000002980232239" fillColor="BlanchedAlmond">
|
||||
<rSIInPortMoniker name="//MAP2DIGOUT1/In1" />
|
||||
<relativeChildShapes />
|
||||
</rSIInPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a100000f-0002-0000-0000-000000000001" isExpanded="false" absoluteBounds="10.015, 11.51, 1.9700000000000002, 0.2493896484375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<!-- Row 5: MAP2SEN_PREA objects -->
|
||||
<rSIElementShape Id="a1000010-0000-0000-0000-000000000001" absoluteBounds="13, 4, 1.5, 0.8593896484375001" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//MAP2SEN_PREA1" />
|
||||
<relativeChildShapes>
|
||||
<rSIInPortShape Id="a1000010-0001-0000-0000-000000000001" absoluteBounds="12.6, 4.25, 0.40000000596046448, 0.075000002980232239" fillColor="BlanchedAlmond">
|
||||
<rSIInPortMoniker name="//MAP2SEN_PREA1/In1" />
|
||||
<relativeChildShapes />
|
||||
</rSIInPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a1000010-0002-0000-0000-000000000001" isExpanded="false" absoluteBounds="13.015, 4.51, 1.4700000000000002, 0.2493896484375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<rSIElementShape Id="a1000011-0000-0000-0000-000000000001" absoluteBounds="13, 5.25, 1.5, 0.8593896484375001" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//MAP2SEN_PREA2" />
|
||||
<relativeChildShapes>
|
||||
<rSIInPortShape Id="a1000011-0001-0000-0000-000000000001" absoluteBounds="12.6, 5.5, 0.40000000596046448, 0.075000002980232239" fillColor="BlanchedAlmond">
|
||||
<rSIInPortMoniker name="//MAP2SEN_PREA2/In1" />
|
||||
<relativeChildShapes />
|
||||
</rSIInPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a1000011-0002-0000-0000-000000000001" isExpanded="false" absoluteBounds="13.015, 5.76, 1.4700000000000002, 0.2493896484375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<rSIElementShape Id="a1000012-0000-0000-0000-000000000001" absoluteBounds="13, 6.5, 1.5, 0.8593896484375001" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//MAP2SEN_PREA3" />
|
||||
<relativeChildShapes>
|
||||
<rSIInPortShape Id="a1000012-0001-0000-0000-000000000001" absoluteBounds="12.6, 6.75, 0.40000000596046448, 0.075000002980232239" fillColor="BlanchedAlmond">
|
||||
<rSIInPortMoniker name="//MAP2SEN_PREA3/In1" />
|
||||
<relativeChildShapes />
|
||||
</rSIInPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a1000012-0002-0000-0000-000000000001" isExpanded="false" absoluteBounds="13.015, 7.01, 1.4700000000000002, 0.2493896484375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<!-- Row 6: Monitoring objects -->
|
||||
<rSIElementShape Id="a1000013-0000-0000-0000-000000000001" absoluteBounds="14.5, 0.5, 1.5, 2.475" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//POSCORRMON1" />
|
||||
<relativeChildShapes>
|
||||
<rSIOutPortShape Id="a1000013-0001-0000-0000-000000000001" absoluteBounds="16, 0.75, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIOutPortMoniker name="//POSCORRMON1/X" />
|
||||
<relativeChildShapes />
|
||||
</rSIOutPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a1000013-0002-0000-0000-000000000001" absoluteBounds="14.515, 1.01, 1.4700000000000002, 0.63399251302083326" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
<rSIElementShape Id="a1000014-0000-0000-0000-000000000001" absoluteBounds="14.5, 3.5, 1.5, 4.875" fillColor="BlanchedAlmond">
|
||||
<rSIElementMoniker name="//AXISCORRMON1" />
|
||||
<relativeChildShapes>
|
||||
<rSIOutPortShape Id="a1000014-0001-0000-0000-000000000001" absoluteBounds="16, 3.75, 0.40000000596046448, 0.075000002980232239" fillColor="White">
|
||||
<rSIOutPortMoniker name="//AXISCORRMON1/A1" />
|
||||
<relativeChildShapes />
|
||||
</rSIOutPortShape>
|
||||
</relativeChildShapes>
|
||||
<nestedChildShapes>
|
||||
<elementListCompartment Id="a1000014-0002-0000-0000-000000000001" absoluteBounds="14.515, 4.01, 1.4700000000000002, 2.5570068359375" name="RSIParameters" titleTextColor="Black" itemTextColor="Black" />
|
||||
</nestedChildShapes>
|
||||
</rSIElementShape>
|
||||
</nestedChildShapes>
|
||||
</rSIObjectDiagram>
|
||||
@ -1,203 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<RSIObjects xsi:noNamespaceSchemaLocation="/Roboter/Config/System/Common/Schemes/RSIContext.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<!-- =================== Signal Sources (Robot State) =================== -->
|
||||
<RSIObject ObjType="POSACT" ObjTypeID="46" ObjID="POSACT1">
|
||||
<Parameters>
|
||||
<Parameter Name="Type" ParamID="1" ParamValue="1" IsRuntime="false" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
<RSIObject ObjType="AXISACT" ObjTypeID="44" ObjID="AXISACT1">
|
||||
<Parameters>
|
||||
<Parameter Name="Type" ParamID="1" ParamValue="1" IsRuntime="false" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
<RSIObject ObjType="AXISACTEXT" ObjTypeID="69" ObjID="AXISACTEXT1">
|
||||
<Parameters>
|
||||
<Parameter Name="Type" ParamID="1" ParamValue="1" IsRuntime="false" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
<RSIObject ObjType="MOTORCURRENT" ObjTypeID="57" ObjID="MOTORCURRENT1">
|
||||
</RSIObject>
|
||||
<RSIObject ObjType="DIGIN" ObjTypeID="29" ObjID="DIGIN1">
|
||||
<Parameters>
|
||||
<Parameter Name="Index" ParamID="1" ParamValue="1" />
|
||||
<Parameter Name="DataSize" ParamID="2" ParamValue="2" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
<RSIObject ObjType="DIGOUT" ObjTypeID="43" ObjID="DIGOUT1">
|
||||
<Parameters>
|
||||
<Parameter Name="Index" ParamID="1" ParamValue="1" />
|
||||
<Parameter Name="DataSize" ParamID="2" ParamValue="0" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
<RSIObject ObjType="DIGOUT" ObjTypeID="43" ObjID="DIGOUT2">
|
||||
<Parameters>
|
||||
<Parameter Name="Index" ParamID="1" ParamValue="2" />
|
||||
<Parameter Name="DataSize" ParamID="2" ParamValue="0" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
<RSIObject ObjType="DIGOUT" ObjTypeID="43" ObjID="DIGOUT3">
|
||||
<Parameters>
|
||||
<Parameter Name="Index" ParamID="1" ParamValue="3" />
|
||||
<Parameter Name="DataSize" ParamID="2" ParamValue="0" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
<RSIObject ObjType="SOURCE" ObjTypeID="45" ObjID="SOURCE1">
|
||||
<Parameters>
|
||||
<Parameter Name="Type" ParamID="1" ParamValue="1" />
|
||||
<Parameter Name="Offset" ParamID="2" ParamValue="0" />
|
||||
<Parameter Name="Amplitude" ParamID="3" ParamValue="0" />
|
||||
<Parameter Name="Period" ParamID="4" ParamValue="0" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
<RSIObject ObjType="OV_PRO" ObjTypeID="73" ObjID="OV_PRO1">
|
||||
</RSIObject>
|
||||
<RSIObject ObjType="STATUS" ObjTypeID="72" ObjID="STATUS1">
|
||||
</RSIObject>
|
||||
|
||||
<!-- =================== Action Objects (PC → Robot) =================== -->
|
||||
<RSIObject ObjType="POSCORR" ObjTypeID="27" ObjID="POSCORR1">
|
||||
<Inputs>
|
||||
<Input InIdx="1" OutObjID="ETHERNET1" OutIdx="1" />
|
||||
<Input InIdx="2" OutObjID="ETHERNET1" OutIdx="2" />
|
||||
<Input InIdx="3" OutObjID="ETHERNET1" OutIdx="3" />
|
||||
<Input InIdx="4" OutObjID="ETHERNET1" OutIdx="4" />
|
||||
<Input InIdx="5" OutObjID="ETHERNET1" OutIdx="5" />
|
||||
<Input InIdx="6" OutObjID="ETHERNET1" OutIdx="6" />
|
||||
</Inputs>
|
||||
<Parameters>
|
||||
<Parameter Name="LowerLimX" ParamID="1" ParamValue="-500" />
|
||||
<Parameter Name="LowerLimY" ParamID="2" ParamValue="-500" />
|
||||
<Parameter Name="LowerLimZ" ParamID="3" ParamValue="-500" />
|
||||
<Parameter Name="UpperLimX" ParamID="4" ParamValue="500" />
|
||||
<Parameter Name="UpperLimY" ParamID="5" ParamValue="500" />
|
||||
<Parameter Name="UpperLimZ" ParamID="6" ParamValue="500" />
|
||||
<Parameter Name="MaxRotAngle" ParamID="7" ParamValue="500" />
|
||||
<Parameter Name="RefCorrSys" ParamID="1" ParamValue="1" IsRuntime="false" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
<RSIObject ObjType="AXISCORR" ObjTypeID="24" ObjID="AXISCORR1">
|
||||
<Inputs>
|
||||
<Input InIdx="1" OutObjID="ETHERNET1" OutIdx="7" />
|
||||
<Input InIdx="2" OutObjID="ETHERNET1" OutIdx="8" />
|
||||
<Input InIdx="3" OutObjID="ETHERNET1" OutIdx="9" />
|
||||
<Input InIdx="4" OutObjID="ETHERNET1" OutIdx="10" />
|
||||
<Input InIdx="5" OutObjID="ETHERNET1" OutIdx="11" />
|
||||
<Input InIdx="6" OutObjID="ETHERNET1" OutIdx="12" />
|
||||
</Inputs>
|
||||
<Parameters>
|
||||
<Parameter Name="LowerLimA1" ParamID="1" ParamValue="-180" />
|
||||
<Parameter Name="LowerLimA2" ParamID="2" ParamValue="-180" />
|
||||
<Parameter Name="LowerLimA3" ParamID="3" ParamValue="-180" />
|
||||
<Parameter Name="LowerLimA4" ParamID="4" ParamValue="-180" />
|
||||
<Parameter Name="LowerLimA5" ParamID="5" ParamValue="-180" />
|
||||
<Parameter Name="LowerLimA6" ParamID="6" ParamValue="-180" />
|
||||
<Parameter Name="UpperLimA1" ParamID="7" ParamValue="180" />
|
||||
<Parameter Name="UpperLimA2" ParamID="8" ParamValue="180" />
|
||||
<Parameter Name="UpperLimA3" ParamID="9" ParamValue="180" />
|
||||
<Parameter Name="UpperLimA4" ParamID="10" ParamValue="180" />
|
||||
<Parameter Name="UpperLimA5" ParamID="11" ParamValue="180" />
|
||||
<Parameter Name="UpperLimA6" ParamID="12" ParamValue="180" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
<RSIObject ObjType="MAP2DIGOUT" ObjTypeID="14" ObjID="MAP2DIGOUT1">
|
||||
<Inputs>
|
||||
<Input InIdx="1" OutObjID="ETHERNET1" OutIdx="13" />
|
||||
</Inputs>
|
||||
<Parameters>
|
||||
<Parameter Name="Index" ParamID="1" ParamValue="20" />
|
||||
<Parameter Name="DataSize" ParamID="2" ParamValue="2" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
<RSIObject ObjType="MAP2SEN_PREA" ObjTypeID="17" ObjID="MAP2SEN_PREA1">
|
||||
<Inputs>
|
||||
<Input InIdx="1" OutObjID="ETHERNET1" OutIdx="1" />
|
||||
</Inputs>
|
||||
<Parameters>
|
||||
<Parameter Name="Index" ParamID="1" ParamValue="1" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
<RSIObject ObjType="MAP2SEN_PREA" ObjTypeID="17" ObjID="MAP2SEN_PREA2">
|
||||
<Inputs>
|
||||
<Input InIdx="1" OutObjID="ETHERNET1" OutIdx="2" />
|
||||
</Inputs>
|
||||
<Parameters>
|
||||
<Parameter Name="Index" ParamID="1" ParamValue="2" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
<RSIObject ObjType="MAP2SEN_PREA" ObjTypeID="17" ObjID="MAP2SEN_PREA3">
|
||||
<Inputs>
|
||||
<Input InIdx="1" OutObjID="ETHERNET1" OutIdx="3" />
|
||||
</Inputs>
|
||||
<Parameters>
|
||||
<Parameter Name="Index" ParamID="1" ParamValue="3" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
|
||||
<!-- =================== Monitoring =================== -->
|
||||
<RSIObject ObjType="POSCORRMON" ObjTypeID="81" ObjID="POSCORRMON1">
|
||||
<Parameters>
|
||||
<Parameter Name="MaxTrans" ParamID="1" ParamValue="500" />
|
||||
<Parameter Name="MaxRotAngle" ParamID="2" ParamValue="180" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
<RSIObject ObjType="AXISCORRMON" ObjTypeID="82" ObjID="AXISCORRMON1">
|
||||
<Parameters>
|
||||
<Parameter Name="MaxA1" ParamID="1" ParamValue="180" />
|
||||
<Parameter Name="MaxA2" ParamID="2" ParamValue="180" />
|
||||
<Parameter Name="MaxA3" ParamID="3" ParamValue="180" />
|
||||
<Parameter Name="MaxA4" ParamID="4" ParamValue="180" />
|
||||
<Parameter Name="MaxA5" ParamID="5" ParamValue="180" />
|
||||
<Parameter Name="MaxA6" ParamID="6" ParamValue="180" />
|
||||
<Parameter Name="MaxE1" ParamID="7" ParamValue="180" />
|
||||
<Parameter Name="MaxE2" ParamID="8" ParamValue="180" />
|
||||
<Parameter Name="MaxE3" ParamID="9" ParamValue="180" />
|
||||
<Parameter Name="MaxE4" ParamID="10" ParamValue="180" />
|
||||
<Parameter Name="MaxE5" ParamID="11" ParamValue="180" />
|
||||
<Parameter Name="MaxE6" ParamID="12" ParamValue="180" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
|
||||
<!-- =================== ETHERNET Communication =================== -->
|
||||
<RSIObject ObjType="ETHERNET" ObjTypeID="64" ObjID="ETHERNET1">
|
||||
<Inputs>
|
||||
<Input InIdx="1" OutObjID="DIGIN1" OutIdx="1" />
|
||||
<Input InIdx="2" OutObjID="DIGOUT1" OutIdx="1" />
|
||||
<Input InIdx="3" OutObjID="DIGOUT2" OutIdx="1" />
|
||||
<Input InIdx="4" OutObjID="DIGOUT3" OutIdx="1" />
|
||||
<Input InIdx="5" OutObjID="SOURCE1" OutIdx="1" />
|
||||
<Input InIdx="13" OutObjID="POSACT1" OutIdx="1" />
|
||||
<Input InIdx="14" OutObjID="POSACT1" OutIdx="2" />
|
||||
<Input InIdx="15" OutObjID="POSACT1" OutIdx="3" />
|
||||
<Input InIdx="16" OutObjID="POSACT1" OutIdx="4" />
|
||||
<Input InIdx="17" OutObjID="POSACT1" OutIdx="5" />
|
||||
<Input InIdx="18" OutObjID="POSACT1" OutIdx="6" />
|
||||
<Input InIdx="19" OutObjID="AXISACT1" OutIdx="1" />
|
||||
<Input InIdx="20" OutObjID="AXISACT1" OutIdx="2" />
|
||||
<Input InIdx="21" OutObjID="AXISACT1" OutIdx="3" />
|
||||
<Input InIdx="22" OutObjID="AXISACT1" OutIdx="4" />
|
||||
<Input InIdx="23" OutObjID="AXISACT1" OutIdx="5" />
|
||||
<Input InIdx="24" OutObjID="AXISACT1" OutIdx="6" />
|
||||
<Input InIdx="25" OutObjID="AXISACTEXT1" OutIdx="1" />
|
||||
<Input InIdx="26" OutObjID="AXISACTEXT1" OutIdx="2" />
|
||||
<Input InIdx="27" OutObjID="AXISACTEXT1" OutIdx="3" />
|
||||
<Input InIdx="28" OutObjID="AXISACTEXT1" OutIdx="4" />
|
||||
<Input InIdx="29" OutObjID="AXISACTEXT1" OutIdx="5" />
|
||||
<Input InIdx="30" OutObjID="AXISACTEXT1" OutIdx="6" />
|
||||
<Input InIdx="31" OutObjID="MOTORCURRENT1" OutIdx="1" />
|
||||
<Input InIdx="32" OutObjID="MOTORCURRENT1" OutIdx="2" />
|
||||
<Input InIdx="33" OutObjID="MOTORCURRENT1" OutIdx="3" />
|
||||
<Input InIdx="34" OutObjID="MOTORCURRENT1" OutIdx="4" />
|
||||
<Input InIdx="35" OutObjID="MOTORCURRENT1" OutIdx="5" />
|
||||
<Input InIdx="36" OutObjID="MOTORCURRENT1" OutIdx="6" />
|
||||
<Input InIdx="37" OutObjID="OV_PRO1" OutIdx="1" />
|
||||
<Input InIdx="38" OutObjID="STATUS1" OutIdx="1" />
|
||||
</Inputs>
|
||||
<Parameters>
|
||||
<Parameter Name="ConfigFile" ParamID="1" ParamValue="RSI_EthernetConfig_Full.xml" IsRuntime="false" />
|
||||
<Parameter Name="Timeout" ParamID="1" ParamValue="100" />
|
||||
<Parameter Name="Flag" ParamID="4" ParamValue="1" />
|
||||
<Parameter Name="Precision" ParamID="8" ParamValue="1" />
|
||||
</Parameters>
|
||||
</RSIObject>
|
||||
</RSIObjects>
|
||||
@ -1,207 +0,0 @@
|
||||
&H NOBOUNDSCHECK
|
||||
DEF RSIPI_Test()
|
||||
; =========================================================================
|
||||
; RSIPI Comprehensive Test Program
|
||||
; =========================================================================
|
||||
; Tests all RSIPI Python library functionality:
|
||||
; 1. RSI initialisation and connection
|
||||
; 2. Cartesian correction (RSI_MOVECORR)
|
||||
; 3. Tech variable exchange (Python <-> KRL)
|
||||
; 4. $SEN_PREA variable reading
|
||||
; 5. Digital I/O coordination
|
||||
; 6. Handshake patterns (wait for Python, signal back)
|
||||
;
|
||||
; Matching Python script: rsi_config/rsipi_test.py
|
||||
;
|
||||
; Protocol (Tech.C11 = state from KRL, Tech.T11 = command from Python):
|
||||
; State 0: Idle
|
||||
; State 1: RSI connected, waiting for Python
|
||||
; State 2: Running corrections (RSI_MOVECORR active)
|
||||
; State 3: Corrections complete, reading SEN_PREA
|
||||
; State 4: I/O test phase
|
||||
; State 5: Complete
|
||||
; State 99: Error
|
||||
;
|
||||
; Python commands via Tech.T11:
|
||||
; 0: No command
|
||||
; 1: Python ready, start corrections
|
||||
; 2: Stop corrections
|
||||
; 3: SEN_PREA values written, read them
|
||||
; 4: Start I/O test
|
||||
; 5: Shutdown
|
||||
; =========================================================================
|
||||
|
||||
DECL INT ret, CONTID
|
||||
DECL INT python_cmd
|
||||
DECL REAL sen_val1, sen_val2, sen_val3
|
||||
DECL E6POS start_pos
|
||||
|
||||
INI
|
||||
|
||||
; -- Store start position ------------------------------------------------
|
||||
start_pos = $POS_ACT
|
||||
|
||||
; -- Move to a safe starting position ------------------------------------
|
||||
; (Adjust these coordinates for your robot/cell)
|
||||
PTP start_pos
|
||||
|
||||
; ========================================================================
|
||||
; PHASE 1: Initialise RSI
|
||||
; ========================================================================
|
||||
|
||||
; Load RSI signal flow configuration
|
||||
ret = RSI_CREATE("RSIPI_Full.rsi", CONTID, TRUE)
|
||||
IF (ret <> RSIOK) THEN
|
||||
MsgNotify("RSI_CREATE failed", "RSIPI_Test")
|
||||
HALT
|
||||
ENDIF
|
||||
|
||||
; Activate RSI in RELATIVE mode at 4ms cycle
|
||||
; Change to #ABSOLUTE / #IPO as needed
|
||||
ret = RSI_ON(#RELATIVE, #IPO_FAST)
|
||||
IF (ret <> RSIOK) THEN
|
||||
MsgNotify("RSI_ON failed", "RSIPI_Test")
|
||||
HALT
|
||||
ENDIF
|
||||
|
||||
; Signal state 1: RSI connected, waiting for Python
|
||||
$TECH.C[11] = 1
|
||||
MsgNotify("RSI active - waiting for Python...", "RSIPI_Test")
|
||||
|
||||
; ========================================================================
|
||||
; PHASE 2: Wait for Python to connect and signal ready
|
||||
; ========================================================================
|
||||
|
||||
; Poll Tech.T11 for Python's "ready" command (value = 1)
|
||||
python_cmd = 0
|
||||
WHILE (python_cmd <> 1)
|
||||
python_cmd = $TECH.T[11]
|
||||
WAIT SEC 0.012 ; Check every 12ms
|
||||
ENDWHILE
|
||||
|
||||
MsgNotify("Python connected - starting corrections", "RSIPI_Test")
|
||||
|
||||
; Send current position to Python via Tech.C12-C17
|
||||
$TECH.C[12] = $POS_ACT.X
|
||||
$TECH.C[13] = $POS_ACT.Y
|
||||
$TECH.C[14] = $POS_ACT.Z
|
||||
$TECH.C[15] = $POS_ACT.A
|
||||
$TECH.C[16] = $POS_ACT.B
|
||||
$TECH.C[17] = $POS_ACT.C
|
||||
|
||||
; ========================================================================
|
||||
; PHASE 3: Sensor-guided motion (Python sends corrections)
|
||||
; ========================================================================
|
||||
|
||||
; Signal state 2: corrections active
|
||||
$TECH.C[11] = 2
|
||||
|
||||
; RSI_MOVECORR - robot is now purely controlled by Python corrections
|
||||
; The robot will hold position and apply RKorr corrections from Python
|
||||
; Python sends corrections via api.motion.update_cartesian()
|
||||
; This blocks until Python sends stop command (Tech.T11 = 2)
|
||||
; or until RSI is turned off
|
||||
RSI_MOVECORR()
|
||||
|
||||
MsgNotify("Corrections phase complete", "RSIPI_Test")
|
||||
|
||||
; ========================================================================
|
||||
; PHASE 4: Read $SEN_PREA values from Python
|
||||
; ========================================================================
|
||||
|
||||
; Signal state 3: ready to read SEN_PREA
|
||||
$TECH.C[11] = 3
|
||||
|
||||
; Wait for Python to write SEN_PREA values (command = 3)
|
||||
python_cmd = 0
|
||||
WHILE (python_cmd <> 3)
|
||||
python_cmd = $TECH.T[11]
|
||||
WAIT SEC 0.012
|
||||
ENDWHILE
|
||||
|
||||
; Read values that Python wrote via MAP2SEN_PREA
|
||||
sen_val1 = $SEN_PREA[1]
|
||||
sen_val2 = $SEN_PREA[2]
|
||||
sen_val3 = $SEN_PREA[3]
|
||||
|
||||
; Echo them back to Python via Tech.C18-C20
|
||||
$TECH.C[18] = sen_val1
|
||||
$TECH.C[19] = sen_val2
|
||||
$TECH.C[110] = sen_val3
|
||||
|
||||
MsgNotify("SEN_PREA read complete", "RSIPI_Test")
|
||||
|
||||
; ========================================================================
|
||||
; PHASE 5: Digital I/O test
|
||||
; ========================================================================
|
||||
|
||||
; Signal state 4: I/O test phase
|
||||
$TECH.C[11] = 4
|
||||
|
||||
; Wait for Python to start I/O test (command = 4)
|
||||
python_cmd = 0
|
||||
WHILE (python_cmd <> 4)
|
||||
python_cmd = $TECH.T[11]
|
||||
WAIT SEC 0.012
|
||||
ENDWHILE
|
||||
|
||||
; Activate gripper (digital output 1)
|
||||
$OUT[1] = TRUE
|
||||
MsgNotify("Gripper ON - $OUT[1] = TRUE", "RSIPI_Test")
|
||||
WAIT SEC 1.0
|
||||
|
||||
; Python should see Digout.o1 = TRUE in its send_variables
|
||||
; Signal to Python that gripper is on
|
||||
$TECH.C[11] = 41 ; Sub-state: gripper activated
|
||||
|
||||
; Wait for Python acknowledgement (command = 41)
|
||||
python_cmd = 0
|
||||
WHILE (python_cmd <> 41)
|
||||
python_cmd = $TECH.T[11]
|
||||
WAIT SEC 0.012
|
||||
ENDWHILE
|
||||
|
||||
; Deactivate gripper
|
||||
$OUT[1] = FALSE
|
||||
MsgNotify("Gripper OFF - $OUT[1] = FALSE", "RSIPI_Test")
|
||||
WAIT SEC 0.5
|
||||
|
||||
; Signal gripper off
|
||||
$TECH.C[11] = 42 ; Sub-state: gripper deactivated
|
||||
|
||||
; Wait for Python acknowledgement
|
||||
python_cmd = 0
|
||||
WHILE (python_cmd <> 42)
|
||||
python_cmd = $TECH.T[11]
|
||||
WAIT SEC 0.012
|
||||
ENDWHILE
|
||||
|
||||
; ========================================================================
|
||||
; PHASE 6: Shutdown
|
||||
; ========================================================================
|
||||
|
||||
; Signal state 5: complete
|
||||
$TECH.C[11] = 5
|
||||
MsgNotify("Test complete - shutting down RSI", "RSIPI_Test")
|
||||
|
||||
; Wait for Python to acknowledge shutdown (command = 5)
|
||||
python_cmd = 0
|
||||
WHILE (python_cmd <> 5)
|
||||
python_cmd = $TECH.T[11]
|
||||
WAIT SEC 0.012
|
||||
ENDWHILE
|
||||
|
||||
; Clean up RSI
|
||||
ret = RSI_OFF()
|
||||
IF (ret <> RSIOK) THEN
|
||||
MsgNotify("RSI_OFF warning", "RSIPI_Test")
|
||||
ENDIF
|
||||
|
||||
ret = RSI_DELETE(CONTID)
|
||||
|
||||
; Return to start
|
||||
PTP start_pos
|
||||
|
||||
MsgNotify("RSIPI_Test complete!", "RSIPI_Test")
|
||||
|
||||
END
|
||||
@ -1,159 +0,0 @@
|
||||
<ROOT>
|
||||
<CONFIG>
|
||||
<IP_NUMBER>10.10.10.10</IP_NUMBER>
|
||||
<PORT>64000</PORT>
|
||||
<SENTYPE>ImFree</SENTYPE>
|
||||
<ONLYSEND>FALSE</ONLYSEND>
|
||||
</CONFIG>
|
||||
|
||||
<!-- =================================================================
|
||||
RSI Channel Budget: 64 max across SEND + RECEIVE
|
||||
INTERNAL tags don't count toward the 64-channel limit
|
||||
|
||||
SEND channels used: 38 (DiL, Digout x3, Source1, PosAct x6,
|
||||
AxisAct x6, ExtAct x6, MotCur x6,
|
||||
OvPro, Status)
|
||||
RECEIVE channels used: 13 (RKorr x6, AKorr x6, DiO)
|
||||
Total: 51 / 64
|
||||
|
||||
All DEF_ tags are INTERNAL (free)
|
||||
================================================================= -->
|
||||
|
||||
<!-- ===================== SEND: Robot to PC ========================= -->
|
||||
<SEND>
|
||||
<ELEMENTS>
|
||||
<!-- INTERNAL: Cartesian actual position (expanded to X,Y,Z,A,B,C) -->
|
||||
<ELEMENT TAG="DEF_RIst" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- INTERNAL: Cartesian setpoint position -->
|
||||
<ELEMENT TAG="DEF_RSol" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- INTERNAL: Robot axis actual positions (A1-A6 in deg) -->
|
||||
<ELEMENT TAG="DEF_AIPos" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- INTERNAL: Robot axis setpoint positions (A1-A6 in deg) -->
|
||||
<ELEMENT TAG="DEF_ASPos" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- INTERNAL: External axis actual positions (E1-E6) -->
|
||||
<ELEMENT TAG="DEF_EIPos" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- INTERNAL: External axis setpoint positions (E1-E6) -->
|
||||
<ELEMENT TAG="DEF_ESPos" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- INTERNAL: Robot motor currents (A1-A6, % of max) -->
|
||||
<ELEMENT TAG="DEF_MACur" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- INTERNAL: External motor currents (E1-E6, % of max) -->
|
||||
<ELEMENT TAG="DEF_MECur" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- INTERNAL: Late packet counter -->
|
||||
<ELEMENT TAG="DEF_Delay" TYPE="LONG" INDX="INTERNAL" />
|
||||
|
||||
<!-- INTERNAL: Tech channels -->
|
||||
<ELEMENT TAG="DEF_Tech.C1" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.C2" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.C3" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.C4" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.C5" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.C6" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.T1" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.T2" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.T3" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.T4" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.T5" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
<ELEMENT TAG="DEF_Tech.T6" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
|
||||
<!-- Channel 1: Digital input latch (from DIGIN1) -->
|
||||
<ELEMENT TAG="DiL" TYPE="LONG" INDX="1" />
|
||||
|
||||
<!-- Channels 2-4: Digital output readback (from DIGOUT1-3) -->
|
||||
<ELEMENT TAG="Digout.o1" TYPE="BOOL" INDX="2" />
|
||||
<ELEMENT TAG="Digout.o2" TYPE="BOOL" INDX="3" />
|
||||
<ELEMENT TAG="Digout.o3" TYPE="BOOL" INDX="4" />
|
||||
|
||||
<!-- Channel 5: Signal source (from SOURCE1) -->
|
||||
<ELEMENT TAG="Source1" TYPE="DOUBLE" INDX="5" />
|
||||
|
||||
<!-- Channels 13-18: Cartesian actual position (from POSACT1) -->
|
||||
<ELEMENT TAG="PosAct.X" TYPE="DOUBLE" INDX="13" />
|
||||
<ELEMENT TAG="PosAct.Y" TYPE="DOUBLE" INDX="14" />
|
||||
<ELEMENT TAG="PosAct.Z" TYPE="DOUBLE" INDX="15" />
|
||||
<ELEMENT TAG="PosAct.A" TYPE="DOUBLE" INDX="16" />
|
||||
<ELEMENT TAG="PosAct.B" TYPE="DOUBLE" INDX="17" />
|
||||
<ELEMENT TAG="PosAct.C" TYPE="DOUBLE" INDX="18" />
|
||||
|
||||
<!-- Channels 19-24: Joint axis actual positions (from AXISACT1) -->
|
||||
<ELEMENT TAG="AxisAct.A1" TYPE="DOUBLE" INDX="19" />
|
||||
<ELEMENT TAG="AxisAct.A2" TYPE="DOUBLE" INDX="20" />
|
||||
<ELEMENT TAG="AxisAct.A3" TYPE="DOUBLE" INDX="21" />
|
||||
<ELEMENT TAG="AxisAct.A4" TYPE="DOUBLE" INDX="22" />
|
||||
<ELEMENT TAG="AxisAct.A5" TYPE="DOUBLE" INDX="23" />
|
||||
<ELEMENT TAG="AxisAct.A6" TYPE="DOUBLE" INDX="24" />
|
||||
|
||||
<!-- Channels 25-30: External axis actual positions (from AXISACTEXT1) -->
|
||||
<ELEMENT TAG="ExtAct.E1" TYPE="DOUBLE" INDX="25" />
|
||||
<ELEMENT TAG="ExtAct.E2" TYPE="DOUBLE" INDX="26" />
|
||||
<ELEMENT TAG="ExtAct.E3" TYPE="DOUBLE" INDX="27" />
|
||||
<ELEMENT TAG="ExtAct.E4" TYPE="DOUBLE" INDX="28" />
|
||||
<ELEMENT TAG="ExtAct.E5" TYPE="DOUBLE" INDX="29" />
|
||||
<ELEMENT TAG="ExtAct.E6" TYPE="DOUBLE" INDX="30" />
|
||||
|
||||
<!-- Channels 31-36: Motor currents (from MOTORCURRENT1) -->
|
||||
<ELEMENT TAG="MotCur.A1" TYPE="DOUBLE" INDX="31" />
|
||||
<ELEMENT TAG="MotCur.A2" TYPE="DOUBLE" INDX="32" />
|
||||
<ELEMENT TAG="MotCur.A3" TYPE="DOUBLE" INDX="33" />
|
||||
<ELEMENT TAG="MotCur.A4" TYPE="DOUBLE" INDX="34" />
|
||||
<ELEMENT TAG="MotCur.A5" TYPE="DOUBLE" INDX="35" />
|
||||
<ELEMENT TAG="MotCur.A6" TYPE="DOUBLE" INDX="36" />
|
||||
|
||||
<!-- Channel 37: Program override percentage (from OV_PRO1) -->
|
||||
<ELEMENT TAG="OvPro" TYPE="DOUBLE" INDX="37" />
|
||||
|
||||
<!-- Channel 38: Robot status (from STATUS1) -->
|
||||
<ELEMENT TAG="Status" TYPE="LONG" INDX="38" />
|
||||
</ELEMENTS>
|
||||
</SEND>
|
||||
|
||||
<!-- =================== RECEIVE: PC to Robot ======================== -->
|
||||
<RECEIVE>
|
||||
<ELEMENTS>
|
||||
<!-- INTERNAL: Status/error string to robot -->
|
||||
<ELEMENT TAG="DEF_EStr" TYPE="STRING" INDX="INTERNAL" />
|
||||
|
||||
<!-- INTERNAL: Tech channels (advance parameters, PC to robot) -->
|
||||
<ELEMENT TAG="DEF_Tech.T1" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.T2" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.T3" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.T4" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.T5" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.T6" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
|
||||
<!-- INTERNAL: Tech channels (main run parameters, PC to robot) -->
|
||||
<ELEMENT TAG="DEF_Tech.C1" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.C2" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.C3" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.C4" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.C5" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
<ELEMENT TAG="DEF_Tech.C6" TYPE="DOUBLE" INDX="INTERNAL" HOLDON="0" />
|
||||
|
||||
<!-- Channels 1-6: Cartesian corrections (to POSCORR1, HOLDON keeps last value) -->
|
||||
<ELEMENT TAG="RKorr.X" TYPE="DOUBLE" INDX="1" HOLDON="1" />
|
||||
<ELEMENT TAG="RKorr.Y" TYPE="DOUBLE" INDX="2" HOLDON="1" />
|
||||
<ELEMENT TAG="RKorr.Z" TYPE="DOUBLE" INDX="3" HOLDON="1" />
|
||||
<ELEMENT TAG="RKorr.A" TYPE="DOUBLE" INDX="4" HOLDON="1" />
|
||||
<ELEMENT TAG="RKorr.B" TYPE="DOUBLE" INDX="5" HOLDON="1" />
|
||||
<ELEMENT TAG="RKorr.C" TYPE="DOUBLE" INDX="6" HOLDON="1" />
|
||||
|
||||
<!-- Channels 7-12: Joint corrections (to AXISCORR1) -->
|
||||
<ELEMENT TAG="AKorr.A1" TYPE="DOUBLE" INDX="7" HOLDON="1" />
|
||||
<ELEMENT TAG="AKorr.A2" TYPE="DOUBLE" INDX="8" HOLDON="1" />
|
||||
<ELEMENT TAG="AKorr.A3" TYPE="DOUBLE" INDX="9" HOLDON="1" />
|
||||
<ELEMENT TAG="AKorr.A4" TYPE="DOUBLE" INDX="10" HOLDON="1" />
|
||||
<ELEMENT TAG="AKorr.A5" TYPE="DOUBLE" INDX="11" HOLDON="1" />
|
||||
<ELEMENT TAG="AKorr.A6" TYPE="DOUBLE" INDX="12" HOLDON="1" />
|
||||
|
||||
<!-- Channel 13: Digital output word (to MAP2DIGOUT1) -->
|
||||
<ELEMENT TAG="DiO" TYPE="LONG" INDX="13" HOLDON="1" />
|
||||
</ELEMENTS>
|
||||
</RECEIVE>
|
||||
</ROOT>
|
||||
@ -1,196 +0,0 @@
|
||||
"""
|
||||
RSIPI Comprehensive Test Script
|
||||
================================
|
||||
Matching Python counterpart for RSIPI_Test.src KRL program.
|
||||
Tests all RSIPI functionality in coordination with the robot.
|
||||
|
||||
Protocol (Tech.C11 = state from KRL, Tech.T11 = command from Python):
|
||||
KRL States: 0=Idle, 1=Waiting, 2=Corrections, 3=SEN_PREA, 4=I/O, 5=Done
|
||||
Python Cmds: 1=Ready, 2=Stop, 3=SEN_PREA written, 4=Start I/O, 5=Shutdown
|
||||
|
||||
Usage:
|
||||
1. Load RSIPI_Test.src on the robot controller
|
||||
2. Run this script: python rsipi_test.py
|
||||
3. Start the KRL program on the pendant
|
||||
"""
|
||||
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
from multiprocessing import freeze_support
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
|
||||
from RSIPI import RSIAPI
|
||||
|
||||
# ── Helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
def wait_for_state(api, state, timeout=30):
|
||||
"""Wait for KRL to reach a specific state via Tech.C11."""
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
try:
|
||||
krl_state = int(api.krl.read_param('C11'))
|
||||
if krl_state == state:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.05)
|
||||
print(f" TIMEOUT waiting for KRL state {state}")
|
||||
return False
|
||||
|
||||
|
||||
def send_command(api, cmd):
|
||||
"""Send a command to KRL via Tech.T11."""
|
||||
api.krl.write_param('T11', cmd)
|
||||
print(f" -> Sent command: {cmd}")
|
||||
|
||||
|
||||
# ── Main Test Sequence ───────────────────────────────────────────────────
|
||||
|
||||
if __name__ == '__main__':
|
||||
freeze_support()
|
||||
|
||||
api = RSIAPI(
|
||||
os.path.join(os.path.dirname(__file__), '..', 'RSI_EthernetConfig_Full.xml'),
|
||||
rsi_mode='relative',
|
||||
max_cartesian_rate=0.5,
|
||||
max_joint_rate=0.2,
|
||||
cycle_time=0.004
|
||||
)
|
||||
|
||||
print("=" * 60)
|
||||
print("RSIPI Comprehensive Test")
|
||||
print("=" * 60)
|
||||
|
||||
# ── Start RSI and wait for robot ────────────────────────────────
|
||||
print("\n[1] Starting RSI connection...")
|
||||
api.start()
|
||||
if not api.wait_for_connection(timeout=30):
|
||||
print(" FAILED: No connection. Is the KRL program running?")
|
||||
api.stop()
|
||||
sys.exit(1)
|
||||
print(f" Connected! IPOC: {api.monitoring.get_ipoc()}")
|
||||
|
||||
# ── Wait for KRL to reach state 1 (RSI active, waiting) ────────
|
||||
print("\n[2] Waiting for KRL program to initialise RSI...")
|
||||
if not wait_for_state(api, 1):
|
||||
print(" FAILED: KRL did not reach state 1")
|
||||
api.stop()
|
||||
sys.exit(1)
|
||||
print(" KRL is ready and waiting for us")
|
||||
|
||||
# Read the position KRL sent us
|
||||
try:
|
||||
pos_x = api.krl.read_param('C12')
|
||||
pos_y = api.krl.read_param('C13')
|
||||
pos_z = api.krl.read_param('C14')
|
||||
print(f" Robot position from KRL: X={pos_x:.1f} Y={pos_y:.1f} Z={pos_z:.1f}")
|
||||
except Exception as e:
|
||||
print(f" Could not read position: {e}")
|
||||
|
||||
# ── Signal ready and start corrections ──────────────────────────
|
||||
print("\n[3] Signalling ready, starting correction phase...")
|
||||
send_command(api, 1)
|
||||
|
||||
if not wait_for_state(api, 2):
|
||||
print(" FAILED: KRL did not enter correction mode")
|
||||
api.stop()
|
||||
sys.exit(1)
|
||||
print(" KRL is in RSI_MOVECORR - sending corrections...")
|
||||
|
||||
# Send a small circle pattern as corrections
|
||||
circle = api.motion.generate_circle(
|
||||
center={"X": 0, "Y": 0, "Z": 0},
|
||||
radius=3, steps=100)
|
||||
|
||||
# Convert to relative deltas
|
||||
circle_rel = []
|
||||
prev = circle[0]
|
||||
for pt in circle[1:]:
|
||||
delta = {k: pt[k] - prev.get(k, 0) for k in pt}
|
||||
circle_rel.append(delta)
|
||||
prev = pt
|
||||
|
||||
print(f" Executing circle: {len(circle_rel)} steps, radius=3mm")
|
||||
api.motion.execute_trajectory(circle_rel, space="cartesian", rate=0.012)
|
||||
print(" Circle complete!")
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
# Tell KRL to stop corrections
|
||||
print(" Stopping corrections...")
|
||||
send_command(api, 2)
|
||||
time.sleep(1)
|
||||
|
||||
# ── SEN_PREA test ───────────────────────────────────────────────
|
||||
print("\n[4] Testing SEN_PREA variable exchange...")
|
||||
if not wait_for_state(api, 3):
|
||||
print(" FAILED: KRL did not reach SEN_PREA phase")
|
||||
api.stop()
|
||||
sys.exit(1)
|
||||
|
||||
# Write test values to SEN_PREA via the corrections
|
||||
# (MAP2SEN_PREA in the RSI config maps ETHERNET Out1-3 to SEN_PREA[1-3])
|
||||
# These go through RKorr.X/Y/Z → ETHERNET Out1-3 → MAP2SEN_PREA
|
||||
test_vals = [42.0, 123.456, -99.9]
|
||||
print(f" Writing SEN_PREA test values: {test_vals}")
|
||||
api.motion.update_cartesian(X=test_vals[0], Y=test_vals[1], Z=test_vals[2])
|
||||
time.sleep(0.5)
|
||||
|
||||
# Signal KRL to read them
|
||||
send_command(api, 3)
|
||||
time.sleep(1)
|
||||
|
||||
# Read back what KRL echoed via Tech.C18-C110
|
||||
try:
|
||||
echo1 = api.krl.read_param('C18')
|
||||
echo2 = api.krl.read_param('C19')
|
||||
echo3 = api.krl.read_param('C110')
|
||||
print(f" KRL echoed back: [{echo1}, {echo2}, {echo3}]")
|
||||
print(f" Match: {abs(echo1 - test_vals[0]) < 0.1 and abs(echo2 - test_vals[1]) < 0.1}")
|
||||
except Exception as e:
|
||||
print(f" Could not read echo values: {e}")
|
||||
|
||||
# Zero corrections
|
||||
api.motion.update_cartesian(X=0, Y=0, Z=0)
|
||||
|
||||
# ── Digital I/O test ────────────────────────────────────────────
|
||||
print("\n[5] Testing Digital I/O coordination...")
|
||||
if not wait_for_state(api, 4, timeout=10):
|
||||
print(" Skipping I/O test (KRL not in I/O phase)")
|
||||
else:
|
||||
send_command(api, 4)
|
||||
|
||||
# Wait for KRL to activate gripper (state 41)
|
||||
if wait_for_state(api, 41, timeout=10):
|
||||
# Read digital output state from robot
|
||||
live = api.monitoring.get_live_data()
|
||||
print(f" KRL activated gripper ($OUT[1])")
|
||||
print(f" Live position: {live['position']}")
|
||||
|
||||
# Acknowledge
|
||||
send_command(api, 41)
|
||||
|
||||
# Wait for KRL to deactivate (state 42)
|
||||
if wait_for_state(api, 42, timeout=10):
|
||||
print(f" KRL deactivated gripper ($OUT[1])")
|
||||
send_command(api, 42)
|
||||
else:
|
||||
print(" TIMEOUT waiting for gripper off")
|
||||
else:
|
||||
print(" TIMEOUT waiting for gripper on")
|
||||
|
||||
# ── Shutdown ────────────────────────────────────────────────────
|
||||
print("\n[6] Shutting down...")
|
||||
if wait_for_state(api, 5, timeout=10):
|
||||
send_command(api, 5)
|
||||
print(" KRL acknowledged shutdown")
|
||||
else:
|
||||
print(" KRL did not reach shutdown state, stopping anyway")
|
||||
|
||||
time.sleep(1)
|
||||
api.stop()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("RSIPI Test Complete!")
|
||||
print("=" * 60)
|
||||
@ -251,8 +251,6 @@ Requires-Dist: numpy>=1.22
|
||||
Requires-Dist: matplotlib>=3.5
|
||||
Requires-Dist: lxml>=4.9
|
||||
Requires-Dist: scipy>=1.8
|
||||
Provides-Extra: dev
|
||||
Requires-Dist: pytest>=7.0; extra == "dev"
|
||||
Dynamic: author
|
||||
Dynamic: license-file
|
||||
Dynamic: requires-python
|
||||
|
||||
@ -4,20 +4,12 @@ README.md
|
||||
pyproject.toml
|
||||
setup.py
|
||||
src/RSIPI/__init__.py
|
||||
src/RSIPI/auto_reconnect.py
|
||||
src/RSIPI/config_parser.py
|
||||
src/RSIPI/diagnostics_api.py
|
||||
src/RSIPI/echo_server_gui.py
|
||||
src/RSIPI/exceptions.py
|
||||
src/RSIPI/inject_rsi_to_krl.py
|
||||
src/RSIPI/io_api.py
|
||||
src/RSIPI/krl_api.py
|
||||
src/RSIPI/krl_to_csv_parser.py
|
||||
src/RSIPI/kuka_visualiser.py
|
||||
src/RSIPI/live_plotter.py
|
||||
src/RSIPI/logging_api.py
|
||||
src/RSIPI/monitoring_api.py
|
||||
src/RSIPI/motion_api.py
|
||||
src/RSIPI/network_handler.py
|
||||
src/RSIPI/rsi_api.py
|
||||
src/RSIPI/rsi_cli.py
|
||||
@ -26,19 +18,13 @@ src/RSIPI/rsi_config.py
|
||||
src/RSIPI/rsi_echo_server.py
|
||||
src/RSIPI/rsi_graphing.py
|
||||
src/RSIPI/rsi_limit_parser.py
|
||||
src/RSIPI/safety_api.py
|
||||
src/RSIPI/safety_manager.py
|
||||
src/RSIPI/static_plotter.py
|
||||
src/RSIPI/timing_metrics.py
|
||||
src/RSIPI/tools_api.py
|
||||
src/RSIPI/trajectory_planner.py
|
||||
src/RSIPI/viz_api.py
|
||||
src/RSIPI/xml_handler.py
|
||||
src/RSIPI.egg-info/PKG-INFO
|
||||
src/RSIPI.egg-info/SOURCES.txt
|
||||
src/RSIPI.egg-info/dependency_links.txt
|
||||
src/RSIPI.egg-info/requires.txt
|
||||
src/RSIPI.egg-info/top_level.txt
|
||||
tests/test_safety_manager.py
|
||||
tests/test_trajectory_planner.py
|
||||
tests/test_xml_handler.py
|
||||
tests/test_rsipi.py
|
||||
@ -3,6 +3,3 @@ numpy>=1.22
|
||||
matplotlib>=3.5
|
||||
lxml>=4.9
|
||||
scipy>=1.8
|
||||
|
||||
[dev]
|
||||
pytest>=7.0
|
||||
|
||||
@ -1,236 +0,0 @@
|
||||
"""
|
||||
Auto-reconnection manager for RSI network reliability.
|
||||
|
||||
Monitors network health and automatically reconnects when communication
|
||||
is lost, with configurable retry logic and backoff strategies.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
import threading
|
||||
from typing import Optional, Callable, TYPE_CHECKING
|
||||
from enum import Enum, auto
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .rsi_client import RSIClient
|
||||
|
||||
|
||||
class ReconnectStrategy(Enum):
|
||||
"""Reconnection strategy options."""
|
||||
IMMEDIATE = auto() # Reconnect immediately
|
||||
LINEAR_BACKOFF = auto() # Increase delay linearly
|
||||
EXPONENTIAL_BACKOFF = auto() # Double delay each retry
|
||||
|
||||
|
||||
class AutoReconnectManager:
|
||||
"""
|
||||
Automatic reconnection manager for RSI communication.
|
||||
|
||||
Monitors network health via watchdog timer and automatically
|
||||
attempts reconnection when communication is lost.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
client: 'RSIClient',
|
||||
enabled: bool = True,
|
||||
check_interval: float = 2.0,
|
||||
max_retries: int = 5,
|
||||
retry_delay: float = 5.0,
|
||||
strategy: ReconnectStrategy = ReconnectStrategy.LINEAR_BACKOFF,
|
||||
on_reconnect: Optional[Callable] = None,
|
||||
on_failure: Optional[Callable] = None,
|
||||
):
|
||||
"""
|
||||
Initialize auto-reconnect manager.
|
||||
|
||||
Args:
|
||||
client: RSIClient instance to monitor
|
||||
enabled: Whether auto-reconnect is enabled
|
||||
check_interval: How often to check health (seconds)
|
||||
max_retries: Maximum reconnection attempts (0 = unlimited)
|
||||
retry_delay: Base delay between retries (seconds)
|
||||
strategy: Reconnection strategy (IMMEDIATE, LINEAR_BACKOFF, EXPONENTIAL_BACKOFF)
|
||||
on_reconnect: Optional callback called after successful reconnect
|
||||
on_failure: Optional callback called when max retries exceeded
|
||||
"""
|
||||
self.client = client
|
||||
self.enabled = enabled
|
||||
self.check_interval = check_interval
|
||||
self.max_retries = max_retries
|
||||
self.retry_delay = retry_delay
|
||||
self.strategy = strategy
|
||||
self.on_reconnect = on_reconnect
|
||||
self.on_failure = on_failure
|
||||
|
||||
self._monitor_thread: Optional[threading.Thread] = None
|
||||
self._stop_event = threading.Event()
|
||||
self._running = False
|
||||
|
||||
# Statistics
|
||||
self.total_reconnects = 0
|
||||
self.failed_reconnects = 0
|
||||
self.last_reconnect_time: Optional[float] = None
|
||||
|
||||
def start(self) -> None:
|
||||
"""Start the auto-reconnect monitor thread."""
|
||||
if self._running:
|
||||
logging.warning("Auto-reconnect manager already running")
|
||||
return
|
||||
|
||||
if not self.enabled:
|
||||
logging.info("Auto-reconnect is disabled")
|
||||
return
|
||||
|
||||
self._stop_event.clear()
|
||||
self._running = True
|
||||
self._monitor_thread = threading.Thread(target=self._monitor_loop, daemon=True)
|
||||
self._monitor_thread.start()
|
||||
logging.info("Auto-reconnect manager started")
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Stop the auto-reconnect monitor thread."""
|
||||
if not self._running:
|
||||
return
|
||||
|
||||
self._running = False
|
||||
self._stop_event.set()
|
||||
|
||||
if self._monitor_thread and self._monitor_thread.is_alive():
|
||||
self._monitor_thread.join(timeout=5)
|
||||
|
||||
logging.info("Auto-reconnect manager stopped")
|
||||
|
||||
def _monitor_loop(self) -> None:
|
||||
"""Main monitoring loop (runs in background thread)."""
|
||||
while not self._stop_event.is_set():
|
||||
try:
|
||||
# Check if watchdog has timed out
|
||||
if hasattr(self.client, 'metrics_dict'):
|
||||
metrics = dict(self.client.metrics_dict)
|
||||
watchdog_timeout = metrics.get('watchdog_timeout', False)
|
||||
|
||||
if watchdog_timeout and self.client.is_running():
|
||||
logging.error("Watchdog timeout detected - initiating auto-reconnect")
|
||||
self._attempt_reconnection()
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Error in auto-reconnect monitor: {e}")
|
||||
|
||||
# Sleep with interruptible wait
|
||||
self._stop_event.wait(self.check_interval)
|
||||
|
||||
def _attempt_reconnection(self) -> bool:
|
||||
"""
|
||||
Attempt to reconnect with configured retry logic.
|
||||
|
||||
Returns:
|
||||
True if reconnection successful, False otherwise
|
||||
"""
|
||||
retry_count = 0
|
||||
current_delay = self.retry_delay
|
||||
|
||||
while True:
|
||||
# Check if we've exceeded max retries
|
||||
if self.max_retries > 0 and retry_count >= self.max_retries:
|
||||
logging.error(f"Max reconnection retries ({self.max_retries}) exceeded")
|
||||
self.failed_reconnects += 1
|
||||
if self.on_failure:
|
||||
try:
|
||||
self.on_failure()
|
||||
except Exception as e:
|
||||
logging.error(f"Error in on_failure callback: {e}")
|
||||
return False
|
||||
|
||||
retry_count += 1
|
||||
logging.info(f"Reconnection attempt {retry_count}/{self.max_retries if self.max_retries > 0 else '∞'}")
|
||||
|
||||
try:
|
||||
# Attempt reconnect
|
||||
self.client.reconnect()
|
||||
|
||||
# Wait a moment for connection to stabilize
|
||||
time.sleep(2)
|
||||
|
||||
# Verify connection is working
|
||||
if self._verify_connection():
|
||||
logging.info(f"✅ Reconnection successful after {retry_count} attempt(s)")
|
||||
self.total_reconnects += 1
|
||||
self.last_reconnect_time = time.time()
|
||||
|
||||
if self.on_reconnect:
|
||||
try:
|
||||
self.on_reconnect()
|
||||
except Exception as e:
|
||||
logging.error(f"Error in on_reconnect callback: {e}")
|
||||
|
||||
return True
|
||||
else:
|
||||
logging.warning("Reconnection completed but connection verification failed")
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Reconnection attempt {retry_count} failed: {e}")
|
||||
|
||||
# Calculate delay for next retry based on strategy
|
||||
if self.strategy == ReconnectStrategy.IMMEDIATE:
|
||||
delay = 0
|
||||
elif self.strategy == ReconnectStrategy.LINEAR_BACKOFF:
|
||||
delay = self.retry_delay * retry_count
|
||||
elif self.strategy == ReconnectStrategy.EXPONENTIAL_BACKOFF:
|
||||
delay = self.retry_delay * (2 ** (retry_count - 1))
|
||||
else:
|
||||
delay = self.retry_delay
|
||||
|
||||
if delay > 0:
|
||||
logging.info(f"Waiting {delay:.1f}s before next reconnection attempt...")
|
||||
self._stop_event.wait(delay)
|
||||
|
||||
# Check if we were stopped during the wait
|
||||
if self._stop_event.is_set():
|
||||
return False
|
||||
|
||||
def _verify_connection(self) -> bool:
|
||||
"""
|
||||
Verify that the connection is actually working.
|
||||
|
||||
Returns:
|
||||
True if connection is healthy, False otherwise
|
||||
"""
|
||||
# Wait a moment for metrics to update
|
||||
time.sleep(1)
|
||||
|
||||
if not hasattr(self.client, 'metrics_dict'):
|
||||
return False
|
||||
|
||||
metrics = dict(self.client.metrics_dict)
|
||||
|
||||
# Check that we're receiving packets
|
||||
total_cycles = metrics.get('total_cycles', 0)
|
||||
if total_cycles == 0:
|
||||
return False
|
||||
|
||||
# Check that watchdog is not timing out
|
||||
watchdog_timeout = metrics.get('watchdog_timeout', True)
|
||||
if watchdog_timeout:
|
||||
return False
|
||||
|
||||
# Connection appears healthy
|
||||
return True
|
||||
|
||||
def get_stats(self) -> dict:
|
||||
"""
|
||||
Get auto-reconnect statistics.
|
||||
|
||||
Returns:
|
||||
Dictionary with reconnection statistics
|
||||
"""
|
||||
return {
|
||||
'enabled': self.enabled,
|
||||
'running': self._running,
|
||||
'total_reconnects': self.total_reconnects,
|
||||
'failed_reconnects': self.failed_reconnects,
|
||||
'last_reconnect_time': self.last_reconnect_time,
|
||||
'strategy': self.strategy.name,
|
||||
'max_retries': self.max_retries,
|
||||
'retry_delay': self.retry_delay,
|
||||
}
|
||||
@ -1,8 +1,7 @@
|
||||
"""Digital I/O API namespace for RSIPI."""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Union, Optional, TYPE_CHECKING
|
||||
from typing import Union, TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .rsi_client import RSIClient
|
||||
@ -24,8 +23,6 @@ class IOAPI:
|
||||
client: RSIClient instance for variable access
|
||||
"""
|
||||
self.client = client
|
||||
from .tools_api import ToolsAPI
|
||||
self._tools = ToolsAPI(client)
|
||||
|
||||
def toggle(self, group: str, name: str, state: Union[bool, int]) -> str:
|
||||
"""
|
||||
@ -56,139 +53,23 @@ class IOAPI:
|
||||
var_name = f"{group}.{name}"
|
||||
state_value = int(bool(state)) # Ensure binary 0 or 1
|
||||
|
||||
result = self._tools.update_variable(var_name, state_value)
|
||||
logging.debug("I/O %s set to %d", var_name, state_value)
|
||||
# Import here to avoid circular dependency
|
||||
from .tools_api import ToolsAPI
|
||||
|
||||
tools = ToolsAPI(self.client)
|
||||
result = tools.update_variable(var_name, state_value)
|
||||
logging.debug(f"I/O {var_name} set to {state_value}")
|
||||
return result
|
||||
|
||||
def set_output(self, channel: int, value: bool, group: str = 'Digout') -> str:
|
||||
"""
|
||||
Set digital output by channel number.
|
||||
|
||||
Args:
|
||||
channel: Output channel number (1-based, e.g., 1 for o1)
|
||||
value: Desired state (True = ON, False = OFF)
|
||||
group: I/O group name (default: 'Digout')
|
||||
|
||||
Returns:
|
||||
Status message indicating success
|
||||
|
||||
Raises:
|
||||
RSIVariableError: If the output channel doesn't exist
|
||||
RSISafetyViolation: If safety checks prevent the operation
|
||||
|
||||
Example:
|
||||
>>> api.io.set_output(1, True) # Turn ON output 1
|
||||
>>> api.io.set_output(3, False) # Turn OFF output 3
|
||||
|
||||
Note:
|
||||
Digout must be configured in the RSI config RECEIVE section
|
||||
for this to work. Check your RSI_EthernetConfig.xml.
|
||||
"""
|
||||
channel_name = f"o{channel}"
|
||||
return self.toggle(group, channel_name, value)
|
||||
|
||||
def get_input(self, channel: int, group: str = 'Digin') -> bool:
|
||||
"""
|
||||
Read digital input by channel number.
|
||||
|
||||
High-level wrapper for reading digital input states from the robot
|
||||
controller. Returns current state as boolean.
|
||||
|
||||
Args:
|
||||
channel: Input channel number (1-based, e.g., 1 for i1)
|
||||
group: I/O group name (default: 'Digin')
|
||||
|
||||
Returns:
|
||||
True if input is HIGH/ON, False if LOW/OFF
|
||||
|
||||
Raises:
|
||||
RSIVariableError: If the input channel doesn't exist in receive_variables
|
||||
|
||||
Example:
|
||||
>>> # Check if input 1 is active
|
||||
>>> if api.io.get_input(1):
|
||||
... print("Sensor triggered!")
|
||||
Sensor triggered!
|
||||
|
||||
>>> # Read from custom group
|
||||
>>> state = api.io.get_input(5, group='DiI')
|
||||
>>> print(f"Input 5 state: {state}")
|
||||
Input 5 state: True
|
||||
|
||||
Note:
|
||||
This reads from receive_variables, which contains the robot
|
||||
controller's current I/O state. Values are updated every RSI
|
||||
cycle (~4ms).
|
||||
"""
|
||||
from .exceptions import RSIVariableError
|
||||
|
||||
channel_name = f"i{channel}"
|
||||
var_name = f"{group}.{channel_name}"
|
||||
|
||||
# Digital inputs come from the robot (send_variables = what robot sends us)
|
||||
if group in self.client.send_variables:
|
||||
group_dict = self.client.send_variables.get(group, {})
|
||||
if isinstance(group_dict, dict) and channel_name in group_dict:
|
||||
value = group_dict[channel_name]
|
||||
return bool(value)
|
||||
else:
|
||||
raise RSIVariableError(f"Input channel '{channel_name}' not found in group '{group}'")
|
||||
else:
|
||||
raise RSIVariableError(f"Input group '{group}' not found in send_variables")
|
||||
|
||||
def pulse(self, channel: int, duration: float = 0.1, group: str = 'Digout') -> str:
|
||||
"""
|
||||
Generate a timed pulse on the specified output channel.
|
||||
|
||||
Turns the output ON, waits for the specified duration, then turns it OFF.
|
||||
Useful for triggering pneumatic actuators, solenoids, or signaling events.
|
||||
|
||||
Args:
|
||||
channel: Output channel number (1-based)
|
||||
duration: Pulse duration in seconds (default: 0.1 = 100ms)
|
||||
group: I/O group name (default: 'Digout')
|
||||
|
||||
Returns:
|
||||
Status message indicating completion
|
||||
|
||||
Raises:
|
||||
RSIVariableError: If the output channel doesn't exist
|
||||
RSISafetyViolation: If safety checks prevent the operation
|
||||
|
||||
Example:
|
||||
>>> # 100ms pulse on output 2
|
||||
>>> api.io.pulse(2)
|
||||
'Pulse completed on Digout.o2 (duration: 0.1s)'
|
||||
|
||||
>>> # 500ms pulse on output 5
|
||||
>>> api.io.pulse(5, duration=0.5)
|
||||
'Pulse completed on Digout.o5 (duration: 0.5s)'
|
||||
|
||||
>>> # Trigger pneumatic gripper on custom channel
|
||||
>>> api.io.pulse(3, duration=0.2, group='DiO')
|
||||
'Pulse completed on DiO.o3 (duration: 0.2s)'
|
||||
|
||||
Warning:
|
||||
This method blocks for the duration of the pulse. For non-blocking
|
||||
pulses, consider using threading or async I/O patterns.
|
||||
|
||||
Note:
|
||||
Pulse timing accuracy depends on system load and RSI cycle time.
|
||||
For critical timing requirements, consider hardware-timed outputs
|
||||
or KRL-based pulse generation.
|
||||
"""
|
||||
channel_name = f"o{channel}"
|
||||
var_name = f"{group}.{channel_name}"
|
||||
|
||||
# Turn ON
|
||||
self.set_output(channel, True, group=group)
|
||||
logging.debug("Pulse started on %s", var_name)
|
||||
|
||||
# Wait for duration
|
||||
time.sleep(duration)
|
||||
|
||||
# Turn OFF
|
||||
self.set_output(channel, False, group=group)
|
||||
logging.info("Pulse completed on %s (duration: %ss)", var_name, duration)
|
||||
|
||||
return f"Pulse completed on {var_name} (duration: {duration}s)"
|
||||
# TODO (Phase 3): Implement high-level I/O helpers
|
||||
# def set_output(self, channel: int, value: bool) -> str:
|
||||
# """Set digital output by channel number."""
|
||||
# pass
|
||||
#
|
||||
# def get_input(self, channel: int) -> bool:
|
||||
# """Read digital input by channel number."""
|
||||
# pass
|
||||
#
|
||||
# def pulse(self, channel: int, duration: float = 0.1) -> None:
|
||||
# """Generate a pulse on the specified output channel."""
|
||||
# pass
|
||||
|
||||
@ -1,8 +1,7 @@
|
||||
"""KRL program manipulation API namespace for RSIPI."""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Optional, Union, TYPE_CHECKING
|
||||
from typing import Optional, TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .rsi_client import RSIClient
|
||||
@ -116,267 +115,19 @@ class KRLAPI:
|
||||
logging.error(f"RSI injection failed: {e}")
|
||||
return f"RSI injection failed: {e}"
|
||||
|
||||
def wait_for_signal(
|
||||
self,
|
||||
channel: int,
|
||||
timeout: float = 5.0,
|
||||
check_interval: float = 0.01,
|
||||
group: str = 'Digin'
|
||||
) -> bool:
|
||||
"""
|
||||
Wait for KRL to set a specific I/O signal.
|
||||
|
||||
Blocks until the specified digital input becomes HIGH, or timeout occurs.
|
||||
Commonly used for synchronization where Python waits for KRL to signal
|
||||
completion of a robot operation before proceeding.
|
||||
|
||||
Args:
|
||||
channel: Input channel number to monitor (1-based)
|
||||
timeout: Maximum wait time in seconds (default: 5.0)
|
||||
check_interval: Polling interval in seconds (default: 0.01 = 10ms)
|
||||
group: I/O group name (default: 'Digin')
|
||||
|
||||
Returns:
|
||||
True if signal received, False if timeout occurred
|
||||
|
||||
Example:
|
||||
>>> # Wait for KRL to signal ready on input 3
|
||||
>>> if api.krl.wait_for_signal(3, timeout=10.0):
|
||||
... print("KRL signaled ready!")
|
||||
... # Proceed with Python-side processing
|
||||
... else:
|
||||
... print("Timeout waiting for KRL signal")
|
||||
|
||||
>>> # Handshake pattern: Python waits → KRL signals → Python continues
|
||||
>>> api.motion.update_cartesian(X=100) # Send correction
|
||||
>>> api.krl.wait_for_signal(1) # Wait for KRL to acknowledge
|
||||
>>> # KRL has processed the correction, safe to continue
|
||||
|
||||
Note:
|
||||
This is a blocking operation. The check_interval determines polling
|
||||
frequency - lower values provide faster response but higher CPU usage.
|
||||
For typical RSI applications, 10-50ms intervals are appropriate.
|
||||
|
||||
Warning:
|
||||
Ensure the KRL program actually sets the signal, otherwise this will
|
||||
block until timeout. Consider using try/except for timeout handling.
|
||||
"""
|
||||
from .io_api import IOAPI
|
||||
|
||||
io_api = IOAPI(self.client)
|
||||
start_time = time.time()
|
||||
|
||||
logging.debug(f"Waiting for signal on {group}.i{channel} (timeout: {timeout}s)")
|
||||
|
||||
while (time.time() - start_time) < timeout:
|
||||
if io_api.get_input(channel, group=group):
|
||||
elapsed = time.time() - start_time
|
||||
logging.info(f"Signal received on {group}.i{channel} after {elapsed:.3f}s")
|
||||
return True
|
||||
time.sleep(check_interval)
|
||||
|
||||
logging.warning(f"Timeout waiting for signal on {group}.i{channel} after {timeout}s")
|
||||
return False
|
||||
|
||||
def signal_complete(self, channel: int, group: str = 'Digout') -> str:
|
||||
"""
|
||||
Signal to KRL that Python-side operation is complete.
|
||||
|
||||
Sets the specified digital output HIGH to notify the KRL program that
|
||||
Python has finished processing and KRL can proceed.
|
||||
|
||||
Args:
|
||||
channel: Output channel number to signal on (1-based)
|
||||
group: I/O group name (default: 'Digout')
|
||||
|
||||
Returns:
|
||||
Status message indicating success
|
||||
|
||||
Raises:
|
||||
RSIVariableError: If the output channel doesn't exist
|
||||
RSISafetyViolation: If safety checks prevent the operation
|
||||
|
||||
Example:
|
||||
>>> # Signal KRL that data processing is complete
|
||||
>>> api.krl.signal_complete(2)
|
||||
'Signaled complete on Digout.o2'
|
||||
|
||||
>>> # Typical coordination pattern:
|
||||
>>> # 1. KRL sends data via Tech variables
|
||||
>>> # 2. Python processes data
|
||||
>>> result = api.krl.read_param('T11') # Read from KRL
|
||||
>>> processed = result * 2.0 # Process
|
||||
>>> api.krl.write_param('C11', processed) # Write result
|
||||
>>> api.krl.signal_complete(1) # Tell KRL we're done
|
||||
|
||||
Note:
|
||||
This sets the output and leaves it HIGH. If you need to reset the
|
||||
signal after KRL acknowledges, use api.io.pulse() instead or manually
|
||||
call api.io.set_output(channel, False) after KRL reads the signal.
|
||||
|
||||
See Also:
|
||||
wait_for_signal() - Complementary method for waiting on inputs
|
||||
api.io.pulse() - For temporary signal pulses
|
||||
"""
|
||||
from .io_api import IOAPI
|
||||
|
||||
io_api = IOAPI(self.client)
|
||||
io_api.set_output(channel, True, group=group)
|
||||
logging.info(f"Signaled complete on {group}.o{channel}")
|
||||
return f"Signaled complete on {group}.o{channel}"
|
||||
|
||||
def write_param(self, slot: Union[int, str], value: float) -> str:
|
||||
"""
|
||||
Write parameter to Tech.C variable for KRL to read.
|
||||
|
||||
Tech.C variables (C11-C199) are "Control" parameters written by Python
|
||||
and read by KRL programs. Used for passing numerical data from Python
|
||||
to the robot controller.
|
||||
|
||||
Args:
|
||||
slot: Tech.C slot number (11-199) or string like 'C11', 'c15'
|
||||
value: Numerical value to write
|
||||
|
||||
Returns:
|
||||
Status message indicating success
|
||||
|
||||
Raises:
|
||||
ValueError: If slot number is invalid (must be 11-199)
|
||||
RSIVariableError: If Tech variable group doesn't exist
|
||||
RSISafetyViolation: If safety checks prevent the operation
|
||||
|
||||
Example:
|
||||
>>> # Send target position to KRL
|
||||
>>> api.krl.write_param(11, 650.5) # Tech.C11 = 650.5
|
||||
'Updated Tech.C11 to 650.5'
|
||||
|
||||
>>> # Send multiple parameters
|
||||
>>> api.krl.write_param('C12', 120.0) # X coordinate
|
||||
>>> api.krl.write_param('C13', -50.0) # Y coordinate
|
||||
>>> api.krl.write_param('C14', 800.0) # Z coordinate
|
||||
|
||||
>>> # KRL side reads with: target_x = $TECH.C[12]
|
||||
|
||||
Note:
|
||||
KUKA RSI Tech variables support slots 11-199. Slots 1-10 are reserved.
|
||||
The KRL program must read from $TECH.C[n] to access these values.
|
||||
|
||||
KRL Example:
|
||||
```krl
|
||||
DEF my_program()
|
||||
DECL REAL target_x, target_y, target_z
|
||||
; Python writes to C12, C13, C14
|
||||
target_x = $TECH.C[12]
|
||||
target_y = $TECH.C[13]
|
||||
target_z = $TECH.C[14]
|
||||
; Use coordinates...
|
||||
END
|
||||
```
|
||||
|
||||
See Also:
|
||||
read_param() - Read Tech.T variables written by KRL
|
||||
"""
|
||||
# Normalize slot to integer
|
||||
if isinstance(slot, str):
|
||||
slot_str = slot.upper().strip()
|
||||
if slot_str.startswith('C'):
|
||||
slot_num = int(slot_str[1:])
|
||||
else:
|
||||
slot_num = int(slot_str)
|
||||
else:
|
||||
slot_num = int(slot)
|
||||
|
||||
# Validate slot range (KUKA reserves 1-10, usable range is 11-199)
|
||||
if not (11 <= slot_num <= 199):
|
||||
raise ValueError(f"Tech slot must be between 11-199, got {slot_num}")
|
||||
|
||||
from .tools_api import ToolsAPI
|
||||
|
||||
tools = ToolsAPI(self.client)
|
||||
var_name = f"Tech.C{slot_num}"
|
||||
result = tools.update_variable(var_name, value)
|
||||
logging.debug(f"Wrote {value} to {var_name}")
|
||||
return result
|
||||
|
||||
def read_param(self, slot: Union[int, str]) -> float:
|
||||
"""
|
||||
Read parameter from Tech.T variable written by KRL.
|
||||
|
||||
Tech.T variables (T11-T199) are "Transfer" parameters written by KRL
|
||||
programs and read by Python. Used for passing numerical data from the
|
||||
robot controller to Python.
|
||||
|
||||
Args:
|
||||
slot: Tech.T slot number (11-199) or string like 'T11', 't15'
|
||||
|
||||
Returns:
|
||||
Numerical value from the Tech.T slot
|
||||
|
||||
Raises:
|
||||
ValueError: If slot number is invalid (must be 11-199)
|
||||
RSIVariableError: If Tech variable group doesn't exist or slot not found
|
||||
|
||||
Example:
|
||||
>>> # Read sensor value from KRL
|
||||
>>> force = api.krl.read_param(11) # Read Tech.T11
|
||||
>>> print(f"Force reading: {force}")
|
||||
Force reading: 125.5
|
||||
|
||||
>>> # Read multiple parameters
|
||||
>>> actual_x = api.krl.read_param('T12')
|
||||
>>> actual_y = api.krl.read_param('T13')
|
||||
>>> actual_z = api.krl.read_param('T14')
|
||||
|
||||
>>> # KRL side writes with: $TECH.T[12] = actual_pos.X
|
||||
|
||||
Note:
|
||||
Tech.T variables are updated every RSI cycle (~4ms) from the robot
|
||||
controller. Values reflect the KRL program's last write operation.
|
||||
|
||||
KRL Example:
|
||||
```krl
|
||||
DEF my_program()
|
||||
DECL E6POS actual_pos
|
||||
actual_pos = $POS_ACT
|
||||
; Write to Tech.T for Python to read
|
||||
$TECH.T[12] = actual_pos.X
|
||||
$TECH.T[13] = actual_pos.Y
|
||||
$TECH.T[14] = actual_pos.Z
|
||||
END
|
||||
```
|
||||
|
||||
Warning:
|
||||
Ensure the KRL program has written to the Tech.T slot before reading,
|
||||
otherwise you'll receive the default value (typically 0.0).
|
||||
|
||||
See Also:
|
||||
write_param() - Write Tech.C variables for KRL to read
|
||||
"""
|
||||
from .exceptions import RSIVariableError
|
||||
|
||||
# Normalize slot to integer
|
||||
if isinstance(slot, str):
|
||||
slot_str = slot.upper().strip()
|
||||
if slot_str.startswith('T'):
|
||||
slot_num = int(slot_str[1:])
|
||||
else:
|
||||
slot_num = int(slot_str)
|
||||
else:
|
||||
slot_num = int(slot)
|
||||
|
||||
# Validate slot range
|
||||
if not (11 <= slot_num <= 199):
|
||||
raise ValueError(f"Tech slot must be between 11-199, got {slot_num}")
|
||||
|
||||
# Tech.T variables are written by KRL and sent to us (send_variables)
|
||||
if 'Tech' in self.client.send_variables:
|
||||
tech_dict = self.client.send_variables.get('Tech', {})
|
||||
var_name = f"T{slot_num}"
|
||||
if isinstance(tech_dict, dict) and var_name in tech_dict:
|
||||
value = tech_dict[var_name]
|
||||
logging.debug(f"Read {value} from Tech.{var_name}")
|
||||
return float(value)
|
||||
else:
|
||||
raise RSIVariableError(f"Tech.{var_name} not found in send_variables")
|
||||
else:
|
||||
raise RSIVariableError("Tech variable group not found in send_variables")
|
||||
# TODO (Phase 3): Implement KRL coordination helpers
|
||||
# def wait_for_signal(self, channel: int, timeout: float = 5.0) -> bool:
|
||||
# """Wait for KRL to set a specific I/O signal."""
|
||||
# pass
|
||||
#
|
||||
# def signal_complete(self, channel: int) -> None:
|
||||
# """Signal to KRL that Python-side operation is complete."""
|
||||
# pass
|
||||
#
|
||||
# def write_param(self, slot: str, value: float) -> str:
|
||||
# """Write parameter to Tech.C variable for KRL to read."""
|
||||
# pass
|
||||
#
|
||||
# def read_param(self, slot: str) -> float:
|
||||
# """Read parameter from Tech.T variable written by KRL."""
|
||||
# pass
|
||||
|
||||
@ -48,11 +48,11 @@ class MonitoringAPI:
|
||||
IPOC: 123456
|
||||
"""
|
||||
return {
|
||||
"position": dict(self.client.send_variables.get("RIst", {"X": 0, "Y": 0, "Z": 0})),
|
||||
"velocity": dict(self.client.send_variables.get("Velocity", {"X": 0, "Y": 0, "Z": 0})),
|
||||
"acceleration": dict(self.client.send_variables.get("Acceleration", {"X": 0, "Y": 0, "Z": 0})),
|
||||
"force": dict(self.client.send_variables.get("MaCur", {"A1": 0, "A2": 0, "A3": 0, "A4": 0, "A5": 0, "A6": 0})),
|
||||
"ipoc": self.client.send_variables.get("IPOC", "N/A")
|
||||
"position": dict(self.client.receive_variables.get("RIst", {"X": 0, "Y": 0, "Z": 0})),
|
||||
"velocity": dict(self.client.receive_variables.get("Velocity", {"X": 0, "Y": 0, "Z": 0})),
|
||||
"acceleration": dict(self.client.receive_variables.get("Acceleration", {"X": 0, "Y": 0, "Z": 0})),
|
||||
"force": dict(self.client.receive_variables.get("MaCur", {"A1": 0, "A2": 0, "A3": 0, "A4": 0, "A5": 0, "A6": 0})),
|
||||
"ipoc": self.client.receive_variables.get("IPOC", "N/A")
|
||||
}
|
||||
|
||||
def get_live_data_as_numpy(self) -> np.ndarray:
|
||||
@ -118,7 +118,7 @@ class MonitoringAPI:
|
||||
>>> print(ipoc)
|
||||
123456
|
||||
"""
|
||||
return self.client.send_variables.get("IPOC", "N/A")
|
||||
return self.client.receive_variables.get("IPOC", "N/A")
|
||||
|
||||
def get_position(self) -> Dict[str, float]:
|
||||
"""
|
||||
@ -132,7 +132,7 @@ class MonitoringAPI:
|
||||
>>> print(f"TCP at X={pos['X']}, Y={pos['Y']}, Z={pos['Z']}")
|
||||
TCP at X=600.5, Y=-200.3, Z=1450.8
|
||||
"""
|
||||
return dict(self.client.send_variables.get("RIst", {"X": 0, "Y": 0, "Z": 0, "A": 0, "B": 0, "C": 0}))
|
||||
return dict(self.client.receive_variables.get("RIst", {"X": 0, "Y": 0, "Z": 0, "A": 0, "B": 0, "C": 0}))
|
||||
|
||||
def get_force(self) -> Dict[str, float]:
|
||||
"""
|
||||
@ -149,7 +149,7 @@ class MonitoringAPI:
|
||||
>>> print(f"Joint A1 current: {force['A1']}")
|
||||
Joint A1 current: 12.5
|
||||
"""
|
||||
return dict(self.client.send_variables.get("MaCur", {"A1": 0, "A2": 0, "A3": 0, "A4": 0, "A5": 0, "A6": 0}))
|
||||
return dict(self.client.receive_variables.get("MaCur", {"A1": 0, "A2": 0, "A3": 0, "A4": 0, "A5": 0, "A6": 0}))
|
||||
|
||||
def watch_network(self, duration: Optional[float] = None, rate: float = 0.2) -> None:
|
||||
"""
|
||||
@ -178,7 +178,7 @@ class MonitoringAPI:
|
||||
try:
|
||||
while True:
|
||||
live_data = self.get_live_data()
|
||||
ipoc = live_data.get("ipoc", "N/A")
|
||||
ipoc = live_data.get("IPOC", "N/A")
|
||||
rpos = live_data.get("position", {})
|
||||
timestamp = datetime.datetime.now().strftime('%H:%M:%S')
|
||||
print(f"[{timestamp}] IPOC: {ipoc} | RIst: {rpos}")
|
||||
|
||||
@ -1,10 +1,8 @@
|
||||
"""Motion control API namespace for RSIPI."""
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import math
|
||||
import numpy as np
|
||||
from typing import Dict, List, Any, Optional, Tuple, TYPE_CHECKING
|
||||
import asyncio
|
||||
from typing import Dict, List, Any, Optional, TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .rsi_client import RSIClient
|
||||
@ -29,9 +27,6 @@ class MotionAPI:
|
||||
self.client = client
|
||||
self.trajectory_queue: List[Dict[str, Any]] = []
|
||||
|
||||
from .tools_api import ToolsAPI
|
||||
self._tools = ToolsAPI(client)
|
||||
|
||||
def update_cartesian(self, **kwargs: float) -> None:
|
||||
"""
|
||||
Update Cartesian correction values (RKorr).
|
||||
@ -61,13 +56,17 @@ class MotionAPI:
|
||||
RKorr must be configured in the RSI config file and enabled in KRL
|
||||
using RSI_MOVECORR() for corrections to take effect.
|
||||
"""
|
||||
if "RKorr" not in self.client.receive_variables:
|
||||
logging.warning("RKorr not configured in receive_variables. Skipping Cartesian update.")
|
||||
if "RKorr" not in self.client.send_variables:
|
||||
logging.warning("RKorr not configured in send_variables. Skipping Cartesian update.")
|
||||
return
|
||||
|
||||
# Import here to avoid circular dependency
|
||||
from .tools_api import ToolsAPI
|
||||
tools = ToolsAPI(self.client)
|
||||
|
||||
for axis, value in kwargs.items():
|
||||
self._tools.update_variable(f"RKorr.{axis}", float(value))
|
||||
logging.debug("RKorr.%s set to %s", axis, value)
|
||||
tools.update_variable(f"RKorr.{axis}", float(value))
|
||||
logging.debug(f"RKorr.{axis} set to {value}")
|
||||
|
||||
def update_joints(self, **kwargs: float) -> None:
|
||||
"""
|
||||
@ -94,33 +93,16 @@ class MotionAPI:
|
||||
AKorr must be configured in the RSI config file and enabled in KRL
|
||||
using RSI_MOVECORR() for corrections to take effect.
|
||||
"""
|
||||
if "AKorr" not in self.client.receive_variables:
|
||||
logging.warning("AKorr not configured in receive_variables. Skipping Joint update.")
|
||||
if "AKorr" not in self.client.send_variables:
|
||||
logging.warning("AKorr not configured in send_variables. Skipping Joint update.")
|
||||
return
|
||||
|
||||
from .tools_api import ToolsAPI
|
||||
tools = ToolsAPI(self.client)
|
||||
|
||||
for axis, value in kwargs.items():
|
||||
self._tools.update_variable(f"AKorr.{axis}", float(value))
|
||||
logging.debug("AKorr.%s set to %s", axis, value)
|
||||
|
||||
def get_current_pose(self) -> Dict[str, float]:
|
||||
"""
|
||||
Get current TCP position from robot.
|
||||
|
||||
Returns:
|
||||
Dict with X, Y, Z (mm) and A, B, C (degrees)
|
||||
"""
|
||||
rist = self.client.send_variables.get("RIst", {})
|
||||
return dict(rist) if isinstance(rist, dict) else {"X": 0, "Y": 0, "Z": 0, "A": 0, "B": 0, "C": 0}
|
||||
|
||||
def get_current_joints(self) -> Dict[str, float]:
|
||||
"""
|
||||
Get current joint positions from robot.
|
||||
|
||||
Returns:
|
||||
Dict with A1-A6 in degrees
|
||||
"""
|
||||
aspos = self.client.send_variables.get("ASPos", {})
|
||||
return dict(aspos) if isinstance(aspos, dict) else {"A1": 0, "A2": 0, "A3": 0, "A4": 0, "A5": 0, "A6": 0}
|
||||
tools.update_variable(f"AKorr.{axis}", float(value))
|
||||
logging.debug(f"AKorr.{axis} set to {value}")
|
||||
|
||||
def correct_position(self, correction_type: str, axis: str, value: float) -> str:
|
||||
"""
|
||||
@ -146,7 +128,9 @@ class MotionAPI:
|
||||
>>> api.motion.correct_position('AKorr', 'A1', 5.0)
|
||||
'Updated AKorr.A1 to 5.0'
|
||||
"""
|
||||
return self._tools.update_variable(f"{correction_type}.{axis}", value)
|
||||
from .tools_api import ToolsAPI
|
||||
tools = ToolsAPI(self.client)
|
||||
return tools.update_variable(f"{correction_type}.{axis}", value)
|
||||
|
||||
def move_external_axis(self, axis: str, value: float) -> str:
|
||||
"""
|
||||
@ -170,7 +154,9 @@ class MotionAPI:
|
||||
>>> api.motion.move_external_axis('E1', 500.0)
|
||||
'Updated ELPos.E1 to 500.0'
|
||||
"""
|
||||
return self._tools.update_variable(f"ELPos.{axis}", value)
|
||||
from .tools_api import ToolsAPI
|
||||
tools = ToolsAPI(self.client)
|
||||
return tools.update_variable(f"ELPos.{axis}", value)
|
||||
|
||||
def adjust_speed(self, tech_param: str, value: float) -> str:
|
||||
"""
|
||||
@ -195,7 +181,9 @@ class MotionAPI:
|
||||
Tech variable meanings depend on your KRL program implementation.
|
||||
Coordinate with your KRL developer on parameter assignments.
|
||||
"""
|
||||
return self._tools.update_variable(tech_param, value)
|
||||
from .tools_api import ToolsAPI
|
||||
tools = ToolsAPI(self.client)
|
||||
return tools.update_variable(tech_param, value)
|
||||
|
||||
@staticmethod
|
||||
def generate_trajectory(
|
||||
@ -255,10 +243,10 @@ class MotionAPI:
|
||||
rate: float = 0.012
|
||||
) -> None:
|
||||
"""
|
||||
Execute a trajectory, blocking until complete.
|
||||
Execute a trajectory asynchronously.
|
||||
|
||||
Sends waypoints sequentially to the robot at the specified rate.
|
||||
Can be cancelled via cancel_trajectory().
|
||||
Uses asyncio for non-blocking execution.
|
||||
|
||||
Args:
|
||||
trajectory: List of waypoint dictionaries
|
||||
@ -267,98 +255,96 @@ class MotionAPI:
|
||||
|
||||
Raises:
|
||||
RSITrajectoryError: If space is invalid
|
||||
|
||||
Example:
|
||||
>>> # Generate and execute Cartesian trajectory
|
||||
>>> traj = api.motion.generate_trajectory(
|
||||
... {"X":0, "Y":0, "Z":500},
|
||||
... {"X":100, "Y":0, "Z":500},
|
||||
... steps=50
|
||||
... )
|
||||
>>> api.motion.execute_trajectory(traj, space="cartesian", rate=0.02)
|
||||
|
||||
Note:
|
||||
This method uses asyncio. If no event loop is running, one will
|
||||
be created automatically. The trajectory executes in the background.
|
||||
"""
|
||||
import time
|
||||
from .exceptions import RSITrajectoryError
|
||||
|
||||
self._trajectory_cancel = threading.Event()
|
||||
|
||||
def runner():
|
||||
async def runner():
|
||||
for idx, point in enumerate(trajectory):
|
||||
if self._trajectory_cancel.is_set():
|
||||
logging.info("Trajectory cancelled at step %d/%d", idx, len(trajectory))
|
||||
return
|
||||
if space == "cartesian":
|
||||
self.update_cartesian(**point)
|
||||
elif space == "joint":
|
||||
self.update_joints(**point)
|
||||
else:
|
||||
raise RSITrajectoryError("space must be 'cartesian' or 'joint'")
|
||||
logging.debug("Trajectory step %d/%d", idx + 1, len(trajectory))
|
||||
time.sleep(rate)
|
||||
logging.debug(f"Trajectory step {idx + 1}/{len(trajectory)}")
|
||||
await asyncio.sleep(rate)
|
||||
|
||||
self._trajectory_thread = threading.Thread(target=runner, daemon=True)
|
||||
self._trajectory_thread.start()
|
||||
self._trajectory_thread.join() # Block until complete
|
||||
|
||||
# Zero corrections after trajectory to stop motion in relative mode
|
||||
if space == "cartesian":
|
||||
self.update_cartesian(**{k: 0.0 for k in trajectory[0]})
|
||||
elif space == "joint":
|
||||
self.update_joints(**{k: 0.0 for k in trajectory[0]})
|
||||
|
||||
def cancel_trajectory(self) -> None:
|
||||
"""Cancel a running trajectory execution."""
|
||||
if hasattr(self, '_trajectory_cancel'):
|
||||
self._trajectory_cancel.set()
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
asyncio.create_task(runner())
|
||||
except RuntimeError:
|
||||
# No event loop running, create one
|
||||
asyncio.run(runner())
|
||||
|
||||
def move_cartesian_trajectory(
|
||||
self,
|
||||
start_pose: Dict[str, float],
|
||||
end_pose: Dict[str, float],
|
||||
start_pose: Optional[Dict[str, float]] = None,
|
||||
steps: int = 50,
|
||||
rate: float = 0.012
|
||||
) -> None:
|
||||
"""
|
||||
Generate and execute Cartesian trajectory in one call.
|
||||
|
||||
Convenience method that combines generate_trajectory() and
|
||||
execute_trajectory() for Cartesian motion.
|
||||
|
||||
Args:
|
||||
end_pose: Target Cartesian pose
|
||||
start_pose: Starting pose (default: current robot position)
|
||||
start_pose: Starting Cartesian pose
|
||||
end_pose: Ending Cartesian pose
|
||||
steps: Number of waypoints (default: 50)
|
||||
rate: Time between waypoints in seconds (default: 0.012)
|
||||
|
||||
Example:
|
||||
>>> # Move to target from current position
|
||||
>>> api.motion.move_cartesian_trajectory({"X":100, "Y":0, "Z":500})
|
||||
>>> # Explicit start
|
||||
>>> api.motion.move_cartesian_trajectory(
|
||||
... {"X":0, "Y":0, "Z":500},
|
||||
... {"X":100, "Y":0, "Z":500},
|
||||
... start_pose={"X":0, "Y":0, "Z":500}
|
||||
... steps=50,
|
||||
... rate=0.02
|
||||
... )
|
||||
"""
|
||||
if start_pose is None:
|
||||
start_pose = self.get_current_pose()
|
||||
trajectory = self.generate_trajectory(start_pose, end_pose, steps=steps, space="cartesian")
|
||||
self.execute_trajectory(trajectory, space="cartesian", rate=rate)
|
||||
|
||||
def move_joint_trajectory(
|
||||
self,
|
||||
start_joints: Dict[str, float],
|
||||
end_joints: Dict[str, float],
|
||||
start_joints: Optional[Dict[str, float]] = None,
|
||||
steps: int = 50,
|
||||
rate: float = 0.4
|
||||
) -> None:
|
||||
"""
|
||||
Generate and execute joint-space trajectory in one call.
|
||||
|
||||
Convenience method for joint-space motion with sensible defaults
|
||||
(slower rate typical for joint motion).
|
||||
|
||||
Args:
|
||||
end_joints: Target joint configuration
|
||||
start_joints: Starting joints (default: current robot joints)
|
||||
start_joints: Starting joint configuration
|
||||
end_joints: Ending joint configuration
|
||||
steps: Number of waypoints (default: 50)
|
||||
rate: Time between waypoints in seconds (default: 0.4)
|
||||
rate: Time between waypoints in seconds (default: 0.4 for smooth joint motion)
|
||||
|
||||
Example:
|
||||
>>> # Move to target from current joints
|
||||
>>> api.motion.move_joint_trajectory({"A1":30, "A2":-15, "A3":45})
|
||||
>>> # Explicit start
|
||||
>>> api.motion.move_joint_trajectory(
|
||||
... {"A1":30, "A2":-15, "A3":45},
|
||||
... start_joints={"A1":0, "A2":0, "A3":0}
|
||||
... {"A1":0, "A2":0, "A3":0, "A4":0, "A5":0, "A6":0},
|
||||
... {"A1":30, "A2":-15, "A3":45, "A4":0, "A5":30, "A6":0},
|
||||
... steps=100
|
||||
... )
|
||||
"""
|
||||
if start_joints is None:
|
||||
start_joints = self.get_current_joints()
|
||||
trajectory = self.generate_trajectory(start_joints, end_joints, steps=steps, space="joint")
|
||||
self.execute_trajectory(trajectory, space="joint", rate=rate)
|
||||
|
||||
@ -392,7 +378,7 @@ class MotionAPI:
|
||||
"space": space,
|
||||
"rate": rate,
|
||||
})
|
||||
logging.debug("Queued trajectory: %d points, %s space", len(trajectory), space)
|
||||
logging.debug(f"Queued trajectory: {len(trajectory)} points, {space} space")
|
||||
|
||||
def queue_cartesian_trajectory(
|
||||
self,
|
||||
@ -477,9 +463,9 @@ class MotionAPI:
|
||||
>>> api.motion.execute_queued_trajectories()
|
||||
>>> # Both trajectories executed sequentially
|
||||
"""
|
||||
logging.info("Executing %d queued trajectories", len(self.trajectory_queue))
|
||||
logging.info(f"Executing {len(self.trajectory_queue)} queued trajectories")
|
||||
for idx, item in enumerate(self.trajectory_queue):
|
||||
logging.debug("Executing queued trajectory %d/%d", idx + 1, len(self.trajectory_queue))
|
||||
logging.debug(f"Executing queued trajectory {idx + 1}/{len(self.trajectory_queue)}")
|
||||
self.execute_trajectory(item["trajectory"], item["space"], item["rate"])
|
||||
self.clear_queue()
|
||||
|
||||
@ -493,7 +479,7 @@ class MotionAPI:
|
||||
"""
|
||||
count = len(self.trajectory_queue)
|
||||
self.trajectory_queue.clear()
|
||||
logging.debug("Cleared %d queued trajectories", count)
|
||||
logging.debug(f"Cleared {count} queued trajectories")
|
||||
|
||||
def get_queue(self) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
@ -519,553 +505,19 @@ class MotionAPI:
|
||||
for item in self.trajectory_queue
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def generate_velocity_profile(
|
||||
trajectory: List[Dict[str, float]],
|
||||
max_velocity: float = 1.0,
|
||||
max_acceleration: float = 2.0,
|
||||
profile: str = 'trapezoidal'
|
||||
) -> List[Tuple[Dict[str, float], float]]:
|
||||
"""
|
||||
Apply velocity profiling to trajectory waypoints.
|
||||
|
||||
Generates time-optimal velocity profiles that respect velocity and
|
||||
acceleration limits. Returns trajectory with timing information.
|
||||
|
||||
Args:
|
||||
trajectory: List of waypoint dictionaries
|
||||
max_velocity: Maximum velocity (units/s)
|
||||
max_acceleration: Maximum acceleration (units/s²)
|
||||
profile: Velocity profile type - 'trapezoidal' or 's-curve'
|
||||
|
||||
Returns:
|
||||
List of tuples (waypoint, velocity) for each point
|
||||
|
||||
Example:
|
||||
>>> traj = api.motion.generate_trajectory(p0, p1, 100)
|
||||
>>> profiled = api.motion.generate_velocity_profile(
|
||||
... traj,
|
||||
... max_velocity=200.0, # mm/s
|
||||
... max_acceleration=500.0, # mm/s²
|
||||
... profile='trapezoidal'
|
||||
... )
|
||||
>>> for waypoint, velocity in profiled:
|
||||
... print(f"Point: {waypoint}, Velocity: {velocity:.2f} mm/s")
|
||||
|
||||
Note:
|
||||
Trapezoidal profiles have sharp velocity transitions (bang-bang control).
|
||||
S-curve profiles have smooth velocity transitions (jerk-limited).
|
||||
S-curve is recommended for sensitive applications requiring smooth motion.
|
||||
"""
|
||||
if not trajectory:
|
||||
return []
|
||||
|
||||
n = len(trajectory)
|
||||
if n < 2:
|
||||
return [(trajectory[0], 0.0)]
|
||||
|
||||
# Calculate distances between consecutive points
|
||||
distances = []
|
||||
for i in range(n - 1):
|
||||
dist = _calculate_distance(trajectory[i], trajectory[i + 1])
|
||||
distances.append(dist)
|
||||
|
||||
total_distance = sum(distances)
|
||||
|
||||
if profile.lower() == 'trapezoidal':
|
||||
velocities = _trapezoidal_profile(distances, total_distance, max_velocity, max_acceleration)
|
||||
elif profile.lower() == 's-curve' or profile.lower() == 'scurve':
|
||||
velocities = _s_curve_profile(distances, total_distance, max_velocity, max_acceleration)
|
||||
else:
|
||||
raise ValueError(f"Unknown profile type: {profile}. Use 'trapezoidal' or 's-curve'")
|
||||
|
||||
# Combine trajectory with velocities
|
||||
result = [(trajectory[i], velocities[i]) for i in range(n)]
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def generate_arc(
|
||||
center: Dict[str, float],
|
||||
radius: float,
|
||||
start_angle: float,
|
||||
end_angle: float,
|
||||
steps: int = 100,
|
||||
plane: str = 'XY'
|
||||
) -> List[Dict[str, float]]:
|
||||
"""
|
||||
Generate circular arc trajectory.
|
||||
|
||||
Creates waypoints along a circular arc in the specified plane.
|
||||
|
||||
Args:
|
||||
center: Arc center point (e.g., {"X": 100, "Y": 0, "Z": 500})
|
||||
radius: Arc radius in mm
|
||||
start_angle: Starting angle in degrees
|
||||
end_angle: Ending angle in degrees
|
||||
steps: Number of waypoints along arc
|
||||
plane: Plane for arc - 'XY', 'XZ', or 'YZ' (default: 'XY')
|
||||
|
||||
Returns:
|
||||
List of Cartesian waypoints along the arc
|
||||
|
||||
Example:
|
||||
>>> # 90-degree arc in XY plane
|
||||
>>> arc = api.motion.generate_arc(
|
||||
... center={"X": 100, "Y": 0, "Z": 500},
|
||||
... radius=50.0,
|
||||
... start_angle=0,
|
||||
... end_angle=90,
|
||||
... steps=50
|
||||
... )
|
||||
>>> api.motion.execute_trajectory(arc, space='cartesian')
|
||||
|
||||
Note:
|
||||
Angles are measured counterclockwise from the positive X/Y/Z axis
|
||||
depending on the plane. Arc direction follows right-hand rule.
|
||||
"""
|
||||
if steps < 2:
|
||||
raise ValueError("Steps must be at least 2")
|
||||
if radius <= 0:
|
||||
raise ValueError("Radius must be positive")
|
||||
|
||||
# Convert angles to radians
|
||||
start_rad = math.radians(start_angle)
|
||||
end_rad = math.radians(end_angle)
|
||||
angle_step = (end_rad - start_rad) / (steps - 1)
|
||||
|
||||
trajectory = []
|
||||
plane = plane.upper()
|
||||
|
||||
for i in range(steps):
|
||||
angle = start_rad + i * angle_step
|
||||
x_offset = radius * math.cos(angle)
|
||||
y_offset = radius * math.sin(angle)
|
||||
|
||||
# Map to specified plane
|
||||
if plane == 'XY':
|
||||
point = {
|
||||
"X": center.get("X", 0) + x_offset,
|
||||
"Y": center.get("Y", 0) + y_offset,
|
||||
"Z": center.get("Z", 0)
|
||||
}
|
||||
elif plane == 'XZ':
|
||||
point = {
|
||||
"X": center.get("X", 0) + x_offset,
|
||||
"Y": center.get("Y", 0),
|
||||
"Z": center.get("Z", 0) + y_offset
|
||||
}
|
||||
elif plane == 'YZ':
|
||||
point = {
|
||||
"X": center.get("X", 0),
|
||||
"Y": center.get("Y", 0) + x_offset,
|
||||
"Z": center.get("Z", 0) + y_offset
|
||||
}
|
||||
else:
|
||||
raise ValueError(f"Unknown plane: {plane}. Use 'XY', 'XZ', or 'YZ'")
|
||||
|
||||
# Preserve orientation if present in center
|
||||
for key in ["A", "B", "C"]:
|
||||
if key in center:
|
||||
point[key] = center[key]
|
||||
|
||||
trajectory.append(point)
|
||||
|
||||
return trajectory
|
||||
|
||||
@staticmethod
|
||||
def generate_circle(
|
||||
center: Dict[str, float],
|
||||
radius: float,
|
||||
steps: int = 100,
|
||||
plane: str = 'XY'
|
||||
) -> List[Dict[str, float]]:
|
||||
"""
|
||||
Generate complete circle trajectory.
|
||||
|
||||
Creates waypoints for a full 360-degree circular path.
|
||||
|
||||
Args:
|
||||
center: Circle center point
|
||||
radius: Circle radius in mm
|
||||
steps: Number of waypoints around circle
|
||||
plane: Plane for circle - 'XY', 'XZ', or 'YZ'
|
||||
|
||||
Returns:
|
||||
List of Cartesian waypoints around the circle
|
||||
|
||||
Example:
|
||||
>>> # Full circle in XY plane
|
||||
>>> circle = api.motion.generate_circle(
|
||||
... center={"X": 100, "Y": 0, "Z": 500},
|
||||
... radius=50.0,
|
||||
... steps=100
|
||||
... )
|
||||
>>> api.motion.execute_trajectory(circle, space='cartesian')
|
||||
"""
|
||||
return MotionAPI.generate_arc(center, radius, 0, 360, steps, plane)
|
||||
|
||||
@staticmethod
|
||||
def generate_spiral(
|
||||
center: Dict[str, float],
|
||||
start_radius: float,
|
||||
end_radius: float,
|
||||
pitch: float,
|
||||
revolutions: float = 1.0,
|
||||
steps: int = 100,
|
||||
plane: str = 'XY',
|
||||
axis: str = 'Z'
|
||||
) -> List[Dict[str, float]]:
|
||||
"""
|
||||
Generate spiral trajectory.
|
||||
|
||||
Creates waypoints for a spiral path with changing radius and height.
|
||||
|
||||
Args:
|
||||
center: Spiral center/start point
|
||||
start_radius: Starting radius in mm
|
||||
end_radius: Ending radius in mm
|
||||
pitch: Height change per revolution in mm
|
||||
revolutions: Number of complete rotations
|
||||
steps: Number of waypoints
|
||||
plane: Planar motion plane - 'XY', 'XZ', or 'YZ'
|
||||
axis: Axis for pitch motion - 'X', 'Y', or 'Z'
|
||||
|
||||
Returns:
|
||||
List of Cartesian waypoints along spiral
|
||||
|
||||
Example:
|
||||
>>> # Expanding spiral (drilling out)
|
||||
>>> spiral = api.motion.generate_spiral(
|
||||
... center={"X": 100, "Y": 0, "Z": 500},
|
||||
... start_radius=10.0,
|
||||
... end_radius=50.0,
|
||||
... pitch=5.0, # 5mm per revolution
|
||||
... revolutions=5,
|
||||
... steps=200
|
||||
... )
|
||||
|
||||
>>> # Contracting spiral (retracting)
|
||||
>>> spiral = api.motion.generate_spiral(
|
||||
... center={"X": 100, "Y": 0, "Z": 500},
|
||||
... start_radius=50.0,
|
||||
... end_radius=10.0,
|
||||
... pitch=-5.0, # Descending
|
||||
... revolutions=5
|
||||
... )
|
||||
"""
|
||||
if steps < 2:
|
||||
raise ValueError("Steps must be at least 2")
|
||||
|
||||
total_angle = revolutions * 2 * math.pi
|
||||
angle_step = total_angle / (steps - 1)
|
||||
radius_step = (end_radius - start_radius) / (steps - 1)
|
||||
pitch_step = pitch * revolutions / (steps - 1)
|
||||
|
||||
trajectory = []
|
||||
plane = plane.upper()
|
||||
axis = axis.upper()
|
||||
|
||||
for i in range(steps):
|
||||
angle = i * angle_step
|
||||
radius = start_radius + i * radius_step
|
||||
pitch_offset = i * pitch_step
|
||||
|
||||
x_offset = radius * math.cos(angle)
|
||||
y_offset = radius * math.sin(angle)
|
||||
|
||||
# Map to specified plane
|
||||
point = {
|
||||
"X": center.get("X", 0),
|
||||
"Y": center.get("Y", 0),
|
||||
"Z": center.get("Z", 0)
|
||||
}
|
||||
|
||||
if plane == 'XY':
|
||||
point["X"] += x_offset
|
||||
point["Y"] += y_offset
|
||||
elif plane == 'XZ':
|
||||
point["X"] += x_offset
|
||||
point["Z"] += y_offset
|
||||
elif plane == 'YZ':
|
||||
point["Y"] += x_offset
|
||||
point["Z"] += y_offset
|
||||
|
||||
# Add pitch along specified axis
|
||||
point[axis] += pitch_offset
|
||||
|
||||
# Preserve orientation
|
||||
for key in ["A", "B", "C"]:
|
||||
if key in center:
|
||||
point[key] = center[key]
|
||||
|
||||
trajectory.append(point)
|
||||
|
||||
return trajectory
|
||||
|
||||
@staticmethod
|
||||
def blend_trajectories(
|
||||
traj1: List[Dict[str, float]],
|
||||
traj2: List[Dict[str, float]],
|
||||
blend_radius: float,
|
||||
blend_steps: int = 20
|
||||
) -> List[Dict[str, float]]:
|
||||
"""
|
||||
Create smooth transition between two trajectories.
|
||||
|
||||
Generates a blended zone between trajectory endpoints using cubic
|
||||
interpolation for smooth velocity transitions.
|
||||
|
||||
Args:
|
||||
traj1: First trajectory
|
||||
traj2: Second trajectory
|
||||
blend_radius: Blend zone radius in mm (distance from junction point)
|
||||
blend_steps: Number of waypoints in blend zone
|
||||
|
||||
Returns:
|
||||
Combined trajectory with smooth blend
|
||||
|
||||
Example:
|
||||
>>> # Create two straight-line trajectories
|
||||
>>> traj1 = api.motion.generate_trajectory(p0, p1, 50)
|
||||
>>> traj2 = api.motion.generate_trajectory(p1, p2, 50)
|
||||
>>>
|
||||
>>> # Blend with 10mm radius
|
||||
>>> blended = api.motion.blend_trajectories(
|
||||
... traj1, traj2,
|
||||
... blend_radius=10.0,
|
||||
... blend_steps=20
|
||||
... )
|
||||
>>> api.motion.execute_trajectory(blended)
|
||||
|
||||
Note:
|
||||
Blend radius should be smaller than the length of either trajectory.
|
||||
Larger radii create smoother blends but deviate more from original path.
|
||||
"""
|
||||
if not traj1 or not traj2:
|
||||
raise ValueError("Both trajectories must be non-empty")
|
||||
if blend_radius <= 0:
|
||||
raise ValueError("Blend radius must be positive")
|
||||
|
||||
# Find blend start/end points based on radius
|
||||
blend_start_idx = _find_blend_point(traj1, blend_radius, from_end=True)
|
||||
blend_end_idx = _find_blend_point(traj2, blend_radius, from_end=False)
|
||||
|
||||
# Extract segments
|
||||
before_blend = traj1[:blend_start_idx]
|
||||
after_blend = traj2[blend_end_idx:]
|
||||
|
||||
# Generate blend zone using cubic interpolation
|
||||
p1 = traj1[blend_start_idx]
|
||||
p2 = traj2[blend_end_idx]
|
||||
blend_zone = _cubic_blend(p1, p2, blend_steps)
|
||||
|
||||
# Combine all segments
|
||||
return before_blend + blend_zone + after_blend
|
||||
|
||||
@staticmethod
|
||||
def transform_coordinates(
|
||||
pose: Dict[str, float],
|
||||
from_frame: str = 'BASE',
|
||||
to_frame: str = 'WORLD',
|
||||
frame_offset: Optional[Dict[str, float]] = None
|
||||
) -> Dict[str, float]:
|
||||
"""
|
||||
Transform pose between coordinate frames.
|
||||
|
||||
Converts Cartesian coordinates between different reference frames
|
||||
(BASE, TOOL, WORLD, ROBROOT).
|
||||
|
||||
Args:
|
||||
pose: Cartesian pose to transform
|
||||
from_frame: Source coordinate frame
|
||||
to_frame: Target coordinate frame
|
||||
frame_offset: Optional frame transformation (X, Y, Z, A, B, C)
|
||||
|
||||
Returns:
|
||||
Transformed pose in target frame
|
||||
|
||||
Example:
|
||||
>>> # Transform from BASE to WORLD frame
|
||||
>>> world_pose = api.motion.transform_coordinates(
|
||||
... pose={"X": 100, "Y": 0, "Z": 500},
|
||||
... from_frame='BASE',
|
||||
... to_frame='WORLD',
|
||||
... frame_offset={"X": 500, "Y": 200, "Z": 0}
|
||||
... )
|
||||
>>> print(world_pose)
|
||||
{'X': 600, 'Y': 200, 'Z': 500}
|
||||
|
||||
Note:
|
||||
For full 6-DOF transformations with rotations, use rotation
|
||||
matrices or quaternions. This implementation handles simple
|
||||
translational offsets and is suitable for most RSI applications.
|
||||
"""
|
||||
if frame_offset is None:
|
||||
# Identity transformation if no offset specified
|
||||
return pose.copy()
|
||||
|
||||
transformed = pose.copy()
|
||||
|
||||
# Apply translational offset
|
||||
for axis in ['X', 'Y', 'Z']:
|
||||
if axis in pose and axis in frame_offset:
|
||||
transformed[axis] = pose[axis] + frame_offset[axis]
|
||||
|
||||
# Apply rotational offset (simple addition for small angles)
|
||||
for axis in ['A', 'B', 'C']:
|
||||
if axis in pose and axis in frame_offset:
|
||||
transformed[axis] = pose[axis] + frame_offset[axis]
|
||||
|
||||
return transformed
|
||||
|
||||
|
||||
# Helper functions for velocity profiling
|
||||
|
||||
def _calculate_distance(p1: Dict[str, float], p2: Dict[str, float]) -> float:
|
||||
"""Calculate Euclidean distance between two waypoints."""
|
||||
squared_diff = 0.0
|
||||
keys = set(p1.keys()) & set(p2.keys())
|
||||
for key in keys:
|
||||
if key in ['X', 'Y', 'Z', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6']:
|
||||
squared_diff += (p2[key] - p1[key]) ** 2
|
||||
return math.sqrt(squared_diff)
|
||||
|
||||
|
||||
def _trapezoidal_profile(
|
||||
distances: List[float],
|
||||
total_distance: float,
|
||||
max_velocity: float,
|
||||
max_acceleration: float
|
||||
) -> List[float]:
|
||||
"""
|
||||
Generate trapezoidal velocity profile.
|
||||
|
||||
Accelerates at max_acceleration until reaching max_velocity,
|
||||
maintains constant velocity, then decelerates symmetrically.
|
||||
"""
|
||||
n = len(distances) + 1
|
||||
velocities = [0.0] * n
|
||||
|
||||
# Calculate acceleration/deceleration distances
|
||||
accel_distance = (max_velocity ** 2) / (2 * max_acceleration)
|
||||
|
||||
if 2 * accel_distance >= total_distance:
|
||||
# Triangular profile (no constant velocity phase)
|
||||
peak_velocity = math.sqrt(max_acceleration * total_distance)
|
||||
distance_traveled = 0.0
|
||||
|
||||
for i in range(n):
|
||||
if distance_traveled < total_distance / 2:
|
||||
# Acceleration phase
|
||||
velocities[i] = min(peak_velocity, math.sqrt(max(0, 2 * max_acceleration * distance_traveled)))
|
||||
else:
|
||||
# Deceleration phase
|
||||
remaining = total_distance - distance_traveled
|
||||
velocities[i] = min(peak_velocity, math.sqrt(max(0, 2 * max_acceleration * remaining)))
|
||||
|
||||
if i < len(distances):
|
||||
distance_traveled += distances[i]
|
||||
else:
|
||||
# Full trapezoidal profile
|
||||
distance_traveled = 0.0
|
||||
|
||||
for i in range(n):
|
||||
if distance_traveled < accel_distance:
|
||||
# Acceleration phase
|
||||
velocities[i] = math.sqrt(max(0, 2 * max_acceleration * distance_traveled))
|
||||
elif distance_traveled < (total_distance - accel_distance):
|
||||
# Constant velocity phase
|
||||
velocities[i] = max_velocity
|
||||
else:
|
||||
# Deceleration phase
|
||||
remaining = total_distance - distance_traveled
|
||||
velocities[i] = math.sqrt(max(0, 2 * max_acceleration * remaining))
|
||||
|
||||
if i < len(distances):
|
||||
distance_traveled += distances[i]
|
||||
|
||||
return velocities
|
||||
|
||||
|
||||
def _s_curve_profile(
|
||||
distances: List[float],
|
||||
total_distance: float,
|
||||
max_velocity: float,
|
||||
max_acceleration: float
|
||||
) -> List[float]:
|
||||
"""
|
||||
Generate S-curve velocity profile (jerk-limited).
|
||||
|
||||
Smooth acceleration/deceleration with limited jerk for
|
||||
reduced vibration and smoother motion.
|
||||
"""
|
||||
n = len(distances) + 1
|
||||
velocities = [0.0] * n
|
||||
|
||||
# Simplified S-curve: use sine function for smooth transitions
|
||||
distance_traveled = 0.0
|
||||
|
||||
for i in range(n):
|
||||
# Normalized position [0, 1]
|
||||
s = distance_traveled / total_distance if total_distance > 0 else 0
|
||||
|
||||
# S-curve using sine function
|
||||
# Smooth acceleration at start, smooth deceleration at end
|
||||
if s < 0.5:
|
||||
# First half: smooth acceleration
|
||||
v_normalized = 0.5 * (1 - math.cos(2 * math.pi * s))
|
||||
else:
|
||||
# Second half: smooth deceleration
|
||||
v_normalized = 0.5 * (1 - math.cos(2 * math.pi * (1 - s)))
|
||||
|
||||
velocities[i] = v_normalized * max_velocity
|
||||
|
||||
if i < len(distances):
|
||||
distance_traveled += distances[i]
|
||||
|
||||
return velocities
|
||||
|
||||
|
||||
def _find_blend_point(
|
||||
trajectory: List[Dict[str, float]],
|
||||
blend_radius: float,
|
||||
from_end: bool = False
|
||||
) -> int:
|
||||
"""Find trajectory index at specified distance from start or end."""
|
||||
if from_end:
|
||||
trajectory = list(reversed(trajectory))
|
||||
|
||||
distance = 0.0
|
||||
for i in range(len(trajectory) - 1):
|
||||
distance += _calculate_distance(trajectory[i], trajectory[i + 1])
|
||||
if distance >= blend_radius:
|
||||
return (len(trajectory) - 1 - i) if from_end else i
|
||||
|
||||
# Blend radius exceeds trajectory length
|
||||
return (len(trajectory) // 2) if from_end else (len(trajectory) // 2)
|
||||
|
||||
|
||||
def _cubic_blend(
|
||||
p1: Dict[str, float],
|
||||
p2: Dict[str, float],
|
||||
steps: int
|
||||
) -> List[Dict[str, float]]:
|
||||
"""Generate cubic interpolation between two points."""
|
||||
blend = []
|
||||
keys = set(p1.keys()) | set(p2.keys())
|
||||
|
||||
for i in range(steps):
|
||||
t = i / max(steps - 1, 1)
|
||||
# Cubic Hermite spline with zero velocity at endpoints
|
||||
h1 = 2 * t**3 - 3 * t**2 + 1
|
||||
h2 = -2 * t**3 + 3 * t**2
|
||||
|
||||
point = {}
|
||||
for key in keys:
|
||||
v1 = p1.get(key, 0)
|
||||
v2 = p2.get(key, 0)
|
||||
point[key] = h1 * v1 + h2 * v2
|
||||
|
||||
blend.append(point)
|
||||
|
||||
return blend
|
||||
# TODO (Phase 4): Implement advanced motion features
|
||||
# def generate_velocity_profile(self, trajectory, profile='trapezoidal'):
|
||||
# """Apply velocity profiling to trajectory waypoints."""
|
||||
# pass
|
||||
#
|
||||
# def generate_arc(self, center, radius, start_angle, end_angle, steps):
|
||||
# """Generate circular arc trajectory."""
|
||||
# pass
|
||||
#
|
||||
# def generate_circle(self, center, radius, steps):
|
||||
# """Generate full circle trajectory."""
|
||||
# pass
|
||||
#
|
||||
# def blend_trajectories(self, traj1, traj2, blend_radius):
|
||||
# """Smooth transition between two trajectories."""
|
||||
# pass
|
||||
|
||||
@ -1,33 +1,48 @@
|
||||
import multiprocessing
|
||||
import socket
|
||||
import logging
|
||||
import threading
|
||||
import xml.etree.ElementTree as ET
|
||||
import os
|
||||
import datetime
|
||||
from queue import Empty, Queue as ThreadQueue
|
||||
from queue import Empty
|
||||
from typing import Dict, Any, Tuple, Optional
|
||||
from .xml_handler import XMLGenerator, FastXMLGenerator
|
||||
from .xml_handler import XMLGenerator
|
||||
from .safety_manager import SafetyManager
|
||||
from .exceptions import RSINetworkError, RSITimeoutError, RSIPacketError, RSILoggingError
|
||||
from .timing_metrics import TimingMetrics
|
||||
|
||||
|
||||
class CSVLogger(threading.Thread):
|
||||
class CSVLogger(multiprocessing.Process):
|
||||
"""
|
||||
Background thread for writing CSV logs without blocking the network loop.
|
||||
Separate process for writing CSV logs without blocking the network loop.
|
||||
|
||||
Uses a thread instead of a subprocess to avoid Windows restrictions on
|
||||
daemon processes spawning child processes.
|
||||
Runs in background and consumes log entries from a queue, writing them
|
||||
to CSV file with British date format timestamps.
|
||||
"""
|
||||
|
||||
def __init__(self, log_queue: ThreadQueue, stop_event: threading.Event, filename: str) -> None:
|
||||
super().__init__(daemon=True)
|
||||
self.log_queue = log_queue
|
||||
self.stop_event = stop_event
|
||||
self.filename = filename
|
||||
def __init__(self, log_queue: multiprocessing.Queue, stop_event: multiprocessing.Event, filename: str) -> None:
|
||||
"""
|
||||
Initialize CSV logger process.
|
||||
|
||||
Args:
|
||||
log_queue: Queue containing log entry dictionaries
|
||||
stop_event: Event to signal shutdown
|
||||
filename: Path to output CSV file
|
||||
"""
|
||||
super().__init__()
|
||||
self.log_queue: multiprocessing.Queue = log_queue
|
||||
self.stop_event: multiprocessing.Event = stop_event
|
||||
self.filename: str = filename
|
||||
self.daemon = True
|
||||
|
||||
def run(self) -> None:
|
||||
"""
|
||||
Write log entries from queue to CSV file.
|
||||
|
||||
Creates directory if needed, writes header on first entry,
|
||||
timestamps each row with British date format (DD/MM/YYYY HH:MM:SS.mmm).
|
||||
"""
|
||||
# Ensure logs directory exists
|
||||
log_dir = os.path.dirname(self.filename)
|
||||
if log_dir and not os.path.exists(log_dir):
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
@ -39,14 +54,16 @@ class CSVLogger(threading.Thread):
|
||||
while not self.stop_event.is_set():
|
||||
try:
|
||||
entry = self.log_queue.get(timeout=0.5)
|
||||
if entry is None:
|
||||
if entry is None: # Poison pill
|
||||
break
|
||||
|
||||
# Write header on first entry
|
||||
if not header_written:
|
||||
headers = ['Timestamp'] + list(entry.keys())
|
||||
f.write(','.join(headers) + '\n')
|
||||
header_written = True
|
||||
|
||||
# Write data row
|
||||
timestamp = datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S.%f")[:-3]
|
||||
values = [timestamp] + [str(v) for v in entry.values()]
|
||||
f.write(','.join(values) + '\n')
|
||||
@ -55,10 +72,10 @@ class CSVLogger(threading.Thread):
|
||||
except Empty:
|
||||
continue
|
||||
except Exception as e:
|
||||
logging.error("CSV logging error: %s", e)
|
||||
logging.error(f"CSV logging error: {e}")
|
||||
|
||||
except Exception as e:
|
||||
logging.error("Failed to open log file %s: %s", self.filename, e)
|
||||
logging.error(f"Failed to open log file {self.filename}: {e}")
|
||||
|
||||
|
||||
class NetworkProcess(multiprocessing.Process):
|
||||
@ -80,13 +97,22 @@ class NetworkProcess(multiprocessing.Process):
|
||||
config_parser: Any, # ConfigParser type
|
||||
start_event: multiprocessing.Event,
|
||||
command_queue: multiprocessing.Queue,
|
||||
metrics_dict: Optional[Any] = None, # multiprocessing.Manager().dict()
|
||||
connected_event: Optional[multiprocessing.Event] = None,
|
||||
rsi_mode: str = 'relative',
|
||||
max_cartesian_rate: float = 0.0,
|
||||
max_joint_rate: float = 0.0,
|
||||
cycle_time: float = 0.004
|
||||
metrics_dict: Optional[Any] = None # multiprocessing.Manager().dict()
|
||||
) -> None:
|
||||
"""
|
||||
Initialize network process.
|
||||
|
||||
Args:
|
||||
ip: IP address to bind UDP socket to
|
||||
port: UDP port number
|
||||
send_variables: Shared dict for variables to send to robot
|
||||
receive_variables: Shared dict for variables received from robot
|
||||
stop_event: Event to signal shutdown
|
||||
config_parser: ConfigParser instance with network settings
|
||||
start_event: Event to signal when to start communication
|
||||
command_queue: Queue for receiving commands from parent process
|
||||
metrics_dict: Optional shared dict for timing metrics
|
||||
"""
|
||||
super().__init__()
|
||||
self.send_variables = send_variables
|
||||
self.receive_variables = receive_variables
|
||||
@ -95,24 +121,16 @@ class NetworkProcess(multiprocessing.Process):
|
||||
self.config_parser = config_parser
|
||||
self.command_queue: multiprocessing.Queue = command_queue
|
||||
self.safety_manager: SafetyManager = SafetyManager(config_parser.safety_limits)
|
||||
self.connected_event = connected_event
|
||||
|
||||
# RSI correction mode and rate limiting
|
||||
self.rsi_mode: str = rsi_mode # 'absolute' or 'relative'
|
||||
self.max_cartesian_rate: float = max_cartesian_rate # mm/cycle, 0 = disabled
|
||||
self.max_joint_rate: float = max_joint_rate # degrees/cycle, 0 = disabled
|
||||
self.cycle_time: float = cycle_time # expected cycle time for metrics
|
||||
|
||||
self.client_address: Tuple[str, int] = (ip, port)
|
||||
self.logging_active: Any = multiprocessing.Value('b', False) # c_bool wrapper
|
||||
self.estop_active: Any = multiprocessing.Value('b', False)
|
||||
|
||||
self.controller_ip_and_port: Optional[Tuple[str, int]] = None
|
||||
self.udp_socket: Optional[socket.socket] = None
|
||||
|
||||
# Logging infrastructure (created when logging starts)
|
||||
self.log_queue: Optional[ThreadQueue] = None
|
||||
self.log_stop_event: Optional[threading.Event] = None
|
||||
self.log_queue: Optional[multiprocessing.Queue] = None
|
||||
self.log_stop_event: Optional[multiprocessing.Event] = None
|
||||
self.csv_logger: Optional[CSVLogger] = None
|
||||
|
||||
# Timing metrics (Phase 2)
|
||||
@ -128,8 +146,8 @@ class NetworkProcess(multiprocessing.Process):
|
||||
"""
|
||||
# Initialize timing metrics in child process
|
||||
if self.metrics_dict is not None:
|
||||
self.timing_metrics = TimingMetrics(expected_cycle_time=self.cycle_time)
|
||||
logging.info("Timing metrics initialized (expected cycle: %.1fms)", self.cycle_time * 1000)
|
||||
self.timing_metrics = TimingMetrics()
|
||||
logging.info("Timing metrics initialized")
|
||||
|
||||
# Wait for start signal, but check stop_event periodically to allow clean shutdown
|
||||
while not self.start_event.wait(timeout=0.5):
|
||||
@ -150,137 +168,56 @@ class NetworkProcess(multiprocessing.Process):
|
||||
Falls back to 0.0.0.0 if specified IP is invalid.
|
||||
"""
|
||||
if not self.is_valid_ip(self.client_address[0]):
|
||||
logging.warning("Invalid IP address '%s'. Falling back to '0.0.0.0'.", self.client_address[0])
|
||||
logging.warning(f"Invalid IP address '{self.client_address[0]}'. Falling back to '0.0.0.0'.")
|
||||
self.client_address = ('0.0.0.0', self.client_address[1])
|
||||
|
||||
self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self.udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
self.udp_socket.settimeout(5)
|
||||
self.udp_socket.bind(self.client_address)
|
||||
logging.info("Network process bound on %s", self.client_address)
|
||||
logging.info(f"Network process bound on {self.client_address}")
|
||||
|
||||
def _run_loop(self) -> None:
|
||||
"""
|
||||
Main communication loop.
|
||||
|
||||
Uses local dict snapshots to avoid per-key IPC overhead on
|
||||
multiprocessing.Manager dicts within the 4ms cycle.
|
||||
Receives UDP messages from robot, processes them, sends responses,
|
||||
and optionally logs data to CSV. Records timing metrics if enabled.
|
||||
"""
|
||||
update_counter = 0
|
||||
metrics_counter = 0
|
||||
cmd_counter = 0
|
||||
first_packet = True
|
||||
|
||||
# Variable naming follows KUKA convention (robot's perspective):
|
||||
# send_variables = what the robot SENDS to us (RIst, RSol, IPOC, etc.)
|
||||
# receive_variables = what the robot RECEIVES from us (RKorr, DiO, EStr, etc.)
|
||||
|
||||
# Local working copies — avoid Manager IPC in the hot path
|
||||
local_robot_out = dict(self.send_variables)
|
||||
local_robot_in = dict(self.receive_variables)
|
||||
network_settings = self.config_parser.network_settings
|
||||
|
||||
# FastXMLGenerator for comparison testing
|
||||
fast_gen = FastXMLGenerator(local_robot_in, root_tag="Sen", type_attr=network_settings["sentype"])
|
||||
xml_mismatch_logged = False
|
||||
|
||||
# Cache zero-correction template for E-stop
|
||||
zero_robot_in = dict(self.receive_variables)
|
||||
for key, value in zero_robot_in.items():
|
||||
if isinstance(value, dict):
|
||||
zero_robot_in[key] = {k: 0.0 for k in value}
|
||||
|
||||
# Previous correction state for absolute mode ramping
|
||||
prev_corrections: Dict[str, Dict[str, float]] = {}
|
||||
for key in ('RKorr', 'AKorr'):
|
||||
if key in local_robot_in and isinstance(local_robot_in[key], dict):
|
||||
prev_corrections[key] = {k: 0.0 for k in local_robot_in[key]}
|
||||
update_counter = 0 # For periodic metrics updates
|
||||
|
||||
while not self.stop_event.is_set():
|
||||
# Check for commands periodically (every 50 cycles ~200ms)
|
||||
cmd_counter += 1
|
||||
if cmd_counter >= 50:
|
||||
# Check for commands (non-blocking)
|
||||
self._process_commands()
|
||||
cmd_counter = 0
|
||||
|
||||
try:
|
||||
self.udp_socket.settimeout(5)
|
||||
data_received, self.controller_ip_and_port = self.udp_socket.recvfrom(1024)
|
||||
message = data_received.decode()
|
||||
|
||||
# Parse robot's outgoing data (ElementTree — handles any attribute order)
|
||||
try:
|
||||
self._parse_received_data(message, local_robot_out)
|
||||
except RSIPacketError:
|
||||
logging.warning("Parse failed, sending last known good response")
|
||||
|
||||
# Signal connection on first valid packet
|
||||
if first_packet:
|
||||
first_packet = False
|
||||
if self.connected_event:
|
||||
self.connected_event.set()
|
||||
|
||||
# Snapshot receive_variables to pick up user changes (single IPC call)
|
||||
local_robot_in = dict(self.receive_variables)
|
||||
|
||||
# Sync IPOC: robot sends it, we echo back IPOC+4
|
||||
if "IPOC" in local_robot_out:
|
||||
ipoc = local_robot_out["IPOC"]
|
||||
local_robot_in["IPOC"] = ipoc + 4
|
||||
|
||||
# Rate-limit corrections
|
||||
self._apply_rate_limit(local_robot_in, prev_corrections)
|
||||
|
||||
# E-stop: zero all corrections, keep IPOC sync
|
||||
if self.estop_active.value:
|
||||
estop_response = dict(zero_robot_in)
|
||||
estop_response["IPOC"] = local_robot_in.get("IPOC", 0)
|
||||
send_xml = XMLGenerator.generate_send_xml(estop_response, network_settings)
|
||||
else:
|
||||
send_xml = XMLGenerator.generate_send_xml(local_robot_in, network_settings)
|
||||
|
||||
# Compare FastXMLGenerator output (debug — log first mismatch only)
|
||||
if not xml_mismatch_logged:
|
||||
try:
|
||||
fast_xml = fast_gen.generate(local_robot_in)
|
||||
if fast_xml != send_xml:
|
||||
xml_mismatch_logged = True
|
||||
logging.warning("XML MISMATCH DETECTED")
|
||||
logging.warning("ET output: %s", send_xml[:200])
|
||||
logging.warning("Fast output: %s", fast_xml[:200])
|
||||
elif metrics_counter == 0:
|
||||
# Log match confirmation once (on first sync cycle)
|
||||
logging.info("XML generators match OK")
|
||||
xml_mismatch_logged = True
|
||||
except Exception as e:
|
||||
logging.warning("FastXMLGenerator error: %s", e)
|
||||
xml_mismatch_logged = True
|
||||
|
||||
self.process_received_data(message)
|
||||
send_xml = XMLGenerator.generate_send_xml(self.send_variables, self.config_parser.network_settings)
|
||||
self.udp_socket.sendto(send_xml.encode(), self.controller_ip_and_port)
|
||||
|
||||
# Sync robot's outgoing data → Manager dict periodically (every 10 cycles ~40ms)
|
||||
metrics_counter += 1
|
||||
if metrics_counter >= 10:
|
||||
self.send_variables.update(local_robot_out)
|
||||
metrics_counter = 0
|
||||
|
||||
# Record timing metrics (Phase 2)
|
||||
if self.timing_metrics is not None:
|
||||
self.timing_metrics.record_cycle(local_robot_out.get("IPOC", 0))
|
||||
ipoc = self.receive_variables.get("IPOC", 0)
|
||||
self.timing_metrics.record_cycle(ipoc)
|
||||
|
||||
# Update shared metrics dict every 100 cycles (~400ms)
|
||||
update_counter += 1
|
||||
if update_counter >= 100:
|
||||
self._update_metrics_dict()
|
||||
update_counter = 0
|
||||
|
||||
if self.logging_active.value and self.log_queue:
|
||||
self._queue_log_entry(local_robot_out, local_robot_in)
|
||||
self._queue_log_entry()
|
||||
|
||||
except socket.timeout:
|
||||
logging.warning("No message received within timeout period")
|
||||
# Check watchdog on timeout
|
||||
if self.timing_metrics and self.timing_metrics.check_watchdog():
|
||||
logging.error("Watchdog timeout - communication lost!")
|
||||
except Exception as e:
|
||||
logging.error("Network process error: %s", e)
|
||||
logging.error(f"Network process error: {e}")
|
||||
|
||||
def _process_commands(self) -> None:
|
||||
"""Process any pending commands from the parent process."""
|
||||
@ -295,64 +232,14 @@ class NetworkProcess(multiprocessing.Process):
|
||||
self._start_logging(cmd.get('filename'))
|
||||
elif action == 'stop_logging':
|
||||
self._stop_logging()
|
||||
elif action == 'estop':
|
||||
self.estop_active.value = True
|
||||
elif action == 'estop_reset':
|
||||
self.estop_active.value = False
|
||||
|
||||
except Empty:
|
||||
pass
|
||||
except Exception as e:
|
||||
logging.error("Error processing command: %s", e)
|
||||
|
||||
def _apply_rate_limit(self, robot_in: dict, prev: Dict[str, Dict[str, float]]) -> None:
|
||||
"""
|
||||
Apply per-cycle rate limiting to correction values in-place.
|
||||
|
||||
In relative mode: clamp each value directly (it IS the per-cycle delta).
|
||||
In absolute mode: clamp the change from previous cycle and ramp toward target.
|
||||
|
||||
Args:
|
||||
robot_in: Current outgoing corrections dict (modified in-place)
|
||||
prev: Previous cycle's correction values (updated in-place)
|
||||
"""
|
||||
cartesian_keys = {'X', 'Y', 'Z', 'A', 'B', 'C'}
|
||||
joint_keys = {'A1', 'A2', 'A3', 'A4', 'A5', 'A6'}
|
||||
|
||||
for corr_key, max_rate, axis_set in [
|
||||
('RKorr', self.max_cartesian_rate, cartesian_keys),
|
||||
('AKorr', self.max_joint_rate, joint_keys),
|
||||
]:
|
||||
if max_rate <= 0:
|
||||
continue # Rate limiting disabled for this type
|
||||
if corr_key not in robot_in or not isinstance(robot_in[corr_key], dict):
|
||||
continue
|
||||
|
||||
corr = robot_in[corr_key]
|
||||
prev_corr = prev.get(corr_key, {})
|
||||
|
||||
if self.rsi_mode == 'relative':
|
||||
# Each value is a per-cycle delta — clamp directly
|
||||
for axis in corr:
|
||||
if axis in axis_set:
|
||||
val = corr[axis]
|
||||
corr[axis] = max(-max_rate, min(max_rate, val))
|
||||
else:
|
||||
# Absolute mode — clamp the change from previous
|
||||
for axis in corr:
|
||||
if axis in axis_set:
|
||||
target = corr[axis]
|
||||
previous = prev_corr.get(axis, 0.0)
|
||||
delta = target - previous
|
||||
clamped_delta = max(-max_rate, min(max_rate, delta))
|
||||
corr[axis] = previous + clamped_delta
|
||||
prev_corr[axis] = corr[axis]
|
||||
|
||||
robot_in[corr_key] = corr
|
||||
prev[corr_key] = prev_corr
|
||||
logging.error(f"Error processing command: {e}")
|
||||
|
||||
def _update_metrics_dict(self) -> None:
|
||||
"""Update shared metrics dictionary with current timing statistics."""
|
||||
"""Update shared metrics dictionary with current timing statistics (Phase 2)."""
|
||||
if self.metrics_dict is None or self.timing_metrics is None:
|
||||
return
|
||||
|
||||
@ -360,6 +247,7 @@ class NetworkProcess(multiprocessing.Process):
|
||||
stats = self.timing_metrics.get_current_stats()
|
||||
health = self.timing_metrics.get_health_status()
|
||||
|
||||
# Update shared dict (Manager dict supports item assignment)
|
||||
for key, value in stats.items():
|
||||
self.metrics_dict[key] = value
|
||||
|
||||
@ -368,48 +256,56 @@ class NetworkProcess(multiprocessing.Process):
|
||||
self.metrics_dict['watchdog_timeout'] = health['watchdog_timeout']
|
||||
|
||||
except Exception as e:
|
||||
logging.debug("Failed to update metrics dict: %s", e)
|
||||
logging.debug(f"Failed to update metrics dict: {e}")
|
||||
|
||||
def _queue_log_entry(self, local_robot_out: dict, local_robot_in: dict) -> None:
|
||||
"""Queue current state for CSV logging using local dicts (no IPC)."""
|
||||
def _queue_log_entry(self) -> None:
|
||||
"""Queue current state for CSV logging (non-blocking)."""
|
||||
try:
|
||||
entry = {}
|
||||
for key, value in local_robot_out.items():
|
||||
# Flatten send variables
|
||||
for key, value in dict(self.send_variables).items():
|
||||
if isinstance(value, dict):
|
||||
for subkey, subval in value.items():
|
||||
entry[f"Send.{key}.{subkey}"] = subval
|
||||
else:
|
||||
entry[f"Send.{key}"] = value
|
||||
|
||||
for key, value in local_robot_in.items():
|
||||
# Flatten receive variables
|
||||
for key, value in dict(self.receive_variables).items():
|
||||
if isinstance(value, dict):
|
||||
for subkey, subval in value.items():
|
||||
entry[f"Receive.{key}.{subkey}"] = subval
|
||||
else:
|
||||
entry[f"Receive.{key}"] = value
|
||||
|
||||
# Non-blocking put - drop entry if queue is full
|
||||
try:
|
||||
self.log_queue.put_nowait(entry)
|
||||
except:
|
||||
pass # Queue full, skip this entry rather than block
|
||||
|
||||
except Exception as e:
|
||||
logging.debug("Failed to queue log entry: %s", e)
|
||||
logging.debug(f"Failed to queue log entry: {e}")
|
||||
|
||||
def _start_logging(self, filename: str) -> None:
|
||||
"""Start CSV logging to the specified file."""
|
||||
"""
|
||||
Start CSV logging to the specified file.
|
||||
|
||||
Args:
|
||||
filename: Path to CSV output file
|
||||
"""
|
||||
if self.logging_active.value:
|
||||
logging.warning("Logging already active")
|
||||
return
|
||||
|
||||
self.log_queue = ThreadQueue(maxsize=1000)
|
||||
self.log_stop_event = threading.Event()
|
||||
self.log_queue = multiprocessing.Queue(maxsize=1000)
|
||||
self.log_stop_event = multiprocessing.Event()
|
||||
|
||||
self.csv_logger = CSVLogger(self.log_queue, self.log_stop_event, filename)
|
||||
self.csv_logger.start()
|
||||
|
||||
self.logging_active.value = True
|
||||
logging.info("CSV logging started: %s", filename)
|
||||
logging.info(f"CSV logging started: {filename}")
|
||||
|
||||
def _stop_logging(self) -> None:
|
||||
"""Stop CSV logging and cleanup resources."""
|
||||
@ -429,6 +325,8 @@ class NetworkProcess(multiprocessing.Process):
|
||||
|
||||
if self.csv_logger and self.csv_logger.is_alive():
|
||||
self.csv_logger.join(timeout=2)
|
||||
if self.csv_logger.is_alive():
|
||||
self.csv_logger.terminate()
|
||||
|
||||
self.csv_logger = None
|
||||
self.log_queue = None
|
||||
@ -437,6 +335,7 @@ class NetworkProcess(multiprocessing.Process):
|
||||
|
||||
def _cleanup(self) -> None:
|
||||
"""Clean up resources on shutdown."""
|
||||
# Stop logging first
|
||||
self._stop_logging()
|
||||
|
||||
if self.udp_socket:
|
||||
@ -444,11 +343,20 @@ class NetworkProcess(multiprocessing.Process):
|
||||
self.udp_socket.close()
|
||||
logging.info("Network socket closed")
|
||||
except Exception as e:
|
||||
logging.error("Error closing socket: %s", e)
|
||||
logging.error(f"Error closing socket: {e}")
|
||||
self.udp_socket = None
|
||||
|
||||
@staticmethod
|
||||
def is_valid_ip(ip: str) -> bool:
|
||||
"""
|
||||
Check if an IP address is valid and bindable.
|
||||
|
||||
Args:
|
||||
ip: IP address string to validate
|
||||
|
||||
Returns:
|
||||
True if IP is valid and can be bound to
|
||||
"""
|
||||
try:
|
||||
socket.inet_aton(ip)
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
|
||||
@ -457,33 +365,33 @@ class NetworkProcess(multiprocessing.Process):
|
||||
except (socket.error, OSError):
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _parse_received_data(xml_string: str, target: dict) -> None:
|
||||
"""Parse received XML message into a local dict (no IPC)."""
|
||||
def process_received_data(self, xml_string: str) -> None:
|
||||
"""
|
||||
Parse received XML message and update receive_variables.
|
||||
|
||||
Handles IPOC synchronization by echoing back IPOC+4.
|
||||
|
||||
Args:
|
||||
xml_string: XML message string from robot controller
|
||||
|
||||
Raises:
|
||||
RSIPacketError: If XML parsing fails
|
||||
"""
|
||||
try:
|
||||
root = ET.fromstring(xml_string)
|
||||
for element in root:
|
||||
if element.tag in target:
|
||||
if element.tag in self.receive_variables:
|
||||
if len(element.attrib) > 0:
|
||||
existing = target.get(element.tag)
|
||||
if isinstance(existing, dict):
|
||||
for k, v in element.attrib.items():
|
||||
existing[k] = float(v)
|
||||
self.receive_variables[element.tag] = {k: float(v) for k, v in element.attrib.items()}
|
||||
else:
|
||||
target[element.tag] = {k: float(v) for k, v in element.attrib.items()}
|
||||
else:
|
||||
target[element.tag] = element.text
|
||||
self.receive_variables[element.tag] = element.text
|
||||
if element.tag == "IPOC":
|
||||
target["IPOC"] = int(element.text)
|
||||
received_ipoc = int(element.text)
|
||||
self.receive_variables["IPOC"] = received_ipoc
|
||||
self.send_variables["IPOC"] = received_ipoc + 4
|
||||
except ET.ParseError as e:
|
||||
logging.error("XML parse error in received message: %s", e)
|
||||
logging.error(f"XML parse error in received message: {e}")
|
||||
raise RSIPacketError(f"Failed to parse received XML: {e}") from e
|
||||
except Exception as e:
|
||||
logging.error("Error processing received message: %s", e)
|
||||
logging.error(f"Error processing received message: {e}")
|
||||
raise RSIPacketError(f"Unexpected error parsing packet: {e}") from e
|
||||
|
||||
def process_received_data(self, xml_string: str) -> None:
|
||||
"""Legacy method kept for compatibility (e.g. echo server)."""
|
||||
self._parse_received_data(xml_string, self.send_variables)
|
||||
if "IPOC" in self.send_variables:
|
||||
self.receive_variables["IPOC"] = self.send_variables["IPOC"] + 4
|
||||
|
||||
@ -26,38 +26,60 @@ class RSIAPI:
|
||||
"""
|
||||
High-level API orchestrator for KUKA RSI robot control.
|
||||
|
||||
Supports context manager usage for safe cleanup:
|
||||
>>> with RSIAPI('RSI_EthernetConfig.xml') as api:
|
||||
... api.start()
|
||||
... api.motion.update_cartesian(X=10)
|
||||
Provides namespaced access to all RSIPI functionality through specialized
|
||||
sub-APIs. This is the main entry point for most users.
|
||||
|
||||
Namespaces:
|
||||
- motion: Motion control (Cartesian, joints, trajectories)
|
||||
- io: Digital I/O control
|
||||
- krl: KRL program manipulation utilities
|
||||
- safety: Safety management and limits
|
||||
- monitoring: Live data access and monitoring
|
||||
- logging: CSV data logging
|
||||
- diagnostics: Network and performance diagnostics (Phase 2)
|
||||
- viz: Static and live visualization
|
||||
- tools: Utilities, debugging, and inspection
|
||||
|
||||
Core Methods (direct access):
|
||||
- start(): Start RSI communication
|
||||
- stop(): Stop RSI communication
|
||||
- reconnect(): Restart network connection
|
||||
- state: Current client state (property)
|
||||
|
||||
Example:
|
||||
>>> api = RSIAPI('RSI_EthernetConfig.xml')
|
||||
>>> api.start()
|
||||
>>> api.motion.update_cartesian(X=10, Y=5, Z=0)
|
||||
>>> api.logging.start('test.csv')
|
||||
>>> # ... robot operation ...
|
||||
>>> api.logging.stop()
|
||||
>>> api.stop()
|
||||
>>> api.viz.plot_static('test.csv', '3d')
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config_file: str = "RSI_EthernetConfig.xml",
|
||||
rsi_mode: str = 'relative',
|
||||
max_cartesian_rate: float = 0.0,
|
||||
max_joint_rate: float = 0.0,
|
||||
cycle_time: float = 0.004
|
||||
) -> None:
|
||||
def __init__(self, config_file: str = "RSI_EthernetConfig.xml") -> None:
|
||||
"""
|
||||
Initialize RSIAPI with configuration file.
|
||||
|
||||
Creates RSIClient instance (lazy initialization) and sets up all
|
||||
namespace APIs for organized access to functionality.
|
||||
|
||||
Args:
|
||||
config_file: Path to RSI_EthernetConfig.xml
|
||||
rsi_mode: 'absolute' or 'relative' — must match KRL RSI_MOVECORR() mode
|
||||
max_cartesian_rate: Max mm/cycle for RKorr corrections (0 = no limit)
|
||||
max_joint_rate: Max degrees/cycle for AKorr corrections (0 = no limit)
|
||||
cycle_time: Expected RSI cycle time in seconds (0.004 = 4ms/250Hz, 0.012 = 12ms/83Hz)
|
||||
config_file: Path to RSI_EthernetConfig.xml configuration file
|
||||
|
||||
Example:
|
||||
>>> api = RSIAPI('config/RSI_EthernetConfig.xml')
|
||||
>>> print(api.state)
|
||||
ClientState.INITIALIZED
|
||||
"""
|
||||
self.config_file: str = config_file
|
||||
self.rsi_mode: str = rsi_mode
|
||||
self.max_cartesian_rate: float = max_cartesian_rate
|
||||
self.max_joint_rate: float = max_joint_rate
|
||||
self.cycle_time: float = cycle_time
|
||||
self.client: Optional['RSIClient'] = None
|
||||
self._thread: Optional[Thread] = None
|
||||
|
||||
# Initialize client
|
||||
self._ensure_client()
|
||||
|
||||
# Initialize namespace APIs
|
||||
self.motion = MotionAPI(self.client)
|
||||
self.io = IOAPI(self.client)
|
||||
self.krl = KRLAPI(self.client)
|
||||
@ -70,79 +92,151 @@ class RSIAPI:
|
||||
|
||||
logging.info("RSIAPI initialized with namespaced structure")
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
try:
|
||||
self.stop()
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
def _ensure_client(self) -> None:
|
||||
"""
|
||||
Ensure RSIClient is initialized (lazy initialization).
|
||||
|
||||
Imports and creates RSIClient only when needed, avoiding circular
|
||||
dependencies and improving startup time.
|
||||
"""
|
||||
if self.client is None:
|
||||
from .rsi_client import RSIClient
|
||||
self.client = RSIClient(
|
||||
self.config_file,
|
||||
rsi_mode=self.rsi_mode,
|
||||
max_cartesian_rate=self.max_cartesian_rate,
|
||||
max_joint_rate=self.max_joint_rate,
|
||||
cycle_time=self.cycle_time
|
||||
)
|
||||
self.client = RSIClient(self.config_file)
|
||||
logging.debug("RSIClient initialized")
|
||||
|
||||
@property
|
||||
def state(self) -> 'ClientState':
|
||||
"""
|
||||
Get current client state.
|
||||
|
||||
Returns:
|
||||
ClientState enum value (INITIALIZED, STARTING, RUNNING, STOPPING, STOPPED, ERROR)
|
||||
|
||||
Example:
|
||||
>>> api = RSIAPI()
|
||||
>>> print(api.state)
|
||||
ClientState.INITIALIZED
|
||||
>>> api.start()
|
||||
>>> print(api.state)
|
||||
ClientState.RUNNING
|
||||
"""
|
||||
return self.client.state
|
||||
|
||||
def start(self) -> str:
|
||||
"""Start RSI communication in background thread."""
|
||||
"""
|
||||
Start RSI communication in background thread.
|
||||
|
||||
Creates a daemon thread that runs the RSI client's main communication
|
||||
loop. The thread handles UDP message exchange with the robot controller.
|
||||
|
||||
Returns:
|
||||
Status message
|
||||
|
||||
Raises:
|
||||
RSIClientNotReady: If client is not in appropriate state to start
|
||||
|
||||
Example:
|
||||
>>> api = RSIAPI()
|
||||
>>> api.start()
|
||||
'RSI started in background'
|
||||
>>> api.state
|
||||
ClientState.RUNNING
|
||||
|
||||
Note:
|
||||
The background thread runs as a daemon, so it will automatically
|
||||
terminate when the main program exits.
|
||||
"""
|
||||
self._thread = Thread(target=self.client.start, daemon=True)
|
||||
self._thread.start()
|
||||
logging.info("RSI communication started in background thread")
|
||||
return "RSI started in background"
|
||||
|
||||
def stop(self) -> str:
|
||||
"""Stop RSI communication gracefully."""
|
||||
"""
|
||||
Stop RSI communication.
|
||||
|
||||
Gracefully shuts down the network process, closes sockets, and
|
||||
stops any active logging. Waits for background threads to complete.
|
||||
|
||||
Returns:
|
||||
Status message
|
||||
|
||||
Example:
|
||||
>>> api.stop()
|
||||
'RSI stopped'
|
||||
|
||||
Note:
|
||||
This method blocks until the network process has fully shut down,
|
||||
which typically takes 1-3 seconds.
|
||||
"""
|
||||
self.client.stop()
|
||||
if self._thread and self._thread.is_alive():
|
||||
self._thread.join(timeout=3)
|
||||
self._thread = None
|
||||
logging.info("RSI communication stopped")
|
||||
return "RSI stopped"
|
||||
|
||||
def wait_for_connection(self, timeout: float = 10.0) -> bool:
|
||||
def reconnect(self) -> str:
|
||||
"""
|
||||
Block until the robot's first packet is received.
|
||||
Restart network connection without stopping RSI client.
|
||||
|
||||
Args:
|
||||
timeout: Maximum time to wait in seconds
|
||||
Terminates the current network process, creates a fresh one with new
|
||||
communication resources, and restarts the connection. Useful for
|
||||
recovering from network errors.
|
||||
|
||||
Returns:
|
||||
True if connected, False if timeout
|
||||
"""
|
||||
return self.client.wait_for_connection(timeout)
|
||||
Status message
|
||||
|
||||
def reconnect(self) -> str:
|
||||
"""Restart network connection with fresh resources."""
|
||||
Example:
|
||||
>>> # Network issue detected
|
||||
>>> api.reconnect()
|
||||
'Network connection restarted'
|
||||
|
||||
Note:
|
||||
This creates fresh multiprocessing Events and Queues. Any queued
|
||||
but unprocessed data in the old network process will be lost.
|
||||
"""
|
||||
self.client.reconnect()
|
||||
# Start client in new thread
|
||||
self._thread = Thread(target=self.client.start, daemon=True)
|
||||
self._thread.start()
|
||||
logging.info("Network connection restarted")
|
||||
return "Network connection restarted"
|
||||
|
||||
def is_running(self) -> bool:
|
||||
"""
|
||||
Check if RSI client is in RUNNING state.
|
||||
|
||||
Returns:
|
||||
True if actively communicating with robot
|
||||
|
||||
Example:
|
||||
>>> api = RSIAPI()
|
||||
>>> api.is_running()
|
||||
False
|
||||
>>> api.start()
|
||||
>>> api.is_running()
|
||||
True
|
||||
"""
|
||||
return self.client.is_running()
|
||||
|
||||
def is_stopped(self) -> bool:
|
||||
"""
|
||||
Check if RSI client is fully stopped.
|
||||
|
||||
Returns:
|
||||
True if in STOPPED state
|
||||
|
||||
Example:
|
||||
>>> api.stop()
|
||||
>>> api.is_stopped()
|
||||
True
|
||||
"""
|
||||
return self.client.is_stopped()
|
||||
|
||||
# Deprecated methods
|
||||
# Deprecated methods for backward compatibility (Phase 5.1 - to be removed)
|
||||
# These are kept temporarily to ease migration. Use namespaced methods instead.
|
||||
|
||||
def start_rsi(self) -> str:
|
||||
"""DEPRECATED: Use api.start() instead."""
|
||||
logging.warning("start_rsi() is deprecated. Use api.start() instead.")
|
||||
return self.start()
|
||||
|
||||
def stop_rsi(self) -> str:
|
||||
"""DEPRECATED: Use api.stop() instead."""
|
||||
logging.warning("stop_rsi() is deprecated. Use api.stop() instead.")
|
||||
return self.stop()
|
||||
|
||||
@ -192,11 +192,5 @@ Available Commands:
|
||||
""")
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser(description="RSI Command-Line Interface")
|
||||
parser.add_argument("--config", type=str, default="RSI_EthernetConfig.xml",
|
||||
help="Path to RSI config XML file (default: RSI_EthernetConfig.xml)")
|
||||
args = parser.parse_args()
|
||||
|
||||
cli = RSICommandLineInterface(args.config)
|
||||
cli = RSICommandLineInterface("../../examples/RSI_EthernetConfig.xml")
|
||||
cli.run()
|
||||
|
||||
@ -8,7 +8,6 @@ from .config_parser import ConfigParser
|
||||
from .network_handler import NetworkProcess
|
||||
from .safety_manager import SafetyManager
|
||||
from .exceptions import RSIStateError, RSIInvalidTransition, RSIClientNotReady
|
||||
from .auto_reconnect import AutoReconnectManager, ReconnectStrategy
|
||||
|
||||
|
||||
class ClientState(Enum):
|
||||
@ -24,44 +23,25 @@ class ClientState(Enum):
|
||||
class RSIClient:
|
||||
"""Main RSI API class that integrates network, config handling, and message processing."""
|
||||
|
||||
# Valid state transitions
|
||||
_VALID_TRANSITIONS = {
|
||||
ClientState.INITIALIZED: {ClientState.STARTING, ClientState.STOPPING},
|
||||
ClientState.STARTING: {ClientState.RUNNING, ClientState.STOPPING, ClientState.ERROR},
|
||||
ClientState.RUNNING: {ClientState.STOPPING, ClientState.ERROR},
|
||||
ClientState.STOPPING: {ClientState.STOPPED, ClientState.ERROR},
|
||||
ClientState.STOPPED: {ClientState.INITIALIZED},
|
||||
ClientState.ERROR: {ClientState.STOPPING, ClientState.INITIALIZED},
|
||||
ClientState.STOPPED: {ClientState.INITIALIZED}, # Via reconnect
|
||||
ClientState.ERROR: {ClientState.STOPPING, ClientState.INITIALIZED}, # Via reconnect
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config_file: str,
|
||||
rsi_limits_file: Optional[str] = None,
|
||||
enable_auto_reconnect: bool = False,
|
||||
auto_reconnect_retries: int = 5,
|
||||
auto_reconnect_delay: float = 5.0,
|
||||
rsi_mode: str = 'relative',
|
||||
max_cartesian_rate: float = 0.0,
|
||||
max_joint_rate: float = 0.0,
|
||||
cycle_time: float = 0.004
|
||||
) -> None:
|
||||
def __init__(self, config_file: str, rsi_limits_file: Optional[str] = None) -> None:
|
||||
"""
|
||||
Initialize RSI client with configuration and safety limits.
|
||||
|
||||
Args:
|
||||
config_file: Path to RSI_EthernetConfig.xml
|
||||
rsi_limits_file: Optional path to .rsi.xml safety limits file
|
||||
enable_auto_reconnect: Enable automatic reconnection on communication loss
|
||||
auto_reconnect_retries: Maximum reconnection attempts (0 = unlimited)
|
||||
auto_reconnect_delay: Base delay between retries in seconds
|
||||
rsi_mode: 'absolute' or 'relative' — must match KRL RSI_MOVECORR() mode
|
||||
max_cartesian_rate: Max mm/cycle for RKorr corrections (0 = disabled)
|
||||
max_joint_rate: Max degrees/cycle for AKorr corrections (0 = disabled)
|
||||
cycle_time: Expected RSI cycle time in seconds (0.004 or 0.012)
|
||||
"""
|
||||
logging.info("Loading RSI configuration from %s...", config_file)
|
||||
self.rsi_mode = rsi_mode
|
||||
self.max_cartesian_rate = max_cartesian_rate
|
||||
self.max_joint_rate = max_joint_rate
|
||||
self.cycle_time = cycle_time
|
||||
logging.info(f"Loading RSI configuration from {config_file}...")
|
||||
|
||||
self._state: ClientState = ClientState.INITIALIZED
|
||||
self._state_lock: Lock = Lock()
|
||||
@ -69,86 +49,22 @@ class RSIClient:
|
||||
self.config_parser: ConfigParser = ConfigParser(config_file, rsi_limits_file)
|
||||
network_settings = self.config_parser.get_network_settings()
|
||||
|
||||
# Validate config on startup
|
||||
self._validate_config()
|
||||
|
||||
self.manager: multiprocessing.Manager = multiprocessing.Manager()
|
||||
self.send_variables = self.manager.dict(self.config_parser.send_variables)
|
||||
self.receive_variables = self.manager.dict(self.config_parser.receive_variables)
|
||||
self.stop_event: multiprocessing.Event = multiprocessing.Event()
|
||||
self.start_event: multiprocessing.Event = multiprocessing.Event()
|
||||
self.connected_event: multiprocessing.Event = multiprocessing.Event()
|
||||
self.command_queue: multiprocessing.Queue = multiprocessing.Queue()
|
||||
|
||||
self.safety_manager: SafetyManager = SafetyManager(self.config_parser.safety_limits)
|
||||
|
||||
# Shared logging state (readable from parent process)
|
||||
self._logging_active = multiprocessing.Value('b', False)
|
||||
self._receive_dirty = multiprocessing.Value('b', True) # Dirty flag for IPC optimization
|
||||
|
||||
# Shared metrics dictionary (Phase 2)
|
||||
self.metrics_dict = self.manager.dict()
|
||||
|
||||
self._create_network_process(network_settings)
|
||||
|
||||
self.logger: Optional[any] = None
|
||||
self.running: bool = False
|
||||
self.thread: Optional[Thread] = None
|
||||
|
||||
self.auto_reconnect_manager: Optional[AutoReconnectManager] = None
|
||||
if enable_auto_reconnect:
|
||||
self.auto_reconnect_manager = AutoReconnectManager(
|
||||
client=self,
|
||||
enabled=True,
|
||||
max_retries=auto_reconnect_retries,
|
||||
retry_delay=auto_reconnect_delay,
|
||||
strategy=ReconnectStrategy.LINEAR_BACKOFF
|
||||
)
|
||||
logging.info("Auto-reconnect enabled")
|
||||
|
||||
def _validate_config(self) -> None:
|
||||
"""Validate config and warn about common misconfigurations."""
|
||||
send = self.config_parser.send_variables
|
||||
recv = self.config_parser.receive_variables
|
||||
|
||||
# Check correction variables are in receive (what we send to robot)
|
||||
if "RKorr" not in recv and "AKorr" not in recv:
|
||||
logging.warning(
|
||||
"Config validation: Neither RKorr nor AKorr found in RECEIVE section. "
|
||||
"You won't be able to send motion corrections to the robot. "
|
||||
"Check your RSI_EthernetConfig.xml <RECEIVE> elements."
|
||||
)
|
||||
|
||||
# Check position feedback is in send (what robot sends to us)
|
||||
if "RIst" not in send:
|
||||
logging.warning(
|
||||
"Config validation: RIst not found in SEND section. "
|
||||
"You won't receive Cartesian position feedback from the robot."
|
||||
)
|
||||
|
||||
if "IPOC" not in send:
|
||||
logging.warning(
|
||||
"Config validation: IPOC not found in SEND section. "
|
||||
"IPOC synchronisation may not work correctly."
|
||||
)
|
||||
|
||||
# Validate RSI mode
|
||||
if self.rsi_mode not in ('absolute', 'relative'):
|
||||
logging.warning(
|
||||
"Config validation: rsi_mode='%s' is not valid. "
|
||||
"Use 'absolute' or 'relative'. Defaulting to 'relative'.",
|
||||
self.rsi_mode
|
||||
)
|
||||
self.rsi_mode = 'relative'
|
||||
|
||||
# Log summary
|
||||
send_keys = [k for k in send if k != "IPOC"]
|
||||
recv_keys = [k for k in recv if k not in ("IPOC", "FREE")]
|
||||
logging.info(
|
||||
"Config validated: SEND=[%s] RECEIVE=[%s] mode=%s",
|
||||
", ".join(send_keys), ", ".join(recv_keys), self.rsi_mode
|
||||
)
|
||||
|
||||
def _create_network_process(self, network_settings: dict) -> None:
|
||||
"""Create and start the NetworkProcess with current settings."""
|
||||
# Create NetworkProcess but don't start communication yet
|
||||
self.network_process: NetworkProcess = NetworkProcess(
|
||||
network_settings["ip"],
|
||||
network_settings["port"],
|
||||
@ -158,17 +74,16 @@ class RSIClient:
|
||||
self.config_parser,
|
||||
self.start_event,
|
||||
self.command_queue,
|
||||
self.metrics_dict,
|
||||
self.connected_event,
|
||||
rsi_mode=self.rsi_mode,
|
||||
max_cartesian_rate=self.max_cartesian_rate,
|
||||
max_joint_rate=self.max_joint_rate,
|
||||
cycle_time=self.cycle_time
|
||||
self.metrics_dict
|
||||
)
|
||||
# Share the logging_active flag
|
||||
self.network_process.logging_active = self._logging_active
|
||||
self.network_process.receive_dirty = self._receive_dirty
|
||||
self.network_process.start()
|
||||
|
||||
self.logger: Optional[any] = None # Reserved for future use
|
||||
self.running: bool = False
|
||||
self.thread: Optional[Thread] = None
|
||||
|
||||
@property
|
||||
def state(self) -> ClientState:
|
||||
"""Get current client state (thread-safe)."""
|
||||
@ -176,15 +91,24 @@ class RSIClient:
|
||||
return self._state
|
||||
|
||||
def _transition_to(self, new_state: ClientState) -> bool:
|
||||
"""
|
||||
Attempt to transition to a new state.
|
||||
|
||||
Args:
|
||||
new_state: Target state to transition to
|
||||
|
||||
Returns:
|
||||
True if transition was valid and completed, False otherwise
|
||||
"""
|
||||
with self._state_lock:
|
||||
if new_state in self._VALID_TRANSITIONS.get(self._state, set()):
|
||||
old_state = self._state
|
||||
self._state = new_state
|
||||
logging.debug("State transition: %s -> %s", old_state.name, new_state.name)
|
||||
logging.debug(f"State transition: {old_state.name} -> {new_state.name}")
|
||||
return True
|
||||
else:
|
||||
logging.warning(
|
||||
"Invalid state transition attempted: %s -> %s", self._state.name, new_state.name
|
||||
f"Invalid state transition attempted: {self._state.name} -> {new_state.name}"
|
||||
)
|
||||
return False
|
||||
|
||||
@ -192,6 +116,9 @@ class RSIClient:
|
||||
"""
|
||||
Send start signal to NetworkProcess and run control loop.
|
||||
|
||||
Transitions through STARTING → RUNNING states and maintains
|
||||
control loop until stopped.
|
||||
|
||||
Raises:
|
||||
RSIClientNotReady: If client is not in appropriate state to start
|
||||
"""
|
||||
@ -211,16 +138,13 @@ class RSIClient:
|
||||
self.running = True
|
||||
logging.info("RSI Client Started")
|
||||
|
||||
if self.auto_reconnect_manager:
|
||||
self.auto_reconnect_manager.start()
|
||||
|
||||
try:
|
||||
while self.running and not self.stop_event.is_set():
|
||||
time.sleep(2)
|
||||
except KeyboardInterrupt:
|
||||
self.stop()
|
||||
except Exception as e:
|
||||
logging.error("RSI Client encountered an error: %s", e)
|
||||
logging.error(f"RSI Client encountered an error: {e}")
|
||||
self._transition_to(ClientState.ERROR)
|
||||
raise
|
||||
|
||||
@ -232,6 +156,7 @@ class RSIClient:
|
||||
|
||||
if not self._transition_to(ClientState.STOPPING):
|
||||
logging.warning("Could not transition to STOPPING state")
|
||||
# Continue anyway to ensure cleanup
|
||||
|
||||
logging.info("Stopping RSI Client...")
|
||||
|
||||
@ -249,15 +174,6 @@ class RSIClient:
|
||||
self.thread.join(timeout=2)
|
||||
self.thread = None
|
||||
|
||||
if self.auto_reconnect_manager:
|
||||
self.auto_reconnect_manager.stop()
|
||||
|
||||
# Shutdown Manager to avoid resource leaks
|
||||
try:
|
||||
self.manager.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self._transition_to(ClientState.STOPPED)
|
||||
logging.info("RSI Client Stopped")
|
||||
|
||||
@ -270,6 +186,7 @@ class RSIClient:
|
||||
"""
|
||||
logging.info("Reconnecting RSI Client network...")
|
||||
|
||||
# Stop if currently running
|
||||
if self.state in (ClientState.RUNNING, ClientState.STARTING):
|
||||
self.stop()
|
||||
|
||||
@ -278,59 +195,74 @@ class RSIClient:
|
||||
self.network_process.terminate()
|
||||
self.network_process.join()
|
||||
|
||||
# Fresh Manager (old one was shut down in stop())
|
||||
self.manager = multiprocessing.Manager()
|
||||
self.send_variables = self.manager.dict(self.config_parser.send_variables)
|
||||
self.receive_variables = self.manager.dict(self.config_parser.receive_variables)
|
||||
self.metrics_dict = self.manager.dict()
|
||||
|
||||
# Reset to initialized state
|
||||
with self._state_lock:
|
||||
self._state = ClientState.INITIALIZED
|
||||
|
||||
# Fresh new events and queue
|
||||
self.stop_event = multiprocessing.Event()
|
||||
self.start_event = multiprocessing.Event()
|
||||
self.connected_event = multiprocessing.Event()
|
||||
self.command_queue = multiprocessing.Queue()
|
||||
self._receive_dirty = multiprocessing.Value('b', True)
|
||||
|
||||
# Reset metrics dictionary (Phase 2)
|
||||
self.metrics_dict.clear()
|
||||
|
||||
# Create new network process
|
||||
network_settings = self.config_parser.get_network_settings()
|
||||
self._create_network_process(network_settings)
|
||||
self.network_process = NetworkProcess(
|
||||
network_settings["ip"],
|
||||
network_settings["port"],
|
||||
self.send_variables,
|
||||
self.receive_variables,
|
||||
self.stop_event,
|
||||
self.config_parser,
|
||||
self.start_event,
|
||||
self.command_queue,
|
||||
self.metrics_dict
|
||||
)
|
||||
self.network_process.logging_active = self._logging_active
|
||||
self.network_process.start()
|
||||
|
||||
def wait_for_connection(self, timeout: float = 10.0) -> bool:
|
||||
"""
|
||||
Block until the first valid packet is received from the robot.
|
||||
|
||||
Args:
|
||||
timeout: Maximum time to wait in seconds
|
||||
|
||||
Returns:
|
||||
True if connected, False if timeout
|
||||
"""
|
||||
return self.connected_event.wait(timeout=timeout)
|
||||
|
||||
def emergency_stop(self) -> None:
|
||||
"""Send E-stop command to network process to zero all corrections."""
|
||||
self.safety_manager.emergency_stop()
|
||||
self.command_queue.put({'action': 'estop'})
|
||||
logging.critical("Emergency stop activated")
|
||||
|
||||
def emergency_reset(self) -> None:
|
||||
"""Reset E-stop and resume normal corrections."""
|
||||
self.safety_manager.reset_stop()
|
||||
self.command_queue.put({'action': 'estop_reset'})
|
||||
logging.info("Emergency stop reset")
|
||||
# Fresh control thread
|
||||
self.thread = Thread(target=self.start, daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
def is_running(self) -> bool:
|
||||
"""
|
||||
Check if client is in running state.
|
||||
|
||||
Returns:
|
||||
True if currently running
|
||||
"""
|
||||
return self.state == ClientState.RUNNING
|
||||
|
||||
def is_stopped(self) -> bool:
|
||||
"""
|
||||
Check if client is fully stopped.
|
||||
|
||||
Returns:
|
||||
True if in STOPPED state
|
||||
"""
|
||||
return self.state == ClientState.STOPPED
|
||||
|
||||
def start_logging(self, filename: str) -> None:
|
||||
"""
|
||||
Start CSV logging to the specified file.
|
||||
|
||||
Args:
|
||||
filename: Path to output CSV file
|
||||
"""
|
||||
self.command_queue.put({'action': 'start_logging', 'filename': filename})
|
||||
|
||||
def stop_logging(self) -> None:
|
||||
"""Stop CSV logging."""
|
||||
self.command_queue.put({'action': 'stop_logging'})
|
||||
|
||||
def is_logging_active(self) -> bool:
|
||||
"""
|
||||
Check if CSV logging is currently active.
|
||||
|
||||
Returns:
|
||||
True if logging is active
|
||||
"""
|
||||
return self._logging_active.value
|
||||
|
||||
@ -1,12 +1,11 @@
|
||||
import copy
|
||||
import socket
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
import logging
|
||||
import threading
|
||||
from .config_parser import ConfigParser
|
||||
from .rsi_config import RSIConfig
|
||||
|
||||
# Toggle logging for debugging purposes
|
||||
# ✅ Toggle logging for debugging purposes
|
||||
LOGGING_ENABLED = True
|
||||
|
||||
if LOGGING_ENABLED:
|
||||
@ -17,13 +16,6 @@ if LOGGING_ENABLED:
|
||||
datefmt="%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
|
||||
# Maps correction tags from client <Sen> XML to robot state tags in <Rob> XML
|
||||
CORRECTION_TO_STATE = {
|
||||
"RKorr": "RIst",
|
||||
"AKorr": "AIPos",
|
||||
"EKorr": "ELPos",
|
||||
}
|
||||
|
||||
|
||||
class EchoServer:
|
||||
"""
|
||||
@ -43,7 +35,7 @@ class EchoServer:
|
||||
delay_ms (int): Delay between messages in milliseconds.
|
||||
mode (str): Correction mode ("relative" or "absolute").
|
||||
"""
|
||||
self.config = ConfigParser(config_file)
|
||||
self.config = RSIConfig(config_file)
|
||||
network_settings = self.config.get_network_settings()
|
||||
|
||||
self.server_address = ("0.0.0.0", 50000) # Local bind
|
||||
@ -56,12 +48,14 @@ class EchoServer:
|
||||
self.delay_ms = delay_ms / 1000 # Convert to seconds
|
||||
self.mode = mode.lower()
|
||||
|
||||
# Build internal state from config send_variables (what the robot sends out).
|
||||
# Deep copy so mutations to self.state don't affect the parser's data.
|
||||
self.state = copy.deepcopy(self.config.send_variables)
|
||||
|
||||
# Ensure IPOC is managed separately (we increment it ourselves)
|
||||
self.state.pop("IPOC", None)
|
||||
# Internal state to simulate robot values
|
||||
self.state = {
|
||||
"RIst": {k: 0.0 for k in ["X", "Y", "Z", "A", "B", "C"]},
|
||||
"AIPos": {f"A{i}": 0.0 for i in range(1, 7)},
|
||||
"ELPos": {f"E{i}": 0.0 for i in range(1, 7)},
|
||||
"DiO": 0,
|
||||
"DiL": 0
|
||||
}
|
||||
|
||||
self.running = True
|
||||
self.thread = threading.Thread(target=self.send_message, daemon=True)
|
||||
@ -72,8 +66,7 @@ class EchoServer:
|
||||
def receive_and_process(self):
|
||||
"""
|
||||
Handles one incoming UDP message and updates the internal state accordingly.
|
||||
Supports correction tags (RKorr->RIst, AKorr->AIPos, EKorr->ELPos),
|
||||
scalar state updates (DiO, DiL, etc.), and IPOC synchronisation.
|
||||
Supports RKorr, AKorr, DiO, DiL, and IPOC updates.
|
||||
"""
|
||||
try:
|
||||
self.udp_socket.settimeout(self.delay_ms)
|
||||
@ -84,37 +77,32 @@ class EchoServer:
|
||||
|
||||
for elem in root:
|
||||
tag = elem.tag
|
||||
|
||||
if tag in CORRECTION_TO_STATE:
|
||||
# Apply correction (RKorr/AKorr/EKorr) to corresponding state variable
|
||||
state_key = CORRECTION_TO_STATE[tag]
|
||||
if state_key in self.state and isinstance(self.state[state_key], dict):
|
||||
if tag in ["RKorr", "AKorr"]:
|
||||
for axis, value in elem.attrib.items():
|
||||
if axis in self.state[state_key]:
|
||||
value = float(value)
|
||||
if tag == "RKorr" and axis in self.state["RIst"]:
|
||||
# Apply Cartesian correction
|
||||
if self.mode == "relative":
|
||||
self.state[state_key][axis] += value
|
||||
self.state["RIst"][axis] += value
|
||||
else:
|
||||
self.state[state_key][axis] = value
|
||||
|
||||
self.state["RIst"][axis] = value
|
||||
elif tag == "AKorr" and axis in self.state["AIPos"]:
|
||||
# Apply joint correction
|
||||
if self.mode == "relative":
|
||||
self.state["AIPos"][axis] += value
|
||||
else:
|
||||
self.state["AIPos"][axis] = value
|
||||
elif tag in ["DiO", "DiL"]:
|
||||
if tag in self.state:
|
||||
self.state[tag] = int(elem.text.strip())
|
||||
elif tag == "IPOC":
|
||||
self.ipoc_value = int(elem.text.strip())
|
||||
|
||||
elif tag in self.state:
|
||||
# Update scalar state values (DiO, DiL, etc.)
|
||||
if isinstance(self.state[tag], dict):
|
||||
# Structured variable sent as attributes
|
||||
for attr, value in elem.attrib.items():
|
||||
if attr in self.state[tag]:
|
||||
self.state[tag][attr] = float(value)
|
||||
elif isinstance(self.state[tag], (int, float)):
|
||||
self.state[tag] = int(elem.text.strip()) if isinstance(self.state[tag], int) else float(elem.text.strip())
|
||||
|
||||
logging.debug(f"Processed input: {ET.tostring(root).decode()}")
|
||||
except socket.timeout:
|
||||
pass # No data within delay window
|
||||
except ConnectionResetError:
|
||||
print("Connection was reset by client. Waiting before retry...")
|
||||
print("⚠️ Connection was reset by client. Waiting before retry...")
|
||||
time.sleep(0.5)
|
||||
except Exception as e:
|
||||
print(f"[ERROR] Failed to process input: {e}")
|
||||
@ -123,22 +111,16 @@ class EchoServer:
|
||||
"""
|
||||
Creates a reply XML message based on current state.
|
||||
Format matches KUKA RSI's expected response structure.
|
||||
Iterates over all state variables from the config's send_variables.
|
||||
"""
|
||||
root = ET.Element("Rob", Type="KUKA")
|
||||
|
||||
for key, value in self.state.items():
|
||||
if isinstance(value, dict):
|
||||
# Structured variable (RIst, AIPos, etc.) -> XML attributes
|
||||
for key in ["RIst", "AIPos", "ELPos"]:
|
||||
element = ET.SubElement(root, key)
|
||||
for sub_key, sub_value in value.items():
|
||||
element.set(sub_key, f"{float(sub_value):.2f}")
|
||||
elif isinstance(value, bool):
|
||||
ET.SubElement(root, key).text = "1" if value else "0"
|
||||
elif isinstance(value, (int, float)):
|
||||
ET.SubElement(root, key).text = str(value)
|
||||
elif isinstance(value, str):
|
||||
ET.SubElement(root, key).text = value
|
||||
for sub_key, value in self.state[key].items():
|
||||
element.set(sub_key, f"{value:.2f}")
|
||||
|
||||
for key in ["DiO", "DiL"]:
|
||||
ET.SubElement(root, key).text = str(self.state[key])
|
||||
|
||||
ET.SubElement(root, "IPOC").text = str(self.ipoc_value)
|
||||
return ET.tostring(root, encoding="utf-8").decode()
|
||||
|
||||
@ -183,12 +183,10 @@ if __name__ == "__main__":
|
||||
parser.add_argument("--mode", choices=["position", "velocity", "acceleration", "force"], default="position", help="Graphing mode")
|
||||
parser.add_argument("--overlay", action="store_true", help="Enable planned vs. actual overlay")
|
||||
parser.add_argument("--plan", type=str, help="CSV file with planned trajectory")
|
||||
parser.add_argument("--config", type=str, default="RSI_EthernetConfig.xml",
|
||||
help="Path to RSI config XML file (default: RSI_EthernetConfig.xml)")
|
||||
parser.add_argument("--alerts", action="store_true", help="Enable real-time alerts")
|
||||
args = parser.parse_args()
|
||||
|
||||
client = RSIClient(args.config)
|
||||
client = RSIClient("../../examples/RSI_EthernetConfig.xml")
|
||||
graphing = RSIGraphing(client, mode=args.mode, overlay=args.overlay, plan_file=args.plan)
|
||||
|
||||
if not args.alerts:
|
||||
|
||||
@ -35,7 +35,7 @@ class SafetyAPI:
|
||||
This is NOT a hardware E-stop and should not be relied upon for
|
||||
safety-critical applications. Always use proper hardware E-stops.
|
||||
"""
|
||||
self.client.emergency_stop()
|
||||
self.client.safety_manager.emergency_stop()
|
||||
logging.critical("Emergency stop activated via SafetyAPI")
|
||||
|
||||
def reset(self) -> None:
|
||||
@ -45,7 +45,7 @@ class SafetyAPI:
|
||||
Clears the E-stop flag, allowing motion commands to proceed again.
|
||||
Use with caution after ensuring the robot workspace is safe.
|
||||
"""
|
||||
self.client.emergency_reset()
|
||||
self.client.safety_manager.reset_stop()
|
||||
logging.info("Emergency stop reset via SafetyAPI")
|
||||
|
||||
def status(self) -> Dict[str, Any]:
|
||||
|
||||
@ -59,32 +59,25 @@ class ToolsAPI:
|
||||
"""
|
||||
from .exceptions import RSIVariableError
|
||||
|
||||
# receive_variables = what the robot receives from us (RKorr, AKorr, DiO, Tech.C, etc.)
|
||||
# send_variables = what the robot sends to us (RIst, RSol, IPOC, etc.)
|
||||
# User corrections go into receive_variables.
|
||||
target = self.client.receive_variables
|
||||
|
||||
if "." in name:
|
||||
parent, child = name.split(".", 1)
|
||||
full_path = f"{parent}.{child}"
|
||||
|
||||
if parent in target:
|
||||
current = dict(target[parent])
|
||||
if parent in self.client.send_variables:
|
||||
current = dict(self.client.send_variables[parent])
|
||||
# Validate using SafetyManager
|
||||
safe_value = self.client.safety_manager.validate(full_path, float(value))
|
||||
current[child] = safe_value
|
||||
target[parent] = current
|
||||
if hasattr(self.client, '_receive_dirty'):
|
||||
self.client._receive_dirty.value = True
|
||||
logging.debug("Updated %s to %s", name, safe_value)
|
||||
self.client.send_variables[parent] = current
|
||||
logging.debug(f"Updated {name} to {safe_value}")
|
||||
return f"Updated {name} to {safe_value}"
|
||||
else:
|
||||
raise RSIVariableError(f"Parent variable '{parent}' not found in receive_variables")
|
||||
raise RSIVariableError(f"Parent variable '{parent}' not found in send_variables")
|
||||
else:
|
||||
# Top-level variable
|
||||
safe_value = self.client.safety_manager.validate(name, float(value))
|
||||
target[name] = safe_value
|
||||
if hasattr(self.client, '_receive_dirty'):
|
||||
self.client._receive_dirty.value = True
|
||||
logging.debug("Updated %s to %s", name, safe_value)
|
||||
self.client.send_variables[name] = safe_value
|
||||
logging.debug(f"Updated {name} to {safe_value}")
|
||||
return f"Updated {name} to {safe_value}"
|
||||
|
||||
def show_variables(self) -> None:
|
||||
@ -246,7 +239,7 @@ class ToolsAPI:
|
||||
else:
|
||||
raise ValueError(f"Unsupported format: {format_type}. Use 'csv', 'json', or 'pdf'.")
|
||||
|
||||
logging.info("Report generated: %s", output_path)
|
||||
logging.info(f"Report generated: {output_path}")
|
||||
return f"Report saved as {output_path}"
|
||||
|
||||
@staticmethod
|
||||
@ -294,5 +287,5 @@ class ToolsAPI:
|
||||
"max_diff": float(delta.max()),
|
||||
}
|
||||
|
||||
logging.info("Compared %d position columns between runs", len(shared_cols))
|
||||
logging.info(f"Compared {len(shared_cols)} position columns between runs")
|
||||
return diffs
|
||||
|
||||
@ -1,7 +1,4 @@
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from typing import Dict, Any, List, Tuple, Optional
|
||||
|
||||
|
||||
class XMLGenerator:
|
||||
"""
|
||||
@ -23,9 +20,10 @@ class XMLGenerator:
|
||||
"""
|
||||
root = ET.Element("Sen", Type=network_settings["sentype"])
|
||||
|
||||
# Convert structured keys (e.g. RKorr, Tech) and flat elements (e.g. IPOC)
|
||||
for key, value in send_variables.items():
|
||||
if key == "FREE":
|
||||
continue
|
||||
continue # Skip unused placeholder fields
|
||||
|
||||
if isinstance(value, dict):
|
||||
element = ET.SubElement(root, key)
|
||||
@ -58,141 +56,3 @@ class XMLGenerator:
|
||||
ET.SubElement(root, key).text = str(value)
|
||||
|
||||
return ET.tostring(root, encoding="utf-8").decode()
|
||||
|
||||
|
||||
class FastXMLGenerator:
|
||||
"""
|
||||
Pre-compiled string template XML generator for the 4ms hot path.
|
||||
|
||||
Compiles format strings at init time from the variable structure,
|
||||
then generates XML via string formatting (no DOM construction).
|
||||
~5-10x faster than ElementTree for fixed-schema RSI messages.
|
||||
"""
|
||||
|
||||
def __init__(self, variables: dict, root_tag: str = "Sen", type_attr: str = "ImFree") -> None:
|
||||
"""
|
||||
Compile a format template from the variable structure.
|
||||
|
||||
Args:
|
||||
variables: Dict of variable names → values/dicts (defines the XML schema)
|
||||
root_tag: Root XML element name ('Sen' for outgoing, 'Rob' for incoming)
|
||||
type_attr: Value for the Type attribute on root element
|
||||
"""
|
||||
self._keys: List[Tuple[str, Optional[List[str]]]] = []
|
||||
parts = [f'<{root_tag} Type="{type_attr}">']
|
||||
|
||||
for key, value in variables.items():
|
||||
if key == "FREE":
|
||||
continue
|
||||
|
||||
if isinstance(value, dict):
|
||||
subkeys = list(value.keys())
|
||||
self._keys.append((key, subkeys))
|
||||
# Use __ separator to avoid Python format_map treating . as attribute access
|
||||
attr_template = " ".join(f'{sk}="{{{key}__{sk}:.2f}}"' for sk in subkeys)
|
||||
parts.append(f"<{key} {attr_template} />")
|
||||
else:
|
||||
self._keys.append((key, None))
|
||||
parts.append(f"<{key}>{{{key}}}</{key}>")
|
||||
|
||||
# Ensure IPOC is always in template (required by robot)
|
||||
if "IPOC" not in variables:
|
||||
self._keys.append(("IPOC", None))
|
||||
parts.append("<IPOC>{IPOC}</IPOC>")
|
||||
|
||||
parts.append(f"</{root_tag}>")
|
||||
self._template = "".join(parts)
|
||||
|
||||
def generate(self, variables: dict) -> str:
|
||||
"""
|
||||
Generate XML string from current variable values using pre-compiled template.
|
||||
|
||||
Args:
|
||||
variables: Current variable values dict
|
||||
|
||||
Returns:
|
||||
XML string ready for UDP transmission
|
||||
"""
|
||||
fmt_args = {}
|
||||
for key, subkeys in self._keys:
|
||||
if subkeys is not None:
|
||||
val = variables.get(key, {})
|
||||
if isinstance(val, dict):
|
||||
for sk in subkeys:
|
||||
fmt_args[f"{key}__{sk}"] = float(val.get(sk, 0.0))
|
||||
else:
|
||||
for sk in subkeys:
|
||||
fmt_args[f"{key}__{sk}"] = 0.0
|
||||
else:
|
||||
fmt_args[key] = variables.get(key, "")
|
||||
return self._template.format_map(fmt_args)
|
||||
|
||||
|
||||
class FastXMLParser:
|
||||
"""
|
||||
Pre-compiled regex XML parser for the 4ms hot path.
|
||||
|
||||
Compiles regex patterns at init time from the known variable structure,
|
||||
then parses incoming XML via targeted regex extraction (no DOM construction).
|
||||
~3-5x faster than ElementTree for fixed-schema RSI messages.
|
||||
"""
|
||||
|
||||
def __init__(self, variables: dict) -> None:
|
||||
"""
|
||||
Compile regex patterns from the variable structure.
|
||||
|
||||
Args:
|
||||
variables: Dict of expected variable names → values/dicts
|
||||
"""
|
||||
self._dict_patterns: List[Tuple[str, re.Pattern, List[str]]] = []
|
||||
self._scalar_patterns: List[Tuple[str, re.Pattern]] = []
|
||||
|
||||
for key, value in variables.items():
|
||||
if isinstance(value, dict):
|
||||
subkeys = list(value.keys())
|
||||
attr_pattern = r"\s+".join(
|
||||
rf'{sk}="([^"]*)"' for sk in subkeys
|
||||
)
|
||||
# Also match any order with a looser pattern as fallback
|
||||
pattern = re.compile(rf"<{re.escape(key)}\s+{attr_pattern}")
|
||||
self._dict_patterns.append((key, pattern, subkeys))
|
||||
else:
|
||||
pattern = re.compile(rf"<{re.escape(key)}>([^<]*)</{re.escape(key)}>")
|
||||
self._scalar_patterns.append((key, pattern))
|
||||
|
||||
# Always parse IPOC specifically
|
||||
self._ipoc_pattern = re.compile(r"<IPOC>(\d+)</IPOC>")
|
||||
|
||||
def parse(self, xml_string: str, target: dict) -> None:
|
||||
"""
|
||||
Parse XML string into target dict using pre-compiled patterns.
|
||||
|
||||
Args:
|
||||
xml_string: Raw XML string from robot
|
||||
target: Dict to update with parsed values (modified in-place)
|
||||
"""
|
||||
# Parse dict-type elements (attributes)
|
||||
for key, pattern, subkeys in self._dict_patterns:
|
||||
if key not in target:
|
||||
continue
|
||||
match = pattern.search(xml_string)
|
||||
if match:
|
||||
existing = target.get(key)
|
||||
if isinstance(existing, dict):
|
||||
for i, sk in enumerate(subkeys):
|
||||
existing[sk] = float(match.group(i + 1))
|
||||
else:
|
||||
target[key] = {sk: float(match.group(i + 1)) for i, sk in enumerate(subkeys)}
|
||||
|
||||
# Parse scalar elements (text content)
|
||||
for key, pattern in self._scalar_patterns:
|
||||
if key not in target:
|
||||
continue
|
||||
match = pattern.search(xml_string)
|
||||
if match:
|
||||
target[key] = match.group(1)
|
||||
|
||||
# IPOC always parsed as int
|
||||
ipoc_match = self._ipoc_pattern.search(xml_string)
|
||||
if ipoc_match:
|
||||
target["IPOC"] = int(ipoc_match.group(1))
|
||||
|
||||
Binary file not shown.
@ -1,393 +0,0 @@
|
||||
# KRL Coordination Templates
|
||||
|
||||
This directory contains KRL program templates demonstrating common Python-KRL coordination patterns using RSIPI.
|
||||
|
||||
## Available Templates
|
||||
|
||||
### 1. basic_handshake.src
|
||||
**Simple I/O handshaking between Python and KRL**
|
||||
|
||||
- KRL signals "ready" via digital output
|
||||
- Python waits for signal, processes data
|
||||
- Python signals "complete" via input
|
||||
- KRL waits for completion, then continues
|
||||
|
||||
**Use Case**: Basic synchronization, ensuring Python completes processing before KRL continues.
|
||||
|
||||
**Coordination Methods Used**:
|
||||
- `api.krl.wait_for_signal(channel, timeout)`
|
||||
- `api.krl.signal_complete(channel)`
|
||||
|
||||
### 2. parameter_passing.src
|
||||
**Bidirectional numerical data exchange via Tech variables**
|
||||
|
||||
- KRL writes current position to Tech.T variables
|
||||
- Python reads position data
|
||||
- Python calculates target and writes to Tech.C variables
|
||||
- KRL reads target and executes motion
|
||||
|
||||
**Use Case**: Passing numerical parameters (positions, forces, tolerances) between Python and KRL.
|
||||
|
||||
**Coordination Methods Used**:
|
||||
- `api.krl.read_param(slot)` - Read from Tech.T
|
||||
- `api.krl.write_param(slot, value)` - Write to Tech.C
|
||||
- `api.krl.wait_for_signal(channel, timeout)`
|
||||
- `api.krl.signal_complete(channel)`
|
||||
|
||||
### 3. state_machine.src
|
||||
**Multi-state workflow with complex coordination**
|
||||
|
||||
Implements a 5-state machine:
|
||||
1. **IDLE**: Waiting to start
|
||||
2. **CALIBRATING**: Python performing calibration
|
||||
3. **READY**: Calibration complete
|
||||
4. **EXECUTING**: Robot motion in progress
|
||||
5. **COMPLETE**: Task finished
|
||||
6. **ERROR**: Error handling state
|
||||
|
||||
**Use Case**: Complex workflows requiring multiple handshakes, error handling, and state tracking.
|
||||
|
||||
**Coordination Methods Used**:
|
||||
- All coordination methods from basic_handshake and parameter_passing
|
||||
- State variable in Tech.T[11]
|
||||
- Command variable in Tech.C[11]
|
||||
|
||||
## Python-KRL Coordination Patterns
|
||||
|
||||
### Pattern 1: Simple Handshake
|
||||
|
||||
```python
|
||||
# Python side
|
||||
api.krl.wait_for_signal(1) # Wait for KRL ready signal
|
||||
# Do processing...
|
||||
api.krl.signal_complete(1) # Signal KRL to continue
|
||||
```
|
||||
|
||||
```krl
|
||||
; KRL side
|
||||
$OUT[1] = TRUE ; Signal ready to Python
|
||||
; Wait for Python completion
|
||||
WHILE $IN[1] == FALSE
|
||||
WAIT SEC 0.1
|
||||
ENDWHILE
|
||||
```
|
||||
|
||||
### Pattern 2: Parameter Exchange
|
||||
|
||||
```python
|
||||
# Python side
|
||||
api.krl.wait_for_signal(1)
|
||||
|
||||
# Read from KRL
|
||||
value = api.krl.read_param('T11')
|
||||
|
||||
# Process and write back
|
||||
result = process(value)
|
||||
api.krl.write_param('C11', result)
|
||||
|
||||
api.krl.signal_complete(1)
|
||||
```
|
||||
|
||||
```krl
|
||||
; KRL side
|
||||
$TECH.T[11] = some_value
|
||||
$OUT[1] = TRUE ; Signal data ready
|
||||
|
||||
; Wait for Python
|
||||
WHILE $IN[1] == FALSE
|
||||
WAIT SEC 0.1
|
||||
ENDWHILE
|
||||
|
||||
; Read result
|
||||
result = $TECH.C[11]
|
||||
```
|
||||
|
||||
### Pattern 3: Continuous Monitoring
|
||||
|
||||
```python
|
||||
# Python side - non-blocking monitoring loop
|
||||
api.start()
|
||||
|
||||
while api.is_running():
|
||||
state = api.krl.read_param('T11')
|
||||
|
||||
if state == 1: # Specific state
|
||||
# React to state change
|
||||
api.krl.write_param('C11', calculated_value)
|
||||
api.krl.signal_complete(1)
|
||||
|
||||
time.sleep(0.1) # Check every 100ms
|
||||
|
||||
api.stop()
|
||||
```
|
||||
|
||||
```krl
|
||||
; KRL side - updates state continuously
|
||||
$TECH.T[11] = current_state
|
||||
|
||||
; Wait for Python response when needed
|
||||
WHILE $IN[1] == FALSE
|
||||
WAIT SEC 0.1
|
||||
ENDWHILE
|
||||
|
||||
calculated = $TECH.C[11]
|
||||
```
|
||||
|
||||
## Tech Variable Conventions
|
||||
|
||||
### Tech.C Variables (Python → KRL)
|
||||
**"Control" variables - Python writes, KRL reads**
|
||||
|
||||
| Slot | Description | Example Usage |
|
||||
|------|-------------|---------------|
|
||||
| C11 | Command/state | 0=continue, 1=pause, 2=abort |
|
||||
| C12-C14 | Position offsets | X, Y, Z corrections |
|
||||
| C15-C17 | Target position | Calculated target coordinates |
|
||||
| C18-C20 | Process parameters | Speed, force, tolerance |
|
||||
| C21+ | Custom parameters | Application-specific data |
|
||||
|
||||
```python
|
||||
# Python writes
|
||||
api.krl.write_param('C11', 0) # Command: continue
|
||||
api.krl.write_param('C12', 5.0) # X offset
|
||||
api.krl.write_param('C13', -2.0) # Y offset
|
||||
```
|
||||
|
||||
```krl
|
||||
; KRL reads
|
||||
command = $TECH.C[11]
|
||||
offset_x = $TECH.C[12]
|
||||
offset_y = $TECH.C[13]
|
||||
```
|
||||
|
||||
### Tech.T Variables (KRL → Python)
|
||||
**"Transfer" variables - KRL writes, Python reads**
|
||||
|
||||
| Slot | Description | Example Usage |
|
||||
|------|-------------|---------------|
|
||||
| T11 | Current state | State machine state number |
|
||||
| T12-T14 | Current position | X, Y, Z coordinates |
|
||||
| T15-T17 | Force/torque | Measured forces |
|
||||
| T18-T20 | Sensor readings | External sensor data |
|
||||
| T21+ | Custom data | Application-specific values |
|
||||
|
||||
```krl
|
||||
; KRL writes
|
||||
$TECH.T[11] = current_state
|
||||
$TECH.T[12] = $POS_ACT.X
|
||||
$TECH.T[13] = $POS_ACT.Y
|
||||
$TECH.T[14] = $POS_ACT.Z
|
||||
```
|
||||
|
||||
```python
|
||||
# Python reads
|
||||
state = api.krl.read_param('T11')
|
||||
pos_x = api.krl.read_param('T12')
|
||||
pos_y = api.krl.read_param('T13')
|
||||
pos_z = api.krl.read_param('T14')
|
||||
```
|
||||
|
||||
## I/O Signal Conventions
|
||||
|
||||
### Standard I/O Mapping
|
||||
|
||||
| Signal | Type | Purpose |
|
||||
|--------|------|---------|
|
||||
| $OUT[1] | Output | KRL → Python state/ready signal |
|
||||
| $IN[1] | Input | Python → KRL completion acknowledgement |
|
||||
| $IN[2] | Input | Python → KRL error signal |
|
||||
| $OUT[2] | Output | KRL → Python auxiliary signal |
|
||||
|
||||
```python
|
||||
# Python I/O methods
|
||||
api.krl.wait_for_signal(1) # Wait for $OUT[1]
|
||||
api.krl.signal_complete(1) # Set $IN[1]
|
||||
api.io.set_output(2, True) # Control $OUT[2]
|
||||
```
|
||||
|
||||
## Error Handling Best Practices
|
||||
|
||||
### Timeouts
|
||||
|
||||
**Always use timeouts to prevent indefinite blocking:**
|
||||
|
||||
```python
|
||||
# Python
|
||||
if not api.krl.wait_for_signal(1, timeout=10.0):
|
||||
print("Timeout waiting for KRL!")
|
||||
# Handle error
|
||||
```
|
||||
|
||||
```krl
|
||||
; KRL
|
||||
INT counter
|
||||
counter = 0
|
||||
WHILE ($IN[1] == FALSE) AND (counter < 100)
|
||||
WAIT SEC 0.1
|
||||
counter = counter + 1
|
||||
ENDWHILE
|
||||
|
||||
IF counter >= 100 THEN
|
||||
; Timeout - handle error
|
||||
HALT
|
||||
ENDIF
|
||||
```
|
||||
|
||||
### Error Signaling
|
||||
|
||||
**Use dedicated error channels:**
|
||||
|
||||
```python
|
||||
# Python detects error
|
||||
if error_condition:
|
||||
api.io.set_output(2, True) # Signal error to KRL
|
||||
```
|
||||
|
||||
```krl
|
||||
; KRL checks for errors
|
||||
IF $IN[2] == TRUE THEN
|
||||
; Python signaled error
|
||||
HALT
|
||||
ENDIF
|
||||
```
|
||||
|
||||
## Integration with RSI Motion Control
|
||||
|
||||
All coordination patterns work seamlessly with RSI real-time motion corrections:
|
||||
|
||||
```python
|
||||
# Python coordinates with KRL AND sends real-time corrections
|
||||
api.start()
|
||||
|
||||
# Wait for KRL to start motion phase
|
||||
api.krl.wait_for_signal(1)
|
||||
|
||||
# Send real-time corrections during KRL motion
|
||||
for i in range(100):
|
||||
correction = calculate_correction()
|
||||
api.motion.update_cartesian(X=correction)
|
||||
time.sleep(0.004) # 250Hz update rate
|
||||
|
||||
# Signal motion phase complete
|
||||
api.krl.signal_complete(1)
|
||||
|
||||
api.stop()
|
||||
```
|
||||
|
||||
```krl
|
||||
; KRL executes motion while Python sends corrections
|
||||
$OUT[1] = TRUE ; Signal motion start
|
||||
|
||||
; Python sends corrections via RSI during this move
|
||||
LIN target_pos Vel=0.5 m/s CPDAT1 Tool[1] Base[0]
|
||||
|
||||
; Wait for Python to finish corrections
|
||||
WHILE $IN[1] == FALSE
|
||||
WAIT SEC 0.1
|
||||
ENDWHILE
|
||||
```
|
||||
|
||||
## Testing Templates
|
||||
|
||||
To test these templates:
|
||||
|
||||
1. **Upload KRL program to robot controller**
|
||||
2. **Start Python coordination script**
|
||||
3. **Execute KRL program on teach pendant**
|
||||
4. **Monitor coordination in Python logs**
|
||||
|
||||
Example Python test script:
|
||||
|
||||
```python
|
||||
from RSIPI import RSIAPI
|
||||
import time
|
||||
|
||||
api = RSIAPI('RSI_EthernetConfig.xml')
|
||||
api.start()
|
||||
|
||||
try:
|
||||
print("Waiting for KRL ready signal...")
|
||||
|
||||
if api.krl.wait_for_signal(1, timeout=30.0):
|
||||
print("✅ KRL signaled ready!")
|
||||
|
||||
# Simulate processing
|
||||
time.sleep(2.0)
|
||||
print("Processing complete")
|
||||
|
||||
# Signal back to KRL
|
||||
api.krl.signal_complete(1)
|
||||
print("✅ Signaled KRL to continue")
|
||||
|
||||
else:
|
||||
print("❌ Timeout waiting for KRL")
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("\n⚠️ Interrupted by user")
|
||||
|
||||
finally:
|
||||
api.stop()
|
||||
print("API stopped")
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Signal Not Received
|
||||
|
||||
**Check I/O configuration in RSI XML:**
|
||||
```xml
|
||||
<SEND>
|
||||
<XML>
|
||||
<ELEMENT Tag="Digin" Type="INT"/>
|
||||
</XML>
|
||||
</SEND>
|
||||
<RECEIVE>
|
||||
<XML>
|
||||
<ELEMENT Tag="Digout" Type="INT"/>
|
||||
</XML>
|
||||
</RECEIVE>
|
||||
```
|
||||
|
||||
### Tech Variable Not Found
|
||||
|
||||
**Ensure Tech variables are configured in RSI XML:**
|
||||
```xml
|
||||
<SEND>
|
||||
<XML>
|
||||
<ELEMENT Tag="Tech" Type="DOUBLE" Indizes="[1..199]"/>
|
||||
</XML>
|
||||
</SEND>
|
||||
<RECEIVE>
|
||||
<XML>
|
||||
<ELEMENT Tag="Tech" Type="DOUBLE" Indizes="[1..199]"/>
|
||||
</XML>
|
||||
</RECEIVE>
|
||||
```
|
||||
|
||||
### Timing Issues
|
||||
|
||||
- **Reduce check_interval for faster response**: `api.krl.wait_for_signal(1, check_interval=0.005)`
|
||||
- **Increase timeout for slow operations**: `api.krl.wait_for_signal(1, timeout=60.0)`
|
||||
- **Add WAIT SEC delays in KRL for signal propagation**
|
||||
|
||||
## Next Steps
|
||||
|
||||
After understanding these templates:
|
||||
|
||||
1. **Adapt templates** to your specific application
|
||||
2. **Test coordination** patterns with your robot
|
||||
3. **Implement error recovery** mechanisms
|
||||
4. **Document custom** coordination protocols
|
||||
5. **Create application-specific** state machines
|
||||
|
||||
## References
|
||||
|
||||
- [RSIPI Documentation](../../README.md)
|
||||
- [Phase 3 Summary](../../PHASE_3_SUMMARY.md) (when available)
|
||||
- [KUKA RSI 3.3 Documentation](https://www.kuka.com)
|
||||
|
||||
---
|
||||
|
||||
**Template Author**: RSIPI Development Team
|
||||
**Last Updated**: January 17, 2026
|
||||
**Version**: 1.0
|
||||
@ -1,80 +0,0 @@
|
||||
&ACCESS RVP
|
||||
&REL 1
|
||||
&PARAM TEMPLATE = C:\KRC\Roboter\Template\vorgabe
|
||||
&PARAM EDITMASK = *
|
||||
DEF basic_handshake()
|
||||
; ================================================================
|
||||
; Basic I/O Handshake Pattern
|
||||
; ================================================================
|
||||
; Demonstrates simple bidirectional signaling between KRL and Python
|
||||
; via digital I/O channels.
|
||||
;
|
||||
; Python-KRL Coordination Flow:
|
||||
; 1. KRL signals "ready" to Python (output 1)
|
||||
; 2. Python waits for signal, then processes
|
||||
; 3. Python signals "complete" to KRL (input 1)
|
||||
; 4. KRL waits for completion signal, then continues
|
||||
;
|
||||
; Python Code Example:
|
||||
; api = RSIAPI('RSI_EthernetConfig.xml')
|
||||
; api.start()
|
||||
;
|
||||
; # Wait for KRL to signal ready
|
||||
; if api.krl.wait_for_signal(1, timeout=10.0):
|
||||
; print("KRL is ready!")
|
||||
;
|
||||
; # Do Python processing here
|
||||
; time.sleep(1.0)
|
||||
;
|
||||
; # Signal completion back to KRL
|
||||
; api.krl.signal_complete(1)
|
||||
;
|
||||
; api.stop()
|
||||
; ================================================================
|
||||
|
||||
; Variable declarations
|
||||
INT i
|
||||
BOOL python_ready
|
||||
|
||||
BAS(#INITMOV, 0) ; Initialize motion
|
||||
|
||||
; ============================================================
|
||||
; STEP 1: KRL signals ready to Python
|
||||
; ============================================================
|
||||
$OUT[1] = TRUE ; Signal ready on digital output 1
|
||||
WAIT SEC 0.1 ; Brief delay for signal propagation
|
||||
|
||||
; ============================================================
|
||||
; STEP 2: Wait for Python to acknowledge completion
|
||||
; ============================================================
|
||||
python_ready = FALSE
|
||||
i = 0
|
||||
|
||||
; Poll input 1 until Python signals completion (max 10 seconds)
|
||||
WHILE (python_ready == FALSE) AND (i < 100)
|
||||
IF $IN[1] == TRUE THEN
|
||||
python_ready = TRUE
|
||||
ELSE
|
||||
WAIT SEC 0.1
|
||||
i = i + 1
|
||||
ENDIF
|
||||
ENDWHILE
|
||||
|
||||
IF python_ready == TRUE THEN
|
||||
; Python signaled completion successfully
|
||||
; Safe to proceed with robot motion
|
||||
|
||||
; Reset handshake signals
|
||||
$OUT[1] = FALSE
|
||||
|
||||
; Example motion with Python coordination
|
||||
PTP HOME Vel=100 % DEFAULT
|
||||
; Python can send corrections during motion via RSI
|
||||
|
||||
ELSE
|
||||
; Timeout - Python did not respond
|
||||
; Halt program for safety
|
||||
HALT
|
||||
ENDIF
|
||||
|
||||
END
|
||||
@ -1,125 +0,0 @@
|
||||
&ACCESS RVP
|
||||
&REL 1
|
||||
&PARAM TEMPLATE = C:\KRC\Roboter\Template\vorgabe
|
||||
&PARAM EDITMASK = *
|
||||
DEF parameter_passing()
|
||||
; ================================================================
|
||||
; Parameter Passing via Tech Variables
|
||||
; ================================================================
|
||||
; Demonstrates bidirectional numerical data exchange between KRL
|
||||
; and Python using RSI Tech variables.
|
||||
;
|
||||
; Tech Variable Conventions:
|
||||
; - Tech.C[11-199]: Python writes, KRL reads (Control variables)
|
||||
; - Tech.T[11-199]: KRL writes, Python reads (Transfer variables)
|
||||
;
|
||||
; Python-KRL Coordination Flow:
|
||||
; 1. KRL writes current position to Tech.T
|
||||
; 2. Python reads position from Tech.T
|
||||
; 3. Python processes data and writes target to Tech.C
|
||||
; 4. KRL reads target from Tech.C and executes motion
|
||||
;
|
||||
; Python Code Example:
|
||||
; api = RSIAPI('RSI_EthernetConfig.xml')
|
||||
; api.start()
|
||||
;
|
||||
; # Wait for KRL to signal data ready
|
||||
; api.krl.wait_for_signal(1)
|
||||
;
|
||||
; # Read current position from KRL
|
||||
; current_x = api.krl.read_param('T11')
|
||||
; current_y = api.krl.read_param('T12')
|
||||
; current_z = api.krl.read_param('T13')
|
||||
;
|
||||
; # Calculate target (e.g., move 100mm in X)
|
||||
; target_x = current_x + 100.0
|
||||
; target_y = current_y
|
||||
; target_z = current_z
|
||||
;
|
||||
; # Write target back to KRL
|
||||
; api.krl.write_param('C11', target_x)
|
||||
; api.krl.write_param('C12', target_y)
|
||||
; api.krl.write_param('C13', target_z)
|
||||
;
|
||||
; # Signal completion
|
||||
; api.krl.signal_complete(1)
|
||||
;
|
||||
; api.stop()
|
||||
; ================================================================
|
||||
|
||||
; Variable declarations
|
||||
E6POS current_pos, target_pos
|
||||
REAL target_x, target_y, target_z
|
||||
INT i
|
||||
BOOL data_ready
|
||||
|
||||
BAS(#INITMOV, 0)
|
||||
|
||||
; ============================================================
|
||||
; STEP 1: KRL writes current position to Tech.T
|
||||
; ============================================================
|
||||
current_pos = $POS_ACT ; Get current TCP position
|
||||
|
||||
; Write position components to Transfer variables (Python reads)
|
||||
$TECH.T[11] = current_pos.X
|
||||
$TECH.T[12] = current_pos.Y
|
||||
$TECH.T[13] = current_pos.Z
|
||||
$TECH.T[14] = current_pos.A
|
||||
$TECH.T[15] = current_pos.B
|
||||
$TECH.T[16] = current_pos.C
|
||||
|
||||
; ============================================================
|
||||
; STEP 2: Signal Python that data is ready
|
||||
; ============================================================
|
||||
$OUT[1] = TRUE
|
||||
WAIT SEC 0.1
|
||||
|
||||
; ============================================================
|
||||
; STEP 3: Wait for Python to process and write target
|
||||
; ============================================================
|
||||
data_ready = FALSE
|
||||
i = 0
|
||||
|
||||
; Poll input 1 for Python completion signal
|
||||
WHILE (data_ready == FALSE) AND (i < 100)
|
||||
IF $IN[1] == TRUE THEN
|
||||
data_ready = TRUE
|
||||
ELSE
|
||||
WAIT SEC 0.1
|
||||
i = i + 1
|
||||
ENDIF
|
||||
ENDWHILE
|
||||
|
||||
IF data_ready == TRUE THEN
|
||||
; ============================================================
|
||||
; STEP 4: Read target position from Tech.C
|
||||
; ============================================================
|
||||
; Python has written to Control variables (KRL reads)
|
||||
target_x = $TECH.C[11]
|
||||
target_y = $TECH.C[12]
|
||||
target_z = $TECH.C[13]
|
||||
|
||||
; Construct target pose
|
||||
target_pos = current_pos ; Copy orientation
|
||||
target_pos.X = target_x
|
||||
target_pos.Y = target_y
|
||||
target_pos.Z = target_z
|
||||
|
||||
; ============================================================
|
||||
; STEP 5: Execute motion to target
|
||||
; ============================================================
|
||||
; Reset signals
|
||||
$OUT[1] = FALSE
|
||||
|
||||
; Move to calculated target
|
||||
LIN target_pos Vel=0.5 m/s CPDAT1 Tool[1] Base[0]
|
||||
|
||||
; Success indication
|
||||
WAIT SEC 0.5
|
||||
|
||||
ELSE
|
||||
; Timeout - halt for safety
|
||||
HALT
|
||||
ENDIF
|
||||
|
||||
END
|
||||
@ -1,189 +0,0 @@
|
||||
&ACCESS RVP
|
||||
&REL 1
|
||||
&PARAM TEMPLATE = C:\KRC\Roboter\Template\vorgabe
|
||||
&PARAM EDITMASK = *
|
||||
DEF state_machine()
|
||||
; ================================================================
|
||||
; Multi-State Coordination Pattern
|
||||
; ================================================================
|
||||
; Demonstrates a state machine for complex Python-KRL workflows.
|
||||
; Uses both I/O signals and Tech variables for robust coordination.
|
||||
;
|
||||
; State Definitions:
|
||||
; State 0: IDLE - Waiting to start
|
||||
; State 1: CALIBRATING - Python performing calibration
|
||||
; State 2: READY - Calibration complete, ready for motion
|
||||
; State 3: EXECUTING - Robot executing motion task
|
||||
; State 4: COMPLETE - Task finished
|
||||
; State 9: ERROR - Error condition
|
||||
;
|
||||
; I/O Mapping:
|
||||
; $OUT[1]: State signal to Python (pulse indicates state change)
|
||||
; $IN[1]: Python acknowledgement
|
||||
; $IN[2]: Python error signal
|
||||
;
|
||||
; Tech Variable Mapping:
|
||||
; Tech.T[11]: Current state (KRL → Python)
|
||||
; Tech.C[11]: Python command (0=continue, 1=pause, 2=abort)
|
||||
; Tech.C[12-14]: Calibration offset (X, Y, Z)
|
||||
;
|
||||
; Python Code Example:
|
||||
; api = RSIAPI('RSI_EthernetConfig.xml')
|
||||
; api.start()
|
||||
;
|
||||
; # Monitor state transitions
|
||||
; while True:
|
||||
; state = api.krl.read_param('T11')
|
||||
;
|
||||
; if state == 1: # CALIBRATING
|
||||
; print("Performing calibration...")
|
||||
; # Calibration logic here
|
||||
; offset_x = 5.0
|
||||
; offset_y = -2.0
|
||||
; offset_z = 0.5
|
||||
;
|
||||
; # Write calibration results
|
||||
; api.krl.write_param('C12', offset_x)
|
||||
; api.krl.write_param('C13', offset_y)
|
||||
; api.krl.write_param('C14', offset_z)
|
||||
;
|
||||
; # Acknowledge state completion
|
||||
; api.krl.signal_complete(1)
|
||||
;
|
||||
; elif state == 3: # EXECUTING
|
||||
; print("Robot executing motion...")
|
||||
; # Monitor execution, send corrections if needed
|
||||
; api.motion.update_cartesian(X=offset_x, Y=offset_y)
|
||||
;
|
||||
; elif state == 4: # COMPLETE
|
||||
; print("Task complete!")
|
||||
; break
|
||||
;
|
||||
; elif state == 9: # ERROR
|
||||
; print("Error detected, aborting!")
|
||||
; break
|
||||
;
|
||||
; time.sleep(0.1)
|
||||
;
|
||||
; api.stop()
|
||||
; ================================================================
|
||||
|
||||
; Variable declarations
|
||||
INT current_state, python_cmd
|
||||
REAL offset_x, offset_y, offset_z
|
||||
E6POS target_pos
|
||||
BOOL ack_received
|
||||
INT timeout_counter
|
||||
|
||||
BAS(#INITMOV, 0)
|
||||
|
||||
; Initialize state machine
|
||||
current_state = 0 ; IDLE
|
||||
$TECH.T[11] = current_state
|
||||
|
||||
; ============================================================
|
||||
; STATE 0: IDLE
|
||||
; ============================================================
|
||||
current_state = 0
|
||||
$TECH.T[11] = current_state
|
||||
WAIT SEC 1.0
|
||||
|
||||
; ============================================================
|
||||
; STATE 1: CALIBRATING
|
||||
; ============================================================
|
||||
current_state = 1
|
||||
$TECH.T[11] = current_state
|
||||
|
||||
; Signal Python to start calibration
|
||||
$OUT[1] = TRUE
|
||||
WAIT SEC 0.1
|
||||
$OUT[1] = FALSE
|
||||
|
||||
; Wait for Python calibration completion
|
||||
ack_received = FALSE
|
||||
timeout_counter = 0
|
||||
|
||||
WHILE (ack_received == FALSE) AND (timeout_counter < 200)
|
||||
; Check for error signal
|
||||
IF $IN[2] == TRUE THEN
|
||||
current_state = 9 ; ERROR
|
||||
$TECH.T[11] = current_state
|
||||
HALT
|
||||
ENDIF
|
||||
|
||||
; Check for completion
|
||||
IF $IN[1] == TRUE THEN
|
||||
ack_received = TRUE
|
||||
ELSE
|
||||
WAIT SEC 0.1
|
||||
timeout_counter = timeout_counter + 1
|
||||
ENDIF
|
||||
ENDWHILE
|
||||
|
||||
IF ack_received == FALSE THEN
|
||||
; Timeout error
|
||||
current_state = 9
|
||||
$TECH.T[11] = current_state
|
||||
HALT
|
||||
ENDIF
|
||||
|
||||
; ============================================================
|
||||
; STATE 2: READY
|
||||
; ============================================================
|
||||
; Read calibration offsets from Python
|
||||
offset_x = $TECH.C[12]
|
||||
offset_y = $TECH.C[13]
|
||||
offset_z = $TECH.C[14]
|
||||
|
||||
current_state = 2
|
||||
$TECH.T[11] = current_state
|
||||
|
||||
; Signal ready
|
||||
$OUT[1] = TRUE
|
||||
WAIT SEC 0.1
|
||||
$OUT[1] = FALSE
|
||||
WAIT SEC 0.5
|
||||
|
||||
; ============================================================
|
||||
; STATE 3: EXECUTING
|
||||
; ============================================================
|
||||
current_state = 3
|
||||
$TECH.T[11] = current_state
|
||||
|
||||
; Calculate target with calibration offset
|
||||
target_pos = $POS_ACT
|
||||
target_pos.X = target_pos.X + offset_x
|
||||
target_pos.Y = target_pos.Y + offset_y
|
||||
target_pos.Z = target_pos.Z + offset_z
|
||||
|
||||
; Execute motion (Python can send RSI corrections during this)
|
||||
LIN target_pos Vel=0.3 m/s CPDAT1 Tool[1] Base[0]
|
||||
|
||||
; Check for pause/abort commands
|
||||
python_cmd = $TECH.C[11]
|
||||
IF python_cmd == 2 THEN
|
||||
; Abort requested
|
||||
current_state = 9
|
||||
$TECH.T[11] = current_state
|
||||
HALT
|
||||
ENDIF
|
||||
|
||||
; ============================================================
|
||||
; STATE 4: COMPLETE
|
||||
; ============================================================
|
||||
current_state = 4
|
||||
$TECH.T[11] = current_state
|
||||
|
||||
; Signal completion
|
||||
$OUT[1] = TRUE
|
||||
WAIT SEC 0.2
|
||||
$OUT[1] = FALSE
|
||||
|
||||
; Return to home
|
||||
PTP HOME Vel=100 % DEFAULT
|
||||
|
||||
; Final state update
|
||||
current_state = 0 ; Back to IDLE
|
||||
$TECH.T[11] = current_state
|
||||
|
||||
END
|
||||
615
test_server.py
615
test_server.py
@ -1,615 +0,0 @@
|
||||
"""
|
||||
RSI TestServer - Python equivalent of KUKA's RSI TestServer.exe
|
||||
|
||||
Simulates the robot side of an RSI connection. Listens on UDP for <Sen> XML
|
||||
from a client, and responds with <Rob> XML containing the current robot state.
|
||||
|
||||
Usage:
|
||||
python test_server.py
|
||||
python test_server.py --config path/to/RSI_EthernetConfig.xml
|
||||
"""
|
||||
|
||||
import socket
|
||||
import threading
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox
|
||||
import xml.etree.ElementTree as ET
|
||||
import argparse
|
||||
import copy
|
||||
import sys
|
||||
import os
|
||||
import time
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
||||
from RSIPI.config_parser import ConfigParser
|
||||
from RSIPI.xml_handler import XMLGenerator
|
||||
|
||||
# --- Theme colours ---
|
||||
BG_DARK = "#1e1e2e"
|
||||
BG_MID = "#282840"
|
||||
BG_CARD = "#313150"
|
||||
BG_INPUT = "#3b3b5c"
|
||||
FG = "#cdd6f4"
|
||||
FG_DIM = "#7f849c"
|
||||
FG_BRIGHT = "#ffffff"
|
||||
ACCENT = "#f5a623"
|
||||
ACCENT_HOVER = "#f7bc5e"
|
||||
GREEN = "#a6e3a1"
|
||||
RED = "#f38ba8"
|
||||
BLUE = "#89b4fa"
|
||||
BORDER = "#45475a"
|
||||
AXIS_COLOURS = {
|
||||
"X": "#f38ba8", "Y": "#a6e3a1", "Z": "#89b4fa",
|
||||
"A": "#fab387", "B": "#cba6f7", "C": "#94e2d5",
|
||||
}
|
||||
|
||||
|
||||
class RSITestServer:
|
||||
"""UDP server simulating a KUKA robot controller for RSI testing."""
|
||||
|
||||
def __init__(self, config_file: str):
|
||||
self.config = ConfigParser(config_file)
|
||||
self.network_settings = self.config.get_network_settings()
|
||||
self.port = self.network_settings["port"]
|
||||
|
||||
self.robot_state = copy.deepcopy(self.config.send_variables)
|
||||
self.receive_template = copy.deepcopy(self.config.receive_variables)
|
||||
|
||||
self.ipoc = 0
|
||||
self.correction_step = 0.01
|
||||
self.running = False
|
||||
self.receive_only = False
|
||||
self.udp_socket = None
|
||||
self.listen_thread = None
|
||||
self.client_address = None
|
||||
self.last_received_xml = ""
|
||||
self.last_sent_xml = ""
|
||||
self.packet_count = 0
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def start(self):
|
||||
if self.running:
|
||||
return
|
||||
try:
|
||||
self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self.udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
self.udp_socket.bind(("0.0.0.0", self.port))
|
||||
self.udp_socket.settimeout(0.5)
|
||||
self.running = True
|
||||
self.packet_count = 0
|
||||
self.listen_thread = threading.Thread(target=self._listen_loop, daemon=True)
|
||||
self.listen_thread.start()
|
||||
return True
|
||||
except OSError as e:
|
||||
self.running = False
|
||||
return str(e)
|
||||
|
||||
def stop(self):
|
||||
self.running = False
|
||||
if self.listen_thread:
|
||||
self.listen_thread.join(timeout=2)
|
||||
if self.udp_socket:
|
||||
self.udp_socket.close()
|
||||
self.udp_socket = None
|
||||
self.client_address = None
|
||||
|
||||
def _listen_loop(self):
|
||||
while self.running:
|
||||
try:
|
||||
data, addr = self.udp_socket.recvfrom(4096)
|
||||
self.client_address = addr
|
||||
xml_string = data.decode("utf-8", errors="replace")
|
||||
|
||||
with self.lock:
|
||||
self.last_received_xml = xml_string
|
||||
self._process_received(xml_string)
|
||||
self.packet_count += 1
|
||||
|
||||
if not self.receive_only:
|
||||
response = self._generate_response()
|
||||
self.last_sent_xml = response
|
||||
self.udp_socket.sendto(response.encode("utf-8"), addr)
|
||||
|
||||
except socket.timeout:
|
||||
continue
|
||||
except OSError:
|
||||
break
|
||||
except Exception as e:
|
||||
if self.running:
|
||||
print(f"[TestServer] Error: {e}")
|
||||
|
||||
def _process_received(self, xml_string: str):
|
||||
try:
|
||||
root = ET.fromstring(xml_string)
|
||||
ipoc_elem = root.find("IPOC")
|
||||
if ipoc_elem is not None and ipoc_elem.text:
|
||||
self.ipoc = int(ipoc_elem.text.strip())
|
||||
except ET.ParseError:
|
||||
self.ipoc = self._extract_ipoc_string(xml_string)
|
||||
|
||||
def _extract_ipoc_string(self, xml_string: str) -> int:
|
||||
end_tag = "</IPOC>"
|
||||
start_tag = "<IPOC>"
|
||||
end_idx = xml_string.find(end_tag)
|
||||
if end_idx == -1:
|
||||
return self.ipoc
|
||||
start_idx = xml_string.find(start_tag)
|
||||
if start_idx == -1:
|
||||
return self.ipoc
|
||||
try:
|
||||
return int(xml_string[start_idx + len(start_tag):end_idx].strip())
|
||||
except ValueError:
|
||||
return self.ipoc
|
||||
|
||||
def _generate_response(self) -> str:
|
||||
state = copy.deepcopy(self.robot_state)
|
||||
state["IPOC"] = self.ipoc
|
||||
return XMLGenerator.generate_receive_xml(state)
|
||||
|
||||
def adjust_position(self, axis: str, delta: float):
|
||||
with self.lock:
|
||||
if "RIst" in self.robot_state and axis in self.robot_state["RIst"]:
|
||||
self.robot_state["RIst"][axis] += delta
|
||||
|
||||
def reset_positions(self):
|
||||
with self.lock:
|
||||
if "RIst" in self.robot_state:
|
||||
for axis in self.robot_state["RIst"]:
|
||||
self.robot_state["RIst"][axis] = 0.0
|
||||
|
||||
|
||||
class TestServerGUI:
|
||||
"""Dark-themed tkinter GUI for the RSI TestServer."""
|
||||
|
||||
def __init__(self, config_file: str):
|
||||
self.server = RSITestServer(config_file)
|
||||
self._prev_packet_count = 0
|
||||
self._prev_time = time.time()
|
||||
self._packets_per_sec = 0.0
|
||||
self.recv_text: tk.Text = None # type: ignore[assignment]
|
||||
self.sent_text: tk.Text = None # type: ignore[assignment]
|
||||
|
||||
self.root = tk.Tk()
|
||||
self.root.title("RSI TestServer")
|
||||
self.root.configure(bg=BG_DARK)
|
||||
self.root.geometry("1100x750")
|
||||
self.root.resizable(True, True)
|
||||
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
|
||||
|
||||
self._build_ui()
|
||||
self._update_display()
|
||||
|
||||
# ── helpers ──────────────────────────────────────────────────────
|
||||
|
||||
def _card(self, parent, **kw):
|
||||
f = tk.Frame(parent, bg=BG_CARD, highlightbackground=BORDER,
|
||||
highlightthickness=1, **kw)
|
||||
return f
|
||||
|
||||
def _label(self, parent, text="", font=("Segoe UI", 10), fg=FG, **kw):
|
||||
return tk.Label(parent, text=text, font=font, fg=fg, bg=parent["bg"], **kw)
|
||||
|
||||
def _btn(self, parent, text, command, width=4, accent=False, **kw):
|
||||
bg = ACCENT if accent else BG_INPUT
|
||||
fg_c = BG_DARK if accent else FG
|
||||
hover = ACCENT_HOVER if accent else "#4e4e7a"
|
||||
b = tk.Button(parent, text=text, command=command, width=width,
|
||||
font=("Segoe UI", 10, "bold"), fg=fg_c, bg=bg,
|
||||
activeforeground=fg_c, activebackground=hover,
|
||||
relief="flat", cursor="hand2", bd=0,
|
||||
highlightthickness=0, **kw)
|
||||
b.bind("<Enter>", lambda e, b=b, h=hover: b.config(bg=h))
|
||||
b.bind("<Leave>", lambda e, b=b, n=bg: b.config(bg=n))
|
||||
return b
|
||||
|
||||
# ── layout ───────────────────────────────────────────────────────
|
||||
|
||||
def _build_ui(self):
|
||||
# ── Header ──
|
||||
header = tk.Frame(self.root, bg=BG_MID, height=56)
|
||||
header.grid(row=0, column=0, sticky="ew")
|
||||
header.grid_columnconfigure(1, weight=1)
|
||||
|
||||
self._label(header, "RSI TestServer",
|
||||
font=("Segoe UI", 16, "bold"), fg=ACCENT).grid(
|
||||
row=0, column=0, padx=16, pady=10, sticky="w")
|
||||
|
||||
self._label(header, f"Port {self.server.port}",
|
||||
font=("Segoe UI Semibold", 11), fg=FG_DIM).grid(
|
||||
row=0, column=1, sticky="w")
|
||||
|
||||
self.status_dot = tk.Canvas(header, width=14, height=14,
|
||||
bg=BG_MID, highlightthickness=0)
|
||||
self.status_dot.create_oval(2, 2, 12, 12, fill=RED, outline="", tags="dot")
|
||||
self.status_dot.grid(row=0, column=2, padx=(0, 4))
|
||||
|
||||
self.status_label = self._label(header, "Offline",
|
||||
font=("Segoe UI Semibold", 11), fg=RED)
|
||||
self.status_label.grid(row=0, column=3, padx=(0, 16))
|
||||
|
||||
# ── Body ──
|
||||
body = tk.Frame(self.root, bg=BG_DARK)
|
||||
body.grid(row=1, column=0, sticky="nsew", padx=12, pady=8)
|
||||
body.grid_columnconfigure(1, weight=1)
|
||||
|
||||
# ── Left column: controls + jog ──
|
||||
left = tk.Frame(body, bg=BG_DARK)
|
||||
left.grid(row=0, column=0, sticky="n", padx=(0, 8))
|
||||
|
||||
# Controls card
|
||||
ctrl = self._card(left)
|
||||
ctrl.grid(row=0, column=0, sticky="ew", pady=(0, 8))
|
||||
|
||||
btn_row = tk.Frame(ctrl, bg=BG_CARD)
|
||||
btn_row.grid(row=0, column=0, padx=10, pady=10, sticky="ew")
|
||||
|
||||
self.start_btn = self._btn(btn_row, "Start", self._start,
|
||||
width=8, accent=True)
|
||||
self.start_btn.grid(row=0, column=0, padx=(0, 4))
|
||||
|
||||
self.stop_btn = self._btn(btn_row, "Stop", self._stop, width=8)
|
||||
self.stop_btn.config(state="disabled")
|
||||
self.stop_btn.grid(row=0, column=1, padx=(0, 12))
|
||||
|
||||
self.mode_var = tk.StringVar(value="Send + Recv")
|
||||
mode_btn = tk.Menubutton(btn_row, textvariable=self.mode_var,
|
||||
font=("Segoe UI", 9), fg=FG, bg=BG_INPUT,
|
||||
activeforeground=FG, activebackground="#4e4e7a",
|
||||
relief="flat", highlightthickness=0,
|
||||
indicatoron=True, cursor="hand2", width=12)
|
||||
mode_menu = tk.Menu(mode_btn, tearoff=0, bg=BG_INPUT, fg=FG,
|
||||
activebackground=ACCENT, activeforeground=BG_DARK)
|
||||
mode_menu.add_command(label="Send + Recv",
|
||||
command=lambda: self._set_mode("Send + Recv"))
|
||||
mode_menu.add_command(label="Recv only",
|
||||
command=lambda: self._set_mode("Recv only"))
|
||||
mode_btn["menu"] = mode_menu
|
||||
mode_btn.grid(row=0, column=2, padx=(0, 8))
|
||||
|
||||
self._label(btn_row, "Step:", font=("Segoe UI", 9), fg=FG_DIM).grid(
|
||||
row=0, column=3)
|
||||
self.step_var = tk.StringVar(value="0.01")
|
||||
step_e = tk.Entry(btn_row, textvariable=self.step_var, width=7,
|
||||
font=("Consolas", 10), fg=ACCENT, bg=BG_INPUT,
|
||||
insertbackground=ACCENT, relief="flat",
|
||||
highlightthickness=1, highlightcolor=ACCENT,
|
||||
highlightbackground=BORDER)
|
||||
step_e.grid(row=0, column=4, padx=4)
|
||||
step_e.bind("<Return>", self._step_changed)
|
||||
step_e.bind("<FocusOut>", self._step_changed)
|
||||
|
||||
# Jog card
|
||||
jog = self._card(left)
|
||||
jog.grid(row=1, column=0, sticky="ew")
|
||||
|
||||
jog_title = tk.Frame(jog, bg=BG_CARD)
|
||||
jog_title.grid(row=0, column=0, columnspan=4, sticky="ew", padx=10,
|
||||
pady=(8, 4))
|
||||
self._label(jog_title, "Jog Control",
|
||||
font=("Segoe UI Semibold", 11), fg=FG_BRIGHT).pack(
|
||||
side="left")
|
||||
|
||||
axes = ["X", "Y", "Z", "A", "B", "C"]
|
||||
self.pos_labels = {}
|
||||
|
||||
for i, axis in enumerate(axes):
|
||||
row_frame = tk.Frame(jog, bg=BG_CARD)
|
||||
row_frame.grid(row=i + 1, column=0, sticky="ew", padx=10, pady=2)
|
||||
row_frame.grid_columnconfigure(1, weight=1)
|
||||
|
||||
colour = AXIS_COLOURS[axis]
|
||||
|
||||
# Colour pip
|
||||
pip = tk.Canvas(row_frame, width=8, height=8,
|
||||
bg=BG_CARD, highlightthickness=0)
|
||||
pip.create_oval(1, 1, 7, 7, fill=colour, outline="")
|
||||
pip.grid(row=0, column=0, padx=(0, 6))
|
||||
|
||||
self._label(row_frame, f"{axis}",
|
||||
font=("Segoe UI Semibold", 11), fg=colour).grid(
|
||||
row=0, column=1, sticky="w")
|
||||
|
||||
self.pos_labels[axis] = self._label(
|
||||
row_frame, "0.0000",
|
||||
font=("Consolas", 12), fg=FG_BRIGHT)
|
||||
self.pos_labels[axis].grid(row=0, column=2, padx=8)
|
||||
|
||||
self._btn(row_frame, "+",
|
||||
lambda a=axis: self._adjust(a, 1), width=3).grid(
|
||||
row=0, column=3, padx=1)
|
||||
self._btn(row_frame, "-",
|
||||
lambda a=axis: self._adjust(a, -1), width=3).grid(
|
||||
row=0, column=4, padx=1)
|
||||
|
||||
reset_row = tk.Frame(jog, bg=BG_CARD)
|
||||
reset_row.grid(row=len(axes) + 1, column=0, sticky="ew",
|
||||
padx=10, pady=(6, 10))
|
||||
self._btn(reset_row, "Reset All", self._reset,
|
||||
width=36, accent=False).pack(fill="x")
|
||||
|
||||
# ── Right column: state + xml ──
|
||||
right = tk.Frame(body, bg=BG_DARK)
|
||||
right.grid(row=0, column=1, sticky="nsew")
|
||||
right.grid_rowconfigure(1, weight=1)
|
||||
|
||||
# Info bar
|
||||
info = self._card(right)
|
||||
info.grid(row=0, column=0, sticky="ew", pady=(0, 8))
|
||||
|
||||
info_inner = tk.Frame(info, bg=BG_CARD)
|
||||
info_inner.grid(padx=10, pady=8, sticky="ew")
|
||||
info.grid_columnconfigure(0, weight=1)
|
||||
info_inner.grid_columnconfigure(1, weight=1)
|
||||
info_inner.grid_columnconfigure(3, weight=1)
|
||||
|
||||
self._label(info_inner, "IPOC", font=("Segoe UI", 9), fg=FG_DIM).grid(
|
||||
row=0, column=0, sticky="w")
|
||||
self.ipoc_val = self._label(info_inner, "0",
|
||||
font=("Consolas", 12, "bold"), fg=BLUE)
|
||||
self.ipoc_val.grid(row=1, column=0, sticky="w")
|
||||
|
||||
self._label(info_inner, "Client", font=("Segoe UI", 9), fg=FG_DIM).grid(
|
||||
row=0, column=1, sticky="w", padx=(20, 0))
|
||||
self.client_val = self._label(info_inner, "--",
|
||||
font=("Consolas", 11), fg=FG)
|
||||
self.client_val.grid(row=1, column=1, sticky="w", padx=(20, 0))
|
||||
|
||||
self._label(info_inner, "Packets/s", font=("Segoe UI", 9), fg=FG_DIM).grid(
|
||||
row=0, column=2, sticky="w", padx=(20, 0))
|
||||
self.pps_val = self._label(info_inner, "0",
|
||||
font=("Consolas", 12, "bold"), fg=GREEN)
|
||||
self.pps_val.grid(row=1, column=2, sticky="w", padx=(20, 0))
|
||||
|
||||
# Robot state card — grid layout
|
||||
state_card = self._card(right)
|
||||
state_card.grid(row=1, column=0, sticky="nsew", pady=(0, 8))
|
||||
|
||||
state_hdr = tk.Frame(state_card, bg=BG_CARD)
|
||||
state_hdr.grid(row=0, column=0, sticky="ew", padx=10, pady=(8, 4))
|
||||
self._label(state_hdr, "Robot State",
|
||||
font=("Segoe UI Semibold", 11), fg=FG_BRIGHT).pack(
|
||||
side="left")
|
||||
|
||||
# Scrollable grid area
|
||||
state_outer = tk.Frame(state_card, bg=BG_MID)
|
||||
state_outer.grid(row=1, column=0, sticky="nsew", padx=8, pady=(0, 8))
|
||||
state_card.grid_rowconfigure(1, weight=1)
|
||||
|
||||
state_canvas = tk.Canvas(state_outer, bg=BG_MID, highlightthickness=0,
|
||||
height=280)
|
||||
state_canvas.pack(side="left", fill="both", expand=True)
|
||||
state_scroll = tk.Scrollbar(state_outer, orient="vertical",
|
||||
command=state_canvas.yview,
|
||||
bg=BG_MID, troughcolor=BG_MID)
|
||||
state_scroll.pack(side="right", fill="y")
|
||||
state_canvas.configure(yscrollcommand=state_scroll.set)
|
||||
|
||||
self._state_grid = tk.Frame(state_canvas, bg=BG_MID)
|
||||
state_canvas.create_window((0, 0), window=self._state_grid, anchor="nw")
|
||||
self._state_canvas = state_canvas
|
||||
|
||||
# Build grid from robot_state
|
||||
self._state_cells = {} # (group, subkey) -> Label
|
||||
self._build_state_grid()
|
||||
|
||||
# XML card
|
||||
xml_card = self._card(right)
|
||||
xml_card.grid(row=2, column=0, sticky="nsew")
|
||||
|
||||
xml_hdr = tk.Frame(xml_card, bg=BG_CARD)
|
||||
xml_hdr.grid(row=0, column=0, columnspan=2, sticky="ew", padx=10,
|
||||
pady=(8, 4))
|
||||
self._label(xml_hdr, "XML Traffic",
|
||||
font=("Segoe UI Semibold", 11), fg=FG_BRIGHT).pack(
|
||||
side="left")
|
||||
|
||||
xml_card.grid_columnconfigure(1, weight=1)
|
||||
for i, (lbl, attr) in enumerate([("RX", "recv_text"), ("TX", "sent_text")]):
|
||||
tag_bg = GREEN if lbl == "RX" else BLUE
|
||||
tag = tk.Label(xml_card, text=f" {lbl} ", font=("Consolas", 9, "bold"),
|
||||
fg=BG_DARK, bg=tag_bg)
|
||||
tag.grid(row=i + 1, column=0, sticky="nw", padx=(10, 4), pady=2)
|
||||
t = tk.Text(xml_card, width=60, height=6, font=("Consolas", 9),
|
||||
fg=FG_DIM, bg=BG_MID, relief="flat", bd=0,
|
||||
padx=6, pady=4, wrap="word", state="disabled")
|
||||
t.grid(row=i + 1, column=1, sticky="nsew", padx=(0, 8), pady=2)
|
||||
setattr(self, attr, t)
|
||||
|
||||
# bottom pad
|
||||
tk.Frame(xml_card, bg=BG_CARD, height=8).grid(
|
||||
row=3, column=0, columnspan=2)
|
||||
|
||||
# ── state grid builder ────────────────────────────────────────────
|
||||
|
||||
def _build_state_grid(self):
|
||||
"""Build the header row and value cells from robot_state structure."""
|
||||
grid = self._state_grid
|
||||
row = 0
|
||||
|
||||
for key, value in self.server.robot_state.items():
|
||||
if isinstance(value, dict):
|
||||
# Group header
|
||||
self._label(grid, key, font=("Segoe UI Semibold", 9),
|
||||
fg=ACCENT).grid(row=row, column=0, sticky="w",
|
||||
padx=(8, 4), pady=(6, 0))
|
||||
row += 1
|
||||
|
||||
# Sub-key headers + value cells in columns
|
||||
subkeys = list(value.keys())
|
||||
# Chunk into rows of 6 for wide dicts like Tech
|
||||
chunk_size = 6
|
||||
for chunk_start in range(0, len(subkeys), chunk_size):
|
||||
chunk = subkeys[chunk_start:chunk_start + chunk_size]
|
||||
for col, sk in enumerate(chunk):
|
||||
# Header
|
||||
self._label(grid, sk, font=("Consolas", 8),
|
||||
fg=FG_DIM).grid(
|
||||
row=row, column=col + 1, padx=4, sticky="e")
|
||||
row += 1
|
||||
for col, sk in enumerate(chunk):
|
||||
# Value cell
|
||||
cell = self._label(grid, "0.0000",
|
||||
font=("Consolas", 10), fg=FG_BRIGHT)
|
||||
cell.grid(row=row, column=col + 1, padx=4, sticky="e")
|
||||
self._state_cells[(key, sk)] = cell
|
||||
row += 1
|
||||
else:
|
||||
# Scalar value
|
||||
self._label(grid, key, font=("Segoe UI Semibold", 9),
|
||||
fg=ACCENT).grid(row=row, column=0, sticky="w",
|
||||
padx=(8, 4), pady=(6, 0))
|
||||
cell = self._label(grid, str(value),
|
||||
font=("Consolas", 10), fg=FG_BRIGHT)
|
||||
cell.grid(row=row, column=1, padx=4, sticky="e")
|
||||
self._state_cells[(key, None)] = cell
|
||||
row += 1
|
||||
|
||||
# Update scroll region after grid is built
|
||||
grid.update_idletasks()
|
||||
self._state_canvas.configure(scrollregion=self._state_canvas.bbox("all"))
|
||||
|
||||
def _update_state_grid(self):
|
||||
"""Update all cell values from current robot_state."""
|
||||
for key, value in self.server.robot_state.items():
|
||||
if isinstance(value, dict):
|
||||
for sk, sv in value.items():
|
||||
cell = self._state_cells.get((key, sk))
|
||||
if cell:
|
||||
try:
|
||||
cell.config(text=f"{float(sv):>8.4f}")
|
||||
except (ValueError, TypeError):
|
||||
cell.config(text=str(sv))
|
||||
else:
|
||||
cell = self._state_cells.get((key, None))
|
||||
if cell:
|
||||
try:
|
||||
cell.config(text=f"{float(value):>8.4f}")
|
||||
except (ValueError, TypeError):
|
||||
cell.config(text=str(value))
|
||||
|
||||
# ── actions ──────────────────────────────────────────────────────
|
||||
|
||||
def _start(self):
|
||||
result = self.server.start()
|
||||
if result is True:
|
||||
self.status_label.config(text="Online", fg=GREEN)
|
||||
self.status_dot.itemconfig("dot", fill=GREEN)
|
||||
self.start_btn.config(state="disabled", bg=BG_INPUT, cursor="arrow")
|
||||
self.stop_btn.config(state="normal", cursor="hand2")
|
||||
self._prev_packet_count = 0
|
||||
self._prev_time = time.time()
|
||||
else:
|
||||
messagebox.showerror("Error",
|
||||
f"Port {self.server.port} is already in use.\n{result}")
|
||||
|
||||
def _stop(self):
|
||||
self.server.stop()
|
||||
self.status_label.config(text="Offline", fg=RED)
|
||||
self.status_dot.itemconfig("dot", fill=RED)
|
||||
self.client_val.config(text="--")
|
||||
self.pps_val.config(text="0")
|
||||
self.start_btn.config(state="normal", bg=ACCENT, cursor="hand2")
|
||||
self.stop_btn.config(state="disabled", cursor="arrow")
|
||||
|
||||
def _set_mode(self, mode):
|
||||
self.mode_var.set(mode)
|
||||
self.server.receive_only = (mode == "Recv only")
|
||||
|
||||
def _step_changed(self, event=None):
|
||||
try:
|
||||
self.server.correction_step = float(self.step_var.get())
|
||||
except ValueError:
|
||||
self.step_var.set(str(self.server.correction_step))
|
||||
|
||||
def _adjust(self, axis: str, direction: int):
|
||||
self.server.adjust_position(axis, direction * self.server.correction_step)
|
||||
|
||||
def _reset(self):
|
||||
self.server.reset_positions()
|
||||
|
||||
# ── display loop ─────────────────────────────────────────────────
|
||||
|
||||
def _update_display(self):
|
||||
with self.server.lock:
|
||||
# Position values
|
||||
rist = self.server.robot_state.get("RIst", {})
|
||||
for axis, label in self.pos_labels.items():
|
||||
val = rist.get(axis, 0.0)
|
||||
label.config(text=f"{val:+.4f}")
|
||||
|
||||
# IPOC
|
||||
self.ipoc_val.config(text=str(self.server.ipoc))
|
||||
|
||||
# Client
|
||||
if self.server.client_address:
|
||||
self.client_val.config(
|
||||
text=f"{self.server.client_address[0]}:{self.server.client_address[1]}")
|
||||
|
||||
# Packets/sec
|
||||
now = time.time()
|
||||
dt = now - self._prev_time
|
||||
if dt >= 1.0:
|
||||
delta = self.server.packet_count - self._prev_packet_count
|
||||
self._packets_per_sec = delta / dt
|
||||
self._prev_packet_count = self.server.packet_count
|
||||
self._prev_time = now
|
||||
self.pps_val.config(text=f"{self._packets_per_sec:.0f}")
|
||||
|
||||
# Robot state grid
|
||||
self._update_state_grid()
|
||||
|
||||
# XML traffic (pretty-printed)
|
||||
self._set_xml(self.recv_text, self.server.last_received_xml)
|
||||
self._set_xml(self.sent_text, self.server.last_sent_xml)
|
||||
|
||||
self.root.after(100, self._update_display)
|
||||
|
||||
@staticmethod
|
||||
def _set_text(widget, text):
|
||||
widget.config(state="normal")
|
||||
widget.delete("1.0", "end")
|
||||
widget.insert("1.0", text)
|
||||
widget.config(state="disabled")
|
||||
|
||||
@staticmethod
|
||||
def _set_xml(widget, xml_string):
|
||||
"""Pretty-print XML into a text widget."""
|
||||
formatted = xml_string
|
||||
if xml_string.strip():
|
||||
try:
|
||||
root = ET.fromstring(xml_string)
|
||||
ET.indent(root)
|
||||
formatted = ET.tostring(root, encoding="unicode")
|
||||
except ET.ParseError:
|
||||
pass
|
||||
widget.config(state="normal")
|
||||
widget.delete("1.0", "end")
|
||||
widget.insert("1.0", formatted)
|
||||
widget.config(state="disabled")
|
||||
|
||||
def _on_close(self):
|
||||
self.server.stop()
|
||||
self.root.destroy()
|
||||
|
||||
def run(self):
|
||||
self.root.mainloop()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="RSI TestServer - KUKA Robot Simulator")
|
||||
parser.add_argument(
|
||||
"--config", type=str, default="RSI_EthernetConfig.xml",
|
||||
help="Path to RSI_EthernetConfig.xml"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if not os.path.exists(args.config):
|
||||
print(f"Error: Config file not found: {args.config}")
|
||||
sys.exit(1)
|
||||
|
||||
app = TestServerGUI(args.config)
|
||||
app.run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Binary file not shown.
@ -1,335 +0,0 @@
|
||||
"""
|
||||
24-Hour RSI Stability Test
|
||||
|
||||
Long-duration stability test for RSIPI network communication.
|
||||
Monitors connection health, tracks metrics, and generates detailed
|
||||
performance reports.
|
||||
|
||||
Usage:
|
||||
python stability_test.py [--duration HOURS] [--config CONFIG_FILE] [--output OUTPUT_FILE]
|
||||
|
||||
Example:
|
||||
# Run for 24 hours
|
||||
python stability_test.py --duration 24
|
||||
|
||||
# Run for 1 hour with custom config
|
||||
python stability_test.py --duration 1 --config custom_config.xml
|
||||
|
||||
# Quick 5-minute test
|
||||
python stability_test.py --duration 0.083 # 5 minutes
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import time
|
||||
import argparse
|
||||
import logging
|
||||
import json
|
||||
import datetime
|
||||
from pathlib import Path
|
||||
|
||||
# Add parent directory to path for imports
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent / 'src'))
|
||||
|
||||
from RSIPI import RSIAPI
|
||||
|
||||
|
||||
class StabilityTest:
|
||||
"""Long-duration stability test for RSI communication."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config_file: str,
|
||||
duration_hours: float,
|
||||
output_file: str,
|
||||
check_interval: float = 60.0
|
||||
):
|
||||
"""
|
||||
Initialize stability test.
|
||||
|
||||
Args:
|
||||
config_file: Path to RSI config file
|
||||
duration_hours: Test duration in hours
|
||||
output_file: Path for results JSON file
|
||||
check_interval: How often to sample metrics (seconds)
|
||||
"""
|
||||
self.config_file = config_file
|
||||
self.duration_hours = duration_hours
|
||||
self.output_file = output_file
|
||||
self.check_interval = check_interval
|
||||
|
||||
self.start_time = None
|
||||
self.end_time = None
|
||||
self.samples = []
|
||||
self.api = None
|
||||
|
||||
def setup(self) -> None:
|
||||
"""Set up logging and RSI connection."""
|
||||
# Configure logging
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s',
|
||||
handlers=[
|
||||
logging.FileHandler(f'stability_test_{datetime.datetime.now().strftime("%Y%m%d_%H%M%S")}.log'),
|
||||
logging.StreamHandler()
|
||||
]
|
||||
)
|
||||
|
||||
logging.info(f"=== RSI Stability Test ===")
|
||||
logging.info(f"Config: {self.config_file}")
|
||||
logging.info(f"Duration: {self.duration_hours} hours")
|
||||
logging.info(f"Check interval: {self.check_interval}s")
|
||||
logging.info(f"Output: {self.output_file}")
|
||||
logging.info("=" * 50)
|
||||
|
||||
# Initialize API with auto-reconnect enabled
|
||||
self.api = RSIAPI(
|
||||
self.config_file,
|
||||
enable_auto_reconnect=True,
|
||||
auto_reconnect_retries=0, # Unlimited retries
|
||||
auto_reconnect_delay=10.0
|
||||
)
|
||||
|
||||
logging.info("Starting RSI communication...")
|
||||
self.api.start()
|
||||
|
||||
# Wait for connection to stabilize
|
||||
time.sleep(3)
|
||||
|
||||
if not self.api.is_running():
|
||||
raise RuntimeError("Failed to start RSI communication")
|
||||
|
||||
logging.info("✅ RSI communication started successfully")
|
||||
|
||||
def run(self) -> None:
|
||||
"""Run the stability test."""
|
||||
self.start_time = time.time()
|
||||
end_time = self.start_time + (self.duration_hours * 3600)
|
||||
|
||||
sample_count = 0
|
||||
error_count = 0
|
||||
|
||||
logging.info(f"Test started at {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
logging.info(f"Will run until {datetime.datetime.fromtimestamp(end_time).strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
|
||||
try:
|
||||
while time.time() < end_time:
|
||||
try:
|
||||
# Collect metrics sample
|
||||
sample = self._collect_sample()
|
||||
self.samples.append(sample)
|
||||
sample_count += 1
|
||||
|
||||
# Log progress
|
||||
elapsed_hours = (time.time() - self.start_time) / 3600
|
||||
remaining_hours = self.duration_hours - elapsed_hours
|
||||
progress = (elapsed_hours / self.duration_hours) * 100
|
||||
|
||||
self._log_progress(sample, elapsed_hours, remaining_hours, progress, sample_count, error_count)
|
||||
|
||||
except Exception as e:
|
||||
error_count += 1
|
||||
logging.error(f"Error collecting sample: {e}")
|
||||
|
||||
# Sleep until next check
|
||||
time.sleep(self.check_interval)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logging.warning("\n⚠️ Test interrupted by user")
|
||||
|
||||
finally:
|
||||
self.end_time = time.time()
|
||||
self._cleanup()
|
||||
|
||||
def _collect_sample(self) -> dict:
|
||||
"""Collect a single metrics sample."""
|
||||
stats = self.api.diagnostics.get_stats()
|
||||
|
||||
sample = {
|
||||
'timestamp': time.time(),
|
||||
'mean_cycle_time': stats.get('mean_cycle_time', 0),
|
||||
'jitter': stats.get('jitter', 0),
|
||||
'packet_loss_rate': stats.get('packet_loss_rate', 0),
|
||||
'ipoc_gap_rate': stats.get('ipoc_gap_rate', 0),
|
||||
'total_cycles': stats.get('total_cycles', 0),
|
||||
'is_healthy': stats.get('is_healthy', False),
|
||||
'warnings': stats.get('warnings', []),
|
||||
'uptime': stats.get('uptime', 0),
|
||||
}
|
||||
|
||||
return sample
|
||||
|
||||
def _log_progress(
|
||||
self,
|
||||
sample: dict,
|
||||
elapsed_hours: float,
|
||||
remaining_hours: float,
|
||||
progress: float,
|
||||
sample_count: int,
|
||||
error_count: int
|
||||
) -> None:
|
||||
"""Log current progress."""
|
||||
health_icon = "✅" if sample['is_healthy'] else "⚠️"
|
||||
|
||||
logging.info(
|
||||
f"{health_icon} Progress: {progress:.1f}% | "
|
||||
f"Elapsed: {elapsed_hours:.2f}h | "
|
||||
f"Remaining: {remaining_hours:.2f}h | "
|
||||
f"Samples: {sample_count} | "
|
||||
f"Jitter: {sample['jitter']*1000:.2f}ms | "
|
||||
f"Loss: {sample['packet_loss_rate']:.2f}%"
|
||||
)
|
||||
|
||||
if sample['warnings']:
|
||||
for warning in sample['warnings']:
|
||||
logging.warning(f" ⚠️ {warning}")
|
||||
|
||||
def _cleanup(self) -> None:
|
||||
"""Clean up and generate report."""
|
||||
logging.info("\n=== Test Complete ===")
|
||||
|
||||
# Stop RSI
|
||||
logging.info("Stopping RSI communication...")
|
||||
self.api.stop()
|
||||
|
||||
# Generate report
|
||||
logging.info("Generating report...")
|
||||
report = self._generate_report()
|
||||
|
||||
# Save results
|
||||
with open(self.output_file, 'w') as f:
|
||||
json.dump(report, f, indent=2)
|
||||
|
||||
logging.info(f"✅ Report saved to: {self.output_file}")
|
||||
|
||||
# Print summary
|
||||
self._print_summary(report)
|
||||
|
||||
def _generate_report(self) -> dict:
|
||||
"""Generate comprehensive test report."""
|
||||
if not self.samples:
|
||||
return {'error': 'No samples collected'}
|
||||
|
||||
# Calculate statistics
|
||||
jitter_values = [s['jitter'] for s in self.samples]
|
||||
packet_loss_values = [s['packet_loss_rate'] for s in self.samples]
|
||||
cycle_time_values = [s['mean_cycle_time'] for s in self.samples]
|
||||
|
||||
healthy_samples = sum(1 for s in self.samples if s['is_healthy'])
|
||||
unhealthy_samples = len(self.samples) - healthy_samples
|
||||
|
||||
report = {
|
||||
'test_info': {
|
||||
'config_file': self.config_file,
|
||||
'duration_hours': self.duration_hours,
|
||||
'start_time': datetime.datetime.fromtimestamp(self.start_time).isoformat(),
|
||||
'end_time': datetime.datetime.fromtimestamp(self.end_time).isoformat(),
|
||||
'actual_duration_hours': (self.end_time - self.start_time) / 3600,
|
||||
'total_samples': len(self.samples),
|
||||
},
|
||||
'health_summary': {
|
||||
'healthy_samples': healthy_samples,
|
||||
'unhealthy_samples': unhealthy_samples,
|
||||
'health_percentage': (healthy_samples / len(self.samples)) * 100,
|
||||
},
|
||||
'timing_stats': {
|
||||
'mean_cycle_time_ms': statistics.mean(cycle_time_values) * 1000 if cycle_time_values else 0,
|
||||
'min_cycle_time_ms': min(cycle_time_values) * 1000 if cycle_time_values else 0,
|
||||
'max_cycle_time_ms': max(cycle_time_values) * 1000 if cycle_time_values else 0,
|
||||
'mean_jitter_ms': statistics.mean(jitter_values) * 1000 if jitter_values else 0,
|
||||
'max_jitter_ms': max(jitter_values) * 1000 if jitter_values else 0,
|
||||
},
|
||||
'network_stats': {
|
||||
'mean_packet_loss_percent': statistics.mean(packet_loss_values) if packet_loss_values else 0,
|
||||
'max_packet_loss_percent': max(packet_loss_values) if packet_loss_values else 0,
|
||||
},
|
||||
'final_metrics': self.samples[-1] if self.samples else {},
|
||||
}
|
||||
|
||||
return report
|
||||
|
||||
def _print_summary(self, report: dict) -> None:
|
||||
"""Print human-readable summary."""
|
||||
print("\n" + "=" * 60)
|
||||
print("STABILITY TEST SUMMARY")
|
||||
print("=" * 60)
|
||||
|
||||
info = report['test_info']
|
||||
health = report['health_summary']
|
||||
timing = report['timing_stats']
|
||||
network = report['network_stats']
|
||||
|
||||
print(f"\nTest Duration: {info['actual_duration_hours']:.2f} hours")
|
||||
print(f"Total Samples: {info['total_samples']}")
|
||||
|
||||
print(f"\nHealth: {health['health_percentage']:.1f}% healthy")
|
||||
print(f" Healthy samples: {health['healthy_samples']}")
|
||||
print(f" Unhealthy samples: {health['unhealthy_samples']}")
|
||||
|
||||
print(f"\nTiming Performance:")
|
||||
print(f" Mean cycle time: {timing['mean_cycle_time_ms']:.2f}ms")
|
||||
print(f" Cycle time range: {timing['min_cycle_time_ms']:.2f} - {timing['max_cycle_time_ms']:.2f}ms")
|
||||
print(f" Mean jitter: {timing['mean_jitter_ms']:.2f}ms")
|
||||
print(f" Max jitter: {timing['max_jitter_ms']:.2f}ms")
|
||||
|
||||
print(f"\nNetwork Quality:")
|
||||
print(f" Mean packet loss: {network['mean_packet_loss_percent']:.3f}%")
|
||||
print(f" Max packet loss: {network['max_packet_loss_percent']:.3f}%")
|
||||
|
||||
health_icon = "✅ PASS" if health['health_percentage'] >= 95 else "⚠️ NEEDS IMPROVEMENT"
|
||||
print(f"\nOverall Result: {health_icon}")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
import statistics
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point."""
|
||||
parser = argparse.ArgumentParser(description='RSI 24-Hour Stability Test')
|
||||
parser.add_argument(
|
||||
'--duration',
|
||||
type=float,
|
||||
default=24.0,
|
||||
help='Test duration in hours (default: 24)'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--config',
|
||||
type=str,
|
||||
default='RSI_EthernetConfig.xml',
|
||||
help='Path to RSI config file'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--output',
|
||||
type=str,
|
||||
default=None,
|
||||
help='Output JSON file (default: stability_test_TIMESTAMP.json)'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--interval',
|
||||
type=float,
|
||||
default=60.0,
|
||||
help='Check interval in seconds (default: 60)'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Generate default output filename if not specified
|
||||
if args.output is None:
|
||||
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
args.output = f'stability_test_{timestamp}.json'
|
||||
|
||||
# Run test
|
||||
test = StabilityTest(
|
||||
config_file=args.config,
|
||||
duration_hours=args.duration,
|
||||
output_file=args.output,
|
||||
check_interval=args.interval
|
||||
)
|
||||
|
||||
test.setup()
|
||||
test.run()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,261 +0,0 @@
|
||||
"""Tests for ConfigParser."""
|
||||
import pytest
|
||||
import sys
|
||||
import os
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
|
||||
|
||||
from RSIPI.config_parser import ConfigParser
|
||||
|
||||
# Path to the real config file in the project root
|
||||
CONFIG_FILE = os.path.join(os.path.dirname(__file__), '..', 'RSI_EthernetConfig.xml')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def parser():
|
||||
"""Create a ConfigParser from the real config file."""
|
||||
return ConfigParser(CONFIG_FILE)
|
||||
|
||||
|
||||
class TestParseWithoutError:
|
||||
"""Verify that the config file parses successfully."""
|
||||
|
||||
def test_parser_initializes(self, parser):
|
||||
"""ConfigParser should initialize without raising."""
|
||||
assert parser is not None
|
||||
|
||||
def test_send_variables_is_dict(self, parser):
|
||||
"""send_variables should be a dict after parsing."""
|
||||
assert isinstance(parser.send_variables, dict)
|
||||
|
||||
def test_receive_variables_is_dict(self, parser):
|
||||
"""receive_variables should be a dict after parsing."""
|
||||
assert isinstance(parser.receive_variables, dict)
|
||||
|
||||
|
||||
class TestNetworkSettings:
|
||||
"""Verify network_settings extraction from <CONFIG>."""
|
||||
|
||||
def test_has_ip(self, parser):
|
||||
"""network_settings must contain 'ip'."""
|
||||
assert "ip" in parser.network_settings
|
||||
assert parser.network_settings["ip"] == "10.10.10.10"
|
||||
|
||||
def test_has_port(self, parser):
|
||||
"""network_settings must contain 'port' as int."""
|
||||
assert "port" in parser.network_settings
|
||||
assert parser.network_settings["port"] == 64000
|
||||
assert isinstance(parser.network_settings["port"], int)
|
||||
|
||||
def test_has_sentype(self, parser):
|
||||
"""network_settings must contain 'sentype'."""
|
||||
assert "sentype" in parser.network_settings
|
||||
assert parser.network_settings["sentype"] == "ImFree"
|
||||
|
||||
def test_has_onlysend(self, parser):
|
||||
"""network_settings must contain 'onlysend' as bool."""
|
||||
assert "onlysend" in parser.network_settings
|
||||
assert parser.network_settings["onlysend"] is False
|
||||
|
||||
def test_get_network_settings_matches(self, parser):
|
||||
"""get_network_settings() should return the same dict."""
|
||||
assert parser.get_network_settings() == parser.network_settings
|
||||
|
||||
|
||||
class TestSendVariables:
|
||||
"""Verify send_variables contains expected keys from the config file."""
|
||||
|
||||
def test_contains_rist(self, parser):
|
||||
"""RIst (robot actual position) should be in send_variables."""
|
||||
assert "RIst" in parser.send_variables
|
||||
|
||||
def test_rist_has_cartesian_keys(self, parser):
|
||||
"""RIst should expand to X, Y, Z, A, B, C sub-keys."""
|
||||
rist = parser.send_variables["RIst"]
|
||||
assert isinstance(rist, dict)
|
||||
for axis in ["X", "Y", "Z", "A", "B", "C"]:
|
||||
assert axis in rist
|
||||
|
||||
def test_contains_rsol(self, parser):
|
||||
"""RSol (robot commanded position) should be in send_variables."""
|
||||
assert "RSol" in parser.send_variables
|
||||
|
||||
def test_contains_ipoc(self, parser):
|
||||
"""IPOC timestamp should always be in send_variables."""
|
||||
assert "IPOC" in parser.send_variables
|
||||
|
||||
def test_contains_delay(self, parser):
|
||||
"""Delay should be in send_variables."""
|
||||
assert "Delay" in parser.send_variables
|
||||
|
||||
def test_contains_digout(self, parser):
|
||||
"""Digout group should be parsed from dotted tags."""
|
||||
assert "Digout" in parser.send_variables
|
||||
|
||||
def test_digout_has_channels(self, parser):
|
||||
"""Digout should contain o1, o2, o3 sub-keys from the config."""
|
||||
digout = parser.send_variables["Digout"]
|
||||
assert isinstance(digout, dict)
|
||||
for ch in ["o1", "o2", "o3"]:
|
||||
assert ch in digout
|
||||
|
||||
def test_contains_source1(self, parser):
|
||||
"""Source1 should be in send_variables as a DOUBLE default."""
|
||||
assert "Source1" in parser.send_variables
|
||||
assert parser.send_variables["Source1"] == 0.0
|
||||
|
||||
def test_contains_dil(self, parser):
|
||||
"""DiL should be in send_variables as a LONG default."""
|
||||
assert "DiL" in parser.send_variables
|
||||
assert parser.send_variables["DiL"] == 0
|
||||
|
||||
|
||||
class TestReceiveVariables:
|
||||
"""Verify receive_variables contains expected keys."""
|
||||
|
||||
def test_contains_rkorr(self, parser):
|
||||
"""RKorr (correction values) should be in receive_variables."""
|
||||
assert "RKorr" in parser.receive_variables
|
||||
|
||||
def test_rkorr_has_cartesian_keys(self, parser):
|
||||
"""RKorr should have X, Y, Z, A, B, C from individual tags."""
|
||||
rkorr = parser.receive_variables["RKorr"]
|
||||
assert isinstance(rkorr, dict)
|
||||
for axis in ["X", "Y", "Z", "A", "B", "C"]:
|
||||
assert axis in rkorr
|
||||
|
||||
def test_contains_estr(self, parser):
|
||||
"""EStr should be in receive_variables."""
|
||||
assert "EStr" in parser.receive_variables
|
||||
|
||||
def test_contains_free(self, parser):
|
||||
"""FREE should be in receive_variables."""
|
||||
assert "FREE" in parser.receive_variables
|
||||
|
||||
def test_contains_dio(self, parser):
|
||||
"""DiO should be in receive_variables."""
|
||||
assert "DiO" in parser.receive_variables
|
||||
|
||||
|
||||
class TestDefPrefixStripping:
|
||||
"""Verify that DEF_ prefix is stripped from tags."""
|
||||
|
||||
def test_rist_not_def_rist(self, parser):
|
||||
"""Key should be 'RIst', not 'DEF_RIst'."""
|
||||
assert "DEF_RIst" not in parser.send_variables
|
||||
assert "RIst" in parser.send_variables
|
||||
|
||||
def test_rsol_not_def_rsol(self, parser):
|
||||
"""Key should be 'RSol', not 'DEF_RSol'."""
|
||||
assert "DEF_RSol" not in parser.send_variables
|
||||
assert "RSol" in parser.send_variables
|
||||
|
||||
def test_estr_not_def_estr(self, parser):
|
||||
"""Key should be 'EStr', not 'DEF_EStr'."""
|
||||
assert "DEF_EStr" not in parser.receive_variables
|
||||
assert "EStr" in parser.receive_variables
|
||||
|
||||
def test_tech_not_def_tech(self, parser):
|
||||
"""Tech keys should not retain DEF_ prefix."""
|
||||
for key in parser.send_variables:
|
||||
assert not key.startswith("DEF_")
|
||||
for key in parser.receive_variables:
|
||||
assert not key.startswith("DEF_")
|
||||
|
||||
|
||||
class TestIPOCAlwaysPresent:
|
||||
"""IPOC must always be in send_variables, even if not in config."""
|
||||
|
||||
def test_ipoc_present(self, parser):
|
||||
"""IPOC should be in send_variables."""
|
||||
assert "IPOC" in parser.send_variables
|
||||
|
||||
def test_ipoc_forced_when_missing(self, tmp_path):
|
||||
"""IPOC should be injected even if the config has no DEF_IPOC."""
|
||||
# Create a minimal config with no IPOC element
|
||||
minimal_xml = tmp_path / "minimal.xml"
|
||||
minimal_xml.write_text("""<ROOT>
|
||||
<CONFIG>
|
||||
<IP_NUMBER>127.0.0.1</IP_NUMBER>
|
||||
<PORT>12345</PORT>
|
||||
<SENTYPE>Test</SENTYPE>
|
||||
<ONLYSEND>FALSE</ONLYSEND>
|
||||
</CONFIG>
|
||||
<SEND><ELEMENTS>
|
||||
<ELEMENT TAG="DEF_RIst" TYPE="DOUBLE" INDX="INTERNAL" />
|
||||
</ELEMENTS></SEND>
|
||||
<RECEIVE><ELEMENTS>
|
||||
<ELEMENT TAG="RKorr.X" TYPE="DOUBLE" INDX="1" />
|
||||
</ELEMENTS></RECEIVE>
|
||||
</ROOT>""")
|
||||
p = ConfigParser(str(minimal_xml))
|
||||
assert "IPOC" in p.send_variables
|
||||
|
||||
|
||||
class TestTechKeyMerging:
|
||||
"""Verify that Tech.CX and Tech.TX keys merge into a single 'Tech' dict."""
|
||||
|
||||
def test_tech_merged_in_send(self, parser):
|
||||
"""Tech.C1 in send config should merge into a single 'Tech' key."""
|
||||
assert "Tech" in parser.send_variables
|
||||
# Should not have the dotted form
|
||||
for key in parser.send_variables:
|
||||
assert not key.startswith("Tech.")
|
||||
|
||||
def test_tech_merged_in_receive(self, parser):
|
||||
"""Tech.T2 in receive config should merge into a single 'Tech' key."""
|
||||
assert "Tech" in parser.receive_variables
|
||||
for key in parser.receive_variables:
|
||||
assert not key.startswith("Tech.")
|
||||
|
||||
def test_tech_contains_sub_keys(self, parser):
|
||||
"""Merged Tech dict should contain the sub-keys from the internal structure."""
|
||||
tech_send = parser.send_variables["Tech"]
|
||||
assert isinstance(tech_send, dict)
|
||||
# Tech.C1 should have expanded to C11, C12, ... C110
|
||||
assert "C11" in tech_send
|
||||
|
||||
def test_tech_receive_contains_sub_keys(self, parser):
|
||||
"""Tech in receive should have T2x keys from Tech.T2."""
|
||||
tech_recv = parser.receive_variables["Tech"]
|
||||
assert isinstance(tech_recv, dict)
|
||||
assert "T21" in tech_recv
|
||||
|
||||
|
||||
class TestGetDefaultValue:
|
||||
"""Test the static get_default_value helper."""
|
||||
|
||||
def test_bool_default(self):
|
||||
assert ConfigParser.get_default_value("BOOL") is False
|
||||
|
||||
def test_string_default(self):
|
||||
assert ConfigParser.get_default_value("STRING") == ""
|
||||
|
||||
def test_long_default(self):
|
||||
assert ConfigParser.get_default_value("LONG") == 0
|
||||
|
||||
def test_double_default(self):
|
||||
assert ConfigParser.get_default_value("DOUBLE") == 0.0
|
||||
|
||||
def test_unknown_default(self):
|
||||
assert ConfigParser.get_default_value("UNKNOWN") is None
|
||||
|
||||
|
||||
class TestRenameTechKeys:
|
||||
"""Test the static rename_tech_keys helper."""
|
||||
|
||||
def test_merges_tech_keys(self):
|
||||
d = {"Tech.C1": {"C11": 0}, "Tech.T2": {"T21": 0}, "Other": 5}
|
||||
ConfigParser.rename_tech_keys(d)
|
||||
assert "Tech" in d
|
||||
assert "Tech.C1" not in d
|
||||
assert "Tech.T2" not in d
|
||||
assert "C11" in d["Tech"]
|
||||
assert "T21" in d["Tech"]
|
||||
assert d["Other"] == 5
|
||||
|
||||
def test_no_tech_keys_leaves_dict_unchanged(self):
|
||||
d = {"RIst": {"X": 0}, "IPOC": 0}
|
||||
ConfigParser.rename_tech_keys(d)
|
||||
assert "Tech" not in d
|
||||
assert "RIst" in d
|
||||
@ -1,184 +0,0 @@
|
||||
"""Tests for IOAPI."""
|
||||
import pytest
|
||||
import sys
|
||||
import os
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
|
||||
|
||||
from RSIPI.io_api import IOAPI
|
||||
from RSIPI.exceptions import RSIVariableError
|
||||
|
||||
|
||||
def _make_mock_client(send_vars=None, receive_vars=None):
|
||||
"""
|
||||
Build a mock RSIClient with plain dict send/receive variables
|
||||
and a safety_manager that passes everything through.
|
||||
"""
|
||||
client = MagicMock()
|
||||
client.send_variables = send_vars if send_vars is not None else {}
|
||||
client.receive_variables = receive_vars if receive_vars is not None else {}
|
||||
|
||||
# Safety manager: validate returns the value unchanged
|
||||
client.safety_manager.validate.side_effect = lambda path, val: val
|
||||
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def io_with_digout():
|
||||
"""IOAPI with Digout in receive_variables and Digin in send_variables."""
|
||||
send = {
|
||||
"Digin": {"i1": 1, "i2": 0, "i3": 1},
|
||||
"IPOC": 12345,
|
||||
}
|
||||
recv = {
|
||||
"Digout": {"o1": 0, "o2": 0, "o3": 0},
|
||||
"DiO": 0,
|
||||
}
|
||||
client = _make_mock_client(send_vars=send, receive_vars=recv)
|
||||
return IOAPI(client)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# toggle
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestToggle:
|
||||
"""Tests for IOAPI.toggle()."""
|
||||
|
||||
def test_toggle_sets_value_via_update_variable(self, io_with_digout):
|
||||
"""toggle should call _tools.update_variable with group.name and int state."""
|
||||
io = io_with_digout
|
||||
io._tools = MagicMock()
|
||||
io._tools.update_variable.return_value = "Updated Digout.o1 to 1"
|
||||
|
||||
result = io.toggle("Digout", "o1", True)
|
||||
|
||||
io._tools.update_variable.assert_called_once_with("Digout.o1", 1)
|
||||
assert result == "Updated Digout.o1 to 1"
|
||||
|
||||
def test_toggle_false_sends_zero(self, io_with_digout):
|
||||
"""toggle with False should send 0."""
|
||||
io = io_with_digout
|
||||
io._tools = MagicMock()
|
||||
io._tools.update_variable.return_value = "Updated Digout.o2 to 0"
|
||||
|
||||
io.toggle("Digout", "o2", False)
|
||||
io._tools.update_variable.assert_called_once_with("Digout.o2", 0)
|
||||
|
||||
def test_toggle_int_one(self, io_with_digout):
|
||||
"""toggle with int 1 should send 1."""
|
||||
io = io_with_digout
|
||||
io._tools = MagicMock()
|
||||
io._tools.update_variable.return_value = "Updated Digout.o3 to 1"
|
||||
|
||||
io.toggle("Digout", "o3", 1)
|
||||
io._tools.update_variable.assert_called_once_with("Digout.o3", 1)
|
||||
|
||||
def test_toggle_truthy_value_normalizes_to_one(self, io_with_digout):
|
||||
"""Any truthy value should normalize to 1."""
|
||||
io = io_with_digout
|
||||
io._tools = MagicMock()
|
||||
io._tools.update_variable.return_value = "ok"
|
||||
|
||||
io.toggle("Digout", "o1", 42)
|
||||
io._tools.update_variable.assert_called_once_with("Digout.o1", 1)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# set_output
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestSetOutput:
|
||||
"""Tests for IOAPI.set_output()."""
|
||||
|
||||
def test_formats_channel_name(self, io_with_digout):
|
||||
"""set_output(3, True) should call toggle with 'o3'."""
|
||||
io = io_with_digout
|
||||
io._tools = MagicMock()
|
||||
io._tools.update_variable.return_value = "Updated Digout.o3 to 1"
|
||||
|
||||
io.set_output(3, True)
|
||||
io._tools.update_variable.assert_called_once_with("Digout.o3", 1)
|
||||
|
||||
def test_custom_group(self, io_with_digout):
|
||||
"""set_output with custom group should use that group."""
|
||||
io = io_with_digout
|
||||
io._tools = MagicMock()
|
||||
io._tools.update_variable.return_value = "Updated DiO.o5 to 1"
|
||||
|
||||
io.set_output(5, True, group="DiO")
|
||||
io._tools.update_variable.assert_called_once_with("DiO.o5", 1)
|
||||
|
||||
def test_set_output_off(self, io_with_digout):
|
||||
"""set_output with False should send 0."""
|
||||
io = io_with_digout
|
||||
io._tools = MagicMock()
|
||||
io._tools.update_variable.return_value = "Updated Digout.o1 to 0"
|
||||
|
||||
io.set_output(1, False)
|
||||
io._tools.update_variable.assert_called_once_with("Digout.o1", 0)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# get_input
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestGetInput:
|
||||
"""Tests for IOAPI.get_input()."""
|
||||
|
||||
def test_reads_true_from_send_variables(self, io_with_digout):
|
||||
"""get_input should read from send_variables (what robot sends us)."""
|
||||
result = io_with_digout.get_input(1, group="Digin")
|
||||
assert result is True # i1 = 1
|
||||
|
||||
def test_reads_false_from_send_variables(self, io_with_digout):
|
||||
"""get_input for channel with value 0 should return False."""
|
||||
result = io_with_digout.get_input(2, group="Digin")
|
||||
assert result is False # i2 = 0
|
||||
|
||||
def test_missing_group_raises(self, io_with_digout):
|
||||
"""get_input with non-existent group should raise RSIVariableError."""
|
||||
with pytest.raises(RSIVariableError, match="not found in send_variables"):
|
||||
io_with_digout.get_input(1, group="NonExistent")
|
||||
|
||||
def test_missing_channel_raises(self, io_with_digout):
|
||||
"""get_input with non-existent channel should raise RSIVariableError."""
|
||||
with pytest.raises(RSIVariableError, match="not found in group"):
|
||||
io_with_digout.get_input(99, group="Digin")
|
||||
|
||||
def test_default_group_is_digin(self):
|
||||
"""Default group should be 'Digin'."""
|
||||
send = {"Digin": {"i1": 1}}
|
||||
client = _make_mock_client(send_vars=send)
|
||||
io = IOAPI(client)
|
||||
assert io.get_input(1) is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# pulse (basic structure test, not timing)
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestPulse:
|
||||
"""Tests for IOAPI.pulse()."""
|
||||
|
||||
def test_pulse_calls_on_then_off(self, io_with_digout):
|
||||
"""pulse should turn output on then off."""
|
||||
io = io_with_digout
|
||||
io._tools = MagicMock()
|
||||
io._tools.update_variable.return_value = "ok"
|
||||
|
||||
result = io.pulse(1, duration=0.0) # zero duration for fast test
|
||||
|
||||
calls = io._tools.update_variable.call_args_list
|
||||
# First call: ON (value=1), second call: OFF (value=0)
|
||||
assert calls[0].args == ("Digout.o1", 1)
|
||||
assert calls[1].args == ("Digout.o1", 0)
|
||||
assert "Pulse completed" in result
|
||||
|
||||
def test_pulse_returns_message_with_duration(self, io_with_digout):
|
||||
"""Return string should include the duration."""
|
||||
io = io_with_digout
|
||||
io._tools = MagicMock()
|
||||
io._tools.update_variable.return_value = "ok"
|
||||
|
||||
result = io.pulse(2, duration=0.0)
|
||||
assert "0.0s" in result
|
||||
assert "Digout.o2" in result
|
||||
@ -1,439 +0,0 @@
|
||||
"""Tests for MotionAPI static/pure methods."""
|
||||
import pytest
|
||||
import math
|
||||
import sys
|
||||
import os
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
|
||||
|
||||
from RSIPI.motion_api import (
|
||||
MotionAPI,
|
||||
_calculate_distance,
|
||||
_trapezoidal_profile,
|
||||
_s_curve_profile,
|
||||
_cubic_blend,
|
||||
_find_blend_point,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# generate_arc
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestGenerateArc:
|
||||
"""Tests for MotionAPI.generate_arc()."""
|
||||
|
||||
def test_basic_arc_length(self):
|
||||
"""Arc with 50 steps should return 50 waypoints."""
|
||||
arc = MotionAPI.generate_arc(
|
||||
center={"X": 0, "Y": 0, "Z": 0},
|
||||
radius=10.0,
|
||||
start_angle=0,
|
||||
end_angle=90,
|
||||
steps=50,
|
||||
)
|
||||
assert len(arc) == 50
|
||||
|
||||
def test_first_point_on_circle(self):
|
||||
"""First point should be at start_angle on the circle."""
|
||||
arc = MotionAPI.generate_arc(
|
||||
center={"X": 100, "Y": 0, "Z": 0},
|
||||
radius=50.0,
|
||||
start_angle=0,
|
||||
end_angle=90,
|
||||
steps=10,
|
||||
)
|
||||
assert arc[0]["X"] == pytest.approx(150.0)
|
||||
assert arc[0]["Y"] == pytest.approx(0.0)
|
||||
|
||||
def test_last_point_at_end_angle(self):
|
||||
"""Last point should be at end_angle on the circle."""
|
||||
arc = MotionAPI.generate_arc(
|
||||
center={"X": 0, "Y": 0, "Z": 0},
|
||||
radius=10.0,
|
||||
start_angle=0,
|
||||
end_angle=90,
|
||||
steps=10,
|
||||
)
|
||||
assert arc[-1]["X"] == pytest.approx(10.0 * math.cos(math.radians(90)))
|
||||
assert arc[-1]["Y"] == pytest.approx(10.0 * math.sin(math.radians(90)))
|
||||
|
||||
def test_xz_plane(self):
|
||||
"""Arc in XZ plane should vary X and Z, keep Y constant."""
|
||||
arc = MotionAPI.generate_arc(
|
||||
center={"X": 0, "Y": 5, "Z": 0},
|
||||
radius=10.0,
|
||||
start_angle=0,
|
||||
end_angle=90,
|
||||
steps=5,
|
||||
plane="XZ",
|
||||
)
|
||||
for pt in arc:
|
||||
assert pt["Y"] == 5
|
||||
|
||||
def test_yz_plane(self):
|
||||
"""Arc in YZ plane should vary Y and Z, keep X constant."""
|
||||
arc = MotionAPI.generate_arc(
|
||||
center={"X": 7, "Y": 0, "Z": 0},
|
||||
radius=10.0,
|
||||
start_angle=0,
|
||||
end_angle=180,
|
||||
steps=5,
|
||||
plane="YZ",
|
||||
)
|
||||
for pt in arc:
|
||||
assert pt["X"] == 7
|
||||
|
||||
def test_preserves_orientation(self):
|
||||
"""Orientation keys A, B, C should carry through from center."""
|
||||
arc = MotionAPI.generate_arc(
|
||||
center={"X": 0, "Y": 0, "Z": 0, "A": 10, "B": 20, "C": 30},
|
||||
radius=5.0,
|
||||
start_angle=0,
|
||||
end_angle=45,
|
||||
steps=3,
|
||||
)
|
||||
for pt in arc:
|
||||
assert pt["A"] == 10
|
||||
assert pt["B"] == 20
|
||||
assert pt["C"] == 30
|
||||
|
||||
def test_invalid_plane_raises(self):
|
||||
with pytest.raises(ValueError, match="Unknown plane"):
|
||||
MotionAPI.generate_arc(
|
||||
center={"X": 0, "Y": 0, "Z": 0},
|
||||
radius=5.0, start_angle=0, end_angle=90, steps=5, plane="AB"
|
||||
)
|
||||
|
||||
def test_zero_radius_raises(self):
|
||||
with pytest.raises(ValueError, match="positive"):
|
||||
MotionAPI.generate_arc(
|
||||
center={"X": 0, "Y": 0, "Z": 0},
|
||||
radius=0.0, start_angle=0, end_angle=90, steps=5
|
||||
)
|
||||
|
||||
def test_one_step_raises(self):
|
||||
with pytest.raises(ValueError, match="at least 2"):
|
||||
MotionAPI.generate_arc(
|
||||
center={"X": 0, "Y": 0, "Z": 0},
|
||||
radius=5.0, start_angle=0, end_angle=90, steps=1
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# generate_circle
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestGenerateCircle:
|
||||
"""Tests for MotionAPI.generate_circle()."""
|
||||
|
||||
def test_returns_360_degree_arc(self):
|
||||
"""Circle should span full 360 degrees."""
|
||||
circle = MotionAPI.generate_circle(
|
||||
center={"X": 0, "Y": 0, "Z": 0},
|
||||
radius=10.0,
|
||||
steps=100,
|
||||
)
|
||||
assert len(circle) == 100
|
||||
# First and last points should be nearly identical (full revolution)
|
||||
assert circle[0]["X"] == pytest.approx(circle[-1]["X"], abs=0.5)
|
||||
assert circle[0]["Y"] == pytest.approx(circle[-1]["Y"], abs=0.5)
|
||||
|
||||
def test_circle_points_on_radius(self):
|
||||
"""All points should lie on the specified radius from center."""
|
||||
cx, cy = 50.0, 30.0
|
||||
radius = 20.0
|
||||
circle = MotionAPI.generate_circle(
|
||||
center={"X": cx, "Y": cy, "Z": 0},
|
||||
radius=radius,
|
||||
steps=36,
|
||||
)
|
||||
for pt in circle:
|
||||
dist = math.sqrt((pt["X"] - cx) ** 2 + (pt["Y"] - cy) ** 2)
|
||||
assert dist == pytest.approx(radius, abs=1e-10)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# generate_spiral
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestGenerateSpiral:
|
||||
"""Tests for MotionAPI.generate_spiral()."""
|
||||
|
||||
def test_expanding_spiral_radius_increases(self):
|
||||
"""Radius should increase from start_radius to end_radius."""
|
||||
spiral = MotionAPI.generate_spiral(
|
||||
center={"X": 0, "Y": 0, "Z": 0},
|
||||
start_radius=5.0,
|
||||
end_radius=50.0,
|
||||
pitch=0.0,
|
||||
revolutions=2,
|
||||
steps=50,
|
||||
)
|
||||
first_r = math.sqrt(spiral[0]["X"] ** 2 + spiral[0]["Y"] ** 2)
|
||||
last_r = math.sqrt(spiral[-1]["X"] ** 2 + spiral[-1]["Y"] ** 2)
|
||||
assert last_r > first_r
|
||||
|
||||
def test_contracting_spiral_radius_decreases(self):
|
||||
"""Radius should decrease when end_radius < start_radius."""
|
||||
spiral = MotionAPI.generate_spiral(
|
||||
center={"X": 0, "Y": 0, "Z": 0},
|
||||
start_radius=50.0,
|
||||
end_radius=5.0,
|
||||
pitch=0.0,
|
||||
revolutions=2,
|
||||
steps=50,
|
||||
)
|
||||
first_r = math.sqrt(spiral[0]["X"] ** 2 + spiral[0]["Y"] ** 2)
|
||||
last_r = math.sqrt(spiral[-1]["X"] ** 2 + spiral[-1]["Y"] ** 2)
|
||||
assert last_r < first_r
|
||||
|
||||
def test_pitch_adds_height(self):
|
||||
"""Positive pitch should increase Z across the spiral."""
|
||||
spiral = MotionAPI.generate_spiral(
|
||||
center={"X": 0, "Y": 0, "Z": 100},
|
||||
start_radius=10.0,
|
||||
end_radius=10.0,
|
||||
pitch=20.0,
|
||||
revolutions=1,
|
||||
steps=20,
|
||||
)
|
||||
assert spiral[-1]["Z"] > spiral[0]["Z"]
|
||||
|
||||
def test_step_count(self):
|
||||
"""Should return exactly the requested number of steps."""
|
||||
spiral = MotionAPI.generate_spiral(
|
||||
center={"X": 0, "Y": 0, "Z": 0},
|
||||
start_radius=10.0,
|
||||
end_radius=20.0,
|
||||
pitch=5.0,
|
||||
steps=33,
|
||||
)
|
||||
assert len(spiral) == 33
|
||||
|
||||
def test_too_few_steps_raises(self):
|
||||
with pytest.raises(ValueError, match="at least 2"):
|
||||
MotionAPI.generate_spiral(
|
||||
center={"X": 0, "Y": 0, "Z": 0},
|
||||
start_radius=5, end_radius=10, pitch=1, steps=1
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# blend_trajectories
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestBlendTrajectories:
|
||||
"""Tests for MotionAPI.blend_trajectories()."""
|
||||
|
||||
@staticmethod
|
||||
def _line(start_x, end_x, n=20):
|
||||
"""Helper: straight line along X."""
|
||||
return [{"X": start_x + i * (end_x - start_x) / (n - 1), "Y": 0, "Z": 0} for i in range(n)]
|
||||
|
||||
def test_blended_length(self):
|
||||
"""Blended trajectory should have points from both segments plus blend zone."""
|
||||
t1 = self._line(0, 100, 20)
|
||||
t2 = self._line(100, 200, 20)
|
||||
blended = MotionAPI.blend_trajectories(t1, t2, blend_radius=10.0, blend_steps=10)
|
||||
# Should have some points; exact count depends on blend_radius vs traj length
|
||||
assert len(blended) > 0
|
||||
|
||||
def test_blended_starts_at_traj1_start(self):
|
||||
"""First point of blended should match first point of traj1."""
|
||||
t1 = self._line(0, 100, 20)
|
||||
t2 = self._line(100, 200, 20)
|
||||
blended = MotionAPI.blend_trajectories(t1, t2, blend_radius=5.0, blend_steps=10)
|
||||
assert blended[0]["X"] == pytest.approx(0.0)
|
||||
|
||||
def test_blended_ends_at_traj2_end(self):
|
||||
"""Last point of blended should match last point of traj2."""
|
||||
t1 = self._line(0, 100, 20)
|
||||
t2 = self._line(100, 200, 20)
|
||||
blended = MotionAPI.blend_trajectories(t1, t2, blend_radius=5.0, blend_steps=10)
|
||||
assert blended[-1]["X"] == pytest.approx(200.0)
|
||||
|
||||
def test_empty_traj_raises(self):
|
||||
with pytest.raises(ValueError, match="non-empty"):
|
||||
MotionAPI.blend_trajectories([], [{"X": 0}], blend_radius=1.0)
|
||||
|
||||
def test_zero_blend_radius_raises(self):
|
||||
with pytest.raises(ValueError, match="positive"):
|
||||
MotionAPI.blend_trajectories(
|
||||
[{"X": 0}], [{"X": 1}], blend_radius=0.0
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# transform_coordinates
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestTransformCoordinates:
|
||||
"""Tests for MotionAPI.transform_coordinates()."""
|
||||
|
||||
def test_no_offset_returns_copy(self):
|
||||
"""No frame_offset should return a copy of the input pose."""
|
||||
pose = {"X": 10, "Y": 20, "Z": 30}
|
||||
result = MotionAPI.transform_coordinates(pose)
|
||||
assert result == pose
|
||||
# Should be a copy, not the same object
|
||||
assert result is not pose
|
||||
|
||||
def test_translational_offset(self):
|
||||
"""Frame offset should add to position values."""
|
||||
pose = {"X": 100, "Y": 0, "Z": 500}
|
||||
offset = {"X": 500, "Y": 200, "Z": 0}
|
||||
result = MotionAPI.transform_coordinates(pose, frame_offset=offset)
|
||||
assert result["X"] == 600
|
||||
assert result["Y"] == 200
|
||||
assert result["Z"] == 500
|
||||
|
||||
def test_rotational_offset(self):
|
||||
"""Frame offset should add to orientation values."""
|
||||
pose = {"X": 0, "Y": 0, "Z": 0, "A": 10, "B": 20, "C": 30}
|
||||
offset = {"A": 5, "B": -10, "C": 15}
|
||||
result = MotionAPI.transform_coordinates(pose, frame_offset=offset)
|
||||
assert result["A"] == 15
|
||||
assert result["B"] == 10
|
||||
assert result["C"] == 45
|
||||
|
||||
def test_partial_offset(self):
|
||||
"""Offset with fewer keys should only affect matching axes."""
|
||||
pose = {"X": 100, "Y": 200, "Z": 300}
|
||||
offset = {"X": 10}
|
||||
result = MotionAPI.transform_coordinates(pose, frame_offset=offset)
|
||||
assert result["X"] == 110
|
||||
assert result["Y"] == 200 # unchanged
|
||||
assert result["Z"] == 300 # unchanged
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# generate_velocity_profile
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestGenerateVelocityProfile:
|
||||
"""Tests for MotionAPI.generate_velocity_profile()."""
|
||||
|
||||
@staticmethod
|
||||
def _simple_traj(n=50):
|
||||
"""Evenly spaced points along X."""
|
||||
return [{"X": i * 1.0, "Y": 0, "Z": 0} for i in range(n)]
|
||||
|
||||
def test_trapezoidal_returns_correct_length(self):
|
||||
traj = self._simple_traj(50)
|
||||
result = MotionAPI.generate_velocity_profile(traj, profile='trapezoidal')
|
||||
assert len(result) == 50
|
||||
|
||||
def test_scurve_returns_correct_length(self):
|
||||
traj = self._simple_traj(50)
|
||||
result = MotionAPI.generate_velocity_profile(traj, profile='s-curve')
|
||||
assert len(result) == 50
|
||||
|
||||
def test_trapezoidal_starts_and_ends_near_zero(self):
|
||||
"""Velocity should be near zero at start and end."""
|
||||
traj = self._simple_traj(100)
|
||||
result = MotionAPI.generate_velocity_profile(
|
||||
traj, max_velocity=10.0, max_acceleration=5.0, profile='trapezoidal'
|
||||
)
|
||||
_, v_first = result[0]
|
||||
_, v_last = result[-1]
|
||||
assert v_first == pytest.approx(0.0, abs=0.5)
|
||||
assert v_last == pytest.approx(0.0, abs=0.5)
|
||||
|
||||
def test_scurve_starts_and_ends_near_zero(self):
|
||||
traj = self._simple_traj(100)
|
||||
result = MotionAPI.generate_velocity_profile(
|
||||
traj, max_velocity=10.0, max_acceleration=5.0, profile='s-curve'
|
||||
)
|
||||
_, v_first = result[0]
|
||||
_, v_last = result[-1]
|
||||
assert v_first == pytest.approx(0.0, abs=0.5)
|
||||
assert v_last == pytest.approx(0.0, abs=0.5)
|
||||
|
||||
def test_empty_trajectory(self):
|
||||
assert MotionAPI.generate_velocity_profile([]) == []
|
||||
|
||||
def test_single_point(self):
|
||||
result = MotionAPI.generate_velocity_profile([{"X": 0}])
|
||||
assert len(result) == 1
|
||||
assert result[0][1] == 0.0
|
||||
|
||||
def test_unknown_profile_raises(self):
|
||||
traj = self._simple_traj(10)
|
||||
with pytest.raises(ValueError, match="Unknown profile"):
|
||||
MotionAPI.generate_velocity_profile(traj, profile='banana')
|
||||
|
||||
def test_trapezoidal_velocity_does_not_exceed_max(self):
|
||||
"""No velocity should exceed max_velocity."""
|
||||
traj = self._simple_traj(100)
|
||||
max_v = 5.0
|
||||
result = MotionAPI.generate_velocity_profile(
|
||||
traj, max_velocity=max_v, max_acceleration=2.0, profile='trapezoidal'
|
||||
)
|
||||
for _, v in result:
|
||||
assert v <= max_v + 1e-9
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _cubic_blend edge cases
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestCubicBlend:
|
||||
"""Tests for _cubic_blend helper."""
|
||||
|
||||
def test_steps_one_no_crash(self):
|
||||
"""steps=1 should not cause division by zero."""
|
||||
result = _cubic_blend({"X": 0, "Y": 0}, {"X": 10, "Y": 10}, steps=1)
|
||||
assert len(result) == 1
|
||||
|
||||
def test_steps_two(self):
|
||||
"""steps=2 should interpolate from p1 to p2."""
|
||||
result = _cubic_blend({"X": 0}, {"X": 100}, steps=2)
|
||||
assert len(result) == 2
|
||||
assert result[0]["X"] == pytest.approx(0.0)
|
||||
assert result[-1]["X"] == pytest.approx(100.0)
|
||||
|
||||
def test_midpoint_is_blended(self):
|
||||
"""Midpoint (t=0.5) of cubic Hermite with zero velocities should be average."""
|
||||
result = _cubic_blend({"X": 0}, {"X": 100}, steps=3)
|
||||
# At t=0.5: h1=0.5, h2=0.5 -> blended = 50
|
||||
assert result[1]["X"] == pytest.approx(50.0)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _trapezoidal_profile edge cases
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestTrapezoidalProfileEdgeCases:
|
||||
"""Edge-case tests for the _trapezoidal_profile helper."""
|
||||
|
||||
def test_single_distance(self):
|
||||
"""Profile with one distance segment should not crash."""
|
||||
velocities = _trapezoidal_profile([10.0], 10.0, 5.0, 2.0)
|
||||
assert len(velocities) == 2 # n = len(distances) + 1
|
||||
|
||||
def test_zero_total_distance(self):
|
||||
"""Zero total distance should produce zero velocities without error."""
|
||||
velocities = _trapezoidal_profile([0.0], 0.0, 5.0, 2.0)
|
||||
assert all(v == 0.0 for v in velocities)
|
||||
|
||||
def test_triangular_profile_triggered(self):
|
||||
"""Short distance forces triangular profile (no constant phase)."""
|
||||
# accel_distance = v^2 / (2*a) = 100/4 = 25
|
||||
# total = 10 < 2*25 => triangular
|
||||
velocities = _trapezoidal_profile([5.0, 5.0], 10.0, 10.0, 2.0)
|
||||
assert len(velocities) == 3
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _calculate_distance
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestCalculateDistance:
|
||||
"""Tests for _calculate_distance helper."""
|
||||
|
||||
def test_zero_distance(self):
|
||||
assert _calculate_distance({"X": 0, "Y": 0}, {"X": 0, "Y": 0}) == 0.0
|
||||
|
||||
def test_unit_distance(self):
|
||||
assert _calculate_distance({"X": 0}, {"X": 1}) == pytest.approx(1.0)
|
||||
|
||||
def test_3d_distance(self):
|
||||
d = _calculate_distance({"X": 0, "Y": 0, "Z": 0}, {"X": 3, "Y": 4, "Z": 0})
|
||||
assert d == pytest.approx(5.0)
|
||||
|
||||
def test_ignores_non_motion_keys(self):
|
||||
"""Keys not in the motion set should be ignored."""
|
||||
d = _calculate_distance({"X": 0, "FOO": 0}, {"X": 3, "FOO": 1000})
|
||||
assert d == pytest.approx(3.0)
|
||||
@ -6,7 +6,6 @@ import os
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
|
||||
|
||||
from RSIPI.safety_manager import SafetyManager
|
||||
from RSIPI.exceptions import RSILimitExceeded, RSIEmergencyStop
|
||||
|
||||
|
||||
class TestValidate:
|
||||
@ -33,15 +32,15 @@ class TestValidate:
|
||||
limits = {"RKorr.X": (-5.0, 5.0)}
|
||||
sm = SafetyManager(limits)
|
||||
|
||||
with pytest.raises(RSILimitExceeded, match="out of bounds"):
|
||||
with pytest.raises(ValueError, match="out of bounds"):
|
||||
sm.validate("RKorr.X", 5.1)
|
||||
|
||||
def test_validate_below_min(self):
|
||||
"""Test that values below min raise RSILimitExceeded."""
|
||||
"""Test that values below min raise ValueError."""
|
||||
limits = {"RKorr.X": (-5.0, 5.0)}
|
||||
sm = SafetyManager(limits)
|
||||
|
||||
with pytest.raises(RSILimitExceeded, match="out of bounds"):
|
||||
with pytest.raises(ValueError, match="out of bounds"):
|
||||
sm.validate("RKorr.X", -5.1)
|
||||
|
||||
def test_validate_unlisted_path(self):
|
||||
@ -72,7 +71,7 @@ class TestEmergencyStop:
|
||||
sm = SafetyManager()
|
||||
sm.emergency_stop()
|
||||
|
||||
with pytest.raises(RSIEmergencyStop, match="E-STOP"):
|
||||
with pytest.raises(RuntimeError, match="E-STOP"):
|
||||
sm.validate("RKorr.X", 0.0)
|
||||
|
||||
def test_estop_reset(self):
|
||||
@ -100,7 +99,7 @@ class TestSetLimit:
|
||||
sm.set_limit("RKorr.Y", -10.0, 10.0)
|
||||
|
||||
assert sm.validate("RKorr.Y", 5.0) == 5.0
|
||||
with pytest.raises(RSILimitExceeded):
|
||||
with pytest.raises(ValueError):
|
||||
sm.validate("RKorr.Y", 15.0)
|
||||
|
||||
def test_override_existing_limit(self):
|
||||
@ -109,7 +108,7 @@ class TestSetLimit:
|
||||
sm = SafetyManager(limits)
|
||||
|
||||
# Original limit blocks this
|
||||
with pytest.raises(RSILimitExceeded):
|
||||
with pytest.raises(ValueError):
|
||||
sm.validate("RKorr.X", 8.0)
|
||||
|
||||
# Override limit
|
||||
|
||||
Loading…
Reference in New Issue
Block a user