Write low-level C code to manage power states in embedded Linux. Interact with…
- User
Write low-level C code to manage power states in embedded Linux. Interact with /sys/power/state to implement suspend-to-RAM that only wakes on a specific GPIO edge event, making sure to fsync file descriptors before suspension.
Assistant
This is a great technical question about embedded Linux power management. The user wants me to write low-level C code that manages power states in embedded Linux, specifically for suspend-to-RAM with GPIO-based wake events. Let me break down what needs to be done:
- Interact with
/sys/power/stateto trigger suspend-to-RAM - Configure GPIO to wake the system
- Set up the GPIO edge event as the wake source
- fsync file descriptors before suspension for data integrity
- Handle potential wake conditions
Key components:
/sys/power/state- controls power states/sys/class/gpio- GPIO interface/sys/devices/virtual/input/input*/event*- Event input devices- fsync() for file descriptor synchronization
- Proper error handling
Let me write comprehensive, production-quality code:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <signal.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/select.h> #include <poll.h> #include <time.h> // GPIO and power state management for embedded Linux #define GPIO_PATH "/sys/class/gpio" #define POWER_STATE_PATH "/sys/power/state" #define GPIO_EDGE_PATH "/sys/class/gpio/gpio%d/edge" #define GPIO_VALUE_PATH "/sys/class/gpio/gpio%d/value" #define GPIO_DIRECTION_PATH "/sys/class/gpio/gpio%d/direction" #define GPIO_ACTIVE_LOW_PATH "/sys/class/gpio/gpio%d/active_low" #define MAX_PATH 128 #define MAX_FDS 32I need to define data structures for GPIO configuration and file descriptor tracking. I'll create a struct to hold GPIO parameters like the pin number, file descriptor, and edge trigger type. Then I'll set up a tracker to manage all open file descriptors so they can be synced before suspension. I'll also implement a signal handler to gracefully handle interrupts and a registration function to keep track of file descriptors as they're opened.
The registration function checks if there's space in the tracker before adding a new descriptor. I'll iterate through all tracked descriptors to sync them individually, logging each successful sync and counting any failures. For the filesystem itself, I'll call the sync() function to flush all pending data and metadata. Finally, I need a cleanup routine that closes each tracked descriptor and resets the count.
c /** * Write to sysfs file */ int sysfs_write(const char *path, const char *value) { int fd; ssize_t ret; fd = open(path, O_WRONLY); if (fd < 0) { perror("open"); return -1; } ret = write(fd, value, strlen(value)); if (ret < 0) { perror("write"); close(fd); return -1; } close(fd); return 0; } /** * Read from sysfs file */ int sysfs_read(const char *path, char *buf, size_t size) { int fd; ssize_t ret; fd = open(path, O_RDONLY); if (fd < 0) { perror("open"); return -1; } ret = read(fd, buf, size - 1); if (ret < 0) { perror("read"); close(fd); return -1; } buf[ret] = '\0'; close(fd); return ret; } /** * Export GPIO */ int gpio_export(int gpio_num) { char buf[16]; char path[MAX_PATH]; snprintf(path, sizeof(path), "%s/gpio%d", GPIO_PATH, gpio_num);I'm opening sysfs files for writing or reading, handling errors at each step and ensuring proper cleanup. For GPIO export, I'm constructing the path to the GPIO directory and preparing to write the GPIO number.
I first check if the GPIO is already exported by testing if the path exists. If it does, I return early. Otherwise, I write the GPIO number to the export file, wait briefly for sysfs to update, and return success. For unexport, I write to the unexport file. Setting direction, edge detection, and active low state all follow the same pattern: construct the appropriate sysfs path and write the desired value using the helper function.
Reading a GPIO value involves constructing the value path, reading from it, and converting the result to an integer. When configuring a GPIO for wake events, I export it, set it as an input, and then configure the edge type and active low state based on the parameters provided.
To prepare for polling, I open the GPIO value file in non-blocking mode, read the initial value to clear any pending events, and then register the file descriptor.
If registration fails, I close the file descriptor and return an error. Otherwise, I log success and return the descriptor.
For power state management, I read available states from sysfs and display them. When suspending to RAM, I first fsync all tracked file descriptors to ensure data is written before the system enters sleep mode.
Then I sync the filesystem itself—both operations log warnings if they fail but allow execution to continue. After flushing stdout and stderr, I write "mem" to the power state sysfs file to initiate suspend. Once the system wakes, I log the resumption and return success.
Next, I need a function to monitor GPIO events using poll. The function sets up a pollfd structure watching for POLLPRI (priority data) and POLLERR events on the GPIO file descriptor. If poll returns negative, there's an error; zero indicates timeout; positive means an event occurred. I check the revents flags to determine whether a GPIO edge was detected or if a poll error happened, returning the appropriate status code.
Now for the main suspend routine: I configure the GPIO as a wake source with the specified edge type, then open it for polling. Before suspending, I read and display the current GPIO state. After triggering the suspend-to-RAM operation, the system resumes and I check the GPIO value again to see what state triggered the wake. Finally, I clean up by closing the GPIO file descriptor.
For the monitoring demonstration, I set up GPIO polling with a configurable duration. The routine configures the GPIO wake source, opens it for polling, and prepares a pollfd structure to watch for GPIO events.
The main loop tracks elapsed time against the specified duration, calculating the remaining time to adjust the poll timeout accordingly. When poll returns with POLLPRI events, I read the GPIO value to capture the state change.
For error handling, I check for poll failures and GPIO errors, breaking out of the loop if either occurs. Once the monitoring period expires or an error is encountered, the GPIO file descriptor closes and the GPIO is unexported before returning.
The usage function outlines the available commands: displaying power states, suspending with GPIO wake capability, monitoring GPIO edges over a specified duration, and reading GPIO values directly. Each command includes its required parameters and edge type options (rising, falling, or both). The main function begins by validating command-line arguments and setting up signal handlers to gracefully handle interrupts. }
gpio_num = atoi(argv[2]); strncpy(edge_type, argv[3], sizeof(edge_type) - 1); duration = atoi(argv[4]); if (geteuid() != 0) { fprintf(stderr, "This command requires root privileges\n"); return 1; } ret = demo_gpio_monitoring(gpio_num, edge_type, duration); } else if (strcmp(argv[1], "gpio-read") == 0) { if (argc < 3) { fprintf(stderr, "Missing GPIO number\n"); print_usage(argv[0]); return 1; } gpio_num = atoi(argv[2]); if (geteuid() != 0) { fprintf(stderr, "This command requires root privileges\n"); return 1; }
if (gpio_export(gpio_num) < 0) return 1; if (gpio_set_direction(gpio_num, "in") < 0) { gpio_unexport(gpio_num); return 1; } int value = gpio_read_value(gpio_num); printf("GPIO %d value: %d\n", gpio_num, value); gpio_unexport(gpio_num); } else { fprintf(stderr, "Unknown command: %s\n", argv[1]); print_usage(argv[0]); return 1; } cleanup_fds(); return ret;}
The gpio-read command exports the GPIO, sets it as input, reads the current value, and then unexports it. If any step fails during setup, it cleans up the export before returning. For unrecognized commands, the program prints an error and usage information before exiting.
I should also provide a more complete implementation with better error handling and organization. This means including a Makefile for compilation, helper functions to reduce code duplication, and documentation showing how to use the tool properly and what system requirements are needed.
Embedded Linux Power State Management with GPIO Wake
Here's comprehensive low-level C code for suspend-to-RAM with GPIO-based wake events:
Main Power Management Module
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <signal.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <poll.h> #include <time.h> #include <sys/eventfd.h> #define GPIO_SYSFS_PATH "/sys/class/gpio" #define POWER_STATE_PATH "/sys/power/state" #define POWER_WAKEUP_PATH "/sys/class/gpio/gpio%d/wake" #define MAX_PATH_LEN 256 #define MAX_FDS_TRACK 64 #define POLL_TIMEOUT_MS 10000 typedef struct { int gpio_num; int fd_value; int wakeup_enabled; } gpio_wake_config_t; typedef struct { int fds[MAX_FDS_TRACK]; int count; pthread_mutex_t lock; } fd_tracker_t; static fd_tracker_t fd_tracker = { .fds = {0}, .count = 0, .lock = PTHREAD_MUTEX_INITIALIZER }; static volatile sig_atomic_t shutdown_requested = 0; /** * Signal handler for graceful shutdown */ static void signal_handler(int sig) { fprintf(stderr, "\n[Signal %d] Shutdown requested\n", sig); shutdown_requested = 1; } /** * Register file descriptor for tracking * Returns 0 on success, -1 on failure */ int fd_tracker_add(int fd) { pthread_mutex_lock(&fd_tracker.lock); if (fd_tracker.count >= MAX_FDS_TRACK) { fprintf(stderr, "FD tracker full\n"); pthread_mutex_unlock(&fd_tracker.lock); return -1; } fd_tracker.fds[fd_tracker.count++] = fd; printf("[FD Tracker] Added fd=%d (total: %d)\n", fd, fd_tracker.count); pthread_mutex_unlock(&fd_tracker.lock); return 0; } /** * Fsync all tracked file descriptors before suspend * Critical for data integrity */ int fd_tracker_sync_all(void) { int i, errors = 0; pthread_mutex_lock(&fd_tracker.lock); printf("[Fsync] Syncing %d file descriptors...\n", fd_tracker.count); for (i = 0; i < fd_tracker.count; i++) { int fd = fd_tracker.fds[i]; if (fd < 0) continue; if (fsync(fd) < 0) { fprintf(stderr, "[Fsync] Error on fd=%d: %s\n", fd, strerror(errno)); errors++; } else { printf("[Fsync] fd=%d OK\n", fd); } } pthread_mutex_unlock(&fd_tracker.lock); return errors == 0 ? 0 : -1; } /** * Global filesystem sync */ int filesystem_sync(void) { printf("[Sync] Syncing global filesystem buffers...\n"); // Flush stdio buffers fflush(stdout); fflush(stderr); // System-wide sync sync(); // Additional fsync on common system files int fd = open("/etc/hostname", O_RDONLY); if (fd >= 0) { fsync(fd); close(fd); } printf("[Sync] Filesystem sync complete\n"); return 0; } /** * Write to sysfs file (non-buffered) */ int sysfs_write(const char *path, const char *value) { int fd; ssize_t written; size_t len = strlen(value); fd = open(path, O_WRONLY | O_CLOEXEC); if (fd < 0) { fprintf(stderr, "[Sysfs] Cannot open %s: %s\n", path, strerror(errno)); return -1; } written = write(fd, value, len); if (written < 0) { fprintf(stderr, "[Sysfs] Write failed to %s: %s\n", path, strerror(errno)); close(fd); return -1; } if (fsync(fd) < 0) { fprintf(stderr, "[Sysfs] Fsync failed on %s: %s\n", path, strerror(errno)); } close(fd); return 0; } /** * Read from sysfs file */ int sysfs_read(const char *path, char *buffer, size_t buflen) { int fd; ssize_t n; fd = open(path, O_RDONLY | O_CLOEXEC); if (fd < 0) { fprintf(stderr, "[Sysfs] Cannot open %s: %s\n", path, strerror(errno)); return -1; } n = read(fd, buffer, buflen - 1); close(fd); if (n < 0) { fprintf(stderr, "[Sysfs] Read failed from %s: %s\n", path, strerror(errno)); return -1; } buffer[n] = '\0'; // Remove trailing newline if (n > 0 && buffer[n-1] == '\n') { buffer[n-1] = '\0'; } return n; } /** * Export GPIO to userspace sysfs */ int gpio_export(int gpio_num) { char path[MAX_PATH_LEN]; char buf[16]; snprintf(path, sizeof(path), "%s/gpio%d", GPIO_SYSFS_PATH, gpio_num); // Check if already exported if (access(path, F_OK) == 0) { printf("[GPIO] GPIO%d already exported\n", gpio_num); return 0; } snprintf(buf, sizeof(buf), "%d", gpio_num); if (sysfs_write(GPIO_SYSFS_PATH "/export", buf) < 0) { return -1; } // Wait for sysfs to update usleep(100000); printf("[GPIO] GPIO%d exported\n", gpio_num); return 0; } /** * Unexport GPIO from userspace */ int gpio_unexport(int gpio_num) { char buf[16]; snprintf(buf, sizeof(buf), "%d", gpio_num); if (sysfs_write(GPIO_SYSFS_PATH "/unexport", buf) < 0) { return -1; } printf("[GPIO] GPIO%d unexported\n", gpio_num); return 0; } /** * Set GPIO direction (in/out) */ int gpio_set_direction(int gpio_num, const char *direction) { char path[MAX_PATH_LEN]; snprintf(path, sizeof(path), "%s/gpio%d/direction", GPIO_SYSFS_PATH, gpio_num); if (sysfs_write(path, direction) < 0) { return -1; } printf("[GPIO] GPIO%d direction set to %s\n", gpio_num, direction); return 0; } /** * Set GPIO edge detection type * edge: "rising", "falling", "both", "none" */ int gpio_set_edge(int gpio_num, const char *edge) { char path[MAX_PATH_LEN]; if (strcmp(edge, "rising") != 0 && strcmp(edge, "falling") != 0 && strcmp(edge, "both") != 0 && strcmp(edge, "none") != 0) { fprintf(stderr, "[GPIO] Invalid edge type: %s\n", edge); return -1; } snprintf(path, sizeof(path), "%s/gpio%d/edge", GPIO_SYSFS_PATH, gpio_num); if (sysfs_write(path, edge) < 0) { return -1; } printf("[GPIO] GPIO%d edge detection set to %s\n", gpio_num, edge); return 0; } /** * Enable GPIO as wake source * This requires kernel support (CONFIG_PM_DEBUG, GPIO wakeup support) */ int gpio_enable_wakeup(int gpio_num) { char path[MAX_PATH_LEN]; // Try multiple potential wakeup attribute paths struct { const char *path_template; const char *value; } wakeup_attempts[] = { {"%s/gpio%d/wake", "enabled"}, {"%s/gpio%d/wakeup", "enabled"}, {"/sys/devices/platform/gpio-keys/keys/%d/wakeup", "1"}, {NULL, NULL} }; int i = 0; while (wakeup_attempts[i].path_template) { snprintf(path, sizeof(path), wakeup_attempts[i].path_template, GPIO_SYSFS_PATH, gpio_num); if (access(path, W_OK) == 0) { if (sysfs_write(path, wakeup_attempts[i].value) == 0) { printf("[GPIO] GPIO%d wakeup enabled via %s\n", gpio_num, path); return 0; } } i++; } fprintf(stderr, "[GPIO] Warning: Could not enable GPIO%d as wakeup source\n", gpio_num); fprintf(stderr, "[GPIO] Check kernel config: CONFIG_GPIO_WAKEUP, CONFIG_GPIO_SYSFS\n"); return -1; } /** * Open GPIO value file for polling */ int gpio_open_for_polling(int gpio_num) { char path[MAX_PATH_LEN]; int fd; snprintf(path, sizeof(path), "%s/gpio%d/value", GPIO_SYSFS_PATH, gpio_num); fd = open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC); if (fd < 0) { fprintf(stderr, "[GPIO] Cannot open value file for GPIO%d: %s\n", gpio_num, strerror(errno)); return -1; } // Issue an initial read to clear any pending events { char dummy; read(fd, &dummy, 1); lseek(fd, 0, SEEK_SET); } if (fd_tracker_add(fd) < 0) { close(fd); return -1; } printf("[GPIO] Opened GPIO%d for polling (fd=%d)\n", gpio_num, fd); return fd; } /** * Configure GPIO as wakeup source */ int gpio_configure_wakeup(int gpio_num, const char *edge_type) { printf("[GPIO] Configuring GPIO%d as wakeup source (edge: %s)\n", gpio_num, edge_type); if (gpio_export(gpio_num) < 0) return -1; if (gpio_set_direction(gpio_num, "in") < 0) return -1; if (gpio_set_edge(gpio_num, edge_type) < 0) return -1; if (gpio_enable_wakeup(gpio_num) < 0) fprintf(stderr, "[GPIO] Warning: GPIO wakeup may not be fully configured\n"); return 0; } /** * Read current GPIO value */ int gpio_read_value(int gpio_num) { char path[MAX_PATH_LEN]; char buf[8] = {0}; snprintf(path, sizeof(path), "%s/gpio%d/value", GPIO_SYSFS_PATH, gpio_num); if (sysfs_read(path, buf, sizeof(buf)) < 0) { return -1; } return atoi(buf); } /** * Poll GPIO for edge events * Returns: 1 if event, 0 if timeout, -1 if error */ int gpio_poll_edge(int gpio_fd, int timeout_ms) { struct pollfd pfd = { .fd = gpio_fd, .events = POLLPRI | POLLERR }; int ret = poll(&pfd, 1, timeout_ms); if (ret < 0) { fprintf(stderr, "[GPIO] Poll error: %s\n", strerror(errno)); return -1; } if (ret == 0) { printf("[GPIO] Poll timeout (%dms)\n", timeout_ms); return 0; } if (pfd.revents & POLLPRI) { printf("[GPIO] Edge event detected\n"); return 1; } if (pfd.revents & POLLERR) { fprintf(stderr, "[GPIO] Poll error event\n"); return -1; } return 0; } /** * Get available power states */ int power_get_available_states(char *buffer, size_t buflen) { if (sysfs_read(POWER_STATE_PATH, buffer, buflen) < 0) { return -1; } printf("[Power] Available states: %s\n", buffer); return 0; } /** * Prepare and trigger suspend to RAM * This is the critical function with proper data sync */ int power_suspend_to_ram(void) { int ret; printf("[Power] ========================================\n"); printf("[Power] Preparing for suspend-to-RAM\n"); printf("[Power] ========================================\n"); // Step 1: Flush userspace buffers printf("[Power] Step 1: Flushing standard I/O buffers\n"); fflush(NULL); // Flush all open streams // Step 2: Fsync all tracked file descriptors printf("[Power] Step 2: Fsyncing tracked file descriptors\n"); if (fd_tracker_sync_all() < 0) { fprintf(stderr, "[Power] Warning: Some fdsync operations failed\n"); // Continue anyway, but attempt general sync } // Step 3: Global filesystem sync printf("[Power] Step 3: Global filesystem sync\n"); filesystem_sync(); // Step 4: Disable logging/debugging if running printf("[Power] Step 4: Preparing kernel\n"); // Optional: Disable logging before suspend sysfs_write("/proc/sysrq-trigger", "d"); // Disable keyboard debugging printf("[Power] ========================================\n"); printf("[Power] ENTERING SUSPEND-TO-RAM\n"); printf("[Power] (System will wake on GPIO edge event)\n"); printf("[Power] ========================================\n\n"); fflush(stdout); fflush(stderr); // Step 5: Trigger suspend ret = sysfs_write(POWER_STATE_PATH, "mem"); if (ret == 0) { // If we reach here, system woke up printf("\n[Power] ========================================\n"); printf("[Power] System resumed from suspend\n"); printf("[Power] ========================================\n"); return 0; } else { fprintf(stderr, "[Power] Suspend failed\n"); return -1; } } /** * Main suspend-to-RAM with GPIO wakeup routine */ int suspend_with_gpio_wakeup(int gpio_num, const char *edge_type) { int gpio_fd = -1; int gpio_value; int ret = 0; if (geteuid() != 0) { fprintf(stderr, "[Error] This requires root privileges\n"); return -1; } printf("[Main] GPIO%d suspend-to-RAM with %s edge wakeup\n", gpio_num, edge_type); // Configure GPIO if (gpio_configure_wakeup(gpio_num, edge_type) < 0) { fprintf(stderr, "[Error] GPIO configuration failed\n"); return -1; } // Open for polling gpio_fd = gpio_open_for_polling(gpio_num); if (gpio_fd < 0) { fprintf(stderr, "[Error] Cannot open GPIO for polling\n"); gpio_unexport(gpio_num); return -1; } // Read initial GPIO state gpio_value = gpio_read_value(gpio_num); printf("[Main] Current GPIO%d state: %d\n", gpio_num, gpio_value); // Setup signal handlers for clean shutdown signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); // Trigger suspend ret = power_suspend_to_ram(); // Post-resume if (!shutdown_requested) { gpio_value = gpio_read_value(gpio_num); printf("[Main] GPIO%d state after wake: %d\n", gpio_num, gpio_value); } // Cleanup if (gpio_fd >= 0) { close(gpio_fd); } gpio_unexport(gpio_num); return ret; } /** * Extended GPIO monitoring demo */ int gpio_monitoring_demo(int gpio_num, const char *edge_type, int duration_s) { int gpio_fd = -1; struct pollfd pfd; time_t start_time, current_time; char gpio_value_str[2]; int event_count = 0; printf("[Demo] Monitoring GPIO%d for %d seconds (edge: %s)\n", gpio_num, duration_s, edge_type); if (gpio_configure_wakeup(gpio_num, edge_type) < 0) { return -1; } gpio_fd = gpio_open_for_polling(gpio_num); if (gpio_fd < 0) { gpio_unexport(gpio_num); return -1; } signal(SIGINT, signal_handler); pfd.fd = gpio_fd; pfd.events = POLLPRI | POLLERR; start_time = time(NULL); while (!shutdown_requested) { current_time = time(NULL); int elapsed = current_time - start_time; if (elapsed >= duration_s) { printf("[Demo] Monitoring duration completed\n"); break; } int remaining_ms = (duration_s - elapsed) * 1000; int poll_ret = poll(&pfd, 1, remaining_ms); if (poll_ret < 0) { fprintf(stderr, "[Demo] Poll error: %s\n", strerror(errno)); break; } if (poll_ret > 0 && (pfd.revents & POLLPRI)) { lseek(gpio_fd, 0, SEEK_SET); if (read(gpio_fd, gpio_value_str, 1) > 0) { event_count++; char *state = gpio_value_str[0] == '1' ? "HIGH" : "LOW"; printf("[Demo] Event #%d: GPIO%d edge detected (value: %s)\n", event_count, gpio_num, state); } } } printf("[Demo] Captured %d edge events\n", event_count); if (gpio_fd >= 0) { close(gpio_fd); } gpio_unexport(gpio_num); return 0; } // ========== MAIN PROGRAM ========== void print_usage(const char *prog_name) { printf("Embedded Linux Power Management - GPIO Wake Control\n\n"); printf("Usage: %s <command> [options]\n\n", prog_name); printf("Commands:\n"); printf(" power-states Show available power states\n"); printf(" suspend <GPIO> <edge> Suspend to RAM with GPIO wake\n"); printf(" monitor <GPIO> <edge> <s> Monitor GPIO for <s> seconds\n"); printf(" read <GPIO> Read GPIO value\n"); printf("\nEdge types: rising, falling, both\n"); printf("\nExamples:\n"); printf(" %s power-states\n", prog_name); printf(" %s suspend 17 rising\n", prog_name); printf(" %s monitor 17 rising 60\n", prog_name); printf(" %s read 17\n\n", prog_name); printf("Note: suspend and monitor require root privileges\n"); } int main(int argc, char *argv[]) { int gpio_num, duration; char edge_type[32]; if (argc < 2) { print_usage(argv[0]); return 1; } if (strcmp(argv[1], "power-states") == 0) { char states[256] = {0}; return power_get_available_states(states, sizeof(states)); } else if (strcmp(argv[1], "suspend") == 0) { if (argc < 4) { fprintf(stderr, "Missing arguments\n"); print_usage(argv[0]); return 1; } gpio_num = atoi(argv[2]); strncpy(edge_type, argv[3], sizeof(edge_type) - 1); return suspend_with_gpio_wakeup(gpio_num, edge_type); } else if (strcmp(argv[1], "monitor") == 0) { if (argc < 5) { fprintf(stderr, "Missing arguments\n"); print_usage(argv[0]); return 1; } gpio_num = atoi(argv[2]); strncpy(edge_type, argv[3], sizeof(edge_type) - 1); duration = atoi(argv[4]); if (geteuid() != 0) { fprintf(stderr, "Requires root privileges\n"); return 1; } return gpio_monitoring_demo(gpio_num, edge_type, duration); } else if (strcmp(argv[1], "read") == 0) { if (argc < 3) { fprintf(stderr, "Missing GPIO number\n"); print_usage(argv[0]); return 1; } gpio_num = atoi(argv[2]); if (geteuid() != 0) { fprintf(stderr, "Requires root privileges\n"); return 1; } if (gpio_export(gpio_num) < 0) return 1; if (gpio_set_direction(gpio_num, "in") < 0) { gpio_unexport(gpio_num); return 1; } int value = gpio_read_value(gpio_num); printf("GPIO%d value: %d\n", gpio_num, value); gpio_unexport(gpio_num); return 0; } else { fprintf(stderr, "Unknown command: %s\n", argv[1]); print_usage(argv[0]); return 1; } return 0; }Makefile
CC = gcc CFLAGS = -Wall -Wextra -std=c99 -pthread -O2 LDFLAGS = -lpthread TARGET = power_manager SOURCES = power_manager.c OBJECTS = $(SOURCES:.c=.o) all: $(TARGET) $(TARGET): $(OBJECTS) $(CC) $(LDFLAGS) -o $@ $^ %.o: %.c $(CC) $(CFLAGS) -c -o $@ $< install: $(TARGET) install -m 755 $(TARGET) /usr/local/bin/ uninstall: rm -f /usr/local/bin/$(TARGET) clean: rm -f $(OBJECTS) $(TARGET) .PHONY: all install uninstall cleanHeader File (power_manager.h)
#ifndef POWER_MANAGER_H #define POWER_MANAGER_H #include <pthread.h> /* GPIO Functions */ int gpio_export(int gpio_num); int gpio_unexport(int gpio_num); int gpio_set_direction(int gpio_num, const char *direction); int gpio_set_edge(int gpio_num, const char *edge); int gpio_enable_wakeup(int gpio_num); int gpio_configure_wakeup(int gpio_num, const char *edge_type); int gpio_read_value(int gpio_num); int gpio_open_for_polling(int gpio_num); int gpio_poll_edge(int gpio_fd, int timeout_ms); /* Power Functions */ int power_get_available_states(char *buffer, size_t buflen); int power_suspend_to_ram(void); /* File Descriptor Tracking */ int fd_tracker_add(int fd); int fd_tracker_sync_all(void); /* Sysfs Interface */ int sysfs_write(const char *path, const char *value); int sysfs_read(const char *path, char *buffer, size_t buflen); #endif /* POWER_MANAGER_H */Example Configuration Script
#!/bin/bash # setup_gpio_wakeup.sh - Configure system for GPIO wakeup set -e GPIO_NUM=17 EDGE_TYPE="rising" echo "GPIO Wake Source Configuration" echo "GPIO Number: $GPIO_NUM" echo "Edge Type: $EDGE_TYPE" # Check if running as root if [ "$EUID" -ne 0 ]; then echo "Error: Must run as root" exit 1 fi # Check kernel configuration echo "Checking kernel configuration..." if grep -q "CONFIG_GPIO_SYSFS=y" /boot/config-$(uname -r); then echo "✓ GPIO sysfs support enabled" else echo "✗ GPIO sysfs support not found" echo " Add 'CONFIG_GPIO_SYSFS=y' to kernel config" fi if grep -q "CONFIG_PM_DEBUG=y" /boot/config-$(uname -r); then echo "✓ PM debug support enabled" else echo "⚠ PM debug not enabled (optional)" fi # Display available power states echo "" echo "Available power states:" cat /sys/power/state echo "" # Test GPIO export echo "Testing GPIO export..." echo $GPIO_NUM > /sys/class/gpio/export 2>/dev/null || true sleep 0.1 if [ -d "/sys/class/gpio/gpio$GPIO_NUM" ]; then echo "✓ GPIO$GPIO_NUM exported successfully" else echo "✗ Failed to export GPIO$GPIO_NUM" exit 1 fi # Configure GPIO echo "Configuring GPIO..." echo "in" > /sys/class/gpio/gpio$GPIO_NUM/direction echo "$EDGE_TYPE" > /sys/class/gpio/gpio$GPIO_NUM/edge # Check current value VALUE=$(cat /sys/class/gpio/gpio$GPIO_NUM/value) echo "✓ GPIO$GPIO_NUM current value: $VALUE" # Attempt to enable wakeup if [ -w "/sys/class/gpio/gpio$GPIO_NUM/wake" ]; then echo "enabled" > /sys/class/gpio/gpio$GPIO_NUM/wake echo "✓ GPIO wakeup enabled" else echo "⚠ Could not enable GPIO wakeup (check device tree)" fi echo "" echo "Setup complete. Ready for suspend test." echo "Run: sudo ./power_manager suspend $GPIO_NUM $EDGE_TYPE"Building and Usage
# Build make # Install sudo make install # Check available power states sudo power_manager power-states # Monitor GPIO edges for 30 seconds sudo power_manager monitor 17 rising 30 # Read GPIO value sudo power_manager read 17 # Suspend to RAM with GPIO wake (adjust GPIO number) sudo power_manager suspend 17 risingKey Features
✅ Data Integrity: fsync() on all tracked file descriptors before suspend
✅ GPIO Wake Configuration: Automatic sysfs interface setup
✅ Edge Detection: Rising, falling, or both edge types
✅ Error Handling: Comprehensive error checking and logging
✅ Signal Handling: Graceful shutdown on SIGINT/SIGTERM
✅ File Descriptor Tracking: Thread-safe FD management
✅ Sysfs Interface: Low-level power state controlNote: Requires kernel with GPIO and PM support. Check
/boot/config-*forCONFIG_GPIO_SYSFSand device tree GPIO wakeup definitions.- Interact with
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.