shell: refactor device_name_get implementation

Several shell modules use cloned code to iterate over all devices and
identify the nth instance that meets some criteria.  The code was
repetitive and included various errors.  Abstract to a helper function
that performs the check consistently.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
This commit is contained in:
Peter Bigot 2020-06-22 09:56:19 -05:00 committed by Carles Cufí
commit a538dcd8f8
5 changed files with 51 additions and 43 deletions

View file

@ -4,6 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
#include <ctype.h>
#include <device.h>
#include "shell_utils.h"
#include "shell_wildcard.h"
@ -459,3 +460,29 @@ void shell_cmd_trim(const struct shell *shell)
buffer_trim(shell->ctx->cmd_buff, &shell->ctx->cmd_buff_len);
shell->ctx->cmd_buff_pos = shell->ctx->cmd_buff_len;
}
struct device *shell_device_lookup(size_t idx,
const char *prefix)
{
size_t match_idx = 0;
struct device *dev;
size_t len = z_device_get_all_static(&dev);
struct device *dev_end = dev + len;
while (dev < dev_end) {
if ((dev->driver_api != NULL)
&& (dev->name != NULL)
&& (strlen(dev->name) != 0)
&& ((prefix == NULL)
|| (strncmp(prefix, dev->name,
strlen(prefix)) == 0))) {
if (match_idx == idx) {
return dev;
}
++match_idx;
}
++dev;
}
return NULL;
}