Skip to contentSkip to conversation

tools: new tool - gpioctl

PATCH New Bartosz Golaszewski 1 participant 7 messages Dec 1

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

v3 cover tools: new tool - gpioctl

Provide gpioctl, a new command-line tool for persistent GPIO line control. Unlike gpioget and gpioset which release lines on exit, gpioctl holds requested lines in a background daemon so their state survives across multiple client invocations.

Before adding the new program: move some code we'll reuse out of gpioset and gpiomon and into tools-common.

I think this version is in relatively good shape and I plan to merge it soon and continue to iron it out in tree.

---
Changes in v3:
- Factor out splitting of line=value arguments into a reusable function
and use it in gpioctl
- Fix parsing of line=value arguments: verify the count of line=value
pairs and fix parsing of line names containing '='
- Actually use the list of headers required by tools in meson.build
- Drop monitors whose request went away
- Unlink the server listening socket before closing it
- Use the EMFILE trick when out of descriptors
- Don't inherit anything from the client spawning the server process
- Reject arguments to stop, ping and debug
- Fix the invalid message size test cases by checking if the emitted log
is the correct one
- Run the tool tests in their own network namespace
- Gracefully handle closed standard descriptors on server startup
- Make --by-name apply to get, set and monitor as well
- Require direction setting for gpioctl reconfigure
- More code reuse/unduplication
- Fix typos
- Don't ignore the return value of write() when reporting a server
startup failure
- Fix helptext formatting for help2man
- Fix parsing of request IDs: don't use strtoul() which accepts blanks
and signs
- Pick up review tags
- Link to v2: https://patch.msgid.link/[email protected]

Changes in v2:
- Make the server startup more robust: use lockfiles to rule out races between multiple processes starting a server on the same socket
- Add a "startup" pipe allowing the server to communicate errors to
client before the server is fully set up and the connection
established
- Don't let slow clients block the server: drop a client that doesn't
read data sent to it fast enough and make client sockets non-blocking
- Make the default output of gpioctl monitor (without the --format option) match that of gpiomon
- Set output values together with settings in build_line_config()
instead of having these ops split into two far from one another
- Fix an unnecessary double fetch of the request list from monitor_resolve()
- Prefer "positive" tests first
- Map reconfigured values to lines by name on the daemon side and ensure the ordering libgpiod requires for a correct reconfigure
- Update loop variables inside the for () statement
- Unify the range of supported event format specifiers across gpiomon
and gpioctl
- Reword the docs to make it clear that the daemon stays alive as long
as there are any active GPIO requests or client connections
- Make examples in docs better match the actual behavior of gpioctl
(they were mostly written earlier with the behavior changed since)
- Use a single counter variable in validate_request_opts()
- Don't let the server die on SIGPIPE
- Don't dispatch pending epoll events to receivers removed while
processing the same batch
- Abstract socket names are not owned by anyone so make sure to verify credentials and only talk to servers and clients of the same user
- Fix regressions introduced by moving event formatting code to tools-common
- Only sent as many bytes as are needed per message type, not a fixed, almost 4k byte message even for small amounts of data like edge events
- Fix several memory leaks
- fix parsing of the -F command-line option in gpioctl monitor
- Use the right die() variants in the server-only code
- Don't look up the user name just to print it in a log message as a call to getpwuid() may block on a NSS request for no reason or drop a valid client with no passwd entry
- Add error checking when redirecting FDs when daemonizing the server
- Reset optind consistently in sub-command parsers
- Reject empty offsets in gpioctl set
- Add meson tests for new headers and functions used in gpioctl
- Fix parsing of line=value pairs for corner-cases, allow '=' in line
names in shunit2 helper
- Reject too many lines given by name
- Refactor the code handling the printing of line events: use less positional arguments in favor of structs and unduplicate parts of the logic
- Rework the gpioctl-test-helper program, add more functionalities
- Many other small tweaks and fixes...
- Link to v1: https://patch.msgid.link/[email protected]

