shell: add a callback-filter variant of shell_device_lookup

Add a shell_device_filter variant of the shell device lookup helper that
takes a callback as an argument. This allows more complex filtering on
the device than the existing name prefix.

Signed-off-by: Fabio Baltieri <fabiobaltieri@google.com>
This commit is contained in:
Fabio Baltieri 2024-04-25 15:01:22 +01:00 committed by David Leach
parent ce29e275c9
commit 48e2f67869
2 changed files with 45 additions and 3 deletions

View file

@ -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.
*

View file

@ -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;