Skip to contentSkip to conversation

dedicated examples

PATCH In review Kent Gibson 3 participants 16 messages Jun 14, 2023 – Jun 15, 2023

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

cover dedicated examples

This series forms the basis of a proposal to rework the libgpiod examples.

IMHO, the examples have a number of issues including:
- no C examples other than the tools - which have become too complicated to be fit for that purpose.
- bindings examples focus on simplifications of the tools rather than demonstrating typical use cases.
- being more complex than necessary to demonstrate a particular use case.
- naming that does not help new users identify the example that demonstrates a particular use case.

To address these issues I propose adding a set of dedicated examples, each of which demonstrates one primary use case with as little additional fat as possible. Each example should be named after the use case it demonstrates. Each examples should be implemented for all supported languages, to provide examples for users considering language choice and for developers to compare the APIs and identify areas for improvement.

The examples are explicitly intended to answer "how do I use libgpiod to do xxx" questions, with as few distractions as possible.

The examples may demonstrate ancillary features, as long as that is relevant to the primary use case. e.g. the watch_line_value examples set the line bias and debounce.

The examples should hard code input parameters, not pull them from the command line or environment, as that is distracting and frequently more complicated than the example itself.

The examples should be standalone - they should not share code. Large chunks of shared code are an indicator that libgpiod probably needs to provide additional functionality to simplify use cases.

The examples are not intended to be distributed in binary form, but could be incorporated into the documentation.

The set of examples provided is a starter set that answer the following questions:
- how do you get the value of a line?
- how do you set the value of a line?
- how do you watch for edge events on a line?
- how do you watch for edge events asynchronously (e.g. using poll())?

I didn't add the latter in Rust as that should be done using one of the many available async reactors and I didn't want to pick one or pull in any dependencies.

I expect that this proposal may be contraversial, and that is one of the reasons I've kept the starter set small.

Cheers,
Kent.

Kent Gibson (4):
core: examples: add dedicated examples
bindings: cxx: examples: add dedicated examples
bindings: python: examples: add dedicated examples
bindings: rust: examples: add dedicated examples

 Makefile.am                                   |   6 +
 bindings/cxx/examples/.gitignore              |   4 +
 bindings/cxx/examples/Makefile.am             |  14 +-
 .../cxx/examples/async_watch_line_value.cpp   |  78 ++++++++++
 bindings/cxx/examples/get_line_value.cpp      |  29 ++++
 bindings/cxx/examples/toggle_line_value.cpp   |  45 ++++++
 bindings/cxx/examples/watch_line_value.cpp    |  62 ++++++++
 .../python/examples/async_watch_line_value.py |  47 ++++++
 bindings/python/examples/get_line_value.py    |  26 ++++
 bindings/python/examples/toggle_line_value.py |  47 ++++++
 bindings/python/examples/watch_line_value.py  |  42 ++++++
 .../rust/libgpiod/examples/get_line_value.rs  |  28 ++++
 .../libgpiod/examples/toggle_line_value.rs    |  43 ++++++
 .../libgpiod/examples/watch_line_value.rs     |  50 +++++++
 configure.ac                                  |   1 +
 examples/.gitignore                           |   7 +
 examples/Makefile.am                          |  17 +++
 examples/async_watch_line_value.c             | 136 ++++++++++++++++++
 examples/get_line_value.c                     |  97 +++++++++++++
 examples/toggle_line_value.c                  | 106 ++++++++++++++
 examples/watch_line_value.c                   | 127 ++++++++++++++++
 21 files changed, 1011 insertions(+), 1 deletion(-)
 create mode 100644 bindings/cxx/examples/async_watch_line_value.cpp
 create mode 100644 bindings/cxx/examples/get_line_value.cpp
 create mode 100644 bindings/cxx/examples/toggle_line_value.cpp
 create mode 100644 bindings/cxx/examples/watch_line_value.cpp
 create mode 100755 bindings/python/examples/async_watch_line_value.py
 create mode 100755 bindings/python/examples/get_line_value.py
 create mode 100755 bindings/python/examples/toggle_line_value.py
 create mode 100755 bindings/python/examples/watch_line_value.py
 create mode 100644 bindings/rust/libgpiod/examples/get_line_value.rs
 create mode 100644 bindings/rust/libgpiod/examples/toggle_line_value.rs
 create mode 100644 bindings/rust/libgpiod/examples/watch_line_value.rs
 create mode 100644 examples/.gitignore
 create mode 100644 examples/Makefile.am
 create mode 100644 examples/async_watch_line_value.c
 create mode 100644 examples/get_line_value.c
 create mode 100644 examples/toggle_line_value.c
 create mode 100644 examples/watch_line_value.c
Signature · 1 line
2.40.1
#1 lore raw

PATCH 1/4 core: examples: add dedicated examples

The tools have served as example code, but have become too complicated to serve that purpose.

Add a set of examples that have no purpose other than providing minimal examples of common use cases.

