From patchwork Wed Jun 14 03:54:23 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Kent Gibson X-Patchwork-Id: 1794808 Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@legolas.ozlabs.org Authentication-Results: legolas.ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=vger.kernel.org (client-ip=2620:137:e000::1:20; helo=out1.vger.email; envelope-from=linux-gpio-owner@vger.kernel.org; receiver=) Authentication-Results: legolas.ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20221208 header.b=r//pll9V; dkim-atps=neutral Received: from out1.vger.email (out1.vger.email [IPv6:2620:137:e000::1:20]) by legolas.ozlabs.org (Postfix) with ESMTP id 4Qgs556w82z20Xd for ; Wed, 14 Jun 2023 13:55:05 +1000 (AEST) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S231878AbjFNDzE (ORCPT ); Tue, 13 Jun 2023 23:55:04 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:55912 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229783AbjFNDzD (ORCPT ); Tue, 13 Jun 2023 23:55:03 -0400 Received: from mail-pg1-x533.google.com (mail-pg1-x533.google.com [IPv6:2607:f8b0:4864:20::533]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 6DF81C2 for ; Tue, 13 Jun 2023 20:55:01 -0700 (PDT) Received: by mail-pg1-x533.google.com with SMTP id 41be03b00d2f7-54f87d5f1abso1733232a12.0 for ; Tue, 13 Jun 2023 20:55:01 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20221208; t=1686714896; x=1689306896; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=lPEVNoMAUXuTCCovRsFfa/0BThxmBEVnBPBOpQtkC4M=; b=r//pll9V4wIN0d5LdPb3gUhPGkm6aNggMCQXBUXGjK1YQoUifjy29jlNT4JMAVQ5AH Hwd5Bw4VNrkXt75i6Km/GJuKjgCFYLv0Zko6/4WP+dxfkjOdYWqmtDNzh0VtDOaZvisK 12BeH5DeOmgZazyU+XBEvBeFXSwV4oKce5FzpvSdXwGwqn4m7CiBq2OigEjdFFqmM60O I8XtBsG+gVk863Lq+/aw+nyuivlqZii+92k9uOe9YQ10eL74hIZ9jFj2bH8x2e+Cak/c s0tUqF5UZRp7UYq2VTP38hm1uvj1FjHQNkWNf5hoS2S9lKV59Kjx5j14SnQ5cKbs8twH MRCA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20221208; t=1686714896; x=1689306896; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=lPEVNoMAUXuTCCovRsFfa/0BThxmBEVnBPBOpQtkC4M=; b=jj7bPkafdEKEeXS7Eo68xqgGPDhajL7LsB5rg5lxQ82TjPUiMPKQIycJqc/U7bjEHE tldkLJsF4uwzYBtgvoUOOGLOOiNvvhw/UVSGJNzBNJunhqS3fLBCFlPNVO90Yx3mPJbU tKuOXJL2i1TWO147r4MWGVvGAHfzHhvHfwteTP4N53CWnBqj9wc7GbAI/TctRnwn/Kad //FC6H+CNBlRqB7bRYRGKqaTZmAIwalmwrhwqAbtRAhQY5AlIaksLyCSpIPW6gEzK6cJ DXkyCWlOVg92n7FNlXEGBJWx5Gz3HGwvKBFsDYRs5ApOr5LBi0pwvOddWiKyx3HLyg3k Z8VQ== X-Gm-Message-State: AC+VfDxKfBQXjktPjURoxkedS5LF/vX7YcsEIIE38KvCGS2y8GN3Md/Y xEYMrzs399V6uwqBC7E4dEC//or3GSY= X-Google-Smtp-Source: ACHHUZ65v24yGZ9jMXs5fR7A7Jb+ANw49aE+E8U42C/HlplBKSXcW4hekxyC2zqK6PaL/9bShBT1jA== X-Received: by 2002:a05:6a21:2c8a:b0:10f:500b:18a2 with SMTP id ua10-20020a056a212c8a00b0010f500b18a2mr361478pzb.48.1686714895743; Tue, 13 Jun 2023 20:54:55 -0700 (PDT) Received: from sol.home.arpa (194-223-178-180.tpgi.com.au. [194.223.178.180]) by smtp.gmail.com with ESMTPSA id l12-20020a170903120c00b001ae6fe84244sm10967412plh.243.2023.06.13.20.54.53 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 13 Jun 2023 20:54:55 -0700 (PDT) From: Kent Gibson To: linux-gpio@vger.kernel.org, brgl@bgdev.pl Cc: Kent Gibson Subject: [libgpiod][PATCH 1/4] core: examples: add dedicated examples Date: Wed, 14 Jun 2023 11:54:23 +0800 Message-Id: <20230614035426.15097-2-warthog618@gmail.com> X-Mailer: git-send-email 2.40.1 In-Reply-To: <20230614035426.15097-1-warthog618@gmail.com> References: <20230614035426.15097-1-warthog618@gmail.com> MIME-Version: 1.0 X-Spam-Status: No, score=-1.9 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_ENVFROM_END_DIGIT, FREEMAIL_FROM,RCVD_IN_DNSWL_NONE,SPF_HELO_NONE,SPF_PASS, T_SCC_BODY_TEXT_LINE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-gpio@vger.kernel.org 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. Signed-off-by: Kent Gibson --- 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 diff --git a/Makefile.am b/Makefile.am index 10d6a9a..941d7e8 100644 --- a/Makefile.am +++ b/Makefile.am @@ -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 diff --git a/configure.ac b/configure.ac index c1005a9..dde2fa5 100644 --- a/configure.ac +++ b/configure.ac @@ -268,6 +268,7 @@ AC_CONFIG_FILES([Makefile lib/Makefile lib/libgpiod.pc contrib/Makefile + examples/Makefile tools/Makefile tests/Makefile tests/gpiosim/Makefile diff --git a/examples/.gitignore b/examples/.gitignore new file mode 100644 index 0000000..bdfde9a --- /dev/null +++ b/examples/.gitignore @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# SPDX-FileCopyrightText: 2023 Kent Gibson + +async_watch_line_value +get_line_value +toggle_line_value +watch_line_value diff --git a/examples/Makefile.am b/examples/Makefile.am new file mode 100644 index 0000000..4ad124b --- /dev/null +++ b/examples/Makefile.am @@ -0,0 +1,17 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# SPDX-FileCopyrightText: 2023 Kent Gibson + +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 diff --git a/examples/async_watch_line_value.c b/examples/async_watch_line_value.c new file mode 100644 index 0000000..de15c97 --- /dev/null +++ b/examples/async_watch_line_value.c @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// SPDX-FileCopyrightText: 2023 Kent Gibson + +/* Minimal example of asynchronously watching for edges on a single line */ + +#include +#include +#include +#include +#include +#include + +/* request a line as input with edge detection */ +struct gpiod_line_request *request_input_line(const char *chip_path, + unsigned int offset, + const char *consumer) +{ + struct gpiod_line_settings *settings; + struct gpiod_line_request *request = NULL; + struct gpiod_request_config *req_cfg = NULL; + struct gpiod_line_config *line_cfg; + struct gpiod_chip *chip; + int ret; + + chip = gpiod_chip_open(chip_path); + if (!chip) + return NULL; + + settings = gpiod_line_settings_new(); + if (!settings) + goto close_chip; + + gpiod_line_settings_set_direction(settings, GPIOD_LINE_DIRECTION_INPUT); + gpiod_line_settings_set_edge_detection(settings, GPIOD_LINE_EDGE_BOTH); + /* assume a button connecting the pin to ground, so pull it up... */ + gpiod_line_settings_set_bias(settings, GPIOD_LINE_BIAS_PULL_UP); + /* ... and provide some debounce. */ + gpiod_line_settings_set_debounce_period_us(settings, 10000); + + line_cfg = gpiod_line_config_new(); + if (!line_cfg) + goto free_settings; + + ret = gpiod_line_config_add_line_settings(line_cfg, &offset, 1, + settings); + if (ret) + goto free_line_config; + + if (consumer) { + req_cfg = gpiod_request_config_new(); + if (!req_cfg) + goto free_line_config; + + gpiod_request_config_set_consumer(req_cfg, consumer); + } + + request = gpiod_chip_request_lines(chip, req_cfg, line_cfg); + + gpiod_request_config_free(req_cfg); +free_line_config: + gpiod_line_config_free(line_cfg); +free_settings: + gpiod_line_settings_free(settings); +close_chip: + gpiod_chip_close(chip); + + return request; +} + +const char *edge_event_type_str(struct gpiod_edge_event *event) +{ + enum gpiod_edge_event_type eet = gpiod_edge_event_get_event_type(event); + + if (eet == GPIOD_EDGE_EVENT_RISING_EDGE) + return "Rising "; + if (eet == GPIOD_EDGE_EVENT_FALLING_EDGE) + return "Falling"; + return "Unknown"; +} + +int main(void) +{ + struct gpiod_line_request *request; + struct gpiod_edge_event_buffer *event_buffer; + struct gpiod_edge_event *event; + struct pollfd pollfd; + int i, ret, event_buf_size; + /* example configuration - customize to suit your situation */ + const char *chip_path = "/dev/gpiochip0"; + int line_offset = 5; + + request = request_input_line(chip_path, line_offset, + "async-watch-line-value"); + if (!request) { + fprintf(stderr, "failed to request line: %s\n", + strerror(errno)); + return EXIT_FAILURE; + } + + /* 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. + */ + event_buf_size = 1; + event_buffer = gpiod_edge_event_buffer_new(event_buf_size); + if (!event_buffer) { + fprintf(stderr, "failed to create event buffer: %s\n", + strerror(errno)); + return EXIT_FAILURE; + } + + pollfd.fd = gpiod_line_request_get_fd(request); + pollfd.events = POLLIN; + while (1) { + ret = poll(&pollfd, 1, -1); + if (ret == -1) { + fprintf(stderr, "error waiting for edge events: %s\n", + strerror(errno)); + return EXIT_FAILURE; + } + ret = gpiod_line_request_read_edge_events(request, event_buffer, + event_buf_size); + if (ret == -1) { + fprintf(stderr, "error reading edge events: %s\n", + strerror(errno)); + return EXIT_FAILURE; + } + for (i = 0; i < ret; i++) { + event = gpiod_edge_event_buffer_get_event(event_buffer, + i); + printf("offset: %d, type: %s, event #%ld\n", + gpiod_edge_event_get_line_offset(event), + edge_event_type_str(event), + gpiod_edge_event_get_line_seqno(event)); + } + } +} diff --git a/examples/get_line_value.c b/examples/get_line_value.c new file mode 100644 index 0000000..fc96a5b --- /dev/null +++ b/examples/get_line_value.c @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// SPDX-FileCopyrightText: 2023 Kent Gibson + +/* Minimal example of reading a single line. */ + +#include +#include +#include +#include +#include + +/* request a line as input */ +struct gpiod_line_request *request_input_line(const char *chip_path, + unsigned int offset, + const char *consumer) +{ + struct gpiod_line_settings *settings; + struct gpiod_line_request *request = NULL; + struct gpiod_request_config *req_cfg = NULL; + struct gpiod_line_config *line_cfg; + struct gpiod_chip *chip; + int ret; + + chip = gpiod_chip_open(chip_path); + if (!chip) + return NULL; + + settings = gpiod_line_settings_new(); + if (!settings) + goto close_chip; + + gpiod_line_settings_set_direction(settings, GPIOD_LINE_DIRECTION_INPUT); + + line_cfg = gpiod_line_config_new(); + if (!line_cfg) + goto free_settings; + + ret = gpiod_line_config_add_line_settings(line_cfg, &offset, 1, + settings); + if (ret) + goto free_line_config; + + if (consumer) { + req_cfg = gpiod_request_config_new(); + if (!req_cfg) + goto free_line_config; + + gpiod_request_config_set_consumer(req_cfg, consumer); + } + + request = gpiod_chip_request_lines(chip, req_cfg, line_cfg); + + gpiod_request_config_free(req_cfg); +free_line_config: + gpiod_line_config_free(line_cfg); +free_settings: + gpiod_line_settings_free(settings); +close_chip: + gpiod_chip_close(chip); + + return request; +} + +int print_value(enum gpiod_line_value value) +{ + if (value == GPIOD_LINE_VALUE_ACTIVE) + printf("Active\n"); + else if (value == GPIOD_LINE_VALUE_INACTIVE) { + printf("Inactive\n"); + } else { + fprintf(stderr, "error reading value: %s\n", + strerror(errno)); + return EXIT_FAILURE; + } + return EXIT_SUCCESS; +} + +int main(void) +{ + struct gpiod_line_request *request; + enum gpiod_line_value value; + int ret; + /* example configuration - customize to suit your situation */ + const char *chip_path = "/dev/gpiochip0"; + int line_offset = 5; + + request = request_input_line(chip_path, line_offset, "get-line-value"); + if (!request) { + fprintf(stderr, "failed to request line: %s\n", + strerror(errno)); + return EXIT_FAILURE; + } + + value = gpiod_line_request_get_value(request, line_offset); + ret = print_value(value); + return ret; +} diff --git a/examples/toggle_line_value.c b/examples/toggle_line_value.c new file mode 100644 index 0000000..ada163e --- /dev/null +++ b/examples/toggle_line_value.c @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// SPDX-FileCopyrightText: 2023 Kent Gibson + +/* Minimal example of toggling a single line. */ + +#include +#include +#include +#include +#include +#include + +struct gpiod_line_request *request_output_line(const char *chip_path, + unsigned int offset, + enum gpiod_line_value value, + const char *consumer) +{ + struct gpiod_line_settings *settings; + struct gpiod_line_request *request = NULL; + struct gpiod_request_config *req_cfg = NULL; + struct gpiod_line_config *line_cfg; + struct gpiod_chip *chip; + int ret; + + chip = gpiod_chip_open(chip_path); + if (!chip) + return NULL; + + settings = gpiod_line_settings_new(); + if (!settings) + goto close_chip; + + gpiod_line_settings_set_direction(settings, + GPIOD_LINE_DIRECTION_OUTPUT); + gpiod_line_settings_set_output_value(settings, value); + + line_cfg = gpiod_line_config_new(); + if (!line_cfg) + goto free_settings; + + ret = gpiod_line_config_add_line_settings(line_cfg, &offset, 1, + settings); + if (ret) + goto free_settings; + + if (consumer) { + req_cfg = gpiod_request_config_new(); + if (!req_cfg) + goto free_line_config; + + gpiod_request_config_set_consumer(req_cfg, consumer); + } + + request = gpiod_chip_request_lines(chip, req_cfg, line_cfg); + + gpiod_request_config_free(req_cfg); +free_line_config: + gpiod_line_config_free(line_cfg); +free_settings: + gpiod_line_settings_free(settings); +close_chip: + gpiod_chip_close(chip); + + return request; +} + +enum gpiod_line_value toggle_line_value(enum gpiod_line_value value) +{ + return (value == GPIOD_LINE_VALUE_ACTIVE) ? GPIOD_LINE_VALUE_INACTIVE : + GPIOD_LINE_VALUE_ACTIVE; +} + +void print_value(enum gpiod_line_value value) +{ + if (value == GPIOD_LINE_VALUE_ACTIVE) + printf("Active\n"); + else + printf("Inactive\n"); +} + +int main(void) +{ + struct gpiod_line_request *request; + enum gpiod_line_value value = GPIOD_LINE_VALUE_ACTIVE; + /* example configuration - customize to suit your situation */ + const char *chip_path = "/dev/gpiochip0"; + int line_offset = 5; + + request = request_output_line(chip_path, line_offset, value, + "toggle-line-value"); + if (!request) { + fprintf(stderr, "failed to request line: %s\n", + strerror(errno)); + return EXIT_FAILURE; + } + + while (1) { + print_value(value); + sleep(1); + value = toggle_line_value(value); + gpiod_line_request_set_value(request, line_offset, value); + } + + gpiod_line_request_release(request); + return EXIT_SUCCESS; +} diff --git a/examples/watch_line_value.c b/examples/watch_line_value.c new file mode 100644 index 0000000..011943e --- /dev/null +++ b/examples/watch_line_value.c @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// SPDX-FileCopyrightText: 2023 Kent Gibson + +/* Minimal example of watching for edges on a single line. */ + +#include +#include +#include +#include +#include + +/* request a line as input with edge detection */ +struct gpiod_line_request *request_input_line(const char *chip_path, + unsigned int offset, + const char *consumer) +{ + struct gpiod_line_settings *settings; + struct gpiod_line_request *request = NULL; + struct gpiod_request_config *req_cfg = NULL; + struct gpiod_line_config *line_cfg; + struct gpiod_chip *chip; + int ret; + + chip = gpiod_chip_open(chip_path); + if (!chip) + return NULL; + + settings = gpiod_line_settings_new(); + if (!settings) + goto close_chip; + + gpiod_line_settings_set_direction(settings, GPIOD_LINE_DIRECTION_INPUT); + gpiod_line_settings_set_edge_detection(settings, GPIOD_LINE_EDGE_BOTH); + /* assume a button connecting the pin to ground, so pull it up... */ + gpiod_line_settings_set_bias(settings, GPIOD_LINE_BIAS_PULL_UP); + /* ... and provide some debounce. */ + gpiod_line_settings_set_debounce_period_us(settings, 10000); + + line_cfg = gpiod_line_config_new(); + if (!line_cfg) + goto free_settings; + + ret = gpiod_line_config_add_line_settings(line_cfg, &offset, 1, + settings); + if (ret) + goto free_line_config; + + if (consumer) { + req_cfg = gpiod_request_config_new(); + if (!req_cfg) + goto free_line_config; + + gpiod_request_config_set_consumer(req_cfg, consumer); + } + + request = gpiod_chip_request_lines(chip, req_cfg, line_cfg); + + gpiod_request_config_free(req_cfg); +free_line_config: + gpiod_line_config_free(line_cfg); +free_settings: + gpiod_line_settings_free(settings); +close_chip: + gpiod_chip_close(chip); + + return request; +} + +const char *edge_event_type_str(struct gpiod_edge_event *event) +{ + enum gpiod_edge_event_type eet = gpiod_edge_event_get_event_type(event); + + if (eet == GPIOD_EDGE_EVENT_RISING_EDGE) + return "Rising "; + if (eet == GPIOD_EDGE_EVENT_FALLING_EDGE) + return "Falling"; + return "Unknown"; +} + +int main(void) +{ + struct gpiod_line_request *request; + struct gpiod_edge_event_buffer *event_buffer; + struct gpiod_edge_event *event; + int i, ret, event_buf_size; + /* example configuration - customize to suit your situation */ + const char *chip_path = "/dev/gpiochip0"; + int line_offset = 5; + + request = request_input_line(chip_path, line_offset, + "watch-line-value"); + if (!request) { + fprintf(stderr, "failed to request line: %s\n", + strerror(errno)); + return EXIT_FAILURE; + } + + /* 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. + */ + event_buf_size = 1; + event_buffer = gpiod_edge_event_buffer_new(event_buf_size); + if (!event_buffer) { + fprintf(stderr, "failed to create event buffer: %s\n", + strerror(errno)); + return EXIT_FAILURE; + } + + while (1) { + /* blocks until at least one event is available */ + ret = gpiod_line_request_read_edge_events(request, event_buffer, + event_buf_size); + if (ret == -1) { + fprintf(stderr, "error reading edge events: %s\n", + strerror(errno)); + return EXIT_FAILURE; + } + for (i = 0; i < ret; i++) { + event = gpiod_edge_event_buffer_get_event(event_buffer, + i); + printf("offset: %d, type: %s, event #%ld\n", + gpiod_edge_event_get_line_offset(event), + edge_event_type_str(event), + gpiod_edge_event_get_line_seqno(event)); + } + } +} From patchwork Wed Jun 14 03:54:24 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Kent Gibson X-Patchwork-Id: 1794809 Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@legolas.ozlabs.org Authentication-Results: legolas.ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=vger.kernel.org (client-ip=2620:137:e000::1:20; helo=out1.vger.email; envelope-from=linux-gpio-owner@vger.kernel.org; receiver=) Authentication-Results: legolas.ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20221208 header.b=huUB6Wp0; dkim-atps=neutral Received: from out1.vger.email (out1.vger.email [IPv6:2620:137:e000::1:20]) by legolas.ozlabs.org (Postfix) with ESMTP id 4Qgs566fT9z20QH for ; Wed, 14 Jun 2023 13:55:06 +1000 (AEST) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S229783AbjFNDzF (ORCPT ); Tue, 13 Jun 2023 23:55:05 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:55914 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S231829AbjFNDzE (ORCPT ); Tue, 13 Jun 2023 23:55:04 -0400 Received: from mail-ot1-x335.google.com (mail-ot1-x335.google.com [IPv6:2607:f8b0:4864:20::335]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id B4CBEC3 for ; Tue, 13 Jun 2023 20:55:02 -0700 (PDT) Received: by mail-ot1-x335.google.com with SMTP id 46e09a7af769-6b280319df5so4399110a34.3 for ; Tue, 13 Jun 2023 20:55:02 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20221208; t=1686714902; x=1689306902; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=wxiywbFhFg/nIUZw7n1iTjVzDeq3Cscpl5spqxkKk84=; b=huUB6Wp0Kdq3FwDpF39/EfxjQUGxBrDd0EK0rXSSoAM+BbcVjrmNqKokJ1098SPEkR 0WjvxPRduZ6Ew3WfnWErdiLelOa+U5M/lJ0qV/BMz4CgOD04fkj7x+WNTUAsY8WHYKBW UEglZialPcVj0qncfeeqwphf5v0PN0JBENI0IhchaX/T6qx4Z9OiDYUHMoFQFtT82/+F pclF6k6r2SjwJ3eGpztFYTF80pWFw7egGMcbMtYgN1ZrvP20CgO4TFCfBjqG5a03vybT /8KMIckUNRXHsWvzEymIQUoDNIgs4G3nrln5FER/VUDaqxq4w+ajeq5nKHHazIQDi+TL D4wA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20221208; t=1686714902; x=1689306902; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=wxiywbFhFg/nIUZw7n1iTjVzDeq3Cscpl5spqxkKk84=; b=hO5VdO4DG2JxjUdotTI72Og2NYCKfcH+ODtSjgQOovsW4S+pBbmESZxHTbPHJkHWFK 6sNn+4X3NPYgg0PnCKKGoZZLYvmqA0GWzxI5EkFKpkuJK0AH/zC1bENcvXUrTI0/D4Bi 6HddqmO73f3sSCHmVR7pUVSWejbl7JHnPT07iB/6ceyAZxKTehc2z2N3aNwYxFf2kUDT OZGDilIEgDDR8QE1pmJ3cuFiGPz+aXYy2ETYphHeEIANtXVpDOK1wUaO/NbIkz6+Gw5+ Qc1Eh7suHuxLLzIWx/SyAyXEajDc2bcZK+mX7+7MaWu1tCiHDrZn3BJ36EKtlRXtQV1M /6wQ== X-Gm-Message-State: AC+VfDxQT52pWa6s1zSnQspki8ZOx66L3nEXaV8rdg0UCJm2WHUW0VLL MNWiPYxO/EdvMGfvLwX+WWG5IDpIngg= X-Google-Smtp-Source: ACHHUZ6NPF9d11O9/syckxQZufWwHzcAdHfH1SnVcBgwclKTx21okOGqjnZz0SzhviMv51BWH1Cd3Q== X-Received: by 2002:a05:6359:29f:b0:12b:e795:2650 with SMTP id ek31-20020a056359029f00b0012be7952650mr5326925rwb.28.1686714901739; Tue, 13 Jun 2023 20:55:01 -0700 (PDT) Received: from sol.home.arpa (194-223-178-180.tpgi.com.au. [194.223.178.180]) by smtp.gmail.com with ESMTPSA id l12-20020a170903120c00b001ae6fe84244sm10967412plh.243.2023.06.13.20.54.59 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 13 Jun 2023 20:55:01 -0700 (PDT) From: Kent Gibson To: linux-gpio@vger.kernel.org, brgl@bgdev.pl Cc: Kent Gibson Subject: [libgpiod][PATCH 2/4] bindings: cxx: examples: add dedicated examples Date: Wed, 14 Jun 2023 11:54:24 +0800 Message-Id: <20230614035426.15097-3-warthog618@gmail.com> X-Mailer: git-send-email 2.40.1 In-Reply-To: <20230614035426.15097-1-warthog618@gmail.com> References: <20230614035426.15097-1-warthog618@gmail.com> MIME-Version: 1.0 X-Spam-Status: No, score=-1.9 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_ENVFROM_END_DIGIT, FREEMAIL_FROM,RCVD_IN_DNSWL_NONE,SPF_HELO_NONE,SPF_PASS, T_SCC_BODY_TEXT_LINE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-gpio@vger.kernel.org Add cxx equivalents of the core examples. Signed-off-by: Kent Gibson --- 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 diff --git a/bindings/cxx/examples/.gitignore b/bindings/cxx/examples/.gitignore index 2209497..268b3f6 100644 --- a/bindings/cxx/examples/.gitignore +++ b/bindings/cxx/examples/.gitignore @@ -8,3 +8,7 @@ gpioinfocxx gpiomoncxx gpionotifycxx gpiosetcxx +async_watch_line_value +get_line_value +toggle_line_value +watch_line_value diff --git a/bindings/cxx/examples/Makefile.am b/bindings/cxx/examples/Makefile.am index 36977ef..0213973 100644 --- a/bindings/cxx/examples/Makefile.am +++ b/bindings/cxx/examples/Makefile.am @@ -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 diff --git a/bindings/cxx/examples/async_watch_line_value.cpp b/bindings/cxx/examples/async_watch_line_value.cpp new file mode 100644 index 0000000..965e7dd --- /dev/null +++ b/bindings/cxx/examples/async_watch_line_value.cpp @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// SPDX-FileCopyrightText: 2023 Kent Gibson + +/* Minimal example of asynchronously watching for edges on a single line. */ + +#include +#include +#include +#include +#include +#include + +const char *edge_event_type_str(const ::gpiod::edge_event &event) +{ + switch (event.type()) { + case ::gpiod::edge_event::event_type::RISING_EDGE: + return "Rising "; + case ::gpiod::edge_event::event_type::FALLING_EDGE: + return "Falling"; + default: + return "Unknown"; + } +} + +int main(void) +{ + // example configuration - customize to suit your situation + const char *chip_path = "/dev/gpiochip0"; + int line_offset = 5; + + // assume a button connecting the pin to ground, + // so pull it up and provide some debounce. + auto request = + ::gpiod::chip(chip_path) + .prepare_request() + .set_consumer("async-watch-line-value") + .add_line_settings( + line_offset, + ::gpiod::line_settings() + .set_direction( + ::gpiod::line::direction::INPUT) + .set_edge_detection( + ::gpiod::line::edge::BOTH) + .set_bias(::gpiod::line::bias::PULL_UP) + .set_debounce_period( + std::chrono::milliseconds(10))) + .do_request(); + + // 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. + ::gpiod::edge_event_buffer buffer(1); + + struct pollfd pollfd; + pollfd.fd = request.fd(); + pollfd.events = POLLIN; + + for (;;) { + // other fds could be registered with the poll and be handled + // separately using the pollfd.revents after poll() + int ret = poll(&pollfd, 1, -1); + if (ret == -1) { + ::std::cerr << "error waiting for edge events: " + << strerror(errno) << ::std::endl; + + return EXIT_FAILURE; + } + + request.read_edge_events(buffer); + + for (const auto &event : buffer) + ::std::cout << "offset: " << event.line_offset() + << ", type: " << edge_event_type_str(event) + << ", event #" << event.line_seqno() + << ::std::endl; + } + + return EXIT_SUCCESS; +} diff --git a/bindings/cxx/examples/get_line_value.cpp b/bindings/cxx/examples/get_line_value.cpp new file mode 100644 index 0000000..3e14b56 --- /dev/null +++ b/bindings/cxx/examples/get_line_value.cpp @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// SPDX-FileCopyrightText: 2023 Kent Gibson + +/* Minimal example of reading a single line. */ + +#include +#include +#include + +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; +} diff --git a/bindings/cxx/examples/toggle_line_value.cpp b/bindings/cxx/examples/toggle_line_value.cpp new file mode 100644 index 0000000..2f47553 --- /dev/null +++ b/bindings/cxx/examples/toggle_line_value.cpp @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// SPDX-FileCopyrightText: 2023 Kent Gibson + +/* Minimal example of toggling a single line. */ + +#include +#include +#include +#include +#include + +using ::gpiod::line::value; + +value toggle_value(value v) +{ + return (v == value::ACTIVE) ? value::INACTIVE : value::ACTIVE; +} + +int main(void) +{ + /* example configuration - customize to suit your situation */ + const char *chip_path = "/dev/gpiochip0"; + int line_offset = 5; + + value v = value::ACTIVE; + + auto request = + ::gpiod::chip(chip_path) + .prepare_request() + .set_consumer("toggle-line-value") + .add_line_settings( + line_offset, + ::gpiod::line_settings().set_direction( + ::gpiod::line::direction::OUTPUT)) + .do_request(); + + for (;;) { + ::std::cout << v << ::std::endl; + std::this_thread::sleep_for(std::chrono::seconds(1)); + v = toggle_value(v); + request.set_value(line_offset, v); + } + + return EXIT_SUCCESS; +} diff --git a/bindings/cxx/examples/watch_line_value.cpp b/bindings/cxx/examples/watch_line_value.cpp new file mode 100644 index 0000000..d3f2390 --- /dev/null +++ b/bindings/cxx/examples/watch_line_value.cpp @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// SPDX-FileCopyrightText: 2023 Kent Gibson + +/* Minimal example of watching for edges on a single line. */ + +#include +#include +#include + +const char *edge_event_type_str(const ::gpiod::edge_event &event) +{ + switch (event.type()) { + case ::gpiod::edge_event::event_type::RISING_EDGE: + return "Rising "; + case ::gpiod::edge_event::event_type::FALLING_EDGE: + return "Falling"; + default: + return "Unknown"; + } +} + +int main(void) +{ + /* example configuration - customize to suit your situation */ + const char *chip_path = "/dev/gpiochip0"; + int line_offset = 5; + + // assume a button connecting the pin to ground, + // so pull it up and provide some debounce. + auto request = + ::gpiod::chip(chip_path) + .prepare_request() + .set_consumer("watch-line-value") + .add_line_settings( + line_offset, + ::gpiod::line_settings() + .set_direction( + ::gpiod::line::direction::INPUT) + .set_edge_detection( + ::gpiod::line::edge::BOTH) + .set_bias(::gpiod::line::bias::PULL_UP) + .set_debounce_period( + std::chrono::milliseconds(10))) + .do_request(); + + // 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. + ::gpiod::edge_event_buffer buffer(1); + + for (;;) { + // blocks until at least one event is available + request.read_edge_events(buffer); + + for (const auto &event : buffer) + ::std::cout << "offset: " << event.line_offset() + << ", type: " << edge_event_type_str(event) + << ", event #" << event.line_seqno() + << ::std::endl; + } + + return EXIT_SUCCESS; +} From patchwork Wed Jun 14 03:54:25 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Kent Gibson X-Patchwork-Id: 1794810 Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@legolas.ozlabs.org Authentication-Results: legolas.ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=vger.kernel.org (client-ip=2620:137:e000::1:20; helo=out1.vger.email; envelope-from=linux-gpio-owner@vger.kernel.org; receiver=) Authentication-Results: legolas.ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20221208 header.b=VEp9kbZL; dkim-atps=neutral Received: from out1.vger.email (out1.vger.email [IPv6:2620:137:e000::1:20]) by legolas.ozlabs.org (Postfix) with ESMTP id 4Qgs5J0Ym8z20Vx for ; Wed, 14 Jun 2023 13:55:16 +1000 (AEST) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S231937AbjFNDzP (ORCPT ); Tue, 13 Jun 2023 23:55:15 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:55950 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S231829AbjFNDzO (ORCPT ); Tue, 13 Jun 2023 23:55:14 -0400 Received: from mail-pl1-x630.google.com (mail-pl1-x630.google.com [IPv6:2607:f8b0:4864:20::630]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id F3434C3 for ; Tue, 13 Jun 2023 20:55:12 -0700 (PDT) Received: by mail-pl1-x630.google.com with SMTP id d9443c01a7336-1b3a6469623so23922025ad.3 for ; Tue, 13 Jun 2023 20:55:12 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20221208; t=1686714912; x=1689306912; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=+HkwAXXE0/XlVIBZBwL0UjyLcXAB59rNKnEN8CXuAfw=; b=VEp9kbZLbN6wBCxR+yU1IYYJXf1lzL02sciqV+Lu9VsffqQ+/wNsuXz6UM9HquhNNQ yC8I63B23KbkVQPLwsRnwMBlzFf6acExRTXe2YnoltBXVxLMCx0vZSiFhHirsWMHg3yh /geinykXQtNBbT2rhgrVtP8tV7ABmpjFYBmr+A1ApcOADRoOiMIO+cJ2VROracmhQjQN Y9+x6F8ZOtFAo1dM1lmcpqtU0ane01cYD/Yz9sqe7CuhfgBTzvkWhrmWSPuhcMIrcLH6 ra/BlBCa8pOjcIEm/XoIrAETzZPMSBf4/fDJeku1rGb+CsdjHcWTEIAIsUp+AGNSdz6p X8Og== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20221208; t=1686714912; x=1689306912; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=+HkwAXXE0/XlVIBZBwL0UjyLcXAB59rNKnEN8CXuAfw=; b=ZVVRcmQ7tswgX6DzD0AOiBmthm7LZYnSbKFxO2L3UCodS80w6/Tr6e5fMfsqUCHZ6y vRs/MqUMQ63MA/m4O/DDT5y6Ych9Ia5Yo6LxKHOLf9y2NjrnrnSinj0WWU7VT9MmRVsU kdnKsOfnejfNajp4n+Cnmaskxc95/E04tkPOI7MOctJz1iu+Qdv11QlXzh3gc/9QOkqb AkPg0tycpU2eemQXOQwgI5SwcDTw7DhSh8T+2RIS0hPWkI7VUBOdI8RfQsZYUNDWqo9M vqdBToAPetM2+mrxQBqsMkFsenH0U4LzU4KxgBQrxJUsSvRJ6ckdxdW5nY0voMDczpCG Phdg== X-Gm-Message-State: AC+VfDyhT2D3FsTQin5dSSUjEcG84OLyRhn9eKS/QyLz3m4Aci6WmSf6 ssfqZvKyDD/ybLamOsBeS2DOUdwOBVA= X-Google-Smtp-Source: ACHHUZ7lu1JQebA4fJYBG/j80SJc73cfmaQoAnP23iIn5dDhtlk4TaXWb5E8j5mgxKzrI4OxIYifKQ== X-Received: by 2002:a17:903:124d:b0:1b1:b2fa:1903 with SMTP id u13-20020a170903124d00b001b1b2fa1903mr11876935plh.41.1686714912250; Tue, 13 Jun 2023 20:55:12 -0700 (PDT) Received: from sol.home.arpa (194-223-178-180.tpgi.com.au. [194.223.178.180]) by smtp.gmail.com with ESMTPSA id l12-20020a170903120c00b001ae6fe84244sm10967412plh.243.2023.06.13.20.55.10 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 13 Jun 2023 20:55:11 -0700 (PDT) From: Kent Gibson To: linux-gpio@vger.kernel.org, brgl@bgdev.pl Cc: Kent Gibson Subject: [libgpiod][PATCH 3/4] bindings: python: examples: add dedicated examples Date: Wed, 14 Jun 2023 11:54:25 +0800 Message-Id: <20230614035426.15097-4-warthog618@gmail.com> X-Mailer: git-send-email 2.40.1 In-Reply-To: <20230614035426.15097-1-warthog618@gmail.com> References: <20230614035426.15097-1-warthog618@gmail.com> MIME-Version: 1.0 X-Spam-Status: No, score=-1.9 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_ENVFROM_END_DIGIT, FREEMAIL_FROM,RCVD_IN_DNSWL_NONE,SPF_HELO_NONE,SPF_PASS, T_SCC_BODY_TEXT_LINE autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-gpio@vger.kernel.org Add python equivalents of the core examples. Signed-off-by: Kent Gibson --- .../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 diff --git a/bindings/python/examples/async_watch_line_value.py b/bindings/python/examples/async_watch_line_value.py new file mode 100755 index 0000000..031a988 --- /dev/null +++ b/bindings/python/examples/async_watch_line_value.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-or-later +# SPDX-FileCopyrightText: 2023 Kent Gibson + +"""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() diff --git a/bindings/python/examples/get_line_value.py b/bindings/python/examples/get_line_value.py new file mode 100755 index 0000000..da9d060 --- /dev/null +++ b/bindings/python/examples/get_line_value.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-or-later +# SPDX-FileCopyrightText: 2023 Kent Gibson + +"""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() diff --git a/bindings/python/examples/toggle_line_value.py b/bindings/python/examples/toggle_line_value.py new file mode 100755 index 0000000..ed84d5b --- /dev/null +++ b/bindings/python/examples/toggle_line_value.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-or-later +# SPDX-FileCopyrightText: 2023 Kent Gibson + +"""Minimal example of toggling a single line.""" + +import gpiod +import time + +from gpiod.line import Direction, Value + +def toggle_value(value): + if value == Value.INACTIVE: + return Value.ACTIVE + return Value.INACTIVE + + +def print_value(value): + if value == Value.ACTIVE: + print("Active") + else: + print("Inactive") + + +def toggle_line_value(): + # example configuration - customise to suit your situation + chip_path = '/dev/gpiochip0' + line_offset = 5 + + value = Value.ACTIVE + + request = gpiod.request_lines( + chip_path, + consumer="toggle-line-value", + config={line_offset: gpiod.LineSettings(direction=Direction.OUTPUT, + output_value=value)}, + ) + + while True: + print_value(value) + time.sleep(1) + value = toggle_value(value) + request.set_value(line_offset, value) + + +if __name__ == "__main__": + toggle_line_value() diff --git a/bindings/python/examples/watch_line_value.py b/bindings/python/examples/watch_line_value.py new file mode 100755 index 0000000..5747706 --- /dev/null +++ b/bindings/python/examples/watch_line_value.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-or-later +# SPDX-FileCopyrightText: 2023 Kent Gibson + +"""Minimal example of watching for edges on a single line.""" + +from datetime import timedelta +import gpiod + +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 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="watch-line-value", + config={line_offset: gpiod.LineSettings(edge_detection=Edge.BOTH, + bias=Bias.PULL_UP, + debounce_period=timedelta(milliseconds=10))}, + ) as request: + while True: + # blocks until at least one event is available + 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__": + watch_line_value() From patchwork Wed Jun 14 03:54:26 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Kent Gibson X-Patchwork-Id: 1794811 Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@legolas.ozlabs.org Authentication-Results: legolas.ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=vger.kernel.org (client-ip=2620:137:e000::1:20; helo=out1.vger.email; envelope-from=linux-gpio-owner@vger.kernel.org; receiver=) Authentication-Results: legolas.ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20221208 header.b=V6Lwc9Qc; dkim-atps=neutral Received: from out1.vger.email (out1.vger.email [IPv6:2620:137:e000::1:20]) by legolas.ozlabs.org (Postfix) with ESMTP id 4Qgs5d2qX8z20Vx for ; Wed, 14 Jun 2023 13:55:33 +1000 (AEST) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S238340AbjFNDzb (ORCPT ); Tue, 13 Jun 2023 23:55:31 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:55994 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233075AbjFNDzZ (ORCPT ); Tue, 13 Jun 2023 23:55:25 -0400 Received: from mail-pf1-x431.google.com (mail-pf1-x431.google.com [IPv6:2607:f8b0:4864:20::431]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 7ECCD10F8 for ; Tue, 13 Jun 2023 20:55:23 -0700 (PDT) Received: by mail-pf1-x431.google.com with SMTP id d2e1a72fcca58-66619138c1eso530724b3a.3 for ; Tue, 13 Jun 2023 20:55:23 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20221208; t=1686714923; x=1689306923; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=GPwzMuSfmHAFDh0ZW1HFnTv+VfQxV64Bk2kl986R1Ek=; b=V6Lwc9Qc0D68pSDfY0aanlTjfOsdrFka7JhvM+AfGfxZHLoZz3M+wlsC6RUGYuH1Pt zm3cavKo00SWtBZh+GTz0WQ2WkPeT6h9zEJTBEQU3a2BredQfDhoaYCy65yuMoJBZu/0 NE/8R8VtGxcywcf4LYBvZ7a/4UcyUkYJ8akp6rxkDiQK3U4Pf4HnAwM03zRxBzUSf9Sw PmyBwUYYEo/QamlQiZNWNloSitMXA9owrIq2pWsCm1RvSUl9yYJxNzCec0wRP8R92jjj 6ACFdeuVBaY02DsFcuJepXOvGhP72nWzhgIyY+rK3o0tK0NIVdZkZGBVo7ghekQwSvC0 CLdg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20221208; t=1686714923; x=1689306923; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=GPwzMuSfmHAFDh0ZW1HFnTv+VfQxV64Bk2kl986R1Ek=; b=NzmZV1msiTyyrDsmjCi5Pj1zCjPLn0TQCBG4Jos7Bbb6ZKOSSdeEGXhl4bxubleFmY W7+c0YNn9a4IJp+EEcoC9AFZA6CMMeTGUKMm8LpnBL1bcGWMdYgWUt5LnUkTBjHqPUL+ 8XOBCt9awQVh+rHRl30RwI0FoNld3Ia/8NJ1sYmHUxacelLREsDItkDHWtCVUHwQTH3w lQVTb/gd0zSGqcTR42e8G7qnR1+h5wn4tr1tpg9G12Z3XM6MingPi6y0axCQPOL+7onm XixEZNreppAhQOKAeVcZW2AO356aUUT4izfd+yJZSFpDMuBGtT76Opp4OC0qDGtWISOx N+EQ== X-Gm-Message-State: AC+VfDwx4Gro6TuGUiNEbXNYJMuys2mVwEXaOycevf+v3YAxoLpovhff 7PO5ZW1/GRBe0b0nnXFjsorTkr/hWzI= X-Google-Smtp-Source: ACHHUZ52gT2UXVDK4cAKTj0BVc+igiigh5BPdCIVY5AIqPMPewRiGCymepUh10uXDDdPtZPrJ8v39g== X-Received: by 2002:a05:6a20:1d8:b0:10c:7916:f9f6 with SMTP id 24-20020a056a2001d800b0010c7916f9f6mr551641pzz.52.1686714922770; Tue, 13 Jun 2023 20:55:22 -0700 (PDT) Received: from sol.home.arpa (194-223-178-180.tpgi.com.au. [194.223.178.180]) by smtp.gmail.com with ESMTPSA id l12-20020a170903120c00b001ae6fe84244sm10967412plh.243.2023.06.13.20.55.20 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 13 Jun 2023 20:55:22 -0700 (PDT) From: Kent Gibson To: linux-gpio@vger.kernel.org, brgl@bgdev.pl Cc: Kent Gibson Subject: [libgpiod][PATCH 4/4] bindings: rust: examples: add dedicated examples Date: Wed, 14 Jun 2023 11:54:26 +0800 Message-Id: <20230614035426.15097-5-warthog618@gmail.com> X-Mailer: git-send-email 2.40.1 In-Reply-To: <20230614035426.15097-1-warthog618@gmail.com> References: <20230614035426.15097-1-warthog618@gmail.com> MIME-Version: 1.0 X-Spam-Status: No, score=-1.9 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_ENVFROM_END_DIGIT, FREEMAIL_FROM,RCVD_IN_DNSWL_NONE,SPF_HELO_NONE,SPF_PASS, T_SCC_BODY_TEXT_LINE autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-gpio@vger.kernel.org Add rust equivalents of the core examples. Signed-off-by: Kent Gibson Reviewed-by: Erik Schilling --- .../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 diff --git a/bindings/rust/libgpiod/examples/get_line_value.rs b/bindings/rust/libgpiod/examples/get_line_value.rs new file mode 100644 index 0000000..732fb71 --- /dev/null +++ b/bindings/rust/libgpiod/examples/get_line_value.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause +// SPDX-FileCopyrightText: 2023 Kent Gibson +// +// 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(()) +} diff --git a/bindings/rust/libgpiod/examples/toggle_line_value.rs b/bindings/rust/libgpiod/examples/toggle_line_value.rs new file mode 100644 index 0000000..cd7038e --- /dev/null +++ b/bindings/rust/libgpiod/examples/toggle_line_value.rs @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause +// SPDX-FileCopyrightText: 2023 Kent Gibson +// +// 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)?; + } +} diff --git a/bindings/rust/libgpiod/examples/watch_line_value.rs b/bindings/rust/libgpiod/examples/watch_line_value.rs new file mode 100644 index 0000000..5a95b6a --- /dev/null +++ b/bindings/rust/libgpiod/examples/watch_line_value.rs @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause +// SPDX-FileCopyrightText: 2023 Kent Gibson +// +// 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 { + 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() + ); + } + } +}