---
Bartosz Golaszewski (6):
tools: factor out line value parsing into tools-common
tools: factor out line event formatting into tools-common
tests: bash: allow '=' in line names in shunit2 helper
tools: factor out splitting of line=value arguments
tests: bash: provide a helper for disabling GPIO sim chips
tools: implement gpioctl

 TODO                                     |   14 -
 docs/.gitignore                          |    2 +
 docs/conf.py                             |    8 +
 docs/gpio_tools.rst                      |   11 +-
 docs/gpioctl_top.rst                     |  213 ++
 man/meson.build                          |   39 +
 meson.build                              |   10 +
 tests/scripts/gpiod-bash-test-helper.inc |   13 +-
 tools/gpio-tools-test.bash               | 2730 ++++++++++++++++++++++
 tools/gpioctl-test-helper.c              |  232 ++
 tools/gpioctl.c                          | 3701 ++++++++++++++++++++++++++++++
 tools/gpiomon.c                          |  128 +-
 tools/gpioset.c                          |   89 -
 tools/meson.build                        |   21 +-
 tools/tools-common.c                     |  263 ++-
 tools/tools-common.h                     |   26 +
 16 files changed, 7268 insertions(+), 232 deletions(-)

---
base-commit: b1071a55288d595a80709204a73932eb19a0a400
change-id: 20251001-gpioctl-336556e702fd

Best regards,

Signature · 1 line
Bartosz Golaszewski <[email protected]>
#1 lore raw

PATCH v3 1/6 tools: factor out line value parsing into tools-common

Move functions for parsing of line value arguments to tools-common so that both gpioset and the upcoming gpioctl can share them.

---
 tools/gpioset.c      | 89 -----------------------------------------------
 tools/tools-common.c | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 tools/tools-common.h |  5 +++
 3 files changed, 103 insertions(+), 89 deletions(-)
tools/gpioset.c +0 -89
index fce4a7de222f93121c99843a761c5308e021343a..87055b2e3ba36f1b5f788c21671514aab9f50152 100644
@@ -227,95 +227,6 @@ static int parse_config(int argc, char **argv, struct config *cfg)
 	return optind;
 }
 