---
 Makefile.am                       |   6 ++
 configure.ac                      |   1 +
 examples/.gitignore               |   7 ++
 examples/Makefile.am              |  17 ++++
 examples/async_watch_line_value.c | 136 ++++++++++++++++++++++++++++++
 examples/get_line_value.c         |  97 +++++++++++++++++++++
 examples/toggle_line_value.c      | 106 +++++++++++++++++++++++
 examples/watch_line_value.c       | 127 ++++++++++++++++++++++++++++
 8 files changed, 497 insertions(+)
 create mode 100644 examples/.gitignore
 create mode 100644 examples/Makefile.am
 create mode 100644 examples/async_watch_line_value.c
 create mode 100644 examples/get_line_value.c
 create mode 100644 examples/toggle_line_value.c
 create mode 100644 examples/watch_line_value.c
Makefile.am +6 -0
index 10d6a9a..941d7e8 100644
@@ -16,6 +16,12 @@ EXTRA_DIST = \
 	LICENSES/LGPL-3.0-or-later.txt \
 	LICENSES/BSD-3-Clause.txt
 
+if WITH_EXAMPLES
+
+SUBDIRS += examples
+
+endif
+
 if WITH_TOOLS
 
 SUBDIRS += tools man
configure.ac +1 -0
index c1005a9..dde2fa5 100644
@@ -268,6 +268,7 @@ AC_CONFIG_FILES([Makefile
 		 lib/Makefile
 		 lib/libgpiod.pc
 		 contrib/Makefile
+		 examples/Makefile
 		 tools/Makefile
 		 tests/Makefile
 		 tests/gpiosim/Makefile
examples/.gitignore new file +7 -0
new file mode 100644
index 0000000..bdfde9a
@@ -0,0 +1,7 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+# SPDX-FileCopyrightText: 2023 Kent Gibson <[email protected]>
+
+async_watch_line_value
+get_line_value
+toggle_line_value
+watch_line_value
examples/Makefile.am new file +17 -0
new file mode 100644
index 0000000..4ad124b
@@ -0,0 +1,17 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+# SPDX-FileCopyrightText: 2023 Kent Gibson <[email protected]>
+
+AM_CFLAGS = -I$(top_srcdir)/include/ -include $(top_builddir)/config.h
+AM_CFLAGS += -Wall -Wextra -g -std=gnu89
+
+LDADD = $(top_builddir)/lib/libgpiod.la
+
+bin_PROGRAMS = async_watch_line_value get_line_value toggle_line_value watch_line_value
+
+async_watch_line_value_SOURCES = async_watch_line_value.c
+
+get_line_value_SOURCES = get_line_value.c
+
+toggle_line_valuer_SOURCES = toggle_line_value.c
+
+watch_line_value_SOURCES = watch_line_value.c
examples/async_watch_line_value.c new file +136 -0

136 lines not on this page · raw message

examples/get_line_value.c new file +97 -0

97 lines not on this page · raw message

examples/toggle_line_value.c new file +106 -0

106 lines not on this page · raw message

examples/watch_line_value.c new file +127 -0

127 lines not on this page · raw message

Signature · 1 line
2.40.1
#2 lore raw

PATCH 2/4 bindings: cxx: examples: add dedicated examples

In reply to Kent Gibson

Add cxx equivalents of the core examples.

---
 bindings/cxx/examples/.gitignore              |  4 +
 bindings/cxx/examples/Makefile.am             | 14 +++-
 .../cxx/examples/async_watch_line_value.cpp   | 78 +++++++++++++++++++
 bindings/cxx/examples/get_line_value.cpp      | 29 +++++++
 bindings/cxx/examples/toggle_line_value.cpp   | 45 +++++++++++
 bindings/cxx/examples/watch_line_value.cpp    | 62 +++++++++++++++
 6 files changed, 231 insertions(+), 1 deletion(-)
 create mode 100644 bindings/cxx/examples/async_watch_line_value.cpp
 create mode 100644 bindings/cxx/examples/get_line_value.cpp
 create mode 100644 bindings/cxx/examples/toggle_line_value.cpp
 create mode 100644 bindings/cxx/examples/watch_line_value.cpp
bindings/cxx/examples/.gitignore +4 -0
index 2209497..268b3f6 100644
@@ -8,3 +8,7 @@ gpioinfocxx
 gpiomoncxx
 gpionotifycxx
 gpiosetcxx
+async_watch_line_value
+get_line_value
+toggle_line_value
+watch_line_value
bindings/cxx/examples/Makefile.am +13 -1
index 36977ef..0213973 100644
@@ -12,7 +12,11 @@ noinst_PROGRAMS = \
 	gpioinfocxx \
 	gpiomoncxx \
 	gpionotifycxx \
-	gpiosetcxx
+	gpiosetcxx \
+	async_watch_line_value \
+	get_line_value \
+	toggle_line_value \
+	watch_line_value
 
 gpiodetectcxx_SOURCES = gpiodetectcxx.cpp
 
@@ -27,3 +31,11 @@ gpiomoncxx_SOURCES = gpiomoncxx.cpp
 gpionotifycxx_SOURCES = gpionotifycxx.cpp
 
 gpiosetcxx_SOURCES = gpiosetcxx.cpp
+
+async_watch_line_value_SOURCES = async_watch_line_value.cpp
+
+get_line_value_SOURCES = get_line_value.cpp
+
+toggle_line_value_SOURCES = toggle_line_value.cpp
+
+watch_line_value_SOURCES = watch_line_value.cpp
bindings/cxx/examples/async_watch_line_value.cpp new file +78 -0

78 lines not on this page · raw message

bindings/cxx/examples/get_line_value.cpp new file +29 -0
new file mode 100644
index 0000000..3e14b56
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+// SPDX-FileCopyrightText: 2023 Kent Gibson <[email protected]>
+
+/* Minimal example of reading a single line. */
+
+#include <cstdlib>
+#include <gpiod.hpp>
+#include <iostream>
+
+int main(void)
+{
+	using ::gpiod::line_settings;
+	/* example configuration - customize to suit your situation */
+	const char *chip_path = "/dev/gpiochip0";
+	int line_offset = 5;
+
+	auto request = ::gpiod::chip(chip_path)
+			       .prepare_request()
+			       .set_consumer("get-line-value")
+			       .add_line_settings(
+				       line_offset,
+				       ::gpiod::line_settings().set_direction(
+					       ::gpiod::line::direction::INPUT))
+			       .do_request();
+
+	::gpiod::line::value value = request.get_value(line_offset);
+	::std::cout << value << ::std::endl;
+	return EXIT_SUCCESS;
+}
bindings/cxx/examples/toggle_line_value.cpp new file +45 -0

45 lines not on this page · raw message

bindings/cxx/examples/watch_line_value.cpp new file +62 -0

62 lines not on this page · raw message

Signature · 1 line
2.40.1
#3 lore raw

PATCH 3/4 bindings: python: examples: add dedicated examples

In reply to Kent Gibson

Add python equivalents of the core examples.

---
 .../python/examples/async_watch_line_value.py | 47 +++++++++++++++++++
 bindings/python/examples/get_line_value.py    | 26 ++++++++++
 bindings/python/examples/toggle_line_value.py | 47 +++++++++++++++++++
 bindings/python/examples/watch_line_value.py  | 42 +++++++++++++++++
 4 files changed, 162 insertions(+)
 create mode 100755 bindings/python/examples/async_watch_line_value.py
 create mode 100755 bindings/python/examples/get_line_value.py
 create mode 100755 bindings/python/examples/toggle_line_value.py
 create mode 100755 bindings/python/examples/watch_line_value.py
bindings/python/examples/async_watch_line_value.py new file +47 -0
new file mode 100755
index 0000000..031a988
@@ -0,0 +1,47 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0-or-later
+# SPDX-FileCopyrightText: 2023 Kent Gibson <[email protected]>
+
+"""Minimal example of asynchronously watching for edges on a single line."""
+
+from datetime import timedelta
+import gpiod
+import select
+
+from gpiod.line import Bias, Edge
+
+def edge_type(event):
+    if event.event_type is event.Type.RISING_EDGE:
+        return "Rising "
+    if event.event_type is event.Type.FALLING_EDGE:
+        return "Falling"
+    return "Unknown"
+
+
+def async_watch_line_value():
+    # example configuration - customise to suit your situation
+    chip_path = '/dev/gpiochip0'
+    line_offset = 5
+
+    # assume a button connecting the pin to ground,
+    # so pull it up and provide some debounce.
+    with gpiod.request_lines(
+        chip_path,
+        consumer="async-watch-line-value",
+        config={line_offset: gpiod.LineSettings(edge_detection=Edge.BOTH,
+                                bias=Bias.PULL_UP,
+                                debounce_period=timedelta(milliseconds=10))},
+    ) as request:
+        poll = select.poll()
+        poll.register(request.fd, select.POLLIN)
+        while True:
+            # other fds could be registered with the poll and be handled
+            # separately using the return value (fd, event) from poll()
+            poll.poll()
+            for event in request.read_edge_events():
+                print("offset: %d, type: %s, event #%d" %
+                      (event.line_offset, edge_type(event), event.line_seqno))
+
+
+if __name__ == "__main__":
+    async_watch_line_value()
bindings/python/examples/get_line_value.py new file +26 -0
new file mode 100755
index 0000000..da9d060
@@ -0,0 +1,26 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0-or-later
+# SPDX-FileCopyrightText: 2023 Kent Gibson <[email protected]>
+
+"""Minimal example of reading a single line."""
+
+import gpiod
+
+from gpiod.line import Direction
+
+def get_line_value():
+    # example configuration - customise to suit your situation
+    chip_path = '/dev/gpiochip0'
+    line_offset = 5
+
+    with gpiod.request_lines(
+        chip_path,
+        consumer="get-line-value",
+        config={line_offset: gpiod.LineSettings(direction=Direction.INPUT)},
+    ) as request:
+        value = request.get_value(line_offset)
+        print(value)
+
+
+if __name__ == "__main__":
+    get_line_value()
bindings/python/examples/toggle_line_value.py new file +47 -0

47 lines not on this page · raw message

bindings/python/examples/watch_line_value.py new file +42 -0

42 lines not on this page · raw message

Signature · 1 line
2.40.1
#4 lore raw

PATCH 4/4 bindings: rust: examples: add dedicated examples

In reply to Kent Gibson

Add rust equivalents of the core examples.

---
 .../rust/libgpiod/examples/get_line_value.rs  | 28 +++++++++++
 .../libgpiod/examples/toggle_line_value.rs    | 43 ++++++++++++++++
 .../libgpiod/examples/watch_line_value.rs     | 50 +++++++++++++++++++
 3 files changed, 121 insertions(+)
 create mode 100644 bindings/rust/libgpiod/examples/get_line_value.rs
 create mode 100644 bindings/rust/libgpiod/examples/toggle_line_value.rs
 create mode 100644 bindings/rust/libgpiod/examples/watch_line_value.rs
bindings/rust/libgpiod/examples/get_line_value.rs new file +28 -0
new file mode 100644
index 0000000..732fb71
@@ -0,0 +1,28 @@
+// SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
+// SPDX-FileCopyrightText: 2023 Kent Gibson <[email protected]>
+//
+// Minimal example of reading a single line.
+
+use libgpiod::line;
+
+fn main() -> libgpiod::Result<()> {
+    // example configuration - customize to suit your situation
+    let chip_path = "/dev/gpiochip0";
+    let line_offset = 5;
+
+    let mut lsettings = line::Settings::new()?;
+    lsettings.set_direction(line::Direction::Input)?;
+
+    let mut lconfig = line::Config::new()?;
+    lconfig.add_line_settings(&[line_offset], lsettings)?;
+
+    let mut rconfig = libgpiod::request::Config::new()?;
+    rconfig.set_consumer("get-line-value")?;
+
+    let chip = libgpiod::chip::Chip::open(&chip_path)?;
+    let request = chip.request_lines(Some(&rconfig), &lconfig)?;
+
+    let value = request.value(line_offset)?;
+    println!("{:?}", value);
+    Ok(())
+}
bindings/rust/libgpiod/examples/toggle_line_value.rs new file +43 -0

43 lines not on this page · raw message

bindings/rust/libgpiod/examples/watch_line_value.rs new file +50 -0

50 lines not on this page · raw message

Signature · 1 line
2.40.1
Reviewed-by on v1 4/4
#5 lore raw

Re: [libgpiod][PATCH 4/4] bindings: rust: examples: add dedicated examples

Quoted 3 lines · Kent Gibson

Add rust equivalents of the core examples.

Some nit-picks below, but those are a matter of taste and the change looks ok either way.

Quoted 15 lines
---
 .../rust/libgpiod/examples/get_line_value.rs  | 28 +++++++++++
 .../libgpiod/examples/toggle_line_value.rs    | 43 ++++++++++++++++
 .../libgpiod/examples/watch_line_value.rs     | 50 +++++++++++++++++++
 3 files changed, 121 insertions(+)
 create mode 100644 bindings/rust/libgpiod/examples/get_line_value.rs
 create mode 100644 bindings/rust/libgpiod/examples/toggle_line_value.rs
 create mode 100644 bindings/rust/libgpiod/examples/watch_line_value.rs
bindings/rust/libgpiod/examples/get_line_value.rs new file +0 -0
new file mode 100644
index 0000000..732fb71

bindings/rust/libgpiod/examples/get_line_value.rs line 6

Quoted 6 lines
bindings/rust/libgpiod/examples/get_line_value.rs new file +6 -0
@@ -0,0 +1,28 @@
+// SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
+// SPDX-FileCopyrightText: 2023 Kent Gibson <[email protected]>
+//
+// Minimal example of reading a single line.
+
+use libgpiod::line;

I think one could also just import the other used modules. Or, since this is an example anyway, just use libgpiod::*.

bindings/rust/libgpiod/examples/get_line_value.rs line 13

Quoted 7 lines
bindings/rust/libgpiod/examples/get_line_value.rs new file +7 -0
+
+fn main() -> libgpiod::Result<()> {
+    // example configuration - customize to suit your situation
+    let chip_path = "/dev/gpiochip0";
+    let line_offset = 5;
+
+    let mut lsettings = line::Settings::new()?;

I think line_settings would still be an okish length (same below) :).

bindings/rust/libgpiod/examples/get_line_value.rs line 26

Quoted 13 lines
bindings/rust/libgpiod/examples/get_line_value.rs new file +13 -0
+    lsettings.set_direction(line::Direction::Input)?;
+
+    let mut lconfig = line::Config::new()?;
+    lconfig.add_line_settings(&[line_offset], lsettings)?;
+
+    let mut rconfig = libgpiod::request::Config::new()?;
+    rconfig.set_consumer("get-line-value")?;
+
+    let chip = libgpiod::chip::Chip::open(&chip_path)?;
+    let request = chip.request_lines(Some(&rconfig), &lconfig)?;
+
+    let value = request.value(line_offset)?;
+    println!("{:?}", value);

Could also be:
+ println!("{value:?}");
(same below)

Quoted 94 lines
bindings/rust/libgpiod/examples/get_line_value.rs new file +2 -0
+    Ok(())
+}
bindings/rust/libgpiod/examples/toggle_line_value.rs new file +43 -0
new file mode 100644
index 0000000..cd7038e
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
+// SPDX-FileCopyrightText: 2023 Kent Gibson <[email protected]>
+//
+// Minimal example of toggling a single line.
+
+use libgpiod::line;
+use std::time::Duration;
+
+fn toggle_value(value: line::Value) -> line::Value {
+    match value {
+        line::Value::Active => line::Value::InActive,
+        line::Value::InActive => line::Value::Active,
+    }
+}
+
+fn main() -> libgpiod::Result<()> {
+    // example configuration - customize to suit your situation
+    let chip_path = "/dev/gpiochip0";
+    let line_offset = 5;
+
+    let mut value = line::Value::Active;
+
+    let mut settings = line::Settings::new()?;
+    settings
+        .set_direction(line::Direction::Output)?
+        .set_output_value(value)?;
+
+    let mut lconfig = line::Config::new()?;
+    lconfig.add_line_settings(&[line_offset], settings)?;
+
+    let mut rconfig = libgpiod::request::Config::new()?;
+    rconfig.set_consumer("toggle-line-value")?;
+
+    let chip = libgpiod::chip::Chip::open(&chip_path)?;
+    let mut req = chip.request_lines(Some(&rconfig), &lconfig)?;
+
+    loop {
+        println!("{:?}", value);
+        std::thread::sleep(Duration::from_secs(1));
+        value = toggle_value(value);
+        req.set_value(line_offset, value)?;
+    }
+}
bindings/rust/libgpiod/examples/watch_line_value.rs new file +37 -0
new file mode 100644
index 0000000..5a95b6a
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
+// SPDX-FileCopyrightText: 2023 Kent Gibson <[email protected]>
+//
+// Minimal example of watching for edges on a single line.
+
+use libgpiod::line;
+use std::time::Duration;
+
+fn main() -> libgpiod::Result<()> {
+    // example configuration - customize to suit your situation
+    let chip_path = "/dev/gpiochip0";
+    let line_offset = 5;
+
+    let mut lsettings = line::Settings::new()?;
+    // assume a button connecting the pin to ground,
+    // so pull it up and provide some debounce.
+    lsettings
+        .set_edge_detection(Some(line::Edge::Both))?
+        .set_bias(Some(line::Bias::PullUp))?
+        .set_debounce_period(Duration::from_millis(10));
+
+    let mut lconfig = line::Config::new()?;
+    lconfig.add_line_settings(&[line_offset], lsettings)?;
+
+    let mut rconfig = libgpiod::request::Config::new()?;
+    rconfig.set_consumer("watch-line-value")?;
+
+    let chip = libgpiod::chip::Chip::open(&chip_path)?;
+    let request = chip.request_lines(Some(&rconfig), &lconfig)?;
+
+    // a larger buffer is an optimisation for reading bursts of events from the
+    // kernel, but that is not necessary in this case, so 1 is fine.
+    let mut buffer = libgpiod::request::Buffer::new(1)?;
+    loop {
+        // blocks until at least one event is available
+        let events = request.read_edge_events(&mut buffer)?;
+        for event in events {

bindings/rust/libgpiod/examples/watch_line_value.rs line 47

Quoted 10 lines
bindings/rust/libgpiod/examples/watch_line_value.rs new file +10 -0
+            let event = event?;
+            println!(
+                "line: {}, type: {}, event #{}",
+                event.line_offset(),
+                match event.event_type()? {
+                    line::EdgeKind::Rising => "Rising ",
+                    line::EdgeKind::Falling => "Falling",
+                },
+                event.line_seqno()
+            );

println!("{: <8}") could also be used to pad things (would allow removing the trailing space).

Quoted 5 lines
bindings/rust/libgpiod/examples/watch_line_value.rs new file +3 -0
+        }
+    }
+}
Signature · 1 line
2.40.1

- Erik

#6 lore raw

Re: [libgpiod][PATCH 4/4] bindings: rust: examples: add dedicated examples

Quoted 7 lines · Erik Schilling
Quoted 3 lines · Kent Gibson

Add rust equivalents of the core examples.

Quoted 9 lines

Some nit-picks below, but those are a matter of taste and the change looks ok either way.

Review

Quoted 2 lines
(quoted diff) +2 -0
+
+use libgpiod::line;

I think one could also just import the other used modules. Or, since this is an example anyway, just use libgpiod::*.

I'm never keen on using ::*, as subsequent changes could pull in symbols that conflict with locals.

And as this is an example I wanted to be explicit as to where the symbols originate, especially as there is some overlap, e.g. line::Config and request::Config.
The general rule is, if it is only used once then use the full name. But there are so many line attributes that using the slightly shortened form made it more readable.

Quoted 8 lines

bindings/rust/libgpiod/examples/get_line_value.rs line 26

Quoted 3 lines
bindings/rust/libgpiod/examples/get_line_value.rs new file +3 -0
+
+    let value = request.value(line_offset)?;
+    println!("{:?}", value);

Could also be:
+ println!("{value:?}");
(same below)

Fair enough. I'm old school so I tend to prefer printf style.

Quoted 9 lines

bindings/rust/libgpiod/examples/watch_line_value.rs line 47

Quoted 8 lines
bindings/rust/libgpiod/examples/watch_line_value.rs new file +8 -0
+                "line: {}, type: {}, event #{}",
+                event.line_offset(),
+                match event.event_type()? {
+                    line::EdgeKind::Rising => "Rising ",
+                    line::EdgeKind::Falling => "Falling",
+                },
+                event.line_seqno()
+            );
Quoted 3 lines

