# 🔧 ESP32-P4 Network Auditing Tool - Debug Configuration Guide

## 📋 **DEBUGGING FEATURES IMPLEMENTED**

Based on the web research from [QMK Debugging FAQ](https://docs.qmk.fm/faq_debug) and [C Debugging Tips](https://www.cs.swarthmore.edu/~newhall/unixhelp/debuggingtips_C.php), the following comprehensive debugging features have been implemented:

### **1. Enhanced Debug Output System**

```c
// Debug configuration
static bool s_debug_enabled = false;
static bool s_debug_matrix_enabled = false;

// Debug print function (only when debug is enabled)
static void debug_print(const char* format, ...) {
    if (!s_debug_enabled) {
        return;
    }
    // Implementation with ESP-IDF logging
}
```

### **2. Network Event Debugging**

```c
// Ethernet event handler with enhanced debugging
static void ethernet_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
    debug_print("Ethernet event: %ld", event_id);
    // Detailed event logging
}
```

### **3. Matrix Scanning Debug (Inspired by QMK)**

```c
// Monitor Ethernet interface status with enhanced debugging
void network_manager_monitor_ethernet(void) {
    bool previous_link_state = ethernet_stats.link_up;
    ethernet_stats.link_up = esp_netif_is_netif_up(ethernet_netif);
    
    // Debug output for link state changes
    if (s_debug_matrix_enabled && previous_link_state != ethernet_stats.link_up) {
        debug_print("Ethernet link state changed: %s -> %s", 
                   previous_link_state ? "UP" : "DOWN",
                   ethernet_stats.link_up ? "UP" : "DOWN");
    }
}
```

### **4. System Monitoring Tasks**

```c
// System monitoring task with enhanced debugging
static void system_monitor_task(void *pvParameters) {
    while (1) {
        // Update network statistics
        network_manager_update_stats();
        
        // Monitor system health with debug output
        if (s_debug_enabled) {
            ESP_LOGD(TAG, "Ethernet: link=%s, rx_pkts=%lu, tx_pkts=%lu", 
                     eth_stats.link_up ? "UP" : "DOWN", 
                     eth_stats.rx_packets, eth_stats.tx_packets);
        }
        
        vTaskDelay(pdMS_TO_TICKS(5000));
    }
}
```

### **5. Debug Information Task**

```c
// Debug information task (inspired by QMK debug examples)
static void debug_info_task(void *pvParameters) {
    while (1) {
        if (s_debug_enabled) {
            ESP_LOGI(TAG, "=== System Debug Information ===");
            ESP_LOGI(TAG, "Free heap: %lu bytes", esp_get_free_heap_size());
            ESP_LOGI(TAG, "Uptime: %lld seconds", esp_timer_get_time() / 1000000);
            
            // Print network status with detailed statistics
            ESP_LOGI(TAG, "Ethernet: link=%s, rx_pkts=%lu, tx_pkts=%lu, rx_err=%lu, tx_err=%lu", 
                     eth_stats.link_up ? "UP" : "DOWN", 
                     eth_stats.rx_packets, eth_stats.tx_packets,
                     eth_stats.rx_errors, eth_stats.tx_errors);
        }
        
        vTaskDelay(pdMS_TO_TICKS(30000));
    }
}
```

## 🛠️ **DEBUGGING TOOLS INTEGRATION**

### **1. ESP-IDF Error Handling (Based on ESP-IDF Documentation)**

```c
// Enhanced error handling with detailed error messages
esp_err_t network_manager_init_ethernet(void) {
    esp_err_t ret = ESP_OK;
    
    // Create network event group if not exists
    if (network_event_group == NULL) {
        network_event_group = xEventGroupCreate();
        if (network_event_group == NULL) {
            ESP_LOGE(TAG, "Failed to create network event group");
            return ESP_ERR_NO_MEM;
        }
        debug_print("Network event group created successfully");
    }
    
    // Detailed error reporting for each step
    ret = esp_eth_driver_install(&eth_config, &eth_handle);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Failed to install Ethernet driver: %s", esp_err_to_name(ret));
        return ret;
    }
    debug_print("Ethernet driver installed successfully");
}
```

### **2. Memory Management Debugging**

```c
// Enhanced memory allocation with error checking
esp_err_t log_manager_get_logs(char** logs, size_t* logs_size) {
    if (logs == NULL || logs_size == NULL) {
        return ESP_ERR_INVALID_ARG;
    }
    
    *logs = malloc(bytes_read + 1);
    if (*logs) {
        memcpy(*logs, buffer, bytes_read);
        (*logs)[bytes_read] = '\0';
        *logs_size = bytes_read;
    } else {
        ESP_LOGE(TAG, "Failed to allocate memory for logs");
        ret = ESP_ERR_NO_MEM;
    }
    return ret;
}
```

### **3. Network Statistics Debugging**

```c
// MAC address debugging with detailed output
esp_err_t network_manager_get_ethernet_mac(uint8_t *mac) {
    esp_err_t ret = esp_netif_get_mac(ethernet_netif, mac);
    if (ret == ESP_OK) {
        debug_print("Ethernet MAC: %02x:%02x:%02x:%02x:%02x:%02x",
                   mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    }
    return ret;
}
```

## 📊 **DEBUGGING CONFIGURATION OPTIONS**

### **1. Debug Levels**

| Level | Description | Usage |
|-------|-------------|-------|
| `s_debug_enabled` | General debug output | Network events, system status |
| `s_debug_matrix_enabled` | Matrix-style debugging | Link state changes, packet statistics |
| `ESP_LOG_DEBUG` | ESP-IDF debug level | Detailed component debugging |

### **2. Debug Functions**

```c
// Enable/disable debug output
esp_err_t network_manager_set_debug(bool enable);

// Enable/disable matrix debug output
esp_err_t network_manager_set_matrix_debug(bool enable);

// Debug print function (only when debug is enabled)
static void debug_print(const char* format, ...);
```

### **3. Debug Information Output**

The system provides comprehensive debug information including:

- **System Information**: Free heap, uptime, task status
- **Network Statistics**: Link status, packet counts, error rates
- **Event Logging**: All network events with timestamps
- **Memory Tracking**: Allocation/deallocation monitoring
- **Error Reporting**: Detailed error messages with context

## 🔍 **DEBUGGING TECHNIQUES APPLIED**

### **1. From QMK Debugging FAQ**
- **Matrix Scanning**: Applied to network interface monitoring
- **Event Logging**: Detailed event tracking with timestamps
- **State Change Detection**: Monitor link state changes
- **Performance Monitoring**: Track packet processing rates

### **2. From C Debugging Tips**
- **Memory Management**: Enhanced malloc/free error checking
- **Error Handling**: Comprehensive error reporting with context
- **System Monitoring**: Continuous health monitoring
- **Resource Tracking**: Monitor system resources

### **3. From ESP-IDF Error Handling**
- **Error Codes**: Use ESP-IDF error code system
- **Error Messages**: Convert error codes to readable messages
- **Assertions**: Use ESP_ERROR_CHECK for critical errors
- **Recovery**: Implement error recovery mechanisms

## 🚀 **USAGE INSTRUCTIONS**

### **1. Enable Debugging**

```c
// In your application initialization
network_manager_set_debug(true);
network_manager_set_matrix_debug(true);
```

### **2. Monitor Debug Output**

The system will output debug information to the console:

```
I (1234) NETWORK_MANAGER: Network manager debug enabled
I (1235) NETWORK_MANAGER: Starting Ethernet initialization sequence
D (1236) NETWORK_MANAGER: Network event group created successfully
D (1237) NETWORK_MANAGER: Ethernet netif created successfully
D (1238) NETWORK_MANAGER: MAC instance created successfully
D (1239) NETWORK_MANAGER: PHY instance created successfully
D (1240) NETWORK_MANAGER: Ethernet driver installed successfully
D (1241) NETWORK_MANAGER: Ethernet driver attached to netif successfully
D (1242) NETWORK_MANAGER: Ethernet event handler registered successfully
D (1243) NETWORK_MANAGER: IP event handler registered successfully
D (1244) NETWORK_MANAGER: Ethernet driver started successfully
I (1245) NETWORK_MANAGER: Ethernet interface initialized successfully
```

### **3. Monitor System Health**

```c
I (30000) MAIN: === System Debug Information ===
I (30001) MAIN: Free heap: 123456 bytes
I (30002) MAIN: Minimum free heap: 98765 bytes
I (30003) MAIN: Uptime: 30 seconds
I (30004) MAIN: Ethernet: link=UP, rx_pkts=1234, tx_pkts=567, rx_err=0, tx_err=0
I (30005) MAIN: WiFi AP: link=DOWN, rx_pkts=0, tx_pkts=0, rx_err=0, tx_err=0
I (30006) MAIN: === End Debug Information ===
```

## ✅ **DEBUGGING FEATURES SUMMARY**

- ✅ **Comprehensive Error Handling**: ESP-IDF error codes with detailed messages
- ✅ **Memory Management Debugging**: Enhanced malloc/free error checking
- ✅ **Network Event Logging**: Detailed event tracking with timestamps
- ✅ **System Health Monitoring**: Continuous resource and status monitoring
- ✅ **Matrix-Style Debugging**: Link state change detection
- ✅ **Performance Tracking**: Packet statistics and error rates
- ✅ **Debug Configuration**: Runtime debug enable/disable
- ✅ **Task-Based Monitoring**: Dedicated debug information task

The debugging system is now ready for comprehensive network auditing operations with full visibility into system behavior and performance. 