-static enum gpiod_line_value parse_value(const char *option)
-{
-	if (strcmp(option, "0") == 0)
-		return GPIOD_LINE_VALUE_INACTIVE;
-	if (strcmp(option, "1") == 0)
-		return GPIOD_LINE_VALUE_ACTIVE;
-	if (strcmp(option, "inactive") == 0)
-		return GPIOD_LINE_VALUE_INACTIVE;
-	if (strcmp(option, "active") == 0)
-		return GPIOD_LINE_VALUE_ACTIVE;
-	if (strcmp(option, "off") == 0)
-		return GPIOD_LINE_VALUE_INACTIVE;
-	if (strcmp(option, "on") == 0)
-		return GPIOD_LINE_VALUE_ACTIVE;
-	if (strcmp(option, "false") == 0)
-		return GPIOD_LINE_VALUE_INACTIVE;
-	if (strcmp(option, "true") == 0)
-		return GPIOD_LINE_VALUE_ACTIVE;
-
-	return GPIOD_LINE_VALUE_ERROR;
-}
-
-/*
- * Parse line id and values from lvs into lines and values.
- *
- * Accepted forms:
- *     'line=value'
- *     '"line"=value'
- *
- * If line id is quoted then it is returned unquoted.
- */
-static bool parse_line_values(int num_lines, char **lvs, char **lines,
-			      enum gpiod_line_value *values, bool interactive)
-{
-	char *value, *line;
-	int i;
-
-	for (i = 0; i < num_lines; i++) {
-		line = lvs[i];
-
-		if (*line != '"') {
-			value = strchr(line, '=');
-		} else {
-			line++;
-			value = strstr(line, "\"=");
-			if (value) {
-				*value = '\0';
-				value++;
-			}
-		}
-
-		if (!value) {
-			if (interactive)
-				printf("invalid line value: '%s'\n", lvs[i]);
-			else
-				print_error("invalid line value: '%s'", lvs[i]);
-
-			return false;
-		}
-
-		*value = '\0';
-		value++;
-		values[i] = parse_value(value);
-
-		if (values[i] == GPIOD_LINE_VALUE_ERROR) {
-			if (interactive)
-				printf("invalid line value: '%s'\n", value);
-			else
-				print_error("invalid line value: '%s'", value);
-
-			return false;
-		}
-
-		lines[i] = line;
-	}
-
-	return true;
-}
-
-/*
- * Parse line id and values from lvs into lines and values, or die trying.
- */
-static void parse_line_values_or_die(int num_lines, char **lvs, char **lines,
-				     enum gpiod_line_value *values)
-{
-	if (!parse_line_values(num_lines, lvs, lines, values, false))
-		exit(EXIT_FAILURE);
-}
-
 static void print_banner(int num_lines, char **lines)
 {
 	int i;
tools/tools-common.c +98 -0

104 lines not on this page · raw message

tools/tools-common.h +5 -0
index 85ee765255bbba991cd2e1fbe6b727a9e998d47e..cd07530b8842be005a5875d347040f88e86a9bf1 100644
@@ -35,6 +35,11 @@ void die_oom(void) NORETURN;
 void die_perror(const char *fmt, ...) NORETURN PRINTF(1, 2);
 void print_version(void);
 int parse_bias_or_die(const char *option);
+int parse_line_value_or_die(const char *option);
+bool parse_line_values(int num_lines, char **lvs, char **lines,
+		       enum gpiod_line_value *values, bool interactive);
+void parse_line_values_or_die(int num_lines, char **lvs, char **lines,
+			      enum gpiod_line_value *values);
 long long parse_period(const char *option);
 unsigned long long parse_period_or_die(const char *option);
 void sleep_us(unsigned long long period);
Signature · 1 line
2.47.3
#2 lore raw

PATCH v3 2/6 tools: factor out line event formatting into tools-common

In reply to Bartosz Golaszewski

Move helpers used by gpiomon for formatting of line events and printing of the help text for format specifiers to tools-common so that both gpiomon and the upcoming gpioctl can reuse the same code. While at it:
refactor the code to avoid taking nine positional arguments in print_event() in favor of structs holding the formatting options and the event details.

---
 tools/gpiomon.c      | 128 ++++++----------------------------------------
 tools/tools-common.c | 142 ++++++++++++++++++++++++++++++++++++++++++++++-----
 tools/tools-common.h |  20 ++++++++
 3 files changed, 166 insertions(+), 124 deletions(-)
tools/gpiomon.c +16 -112
index 2b9a69b8aea60d62d42b34dae510ac0a83e0f013..2846603173ec3ddf44d79764e027cbead751d3ed 100644
@@ -79,16 +79,7 @@ static void print_help(void)
 	printf("  -v, --version\t\toutput version information and exit\n");
 	print_chip_help();
 	print_period_help();
-	printf("\n");
-	printf("Format specifiers:\n");
-	printf("  %%o   GPIO line offset\n");
-	printf("  %%l   GPIO line name\n");
-	printf("  %%c   GPIO chip name\n");
-	printf("  %%e   numeric edge event type ('1' - rising or '2' - falling)\n");
-	printf("  %%E   edge event type ('rising' or 'falling')\n");
-	printf("  %%S   event timestamp as seconds\n");
-	printf("  %%U   event timestamp as UTC\n");
-	printf("  %%L   event timestamp as local time\n");
+	print_event_format_help();
 }
 
 static int parse_edges_or_die(const char *option)
@@ -254,115 +245,28 @@ static void print_banner(int num_lines, char **lines)
 	}
 }
 