println!("{: <8}") could also be used to pad things (would allow removing the trailing space).

So add 4 chars to remove 1?

Ideally the padding would go after the comma, and then you start getting into compound fields, so this was a case of KISS.

Cheers,
Kent.

#7 lore raw

Re: [libgpiod][PATCH 4/4] bindings: rust: examples: add dedicated examples

Quoted 21 lines · Kent Gibson
Quoted 7 lines · Erik Schilling
Quoted 3 lines · Kent Gibson

Add rust equivalents of the core examples.

Quoted 9 lines

Some nit-picks below, but those are a matter of taste and the change looks ok either way.

Review

Quoted 2 lines
(quoted diff) +2 -0
+
+use libgpiod::line;

I think one could also just import the other used modules. Or, since this is an example anyway, just use libgpiod::*.

I'm never keen on using ::*, as subsequent changes could pull in symbols that conflict with locals.

Quoted 6 lines

And as this is an example I wanted to be explicit as to where the symbols originate, especially as there is some overlap, e.g. line::Config and request::Config.
The general rule is, if it is only used once then use the full name. But there are so many line attributes that using the slightly shortened form made it more readable.

Yeah, I assumed that you followed this rule. Fine with me.

Quoted 9 lines
Quoted 9 lines
Quoted 8 lines
bindings/rust/libgpiod/examples/watch_line_value.rs new file +8 -0
+                "line: {}, type: {}, event #{}",
+                event.line_offset(),
+                match event.event_type()? {
+                    line::EdgeKind::Rising => "Rising ",
+                    line::EdgeKind::Falling => "Falling",
+                },
+                event.line_seqno()
+            );
Quoted 8 lines
Quoted 3 lines

