diff --git a/include/zephyr/shell/shell.h b/include/zephyr/shell/shell.h index a19418fa52..d99baf00d5 100644 --- a/include/zephyr/shell/shell.h +++ b/include/zephyr/shell/shell.h @@ -131,6 +131,34 @@ struct shell_static_args { const struct device *shell_device_lookup(size_t idx, const char *prefix); +/** + * @brief Filter callback type, for use with shell_device_lookup_filter + * + * This is used as an argument of shell_device_lookup_filter to only return + * devices that match a specific condition, implemented by the filter. + * + * @param dev pointer to a struct device. + * + * @return bool, true if the filter matches the device type. + */ +typedef bool (*shell_device_filter_t)(const struct device *dev); + +/** + * @brief Get a device by index and filter. + * + * This can be used to return devices matching a specific type. + * + * Devices that the filter returns false for, failed to initialize or do not + * have a non-empty name are excluded from the candidates for a match. + * + * @param idx the device number starting from zero. + * + * @param filter a pointer to a shell_device_filter_t function that returns + * true if the device matches the filter. + */ +const struct device *shell_device_filter(size_t idx, + shell_device_filter_t filter); + /** * @brief Shell command handler prototype. * diff --git a/subsys/shell/shell_utils.c b/subsys/shell/shell_utils.c index bd7523e470..00d3315d0c 100644 --- a/subsys/shell/shell_utils.c +++ b/subsys/shell/shell_utils.c @@ -496,8 +496,9 @@ void z_shell_cmd_trim(const struct shell *sh) sh->ctx->cmd_buff_pos = sh->ctx->cmd_buff_len; } -const struct device *shell_device_lookup(size_t idx, - const char *prefix) +static const struct device *shell_device_internal(size_t idx, + const char *prefix, + shell_device_filter_t filter) { size_t match_idx = 0; const struct device *dev; @@ -510,7 +511,8 @@ const struct device *shell_device_lookup(size_t idx, && (strlen(dev->name) != 0) && ((prefix == NULL) || (strncmp(prefix, dev->name, - strlen(prefix)) == 0))) { + strlen(prefix)) == 0)) + && (filter == NULL || filter(dev))) { if (match_idx == idx) { return dev; } @@ -522,6 +524,18 @@ const struct device *shell_device_lookup(size_t idx, return NULL; } +const struct device *shell_device_filter(size_t idx, + shell_device_filter_t filter) +{ + return shell_device_internal(idx, NULL, filter); +} + +const struct device *shell_device_lookup(size_t idx, + const char *prefix) +{ + return shell_device_internal(idx, prefix, NULL); +} + long shell_strtol(const char *str, int base, int *err) { long val;