# rpi-power-hat Examples

This directory contains practical example scripts that demonstrate common use cases for the rpi-power-hat tool. These scripts provide robust, real-world implementations for device management, testing, and monitoring workflows.

## Quick Start

All scripts should be run from the repository root directory:

```bash
cd rpi-power-hat
./examples/SCRIPT_NAME <arguments>
```

## Example Scripts

### 🚀 `provision` - Complete Device Provisioning

**Purpose:** Fully provision a Raspberry Pi device from scratch with robust error handling.

**Usage:**
```bash
./examples/provision <PORT> <DEVICE>
```

**Parameters:**
- `PORT`: Target port (B1, B2, T1, T2)  
- `DEVICE`: Device model (5, 4, zero2w, etc.)

**What it does:**
1. Boots device into mass-storage mode
2. Downloads and flashes the latest Raspberry Pi OS image
3. Configures SSH keys and network settings
4. Power cycles the device
5. Waits for boot completion (120s)
6. Automatically connects via SSH for verification

**Example:**
```bash
./examples/provision B1 5    # Provision Pi 5 on port B1
./examples/provision T2 4    # Provision Pi 4 on port T2
```

---

### 🔌 `shutdown` - Safe Device Shutdown

**Purpose:** Safely shutdown a device with current monitoring to ensure complete power-down.

**Usage:**
```bash
./examples/shutdown <PORT> <DEVICE>
```

**Parameters:**
- `PORT`: Target port (B1, B2, T1, T2)
- `DEVICE`: Device model for current threshold detection

**What it does:**
1. Sends SSH shutdown command to the device
2. Monitors power consumption in real-time
3. Waits for current to drop below shutdown threshold
4. Cuts power once shutdown is confirmed
5. Includes 60-second timeout for safety

**Features:**
- Hardware-specific current thresholds
- Real-time current monitoring
- Graceful fallback to force power-off
- Handles already-powered-off devices

**Example:**
```bash
./examples/shutdown B1 5     # Safely shutdown Pi 5 on port B1
./examples/shutdown T1 4     # Safely shutdown Pi 4 on port T1
```

---

### ⏱️ `get-boottime` - Boot Performance Analysis

**Purpose:** Measure detailed boot performance metrics including bootloader and userspace timing.

**Usage:**
```bash
./examples/get-boottime <PORT> <DEVICE>
```

**Parameters:**
- `PORT`: Target port (B1, B2, T1, T2)
- `DEVICE`: Device model for proper shutdown

**What it does:**
1. Safely shuts down the target device
2. Power cycles and monitors boot process
3. Waits for SSH connectivity (up to 120s)
4. Collects comprehensive boot timing data:
   - **Bootloader time**: Time spent in bootloader/firmware
   - **Userspace time**: Time from kernel to first GUI draw
   - **Panel first draw**: Desktop environment ready time
   - **Memory information**: System memory details

**Metrics collected:**
- Bootloader execution time
- Kernel initialization time  
- Userspace boot time
- First desktop draw time
- Memory usage statistics

**Example:**
```bash
./examples/get-boottime B1 5    # Analyze Pi 5 boot performance
```

**Sample output:**
```
Userspace time: 12.34 | Bootloader time: 3.45 | Panel first draw time: 15.67
=== MEMINFO START ===
MemTotal:        8123456 kB
MemFree:         7234567 kB
...
=== MEMINFO END ===
```

---

### 📊 `plot-bootup` - Visual Boot Analysis

**Purpose:** Generate visual plots of power consumption and current draw during device boot.

**Usage:**
```bash
./examples/plot-bootup <PORT> <DEVICE> [DURATION]
```

**Parameters:**
- `PORT`: Target port (B1, B2, T1, T2)
- `DEVICE`: Device model for shutdown
- `DURATION`: Optional monitoring duration in seconds (default: 120)

**What it does:**
1. Safely shuts down the target device
2. Starts parallel current and power logging
3. Powers on the device
4. Logs power metrics during boot process
5. Generates PNG plot using gnuplot

**Output:**
- CSV files with raw measurement data
- PNG graph: `./examples/bootup_<PORT>.png`
- Dual-axis plot showing current (mA) and power (mW) over time

**Requirements:**
- `gnuplot` package for visualization
- Install with: `sudo apt install gnuplot`

**Example:**
```bash
./examples/plot-bootup B1 5 60    # 60-second boot plot for Pi 5
./examples/plot-bootup T2 4       # Default 120s plot for Pi 4
```

**Generated files:**
- `/var/lib/rpi-power-hat/measurements/current_B1_*.csv`
- `/var/lib/rpi-power-hat/measurements/power_B1_*.csv`
- `./examples/bootup_B1.png`

---

## Sample Visualizations

The repository includes sample boot analysis plots:

- **`bootup_B2.png`**: Boot current profile for port B2
- **`bootup_T1.png`**: Boot current profile for port T1

These demonstrate typical power consumption patterns during Raspberry Pi boot sequences.

## Prerequisites

### Required packages:
- `rpi-power-hat` tool installed and configured
- `bc` calculator for timing calculations
- `gnuplot` for visualization (plot-bootup only)

### Hardware requirements:
- rpi-power-hat board properly connected
- Target Raspberry Pi devices connected to specified ports
- Network connectivity for image downloads and SSH access

### Configuration:
- SSH keys configured via `rpi-power-hat flash-image`
- Network settings configured in `/etc/rpi-power-hat/network.conf`
- Port mappings defined in `/etc/rpi-power-hat/ports.conf`

## Common Workflows

### Full Device Testing Pipeline:
```bash
# 1. Provision a fresh device
./examples/provision B1 5

# 2. Run boot performance analysis  
./examples/get-boottime B1 5

# 3. Generate boot visualization
./examples/plot-bootup B1 5 90

# 4. Safely shutdown when done
./examples/shutdown B1 5
```

### Automated Testing Loop:
```bash
# Test multiple boot cycles
for i in {1..5}; do
    echo "Boot test cycle $i"
    ./examples/get-boottime B1 5
    sleep 10
done
```

## Troubleshooting

**SSH connection fails:**
- Verify network configuration in `network.conf`
- Check SSH key setup with `rpi-power-hat ssh <PORT>`
- Ensure device has fully booted (wait longer)

**Power monitoring issues:**
- Verify hardware connections
- Check device model matches actual hardware
- Ensure proper permissions for hardware access

**Plotting fails:**
- Install gnuplot: `sudo apt install gnuplot`
- Check CSV file permissions in `/var/lib/rpi-power-hat/measurements/`
- Verify sufficient disk space for output files

## Advanced Usage

### Custom timing analysis:
Modify the boot timing collection in `get-boottime` to add custom systemd service timing or application-specific metrics.

### Extended monitoring:
Adjust the duration parameter in `plot-bootup` for longer-term power analysis or specific use cases.

### Multi-device testing:
Run examples in parallel across multiple ports for comparative analysis:

```bash
./examples/provision B1 5 &
./examples/provision B2 4 &
wait
```

## Contributing

When adding new examples:
1. Follow the existing naming convention
2. Include proper error handling and timeouts
3. Add comprehensive usage documentation
4. Test with multiple device types
5. Update this README with the new example

---

For more information about the rpi-power-hat tool itself, see the main [README.md](../readme.md) in the repository root.