println!("{: <8}") could also be used to pad things (would allow removing the trailing space).

So add 4 chars to remove 1?

Ideally the padding would go after the comma, and then you start getting into compound fields, so this was a case of KISS.

As I said, may be a matter of taste. I am fine with either way (thats why I already provided the Review tag). The extra " " just jumped to my eye since with rustfmt it is not aligned in a way that made it immediately obvious.

- Erik

#8 lore raw
In reply to Kent Gibson
Quoted 102 lines · Kent Gibson

This series forms the basis of a proposal to rework the libgpiod examples.

IMHO, the examples have a number of issues including:
- no C examples other than the tools - which have become too complicated to be fit for that purpose.
- bindings examples focus on simplifications of the tools rather than demonstrating typical use cases.
- being more complex than necessary to demonstrate a particular use case.
- naming that does not help new users identify the example that demonstrates a particular use case.

To address these issues I propose adding a set of dedicated examples, each of which demonstrates one primary use case with as little additional fat as possible. Each example should be named after the use case it demonstrates. Each examples should be implemented for all supported languages, to provide examples for users considering language choice and for developers to compare the APIs and identify areas for improvement.

The examples are explicitly intended to answer "how do I use libgpiod to do xxx" questions, with as few distractions as possible.

The examples may demonstrate ancillary features, as long as that is relevant to the primary use case. e.g. the watch_line_value examples set the line bias and debounce.