-static void event_print_formatted(struct gpiod_edge_event *event,
-				  struct line_resolver *resolver, int chip_num,
-				  struct config *cfg)
-{
-	const char *lname, *prev, *curr;
-	unsigned int offset;
-	uint64_t evtime;
-	int evtype;
-	char fmt;
-
-	offset = gpiod_edge_event_get_line_offset(event);
-	evtime = gpiod_edge_event_get_timestamp_ns(event);
-	evtype = gpiod_edge_event_get_event_type(event);
-
-	for (prev = curr = cfg->fmt;;) {
-		curr = strchr(curr, '%');
-		if (!curr) {
-			fputs(prev, stdout);
-			break;
-		}
-
-		if (prev != curr)
-			fwrite(prev, curr - prev, 1, stdout);
-
-		fmt = *(curr + 1);
-
-		switch (fmt) {
-		case 'c':
-			fputs(get_chip_name(resolver, chip_num), stdout);
-			break;
-		case 'e':
-			printf("%d", evtype);
-			break;
-		case 'E':
-			if (evtype == GPIOD_EDGE_EVENT_RISING_EDGE)
-				fputs("rising", stdout);
-			else
-				fputs("falling", stdout);
-			break;
-		case 'l':
-			lname = get_line_name(resolver, chip_num, offset);
-			if (!lname)
-				lname = "unnamed";
-			fputs(lname, stdout);
-			break;
-		case 'L':
-			print_event_time(evtime, 2);
-			break;
-		case 'o':
-			printf("%u", offset);
-			break;
-		case 'S':
-			print_event_time(evtime, 0);
-			break;
-		case 'U':
-			print_event_time(evtime, 1);
-			break;
-		case '%':
-			fputc('%', stdout);
-			break;
-		case '\0':
-			fputc('%', stdout);
-			goto end;
-		default:
-			fwrite(curr, 2, 1, stdout);
-			break;
-		}
-
-		curr += 2;
-		prev = curr;
-	}
-
-end:
-	fputc('\n', stdout);
-}
-
-static void event_print_human_readable(struct gpiod_edge_event *event,
-				       struct line_resolver *resolver,
-				       int chip_num, struct config *cfg)
-{
-	unsigned int offset;
-	uint64_t evtime;
-
-	offset = gpiod_edge_event_get_line_offset(event);
-	evtime = gpiod_edge_event_get_timestamp_ns(event);
-
-	print_event_time(evtime, cfg->timestamp_fmt);
-
-	if (gpiod_edge_event_get_event_type(event) ==
-	    GPIOD_EDGE_EVENT_RISING_EDGE)
-		fputs("\trising\t", stdout);
-	else
-		fputs("\tfalling\t", stdout);
-
-	print_line_id(resolver, chip_num, offset, cfg->chip_id, cfg->unquoted);
-	fputc('\n', stdout);
-}
-
 static void event_print(struct gpiod_edge_event *event,
 			struct line_resolver *resolver, int chip_num,
 			struct config *cfg)
 {
+	struct event_format_opts opts = {
+		.timestamp_fmt = cfg->timestamp_fmt,
+		.fmt = cfg->fmt,
+		.show_chip = !!cfg->chip_id,
+		.unquoted = cfg->unquoted,
+	};
+	struct event_info ev = { };
+
 	if (cfg->quiet)
 		return;
 
-	if (cfg->fmt)
-		event_print_formatted(event, resolver, chip_num, cfg);
-	else
-		event_print_human_readable(event, resolver, chip_num, cfg);
+	ev.timestamp_ns = gpiod_edge_event_get_timestamp_ns(event);
+	ev.offset = gpiod_edge_event_get_line_offset(event);
+	ev.event_type = gpiod_edge_event_get_event_type(event);
+	ev.line_name = get_line_name(resolver, chip_num, ev.offset);
+	ev.chip_name = get_chip_name(resolver, chip_num);
+
+	print_event(&ev, &opts);
 }
 
 int main(int argc, char **argv)
tools/tools-common.c +130 -12

160 lines not on this page · raw message

tools/tools-common.h +20 -0
index cd07530b8842be005a5875d347040f88e86a9bf1..e981c7c74a98ba4e0cdaa19361e8229a2ecd158e 100644
@@ -48,7 +48,27 @@ unsigned int parse_uint_or_die(const char *option);
 void print_bias_help(void);
 void print_chip_help(void);
 void print_period_help(void);
+void print_event_format_help(void);
 void print_event_time(uint64_t evtime, int format);
+
+struct event_info {
+	uint64_t timestamp_ns;
+	unsigned int offset;
+	int event_type;
+	const char *line_name;
+	const char *chip_name;
+};
+
+struct event_format_opts {
+	int timestamp_fmt;
+	const char *fmt;
+	bool show_chip;
+	bool unquoted;
+};
+
+void print_event(const struct event_info *ev,
+		 const struct event_format_opts *opts);
+
 void print_line_attributes(struct gpiod_line_info *info, bool unquoted_strings);
 void print_line_id(struct line_resolver *resolver, int chip_num,
 		   unsigned int offset, const char *chip_id, bool unquoted);
Signature · 1 line
2.47.3
#4 lore raw

PATCH v3 4/6 tools: factor out splitting of line=value arguments

In reply to Bartosz Golaszewski

