Examples

Device Enumeration Example

This example demonstrates enumerating IIO devices using the C++ bindings.

 1// SPDX-License-Identifier: GPL-2.0-or-later
 2/*
 3 * libiio - C++ API usage
 4 *
 5 * This example libiio program shows the usage of the C++ API for enumerating
 6 * devices, channels and attributes.
 7 *
 8 * Copyright (c) 2023, DIFITEC GmbH
 9 * Author: Tilman Blumhagen <tilman.blumhagen@difitec.de>
10 */
11
12#include <iio.hpp>
13
14#include <iostream>
15#include <iomanip>
16
17using namespace iiopp;
18using namespace std;
19
20string get(Attr const & att)
21{
22    char value[1024] = {0}; // Flawfinder: ignore
23    att.read_raw(value, sizeof(value));
24    return value;
25}
26
27void enumerateIioEntities()
28{
29    cout << boolalpha;
30
31    ContextPtr context = create_context(nullptr, nullptr);
32
33    for (Device device : *context)
34    {
35        cout << "Device:" << endl;
36        cout << "  id: " << quoted(string(device.id())) << endl;
37
38        cout << "  name: ";
39        if (auto name = device.name())
40            cout << quoted(string(*name));
41        cout << endl;
42
43        cout << "  is trigger: " << device.is_trigger() << endl;
44
45        for (auto att : device.attrs)
46            cout << "  attribute " << att.name() << " = " << quoted(get(att)) << endl;
47
48        for (auto att : device.debug_attrs)
49            cout << "  debug attribute " << att.name() << " = " << quoted(get(att)) << endl;
50
51        for (Channel channel : device)
52        {
53            cout << "  Channel: " << channel.id() << endl;
54
55            cout << "    name: ";
56            if (auto name = channel.name())
57                cout << quoted(string(*name));
58            cout << endl;
59
60            cout << "    is output: " << channel.is_output() << endl;
61
62            for (auto att : channel.attrs)
63                cout << "    attribute " << quoted(att.name().c_str()) << " = " << quoted(get(att)) << endl;
64        }
65    }
66
67    ScanPtr s = scan(nullptr, nullptr);
68
69    cout << "scan returned " << s->size() << " results" << endl;
70    for (ScanResult r : *s)
71    {
72        cout << "  uri: " << quoted(r.uri().c_str()) << endl;
73        cout << "  description: " << quoted(r.description().c_str()) << endl;
74    }
75}
76
77int main(int argc, char ** argv)
78{
79    try
80    {
81        enumerateIioEntities();
82    }
83    catch (error & e)
84    {
85        cerr << "ERROR " << e.code().value() << ": " << e.what() << endl;
86        return EXIT_FAILURE;
87    }
88
89    return EXIT_SUCCESS;
90}