The examples should hard code input parameters, not pull them from the command line or environment, as that is distracting and frequently more complicated than the example itself.

The examples should be standalone - they should not share code. Large chunks of shared code are an indicator that libgpiod probably needs to provide additional functionality to simplify use cases.

The examples are not intended to be distributed in binary form, but could be incorporated into the documentation.

The set of examples provided is a starter set that answer the following questions:
- how do you get the value of a line?
- how do you set the value of a line?
- how do you watch for edge events on a line?
- how do you watch for edge events asynchronously (e.g. using poll())?

I didn't add the latter in Rust as that should be done using one of the many available async reactors and I didn't want to pick one or pull in any dependencies.

I expect that this proposal may be contraversial, and that is one of the reasons I've kept the starter set small.

Cheers,
Kent.

Kent Gibson (4):
core: examples: add dedicated examples
bindings: cxx: examples: add dedicated examples
bindings: python: examples: add dedicated examples
bindings: rust: examples: add dedicated examples

 Makefile.am                                   |   6 +
 bindings/cxx/examples/.gitignore              |   4 +
 bindings/cxx/examples/Makefile.am             |  14 +-
 .../cxx/examples/async_watch_line_value.cpp   |  78 ++++++++++
 bindings/cxx/examples/get_line_value.cpp      |  29 ++++
 bindings/cxx/examples/toggle_line_value.cpp   |  45 ++++++
 bindings/cxx/examples/watch_line_value.cpp    |  62 ++++++++
 .../python/examples/async_watch_line_value.py |  47 ++++++
 bindings/python/examples/get_line_value.py    |  26 ++++
 bindings/python/examples/toggle_line_value.py |  47 ++++++
 bindings/python/examples/watch_line_value.py  |  42 ++++++
 .../rust/libgpiod/examples/get_line_value.rs  |  28 ++++
 .../libgpiod/examples/toggle_line_value.rs    |  43 ++++++
 .../libgpiod/examples/watch_line_value.rs     |  50 +++++++
 configure.ac                                  |   1 +
 examples/.gitignore                           |   7 +
 examples/Makefile.am                          |  17 +++
 examples/async_watch_line_value.c             | 136 ++++++++++++++++++
 examples/get_line_value.c                     |  97 +++++++++++++
 examples/toggle_line_value.c                  | 106 ++++++++++++++
 examples/watch_line_value.c                   | 127 ++++++++++++++++
 21 files changed, 1011 insertions(+), 1 deletion(-)
 create mode 100644 bindings/cxx/examples/async_watch_line_value.cpp
 create mode 100644 bindings/cxx/examples/get_line_value.cpp
 create mode 100644 bindings/cxx/examples/toggle_line_value.cpp
 create mode 100644 bindings/cxx/examples/watch_line_value.cpp
 create mode 100755 bindings/python/examples/async_watch_line_value.py
 create mode 100755 bindings/python/examples/get_line_value.py
 create mode 100755 bindings/python/examples/toggle_line_value.py
 create mode 100755 bindings/python/examples/watch_line_value.py
 create mode 100644 bindings/rust/libgpiod/examples/get_line_value.rs
 create mode 100644 bindings/rust/libgpiod/examples/toggle_line_value.rs
 create mode 100644 bindings/rust/libgpiod/examples/watch_line_value.rs
 create mode 100644 examples/.gitignore
 create mode 100644 examples/Makefile.am
 create mode 100644 examples/async_watch_line_value.c
 create mode 100644 examples/get_line_value.c
 create mode 100644 examples/toggle_line_value.c
 create mode 100644 examples/watch_line_value.c