parse_line_values() contains the logic for separating a line id from its value, including the handling of quoted ids that may themselves contain '='. Tools that need to treat the value as optional, such as gpioctl request, cannot reuse it and have to duplicate it.

Extract the splitting into split_line_value() and make parse_line_values() use it.

---
 tools/tools-common.c | 73 +++++++++++++++++++++++++++++++++-------------------
 tools/tools-common.h |  1 +
 2 files changed, 48 insertions(+), 26 deletions(-)
tools/tools-common.c +47 -26
index eec51acdb3110bfeb940f4ff0f925bec1c639b7c..12b0245bfd6a3fc291fb2d671de7e0c5f9ee89c9 100644
@@ -138,14 +138,56 @@ int parse_line_value_or_die(const char *option)
 }
 
 /*
- * Parse line id and value pairs from lvs into lines and values.
+ * Split a single "line=value" argument in place.
  *
  * Accepted forms:
  *     'line=value'
  *     '"line"=value'
  *
- * If line id is quoted it is returned unquoted. A quoted id may contain '=' and
- * '"=' as the value is always the part after the last '"='.
+ * If the line id is quoted, it is returned unquoted. A quoted id may contain
+ * '=' and '"=' as the value is always the part after the last '"='.
+ *
+ * The separator is replaced with a NUL byte so that the returned line id is
+ * a valid string and *value is set to point at the value part of arg.
+ *
+ * Returns NULL, leaving arg untouched, if there's no separator or no line id
+ * in front of it.
+ */
+char *split_line_value(char *arg, char **value)
+{
+	bool quoted = *arg == '"';
+	char *line = arg, *sep;
+
+	if (!quoted) {
+		sep = strchr(line, '=');
+	} else {
+		line++;
+		sep = strrchr(line, '=');
+		if (!sep || sep == line || *(sep - 1) != '"')
+			return NULL;
+
+		/* Point at the closing quote. */
+		sep--;
+	}
+
+	if (!sep || sep == line)
+		return NULL;
+
+	*sep = '\0';
+	sep++;
+
+	/* Skip the '=' after the closing quote. */
+	if (quoted)
+		sep++;
+
+	*value = sep;
+
+	return line;
+}
+
+/*
+ * Parse line id and value pairs from lvs into lines and values. See
+ * split_line_value() for the accepted forms.
  *
  * The strings in lvs are modified in place: the separator is replaced with a
  * NUL byte and lines point into them.
@@ -157,26 +199,11 @@ bool parse_line_values(int num_lines, char **lvs, char **lines,
 		       enum gpiod_line_value *values, bool interactive)
 {
 	char *value, *line;
-	bool quoted;
 	int i;
 
 	for (i = 0; i < num_lines; i++) {
-		line = lvs[i];
-		quoted = *line == '"';
-
-		if (!quoted) {
-			value = strchr(line, '=');
-		} else {
-			line++;
-			value = strrchr(line, '=');
-			if (value && value > line && *(value - 1) == '"')
-				value--;
-			else
-				value = NULL;
-		}
-
-		/* No separator or no line id in front of it. */
-		if (!value || value == line) {
+		line = split_line_value(lvs[i], &value);
+		if (!line) {
 			if (interactive)
 				printf("invalid line value: '%s'\n", lvs[i]);
 			else
@@ -184,12 +211,6 @@ bool parse_line_values(int num_lines, char **lvs, char **lines,
 			return false;
 		}
 
-		*value = '\0';
-		value++;
-
-		/* Skip the '=' after the closing quote. */
-		if (quoted)
-			value++;
 		values[i] = parse_line_value(value);
 
 		if (values[i] == GPIOD_LINE_VALUE_ERROR) {
tools/tools-common.h +1 -0
index e981c7c74a98ba4e0cdaa19361e8229a2ecd158e..b142c7d441030a54685da042de7e8d9c7c43cc03 100644
@@ -36,6 +36,7 @@ void die_perror(const char *fmt, ...) NORETURN PRINTF(1, 2);
 void print_version(void);
 int parse_bias_or_die(const char *option);
 int parse_line_value_or_die(const char *option);
+char *split_line_value(char *arg, char **value);
 bool parse_line_values(int num_lines, char **lvs, char **lines,
 		       enum gpiod_line_value *values, bool interactive);
 void parse_line_values_or_die(int num_lines, char **lvs, char **lines,
Signature · 1 line
2.47.3
#3 lore raw

PATCH v3 3/6 tests: bash: allow '=' in line names in shunit2 helper

In reply to Bartosz Golaszewski

gpiosim_chip() splits its arguments at '=' and only keeps the second field, so line_name=2:a=b creates a line named 'a'. Tests cannot create lines with an '=' in the name, which is what the line=value parsing of the tools needs to be checked with.

Keep everything after the first '=' as the value.

---
 tests/scripts/gpiod-bash-test-helper.inc | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tests/scripts/gpiod-bash-test-helper.inc +1 -1
index d3c5a75a5d46da38250e39a11af18d09ffaca123..6f36e0a0cdac9a51b4fc932a0c30817803e9214d 100644
@@ -73,7 +73,7 @@ gpiosim_chip() {
 	do
 		local KEY VAL
 		KEY=$(echo "$ARG" | cut -d"=" -f1)
-		VAL=$(echo "$ARG" | cut -d"=" -f2)
+		VAL=$(echo "$ARG" | cut -d"=" -f2-)
 
 		if [ "$KEY" = "num_lines" ]
 		then
Signature · 1 line
2.47.3
#5 lore raw

PATCH v3 5/6 tests: bash: provide a helper for disabling GPIO sim chips

In reply to Bartosz Golaszewski

Add a function allowing test cases to manually disable simulated GPIO chips.

---
 tests/scripts/gpiod-bash-test-helper.inc | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
tests/scripts/gpiod-bash-test-helper.inc +10 -1
index 6f36e0a0cdac9a51b4fc932a0c30817803e9214d..c55317c0c6a57d81542bf9e2f550729a8ca0cf39 100644
@@ -17,6 +17,7 @@ DUT_PID=""
 declare -A GPIOSIM_CHIP_NAME
 declare -A GPIOSIM_CHIP_PATH
 declare -A GPIOSIM_DEV_NAME
+declare -A GPIOSIM_OFFLINE
 GPIOSIM_CONFIGFS="/sys/kernel/config/gpio-sim"
 GPIOSIM_SYSFS="/sys/devices/platform/"
 GPIOSIM_APP_NAME="gpio-tools-test"
@@ -99,6 +100,13 @@ gpiosim_chip() {
 	GPIOSIM_DEV_NAME[$1]=$(<"$DEVPATH/dev_name")
 }
 
+gpiosim_chip_disable() {
+	local NAME=${GPIOSIM_APP_NAME}-$$-$1
+
+	echo 0 > "$GPIOSIM_CONFIGFS/$NAME/live"
+	GPIOSIM_OFFLINE[$1]=1
+}
+
 gpiosim_chip_number() {
 	local NAME=${GPIOSIM_CHIP_NAME[$1]}
 	echo "${NAME#gpiochip}"
@@ -157,7 +165,7 @@ gpiosim_cleanup() {
 
 		local DEVPATH=$GPIOSIM_CONFIGFS/$NAME
 
-		echo 0 > "$DEVPATH/live"
+		[ -n "${GPIOSIM_OFFLINE[$CHIP]}" ] || echo 0 > "$DEVPATH/live"
 		find "$DEVPATH" -type d -name hog -exec rmdir '{}' '+'
 		find "$DEVPATH" -type d -name "line*" -exec rmdir '{}' '+'
 		find "$DEVPATH" -type d -name "bank*" -exec rmdir '{}' '+'
@@ -169,6 +177,7 @@ gpiosim_cleanup() {
 	GPIOSIM_CHIP_NAME=()
 	GPIOSIM_CHIP_PATH=()
 	GPIOSIM_DEV_NAME=()
+	GPIOSIM_OFFLINE=()
 }
 
 run_prog() {
Signature · 1 line
2.47.3
#6 lore raw

PATCH v3 6/6 tools: implement gpioctl

In reply to Bartosz Golaszewski

Provide gpioctl, a new command-line tool for persistent GPIO line control. Unlike gpioget and gpioset which release lines on exit, gpioctl holds requested lines in a background daemon so their state survives across multiple client invocations.

The client auto-spawns the daemon on first use. Communication uses a per-user abstract Unix-domain socket, providing automatic cleanup and per-user isolation without filesystem artifacts.

Each set of lines requested through the tool is assigned a unique ID and referred to as a "request". The following sub-commands are provided:

request - Request a set of GPIO lines by offset or name. The daemon
holds them after the client exits.

  release      - Release a previously made request by ID.
  requests     - List all requests currently held by the daemon.
  get          - Read values of requested lines.
  set          - Set the output values of requested lines.
  monitor      - Subscribe to edge events on a held request.
  reconfigure  - Change the settings of a held request in-place without

releasing it (e.g. switch direction, add edge detection).

There are also "hidden" sub-commands that are not documented in the help text but can be used for debugging purposes:

  ping         - Verify the daemon is running (spawns it if not).
  stop         - Ask the daemon to exit, releasing all held lines.
  debug        - Run the daemon in the foreground with logging enabled.

The wire protocol is intentionally private and unstable: only gpioctl itself speaks it, so no ABI commitment is made.

Also add test-cases covering all sub-commands and configuration options. Update documentation, man page generation (main page plus one page per sub-command), and mark the persistent-daemon TODO item as complete.

---
 TODO                        |   14 -
 docs/.gitignore             |    2 +
 docs/conf.py                |    8 +
 docs/gpio_tools.rst         |   11 +-
 docs/gpioctl_top.rst        |  213 +++
 man/meson.build             |   39 +
 meson.build                 |   10 +
 tools/gpio-tools-test.bash  | 2730 +++++++++++++++++++++++++++++++
 tools/gpioctl-test-helper.c |  232 +++
 tools/gpioctl.c             | 3701 +++++++++++++++++++++++++++++++++++++++++++
 tools/meson.build           |   21 +-
 tools/tools-common.c        |    2 +-
 12 files changed, 6966 insertions(+), 17 deletions(-)
TODO +0 -14
index 95bb3e5dfc3c7f5a8d46ae9b144b5a43866abd7b..c9c127ad785c3786648b7058da4df938beb19f1a 100644
@@ -8,20 +8,6 @@ serve as the starting point.
 
 ==========
 
-* implement a simple daemon for controlling GPIOs in C together with a client
-  program
-
-This is by far the lowest priority task. Similarly as with the dbus daemon:
-the goal is to provide a centralized agent controlling GPIOs with a simple
-interface consisting of a command line client communicating with the server
-over unix sockets.
-
-In this case however the goal is to have as few dependencies as possible. This
-is because for some small systems dbus is overkill. Since we won't be using any
-standardized protocol, it will take much more effort to implement it correctly.
-
-----------
-
 * improve gpioset --interactive tab completion
 
 The existing tab completion uses libedit's readline emulation layer which
docs/.gitignore +2 -0
index 61dac9a54aa0fef3ef44b993470ccd789ca630f2..2046e4c1b2c0552fa3ad2762ac47d2f762948233 100644
@@ -11,6 +11,8 @@ gpioget.rst
 gpioset.rst
 gpiomon.rst
 gpionotify.rst
+gpioctl.rst
+gpioctl-*.rst
 
 gpio-manager.rst
 
docs/conf.py +8 -0
index 831d5f01235081e70c552c9a30e2f4711abd1bfb..48f0bae506018ab2f0e1386e2dee933c6cffc66e 100644
@@ -136,6 +136,14 @@ for page in [
     "gpioset",
     "gpiomon",
     "gpionotify",
+    "gpioctl",
+    "gpioctl-get",
+    "gpioctl-monitor",
+    "gpioctl-reconfigure",
+    "gpioctl-release",
+    "gpioctl-request",
+    "gpioctl-requests",
+    "gpioctl-set",
     "gpio-manager",
     "gpiocli",
     "gpiocli-detect",
docs/gpio_tools.rst +10 -1
index 2876970e4028451b05f7b20a551fc97d0a1685c2..5a73f4aa3ef6dacfd7a2fdfac45270eee3928655 100644
@@ -16,7 +16,8 @@ Overview
 The **libgpiod** project includes a suite of **command-line tools** to
 facilitate GPIO manipulation from console and shell scripts.
 
-There are currently six command-line tools available:
+There are currently six stateless command-line tools available, plus
+``gpioctl`` for persistent line control:
 
 * **gpiodetect**: list all gpiochips present on the system, their names, labels
   and number of GPIO lines
@@ -32,6 +33,8 @@ There are currently six command-line tools available:
 * **gpionotify**: wait for changed to the info for GPIO lines, specify which
   changes to watch for, how many events to process before exiting, or if the
   events should be reported to the console
+* **gpioctl**: request and persistently hold GPIO lines via a per-user background
+  daemon; supports get, set, monitor and reconfigure operations on held requests
 
 Shared library
 --------------
@@ -49,6 +52,12 @@ of libgpiotools.
 
    libgpiotools API documentation<gpio_tools_lib>
 
+.. toctree::
+   :maxdepth: 1
+   :caption: GPIO control with persistence
+
+   gpioctl<gpioctl_top>
+
 .. toctree::
    :maxdepth: 1
    :caption: Manual entries
docs/gpioctl_top.rst new file +213 -0

213 lines not on this page · raw message

man/meson.build +39 -0
index f3a2d4e83698e3f9ca1a8ae35cdf3642dca90f23..a7a0ec3da1105e04be1339615139bfc5293c9b87 100644
@@ -22,6 +22,45 @@ if tools_enabled
       install_dir: man1_dir,
     )
   endforeach
+
+  custom_target('gpioctl.1',
+    output: 'gpioctl.1',
+    command: [
+      help2man,
+      tools_exes['gpioctl'],
+      '--include', man_template,
+      '--no-info',
+      '--name=libgpiod command-line utility',
+      '--help-option=--help',
+      '--manual=gpioctl',
+      '--output=@OUTPUT@',
+    ],
+    install: true,
+    install_dir: man1_dir,
+  )
+
+  gpioctl_cmds = [
+    'get', 'monitor', 'reconfigure',
+    'release', 'request', 'requests', 'set',
+  ]
+
+  foreach cmd : gpioctl_cmds
+    custom_target('gpioctl-' + cmd + '.1',
+      output: 'gpioctl-' + cmd + '.1',
+      command: [
+        help2man,
+        tools_exes['gpioctl'],
+        '--include', man_template,
+        '--no-info',
+        '--name=libgpiod command-line utility',
+        '--help-option=' + cmd + ' --help',
+        '--manual=gpioctl-' + cmd,
+        '--output=@OUTPUT@',
+      ],
+      install: true,
+      install_dir: man1_dir,
+    )
+  endforeach
 endif
 
 if dbus_enabled
meson.build +10 -0
index c92179cd8fe1a3f23441fbf311824a284f23e843..310d18ecdcf06a3976662f6d81f4d9f910a6b61a 100644
@@ -214,6 +214,9 @@ lib_funcs = {
   'readlink': 'unistd.h',
 }
 
+tools_headers = [
+  'sys/file.h',
+]
 tools_funcs = {
   'daemon': 'unistd.h',
   'asprintf': 'stdio.h',
@@ -221,6 +224,12 @@ tools_funcs = {
   'versionsort': 'dirent.h',
   'strtoull': 'stdlib.h',
   'nanosleep': 'time.h',
+  'fork': 'unistd.h',
+  'dup2': 'unistd.h',
+  'flock': 'sys/file.h',
+  'pipe': 'unistd.h',
+  'sysconf': 'unistd.h',
+  'qsort': 'stdlib.h',
 }
 
 tests_headers = [
@@ -255,6 +264,7 @@ dbus_funcs = {
 check_headers = lib_headers
 check_funcs = lib_funcs
 if opt_tools.allowed()
+  check_headers += tools_headers
   check_funcs += tools_funcs
 endif
 if tests_enabled
tools/gpio-tools-test.bash +2730 -0

2,643 lines not on this page · raw message

tools/gpioctl-test-helper.c new file +232 -0

232 lines not on this page · raw message

tools/gpioctl.c new file +3701 -0

3,701 lines not on this page · raw message

tools/meson.build +20 -1
index 5ecf7dc5d221d52243478f9a126e6512d2408981..70c4d2fe5484e5621da2184bd6af2041b4fd8de3 100644

Lines of this file are not shown. View the raw message.

tools/tools-common.c +1 -1
index 12b0245bfd6a3fc291fb2d671de7e0c5f9ee89c9..f47f053fa85963d7bb530fdb317cffb13956a27b 100644

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.47.3

Part of the diff is not shown here. View the raw message.