### Setup Development Environment Source: https://github.com/nfraxlab/robo-infra/blob/main/CONTRIBUTING.md Commands to clone the repository, install dependencies, and run quality assurance checks. ```bash git clone https://github.com//robo-infra.git cd robo-infra # Add upstream remote git remote add upstream https://github.com/nfraxlab/robo-infra.git # Install dependencies poetry install # Activate the virtual environment poetry shell # Run tests (simulation mode) ROBO_SIMULATION=true pytest -q # Run linting ruff check # Run type checking mypy src ``` -------------------------------- ### Install Robo-Infra and Dependencies Source: https://github.com/nfraxlab/robo-infra/blob/main/examples/lock/README.md Install the core robo-infra library and additional packages for the API example. ```bash pip install robo-infra pip install svc-infra uvicorn ``` -------------------------------- ### Complete Robot Arm Controller Example Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/utils.md This Python script demonstrates a full robot arm controller setup, including hardware initialization, joint group management, safety validations, and resilient operation with retries and timeouts. ```python """Robust robot controller with utilities.""" import asyncio from robo_infra.controllers import JointGroup from robo_infra.actuators import Servo from robo_infra.drivers import PCA9685Driver from robo_infra.utils.resilience import ( with_retry, with_timeout, create_driver_circuit_breaker, ) from robo_infra.utils.degraded import DegradedModeController from robo_infra.utils.resources import register_cleanup from robo_infra.utils.security import ( check_i2c_access, validate_joint_angles, JointLimits, ) from robo_infra.core.exceptions import CommunicationError async def main(): # Check permissions before accessing hardware check_i2c_access(bus=1) # Setup circuit breaker driver_circuit = create_driver_circuit_breaker("pca9685") # Initialize hardware driver = PCA9685Driver() joints = [ Servo("base", channel=0, driver=driver), Servo("shoulder", channel=1, driver=driver), Servo("elbow", channel=2, driver=driver), ] controller = JointGroup("arm", joints=joints) # Wrap in degraded mode controller degraded = DegradedModeController(controller, max_degraded_ratio=0.5) # Register cleanup register_cleanup(controller.stop) register_cleanup(driver.disconnect) # Define joint limits limits = [ JointLimits(-1.57, 1.57, "base"), JointLimits(-2.0, 0.5, "shoulder"), JointLimits(-2.5, 2.5, "elbow"), ] # Validate target before moving targets = [0.5, -0.3, 1.0] validate_joint_angles(targets, limits) # Move with timeout and retry @with_retry(max_attempts=3, retry_on=(CommunicationError,)) # type: ignore async def safe_move(positions): async with with_timeout(10.0, "move"): async with driver_circuit: return await degraded.move(positions) try: result = await safe_move({ "base": targets[0], "shoulder": targets[1], "elbow": targets[2], }) if result.is_degraded: print(f"Moved in degraded mode, skipped: {result.skipped_targets}") else: print("Move complete") except Exception as e: print(f"Move failed: {e}") controller.stop() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Run Lock API Server Example Source: https://github.com/nfraxlab/robo-infra/blob/main/examples/lock/README.md Start the API server for remote lock control. Access API documentation, health checks, and lock status via provided URLs. ```bash python lock_with_api.py ``` -------------------------------- ### Real Hardware Setup - Ultrasonic Sensor Source: https://github.com/nfraxlab/robo-infra/blob/main/examples/rover/README.md Example code for connecting an ultrasonic sensor using a GPIODriver. ```APIDOC ## Real Hardware Setup: Ultrasonic Sensor ### Description This code snippet demonstrates how to connect an ultrasonic sensor using a `GPIODriver` with the `robo-infra` library. ### Code ```python from robo_infra.sensors import Ultrasonic from robo_infra.drivers import GPIODriver # Initialize the GPIO driver gpio = GPIODriver() gpio.connect() # Create an Ultrasonic sensor instance, specifying trigger and echo pins sensor = Ultrasonic( trigger_pin=gpio.get_digital_pin(23), echo_pin=gpio.get_digital_pin(24), name="front_distance", ) ``` ### Parameters - `trigger_pin`: The GPIO pin configured as the trigger output. - `echo_pin`: The GPIO pin configured as the echo input. - `name`: A string identifier for the sensor. ``` -------------------------------- ### Drone Motor Control Example Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/actuators.md Example implementation for controlling a quadcopter setup with four motors. ```python from robo_infra.actuators import Brushless from robo_infra.drivers import PCA9685Driver # Initialize driver driver = PCA9685Driver(i2c_address=0x40, frequency=50) driver.connect() driver.enable() # Create 4 motors for quadcopter motors = [ Brushless(channel=i, driver=driver, name=f"motor_{i}") for i in range(4) ] # Enable and arm all motors for motor in motors: motor.enable() motor.arm() import time # Spin up slowly for throttle in [0.1, 0.2, 0.3]: for motor in motors: motor.set(throttle) time.sleep(1) # Stop all motors for motor in motors: motor.set(0) motor.disarm() motor.disable() ``` -------------------------------- ### Install robo-infra Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/cli.md Install the package and verify the installation using the version command. ```bash pip install robo-infra # Verify installation robo-infra version ``` -------------------------------- ### Install robo-infra with GPIO Support Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install the robo-infra extra for GPIO control. ```bash pip install robo-infra[gpio] ``` -------------------------------- ### Install robo-infra with All Camera Support Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install the robo-infra extra for all supported camera types. ```bash pip install robo-infra[cameras] ``` -------------------------------- ### Initialize Servo and Driver Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/contributing/documentation.md Example of creating a driver and servo instance. ```python from robo_infra.actuators import Servo from robo_infra.drivers import PCA9685Driver # Create driver driver = PCA9685Driver() # Create servo servo = Servo("gripper", channel=0, driver=driver) servo.angle = 45 ``` -------------------------------- ### Install robo-infra via Poetry Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/getting-started.md Recommended installation method using Poetry for dependency management. ```bash # Clone the repository git clone https://github.com/nfraxlab/robo-infra.git cd robo-infra # Install with Poetry poetry install # Activate the virtual environment poetry shell ``` -------------------------------- ### Run Basic Gripper Control Example Source: https://github.com/nfraxlab/robo-infra/blob/main/examples/gripper/README.md Execute the basic gripper control script. ```bash python gripper.py ``` -------------------------------- ### CI/CD Integration Example for Robo-Infra Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/cli.md A GitHub Actions workflow file (`.github/workflows/test.yml`) for CI/CD integration. It sets up Python, installs robo-infra, verifies the installation, and runs tests in simulation mode. ```yaml # .github/workflows/test.yml name: Test on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11' - name: Install robo-infra run: pip install robo-infra[dev] - name: Verify installation run: robo-infra version - name: Run tests (simulation mode) run: | export ROBO_SIMULATION=true pytest tests/ ``` -------------------------------- ### Install project dependencies Source: https://github.com/nfraxlab/robo-infra/blob/main/examples/arm/README.md Install the required packages for core functionality, AI control, and API services. ```bash # Core requirement pip install robo-infra # For AI-controlled example pip install ai-infra # For API example pip install svc-infra uvicorn ``` -------------------------------- ### Gripper Initialization Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/controllers.md Setup for gripper controllers with actuator configuration. ```python from robo_infra.controllers import Gripper, GripperConfig from robo_infra.actuators import Servo # Create gripper actuator actuator = Servo(name="gripper_servo", channel=0, angle_range=(0, 90)) # Create controller config = GripperConfig( name="gripper", open_position=0, closed_position=90, grip_threshold=5.0, # Position tolerance grip_force_threshold=2.0, # Force threshold (if sensor) ) gripper = Gripper(name="my_gripper", actuator=actuator, config=config) ``` -------------------------------- ### PID Controller Tuning Examples Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/motion.md Provides example PID controller initializations with different gain values (Kp, Ki, Kd) to achieve varying response characteristics, from aggressive to smooth. ```python # Typical starting values for position control pid = PID(kp=1.0, ki=0.01, kd=0.1) # Aggressive response pid = PID(kp=5.0, ki=0.5, kd=0.2) # Smooth, slow response pid = PID(kp=0.5, ki=0.05, kd=0.1) ``` -------------------------------- ### Real Hardware Setup - DC Motors Source: https://github.com/nfraxlab/robo-infra/blob/main/examples/rover/README.md Example code for connecting DC motors using an L298N H-bridge driver. ```APIDOC ## Real Hardware Setup: DC Motors ### Description This code snippet demonstrates how to connect DC motors to an L298N dual H-bridge driver using the `robo-infra` library. ### Code ```python from robo_infra.actuators import DCMotor from robo_infra.drivers import L298N # Initialize the L298N dual H-bridge driver driver = L298N() driver.connect() driver.enable() # Create DCMotor instances for the left and right wheels, specifying pins and the driver left_motor = DCMotor( name="left_wheel", pin_a=0, pin_b=1, enable=2, driver=driver, ) right_motor = DCMotor( name="right_wheel", pin_a=3, pin_b=4, enable=5, driver=driver, ) ``` ### Parameters - `driver`: An instance of the `L298N` driver. - `name`: A string identifier for the motor. - `pin_a`, `pin_b`: GPIO pins for motor direction control. - `enable`: GPIO pin for motor speed control (PWM). ``` -------------------------------- ### Local Documentation Build Commands Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/contributing/documentation.md Commands to install dependencies, serve documentation locally, and build the static site. ```bash # Install MkDocs pip install mkdocs mkdocs-material mkdocstrings[python] # Serve locally mkdocs serve # Build static site mkdocs build ``` -------------------------------- ### Install robo-infra for NVIDIA Jetson Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install the robo-infra platform-specific bundle for NVIDIA Jetson. ```bash pip install robo-infra[jetson] ``` -------------------------------- ### Complete Vision Pipeline Setup Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/vision.md Initializes necessary components for a vision pipeline, including camera calibration loading and creating color and marker detectors. This is a setup snippet. ```python from robo_infra.sensors.camera import USBCamera from robo_infra.vision.color import ColorDetector from robo_infra.vision.markers import ArUcoDetector from robo_infra.vision.calibration import CameraIntrinsics from robo_infra.controllers import PanTilt import time # Load camera calibration intrinsics = CameraIntrinsics.load("camera_calibration.json") # Create detectors color_detector = ColorDetector.red() marker_detector = ArUcoDetector(dictionary="DICT_4X4_50") ``` -------------------------------- ### Install robo-infra with Intel RealSense Support Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install the robo-infra extra for Intel RealSense camera support. ```bash pip install robo-infra[realsense] ``` -------------------------------- ### Install Full robo-infra Package Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install all features of the robo-infra SDK, including core, AI, API, and hardware support. ```bash pip install robo-infra[full] ``` -------------------------------- ### Install robo-infra with SPI Support Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install the robo-infra extra for SPI device support. ```bash pip install robo-infra[spi] ``` -------------------------------- ### Install libgpiod on Debian/Ubuntu Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/platforms.md Install the necessary packages to use libgpiod on Debian-based Linux distributions. ```bash sudo apt-get install gpiod libgpiod-dev python3-libgpiod ``` -------------------------------- ### Install robo-infra with Luxonis OAK Support Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install the robo-infra extra for Luxonis OAK camera support. ```bash pip install robo-infra[oak] ``` -------------------------------- ### Full Servo Control Example Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/actuators.md A complete example showing integration with a PCA9685 PWM driver and asynchronous sweep motion. ```python from robo_infra.actuators import Servo from robo_infra.drivers import PCA9685Driver # Initialize PWM driver driver = PCA9685Driver(i2c_address=0x40) driver.connect() driver.enable() # Create servo on channel 0 servo = Servo( name="pan", driver=driver, channel=0, angle_range=(0, 180), ) # Control the servo servo.enable() servo.set(90) # Center position # Sweep motion import asyncio asyncio.run(servo.sweep(0, 180, speed=60)) # Clean up servo.disable() driver.disconnect() ``` -------------------------------- ### Link Documentation Files Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/contributing/documentation.md Examples of internal, external, and anchor linking. ```markdown See [Actuators](actuators.md) for more details. See [API Reference](reference/api.md) for the full API. ``` ```markdown See the [ROS2 documentation](https://docs.ros.org/) for more. ``` ```markdown See [Circuit Breaker](utils.md#circuit-breaker) for details. ``` -------------------------------- ### Install robo-infra via pip Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/getting-started.md Standard installation using pip, with options for hardware support or all dependencies. ```bash # Core package only pip install robo-infra # With hardware support pip install robo-infra[hardware] # With all optional dependencies pip install robo-infra[all] ``` -------------------------------- ### Install Robo Infra Platform-Specific Bundles Source: https://context7.com/nfraxlab/robo-infra/llms.txt Install platform-specific bundles for Raspberry Pi or NVIDIA Jetson. ```bash pip install robo-infra[raspberry-pi] ``` ```bash pip install robo-infra[jetson] ``` -------------------------------- ### Install robo-infra with AI Integration Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install robo-infra with AI integration for LLM-controlled robots using the ai-infra library. ```bash pip install robo-infra[ai] ``` -------------------------------- ### Install Raspberry Pi OS Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/hardware-setup.md Use Raspberry Pi Imager to install Raspberry Pi OS (64-bit recommended). Ensure SSH is enabled and configure hostname and WiFi. ```bash # Using Raspberry Pi Imager # Select: Raspberry Pi OS (64-bit) # Enable SSH, set hostname, configure WiFi ``` -------------------------------- ### Install lgpio for Raspberry Pi Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/platforms.md Install the lgpio library to resolve RPi.GPIO compatibility issues on Pi 5. ```bash pip install lgpio ``` -------------------------------- ### Install robo-infra with Hardware Support Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install robo-infra with support for real hardware buses like I2C, SPI, Serial, and CAN. ```bash pip install robo-infra[hardware] ``` -------------------------------- ### Install Robo Infra with Vision Support Source: https://context7.com/nfraxlab/robo-infra/llms.txt Install robo-infra with optional vision and camera support, including RealSense integration. ```bash pip install robo-infra[vision] ``` ```bash pip install robo-infra[realsense] ``` -------------------------------- ### Install robo-infra with API Integration Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install robo-infra with API integration for REST/WebSocket APIs using the svc-infra library. ```bash pip install robo-infra[api] ``` -------------------------------- ### Run Basic Rover Control Example Source: https://github.com/nfraxlab/robo-infra/blob/main/examples/rover/README.md Execute the script for basic differential drive rover control. ```bash python rover.py ``` -------------------------------- ### Install robo-infra with Raspberry Pi Camera Support Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install the robo-infra extra for Raspberry Pi camera support. ```bash pip install robo-infra[picamera] ``` -------------------------------- ### Run Rover with Sensors Example Source: https://github.com/nfraxlab/robo-infra/blob/main/examples/rover/README.md Execute the script for rover control with ultrasonic sensors for obstacle avoidance. ```bash python rover_with_sensors.py ``` -------------------------------- ### Setup Hardware with I2C Bus Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/getting-started.md Initialize a driver using a platform-specific I2C bus instance. ```python from robo_infra.platforms import get_i2c, get_gpio from robo_infra.drivers import PCA9685Driver from robo_infra.actuators import Servo # Get platform-appropriate I2C bus i2c = get_i2c(bus=1) # Initialize the PWM driver driver = PCA9685Driver( i2c_bus=i2c, address=0x40, frequency=50, ) # Create servo attached to the driver servo = Servo( name="shoulder", driver=driver, channel=0, ) # Move the servo await servo.move_to(90) ``` -------------------------------- ### Hexapod Initialization Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/controllers.md Setup for hexapod robots using either simulation or manual configuration. ```python from robo_infra.controllers import Hexapod, HexapodConfig, GaitType from robo_infra.controllers import create_hexapod # Create simulated hexapod hexapod = create_hexapod(name="spider", simulated=True) # Or configure manually config = HexapodConfig( name="hexapod", leg_length=0.15, # 150mm legs body_radius=0.1, # 100mm body radius default_height=0.08, # 80mm standing height ) ``` -------------------------------- ### Gripper Actions Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/ros2-integration.md This example demonstrates implementing a ROS2 action server for gripper commands using the `GripperCommand` action type. ```APIDOC ### Gripper Actions ```python from control_msgs.action import GripperCommand class GripperActionNode: def __init__(self, node, gripper): self._gripper = gripper self._action_server = ActionServer( node, GripperCommand, "/gripper/gripper_command", self._execute_gripper, ) async def _execute_gripper(self, goal_handle): command = goal_handle.request.command target_position = command.position max_effort = command.max_effort await self._gripper.move_to( position=target_position, force_limit=max_effort, ) result = GripperCommand.Result() result.position = self._gripper.current_position result.stalled = self._gripper.is_stalled result.reached_goal = abs( self._gripper.current_position - target_position ) < 0.01 goal_handle.succeed() return result ``` ``` -------------------------------- ### Complete Example with Servo and Encoder Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/quickstart.md A comprehensive example demonstrating the integration of a Servo with safety limits and an Encoder for feedback. It includes a main function to move the servo and read sensor data. ```python import asyncio from robo_infra.actuators import Servo from robo_infra.sensors import Encoder from robo_infra.core.types import Limits from robo_infra.safety import SafetyMonitor # Create servo with safety limits servo = Servo( name="arm", channel=0, limits=Limits(min_value=0, max_value=180), speed_limit=90.0, ) # Create encoder for feedback encoder = Encoder(name="arm_encoder", channel=0) # Setup safety monitoring monitor = SafetyMonitor() monitor.add_device(servo) async def main(): # Move to positions for target in [45, 90, 135, 90, 45, 0]: await servo.move_to(target) print(f"Servo: {servo.position}, Encoder: {encoder.read()}") await asyncio.sleep(0.5) asyncio.run(main()) ``` -------------------------------- ### Install Udev Rules Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/troubleshooting.md Creates and applies udev rules to grant group-based access to GPIO and I2C devices. ```bash # Create udev rule for GPIO echo 'SUBSYSTEM=="gpio", KERNEL=="gpiochip*", GROUP="gpio", MODE="0660"' | \ sudo tee /etc/udev/rules.d/99-gpio.rules # Create udev rule for I2C echo 'SUBSYSTEM=="i2c-dev", GROUP="i2c", MODE="0660"' | \ sudo tee /etc/udev/rules.d/99-i2c.rules # Reload udev rules sudo udevadm control --reload-rules sudo udevadm trigger ``` -------------------------------- ### PanTilt Controller Setup and Methods Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/controllers.md Configures a two-axis camera head and provides methods for positioning, tracking, and scanning. ```python from robo_infra.controllers import PanTilt, PanTiltConfig from robo_infra.actuators import Servo # Create servos pan_servo = Servo(name="pan", channel=0, angle_range=(-90, 90)) tilt_servo = Servo(name="tilt", channel=1, angle_range=(-45, 45)) # Create controller config = PanTiltConfig( name="camera_head", pan_range=(-90, 90), tilt_range=(-45, 45), center_pan=0, center_tilt=0, pan_speed=60, # deg/s tilt_speed=45, # deg/s image_width=640, # For tracking image_height=480, fov_horizontal=60, # Camera FOV fov_vertical=45, ) pt = PanTilt( name="camera_head", pan_actuator=pan_servo, tilt_actuator=tilt_servo, config=config, ) ``` ```python pt.enable() # Direct positioning pt.look_at(pan=45.0, tilt=30.0) pt.center() pt.pan_to(90.0) pt.tilt_to(-30.0) # Relative movement pt.pan_by(10.0) # Pan right 10° pt.tilt_by(-5.0) # Tilt down 5° # Track pixel coordinates pt.track((320, 240)) # Track center of image pt.track_object(bbox=(100, 100, 200, 200)) # Track bounding box center # Scanning pattern await pt.scan( pan_start=-45, pan_end=45, tilt_start=-20, tilt_end=20, step=10, dwell=0.5, # Pause at each position ) pt.disable() ``` -------------------------------- ### Quadcopter Initialization Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/controllers.md Configuration and motor setup for quadcopter flight controllers. ```python from robo_infra.controllers import Quadcopter, QuadcopterConfig, FlightMode from robo_infra.actuators import Brushless # Create motors (FL, FR, RL, RR) motors = [Brushless(name=f"motor_{i}", channel=i) for i in range(4)] # Create controller config = QuadcopterConfig( name="drone", arm_length=0.25, # 250mm arm length frame_type="X", # X, +, or H configuration motor_kv=2300, prop_diameter=5.0, # 5-inch props max_tilt_angle=35.0, # Max tilt in degrees ) quad = Quadcopter(name="my_drone", motors=motors, config=config) ``` -------------------------------- ### Leg Controller Setup and Methods Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/controllers.md Configures a 3-DOF robotic leg and provides methods for inverse kinematics and positioning. ```python from robo_infra.controllers import Leg, LegConfig from robo_infra.actuators import Servo # 3-DOF leg (coxa, femur, tibia) joints = { "coxa": Servo(name="coxa", channel=0, angle_range=(-45, 45)), "femur": Servo(name="femur", channel=1, angle_range=(0, 90)), "tibia": Servo(name="tibia", channel=2, angle_range=(0, 135)), } config = LegConfig( name="front_left", coxa_length=0.03, # 30mm femur_length=0.08, # 80mm tibia_length=0.12, # 120mm ) leg = Leg(name="front_left", joints=joints, config=config) ``` ```python leg.enable() # Inverse kinematics - move foot to position leg.move_to(x=0.1, y=0.0, z=-0.1) # 10cm forward, 10cm down # Forward kinematics - get current foot position position = leg.get_foot_position() print(f"Foot at: ({position.x}, {position.y}, {position.z})") # Home position leg.home() leg.disable() ``` -------------------------------- ### Initialize Platform and GPIO Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/troubleshooting.md Demonstrates how to initialize a specific hardware platform and perform basic GPIO operations. ```python from robo_infra.platforms import ( RaspberryPiPlatform, JetsonPlatform, LinuxGenericPlatform, ) # Use specific platform in simulation platform = LinuxGenericPlatform(simulation=True) gpio = platform.get_gpio(17) gpio.set_mode("output") gpio.write(True) # Simulated write ``` -------------------------------- ### Initialize CANopen Master Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/protocols.md Setup the CAN bus interface and instantiate the CANopen master to scan and retrieve nodes. ```python from robo_infra.core.can_bus import get_can from robo_infra.protocols.canopen import CANOpenMaster # Create CAN bus can = get_can("socketcan", "can0", bitrate=500000) can.open() # Create CANopen master master = CANOpenMaster(can) # Scan for nodes nodes = master.scan_nodes() print(f"Found nodes: {nodes}") # Get specific node node = master.get_node(1) # Clean up can.close() ``` -------------------------------- ### Prepare for Async API Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/migration.md Demonstrates the transition from synchronous to asynchronous hardware I/O methods. ```python # 0.1.x (sync) servo.set(90) # 0.2.x (planned - async for hardware I/O) await servo.set(90) ``` -------------------------------- ### Quick Start: Robot Control with AI Agent Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/ai-integration.md Demonstrates setting up a simulated robot controller and actuators, converting them to AI tools, and using an ai-infra Agent to send commands. ```python from robo_infra.core.controller import SimulatedController from robo_infra.core.actuator import SimulatedActuator from robo_infra.core.types import Limits from robo_infra.integrations.ai_infra import controller_to_tools from ai_infra import Agent # Create a controller with actuators controller = SimulatedController(name="arm") controller.add_actuator( "shoulder", SimulatedActuator( name="shoulder", limits=Limits(min=0, max=180, default=90), unit="degrees", ), ) controller.enable() controller.home() # Convert to AI function tools tools = controller_to_tools(controller) # Use with ai-infra Agent agent = Agent(tools=tools) result = agent.run("Move the shoulder to 45 degrees") print(result) # "Moved shoulder to 45.0 degrees" ``` -------------------------------- ### Linear Interpolation Trajectory Example Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/motion.md Illustrates creating and sampling a linear trajectory, which defines constant-velocity motion between a start and end point over a specified duration. ```python from robo_infra.motion.trajectory import LinearInterpolator # Move from 0 to 100 in 2 seconds traj = LinearInterpolator(start=0.0, end=100.0, duration=2.0) # Sample at t=1.0 point = traj.sample(1.0) print(f"Position: {point.position}") # 50.0 print(f"Velocity: {point.velocity}") # 50.0 (constant) ``` -------------------------------- ### Initialize Gripper with Real Hardware Source: https://github.com/nfraxlab/robo-infra/blob/main/examples/gripper/README.md Connect a servo to a PWM driver and create a Gripper controller. Ensure the driver and gripper are enabled before use. ```python from robo_infra.actuators import Servo from robo_infra.controllers import Gripper, GripperConfig from robo_infra.drivers import PCA9685 # Create PWM driver driver = PCA9685() driver.connect() driver.enable() # Create servo on channel 0 servo = Servo( name="gripper_servo", driver=driver, channel=0, angle_range=(0, 90), ) # Create gripper controller config = GripperConfig( name="parallel_gripper", open_position=0, closed_position=90, default_speed=1.0, ) gripper = Gripper(name="gripper", actuator=servo, config=config) gripper.enable() # Control gripper.open() # Open fully gripper.close() # Close fully gripper.set(45) # Move to 50% (45 degrees) ``` -------------------------------- ### Initialize Controller and FastAPI Router Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/api-integration.md Sets up a simulated controller with actuators and exposes it as a FastAPI router. ```python from fastapi import FastAPI from robo_infra.core.controller import SimulatedController from robo_infra.core.actuator import SimulatedActuator from robo_infra.core.types import Limits from robo_infra.integrations.svc_infra import controller_to_router # Create a controller with actuators controller = SimulatedController(name="arm") controller.add_actuator( "shoulder", SimulatedActuator( name="shoulder", limits=Limits(min=0, max=180, default=90), unit="degrees", ), ) # Create FastAPI app and add robot router app = FastAPI() router = controller_to_router(controller, prefix="/arm", auth_required=False) app.include_router(router) ``` -------------------------------- ### Install robo-infra Python Package Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/hardware-setup.md Install robo-infra with hardware support using pip. This includes installing Python 3.11+ and creating a virtual environment. Alternatively, install from source for the latest features. ```bash # Install Python 3.11+ sudo apt-get install -y python3-pip python3-venv # Create virtual environment python3 -m venv ~/robo-env source ~/robo-env/bin/activate # Install robo-infra with hardware support pip install robo-infra[hardware] # Or from source for latest features git clone https://github.com/nfraxlab/robo-infra.git cd robo-infra pip install -e ".[hardware]" ``` -------------------------------- ### Show Help and Programmatic Usage Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/cli.md Display available commands or use the Python API for hardware control. ```bash $ robo-infra help robo-infra - Universal Robotics Infrastructure Commands: robo-infra version - Show version robo-infra help - Show this help message robo-infra info - Show system information robo-infra list drivers - List available drivers robo-infra list platforms - List supported platforms robo-infra discover - Discover connected hardware robo-infra test - Run hardware tests robo-infra simulate - Run in simulation mode For programmatic use, import robo_infra in Python: from robo_infra import Servo, DCMotor, JointGroup servo = Servo(channel=0) servo.angle = 90 ``` -------------------------------- ### Install robo-infra with Observability Support Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/observability.md Install robo-infra with observability support using pip. For full integration with svc-infra, install both packages. ```bash pip install robo-infra[observability] ``` ```bash pip install robo-infra svc-infra[metrics,health] ``` -------------------------------- ### Initialize and Configure PID Controller Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/motion.md Demonstrates initializing a basic PID controller and configuring it with specific limits for output, integral terms, and derivative filtering. ```python from robo_infra.motion.pid import PID, PIDConfig # Basic PID pid = PID(kp=2.0, ki=0.5, kd=0.1) # Configure with limits config = PIDConfig( kp=2.0, ki=0.5, kd=0.1, output_min=-100, output_max=100, integral_min=-10, integral_max=10, derivative_filter=0.1, sample_time=0.01, ) pid = PID(config=config) ``` -------------------------------- ### Install robo-infra with CAN Bus Support Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install the robo-infra extra for CAN bus support. ```bash pip install robo-infra[can] ``` -------------------------------- ### Install robo-infra with Serial/UART Support Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install the robo-infra extra for Serial/UART communication. ```bash pip install robo-infra[serial] ``` -------------------------------- ### Robo-Infra Development Workflow Example Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/cli.md A sequence of commands demonstrating a typical development workflow with robo-infra. It includes checking the system, running in simulation mode, and switching to real hardware. ```bash # 1. Check system robo-infra info # 2. Start in simulation mode export ROBO_SIMULATION=true # 3. Run your robot code python my_robot.py # 4. Switch to real hardware unset ROBO_SIMULATION python my_robot.py ``` -------------------------------- ### Install robo-infra with ROS2 dependencies Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/ros2-integration.md Install the robo-infra package with optional ROS2 dependencies using pip. Alternatively, manually install required ROS2 packages like rclpy and message types. ```bash pip install robo-infra[ros2] ``` -------------------------------- ### Setup Self-Hosted GitHub Actions Runner Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/hardware-testing.md Commands to create a dedicated user, download the runner, and configure it as a system service on a Raspberry Pi. ```bash # Create a dedicated user sudo useradd -m -G gpio,i2c,spi github-runner sudo passwd github-runner # Switch to runner user sudo su - github-runner # Download latest runner mkdir actions-runner && cd actions-runner curl -o actions-runner-linux-arm64-2.311.0.tar.gz -L \ https://github.com/actions/runner/releases/download/v2.311.0/actions-runner-linux-arm64-2.311.0.tar.gz tar xzf ./actions-runner-linux-arm64-2.311.0.tar.gz # Configure runner (get token from GitHub repo settings) ./config.sh --url https://github.com/YOUR_ORG/robo-infra \ --token YOUR_RUNNER_TOKEN \ --labels raspberry-pi,hardware-tests # Install as service sudo ./svc.sh install sudo ./svc.sh start ``` -------------------------------- ### List Hardware Platforms Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/cli.md List all supported hardware platforms. ```bash $ robo-infra list platforms Supported Platforms: ------------------------------ - arduino - beaglebone - esp32 - jetson - linux_generic - raspberry_pi Total: 6 platforms ``` -------------------------------- ### Install robo-infra with I2C Support Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install the robo-infra extra for I2C sensor support. ```bash pip install robo-infra[i2c] ``` -------------------------------- ### Install robo-infra for Raspberry Pi Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install the robo-infra platform-specific bundle for Raspberry Pi. ```bash pip install robo-infra[raspberry-pi] ``` -------------------------------- ### Install robo-infra with OpenCV Support Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install the robo-infra extra for OpenCV integration for vision processing. ```bash pip install robo-infra[vision] ``` -------------------------------- ### Starting the Safety Monitor Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/safety.md Starts the monitoring thread and updates metrics within a control loop. ```python # Start monitoring thread monitor.start() try: while running: # Control loop motor_current = current_sensor.read() motor_temp = temp_sensor.read() monitor.update("motor1", "current", motor_current) monitor.update("motor1", "temperature", motor_temp) time.sleep(0.01) finally: monitor.stop() ``` -------------------------------- ### Implement Complete Power Distribution Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/power.md Sets up a full power distribution board with E-stop integration, current monitoring, and safety callbacks. This example demonstrates a robust system for managing multiple power rails. ```python from robo_infra.power import ( BatteryMonitor, BatteryChemistry, PowerRail, PowerDistributionBoard, ShutdownPriority, ) from robo_infra.power.drivers import INA219Driver from robo_infra.safety import EStop import time # Create E-stop estop = EStop() # Create battery monitor battery = BatteryMonitor( cells=4, chemistry=BatteryChemistry.LIPO, capacity_mah=5000, low_voltage_threshold=3.4, critical_voltage_threshold=3.2, ) # Create power rails with current monitoring motor_monitor = INA219Driver(address=0x40, shunt_ohms=0.01) sensor_monitor = INA219Driver(address=0x41, shunt_ohms=0.1) rails = [ PowerRail("safety", enable_pin=4, priority=ShutdownPriority.CRITICAL), PowerRail("motors", enable_pin=17, priority=ShutdownPriority.LOW, current_monitor=motor_monitor, max_current=20.0), PowerRail("sensors", enable_pin=27, priority=ShutdownPriority.NORMAL, current_monitor=sensor_monitor, max_current=2.0), ] pdb = PowerDistributionBoard(rails) # Register E-stop for emergency shutdown estop.register_actuator(pdb) # Callbacks def on_low_battery(status): print(f"Low battery: {status.percentage:.0f}%") # Reduce motor power pdb.set_power_limit("motors", 0.5) def on_critical_battery(status): print("Critical battery!") estop.trigger("Critical battery level") battery.on_low_battery = on_low_battery battery.on_critical_battery = on_critical_battery # Start systems battery.enable() pdb.enable_all() try: while True: # Monitor battery print(f"Battery: {battery.voltage:.1f}V ({battery.percentage:.0f}%)") # Monitor power rails for rail in pdb.rails: reading = pdb.get_reading(rail.name) if reading.current: print(f" {rail.name}: {reading.current:.2f}A") # Overcurrent protection if rail.max_current and reading.current > rail.max_current: print(f" OVERCURRENT on {rail.name}!") pdb.disable(rail.name) time.sleep(1.0) except KeyboardInterrupt: pass finally: pdb.disable_all() battery.disable() ``` -------------------------------- ### Writing Style Examples Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/contributing/documentation.md Examples of preferred active voice versus passive voice in documentation. ```markdown # [OK] Good You can create a servo using the Servo class. # [X] Bad A servo can be created by the user using the Servo class. ``` -------------------------------- ### Configure Raspberry Pi Platform Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/platforms.md Initialize Raspberry Pi support with specific backends like LGPIO or RPI_GPIO. ```python from robo_infra.platforms import RaspberryPiPlatform, GPIOBackend # Auto-detect backend (RPi.GPIO, lgpio, gpiod, pigpio) pi = RaspberryPiPlatform() # Force specific backend pi = RaspberryPiPlatform(backend=GPIOBackend.LGPIO) # Get platform info info = pi.get_info() print(f"Model: {info.model}") print(f"Revision: {info.revision}") print(f"Is Pi 5: {pi.is_pi5}") ``` -------------------------------- ### Run Basic Lock Control Example Source: https://github.com/nfraxlab/robo-infra/blob/main/examples/lock/README.md Execute the Python script to demonstrate basic lock operations, including creating a servo actuator, building a Lock controller, and performing lock/unlock actions. ```bash python lock.py ``` -------------------------------- ### Install robo-infra Core Source: https://github.com/nfraxlab/robo-infra/blob/main/README.md Install the core robo-infra package for embedded systems or when only robotics abstractions are needed. ```bash pip install robo-infra ``` -------------------------------- ### Full Controller Example Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/core-concepts.md Demonstrates creating, enabling, homing, and moving a JointGroup controller. Includes adding named positions and running predefined sequences. ```python from robo_infra.controllers import JointGroup from robo_infra.actuators import Servo from robo_infra.safety import EStop # Create actuators joints = [ Servo(name="base", channel=0, angle_range=(0, 180)), Servo(name="shoulder", channel=1, angle_range=(0, 180)), Servo(name="elbow", channel=2, angle_range=(0, 180)), ] # Create controller arm = JointGroup(joints) # Enable and home arm.enable_all() await arm.home() # Move to named position arm.add_position("ready", {"base": 90, "shoulder": 45, "elbow": 90}) await arm.move_to_position("ready") # Execute a sequence arm.add_sequence("pick_up", [ {"base": 90, "shoulder": 90, "elbow": 45}, # Extend {"base": 90, "shoulder": 120, "elbow": 30}, # Lower # ... gripper close {"base": 90, "shoulder": 45, "elbow": 90}, # Retract ]) await arm.run_sequence("pick_up") ``` -------------------------------- ### Basic Sensor Usage Example Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/sensors.md Demonstrates the fundamental lifecycle of enabling, reading, and disabling a sensor. Ensure the sensor is enabled before reading and disabled when not in use. ```python from robo_infra.sensors import Ultrasonic # Create sensor sensor = Ultrasonic(trigger_pin=trig, echo_pin=echo, name="front") # Enable before use sensor.enable() # Read sensor data reading = sensor.read() print(f"Distance: {reading.value} {reading.unit}") # Disable when done sensor.disable() ``` -------------------------------- ### List Available Hardware Source: https://github.com/nfraxlab/robo-infra/blob/main/docs/getting-started.md Discover available GPIO, I2C, and SPI resources on the current platform. ```python from robo_infra.platforms import ( list_available_gpio, list_available_i2c, list_available_spi, ) # Discover what's available on this platform print(f"GPIO chips: {list_available_gpio()}") print(f"I2C buses: {list_available_i2c()}") print(f"SPI buses: {list_available_spi()}") ```