Quoted 3 lines

--
2.40.1

Great idea! I applied patches 1-3 with some tweaks (coding style, C++ comments, statify functions, put local functions into anonymous namespaces for C++, apply black to python code etc. etc.).

You can respin the rust patch separately.

Thanks
Bart

#9 lore raw
Quoted 6 lines · Bartosz Golaszewski
Quoted 1 line

Great idea! I applied patches 1-3 with some tweaks (coding style, C++ comments, statify functions, put local functions into anonymous namespaces for C++, apply black to python code etc. etc.).

Ok. Would've been nice to get review comments before having changes pulled straight in, but whatever.

Requiring C style comments in C++ is just weird.

Quoted 2 lines

You can respin the rust patch separately.

And what would you like respun there?

Cheers,
Kent.

#10 lore raw
Quoted 4 lines · Kent Gibson
Quoted 2 lines · Bartosz Golaszewski
Quoted 1 line
Quoted 8 lines
Quoted 4 lines

Great idea! I applied patches 1-3 with some tweaks (coding style, C++ comments, statify functions, put local functions into anonymous namespaces for C++, apply black to python code etc. etc.).

Ok. Would've been nice to get review comments before having changes pulled straight in, but whatever.

No functional changes. I wanted to avoid bikeshedding over coding style etc.

Quoted 7 lines

Requiring C style comments in C++ is just weird.

Quoted 2 lines

You can respin the rust patch separately.

And what would you like respun there?

I saw comments from Erik and though you'd need a v2 but as it's mostly a matter of taste, I'll apply it as is.

Bart

Quoted 2 lines

Cheers,
Kent.

#11 lore raw
Quoted 9 lines · Bartosz Golaszewski
Quoted 8 lines · Kent Gibson
Quoted 6 lines · Bartosz Golaszewski
Quoted 1 line

Great idea! I applied patches 1-3 with some tweaks (coding style, C++ comments, statify functions, put local functions into anonymous namespaces for C++, apply black to python code etc. etc.).

Any opinions on where to go next?
Other use cases to add - e.g. multi-line versions?
Convert the tool examples to use case examples? Or do you still want to distribute the binaries for those?
Any functionality to add to libgpiod?

Cheers,
Kent.

#12 lore raw
Quoted 7 lines · Kent Gibson
Quoted 5 lines · Bartosz Golaszewski
Quoted 4 lines · Kent Gibson
Quoted 2 lines · Bartosz Golaszewski
Quoted 1 line
Quoted 8 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

Great idea! I applied patches 1-3 with some tweaks (coding style, C++ comments, statify functions, put local functions into anonymous namespaces for C++, apply black to python code etc. etc.).

Any opinions on where to go next?
Other use cases to add - e.g. multi-line versions?

Sure, I don't see why not.

Quoted 2 lines

Convert the tool examples to use case examples? Or do you still want to distribute the binaries for those?

No, the examples are built but not installed. And yes, if you have the time and will to convert them to something more useful, please do!

Quoted 2 lines

Any functionality to add to libgpiod?

I don't think so at the moment. Do you see anything obvious? I know, we spoke about putting the line resolver into libgpiod but I'm not sure we really want it. At least in the core library anyway. The GLib layer on top of libgpiod is a place that would be a good target for such a functionality IMO.

Other than that, I think libgpiod now has everything it needs to cover all use-cases for the uAPI.

Bart

Quoted 2 lines

Cheers,
Kent.

#13 lore raw
Quoted 11 lines · Bartosz Golaszewski
Quoted 3 lines · Kent Gibson

Any functionality to add to libgpiod?

I don't think so at the moment. Do you see anything obvious? I know, we spoke about putting the line resolver into libgpiod but I'm not sure we really want it. At least in the core library anyway. The GLib layer on top of libgpiod is a place that would be a good target for such a functionality IMO.

Yeah, making the line resolver generally available is a can of worms. Not prepared to take that one on at the moment.
I'm reasonably content to leave that to the user - as long as they can readily iterate over the chips and lines themselves.
Maybe provide an iterator for all the lines in the system available to the user?

Quoted 3 lines

Other than that, I think libgpiod now has everything it needs to cover all use-cases for the uAPI.

The point isn't that coverage is missing, it is to find ways to make common tasks simpler.

The ones that spring to mind so far are:
- C: requesting a single line as output
- C: requesting a single line as input
- providing a toggle function for line_value, as it is an enum which is a bit awkward.
- the chip iterator in the python tools helpers.py
- streaming operators for the enums where they are not automatically provided

The C ones are specifically for simple sysfs-like equivalence, as telling users they need to replace a single write to a file with ~100 lines of C is really hard to sell.
The config options would be as minimal as possible.
I was going to suggest the user could always reconfigure the line later if they need extra features, but there is no function to return the existing line config :-(.

Cheers,
Kent.

#14 lore raw
Quoted 38 lines · Kent Gibson
Quoted 11 lines · Bartosz Golaszewski
Quoted 3 lines · Kent Gibson

Any functionality to add to libgpiod?

I don't think so at the moment. Do you see anything obvious? I know, we spoke about putting the line resolver into libgpiod but I'm not sure we really want it. At least in the core library anyway. The GLib layer on top of libgpiod is a place that would be a good target for such a functionality IMO.

Yeah, making the line resolver generally available is a can of worms. Not prepared to take that one on at the moment.
I'm reasonably content to leave that to the user - as long as they can readily iterate over the chips and lines themselves.
Maybe provide an iterator for all the lines in the system available to the user?

Quoted 3 lines

Other than that, I think libgpiod now has everything it needs to cover all use-cases for the uAPI.

The point isn't that coverage is missing, it is to find ways to make common tasks simpler.

The ones that spring to mind so far are:
- C: requesting a single line as output
- C: requesting a single line as input
- providing a toggle function for line_value, as it is an enum which is a bit awkward.
- the chip iterator in the python tools helpers.py
- streaming operators for the enums where they are not automatically provided

Quoted 3 lines

The C ones are specifically for simple sysfs-like equivalence, as telling users they need to replace a single write to a file with ~100 lines of C is really hard to sell.

You don't really need 100 LOC for a trivial request in C (it's a bit over-dramatic :) ) but my thinking is: whether it's 5 lines or 10 or 100 - it doesn't change the fact that it is a fundamental change from sysfs in that you need to write the code, compile it, link it against the right libraries etc. etc. It will be so much more work no matter how much you simplify the API and that is already enough to scare away a lot of folks used to just writing to a bunch of files.

This is why I'm proposing the DBus API as a way of replacing several features of sysfs that are so beloved by users: central authority over GPIOs, easy to use from shell scripts (just replace "echo 223 > export; echo output > 223/direction" etc. with "gdbus call --system --dest io.gpiod1 --object-path /io/gpiod1/gpiochip2 --method io.gpiod1.Chip.RequestLines <args>" which is just a tiny bit more verbose but achieves the same goal and exposes all uAPI v2 features) and only requires including the dbus daemon in your system which would be packaged by most distros shipping libgpiod eventually. DBus has the advantage of being usable from any language you fancy and still being relatively fast.

In other words, I'm thinking that packing a lot of "helper" features into libgpiod will only lead to feature creep but not achieve the goal of pulling people away from sysfs.

Bart

Quoted 7 lines

The config options would be as minimal as possible.
I was going to suggest the user could always reconfigure the line later if they need extra features, but there is no function to return the existing line config :-(.

Cheers,
Kent.

#15 lore raw
Quoted 6 lines · Bartosz Golaszewski
Quoted 4 lines · Kent Gibson

The C ones are specifically for simple sysfs-like equivalence, as telling users they need to replace a single write to a file with ~100 lines of C is really hard to sell.

Quoted 8 lines

You don't really need 100 LOC for a trivial request in C (it's a bit over-dramatic :) ) but my thinking is: whether it's 5 lines or 10 or 100 - it doesn't change the fact that it is a fundamental change from sysfs in that you need to write the code, compile it, link it against the right libraries etc. etc. It will be so much more work no matter how much you simplify the API and that is already enough to scare away a lot of folks used to just writing to a bunch of files.

Sure - those using scripts would probably go for Python anyway. But no one in their right mind would elect to use the C API given the alternatives, which makes it basically pointless.

Quoted 12 lines

This is why I'm proposing the DBus API as a way of replacing several features of sysfs that are so beloved by users: central authority over GPIOs, easy to use from shell scripts (just replace "echo 223 > export; echo output > 223/direction" etc. with "gdbus call --system --dest io.gpiod1 --object-path /io/gpiod1/gpiochip2 --method io.gpiod1.Chip.RequestLines <args>" which is just a tiny bit more verbose but achieves the same goal and exposes all uAPI v2 features) and only requires including the dbus daemon in your system which would be packaged by most distros shipping libgpiod eventually. DBus has the advantage of being usable from any language you fancy and still being relatively fast.

Quoted 4 lines

In other words, I'm thinking that packing a lot of "helper" features into libgpiod will only lead to feature creep but not achieve the goal of pulling people away from sysfs.

And you think I'm exaggerating.
Removing a few pain points is not "packing a lot of "helper" features".

Cheers,
Kent.