blob: 1c75f05be16143369afb3f3c4be7c4b34701e96f [file] [log] [blame]
Enrico Granata60a818d2019-05-09 09:56:09 -07001// Copyright 2019 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <memory>
6#include <string>
7
8#include <base/logging.h>
9
Enrico Granata51cdb942019-06-18 16:40:17 -070010#include "libmems/iio_channel_impl.h"
11#include "libmems/iio_context_impl.h"
12#include "libmems/iio_device_impl.h"
Enrico Granata60a818d2019-05-09 09:56:09 -070013
Enrico Granata51cdb942019-06-18 16:40:17 -070014namespace libmems {
Enrico Granata60a818d2019-05-09 09:56:09 -070015
16IioContextImpl::IioContextImpl() {
17 Reload();
18}
19
20void IioContextImpl::Reload() {
21 // This context will only be destroyed when the entire IioContextImpl goes
22 // out of scope. In practice, there will only be at most two contexts
23 // in existence (i.e. the initial one and the one we create if we need
24 // to initialize the IIO sysfs trigger). This is done in the interest of
25 // not having to invalidate existing iio_device pointers, as their lifetime
26 // is statically bound to the context that created them (and contexts are
27 // themselves static objects that do not update as devices are added
28 // and/or removed at runtime).
29 context_.push_back({iio_create_local_context(), iio_context_destroy});
30 CHECK(GetCurrentContext());
31}
32
33iio_context* IioContextImpl::GetCurrentContext() const {
34 if (context_.empty())
35 return nullptr;
36 return context_.back().get();
37}
38
39IioDevice* IioContextImpl::GetDevice(const std::string& name) {
40 auto k = devices_.find(name);
41 if (k != devices_.end())
42 return k->second.get();
43 iio_device* device =
44 iio_context_find_device(GetCurrentContext(), name.c_str());
45 if (device == nullptr)
46 return nullptr;
47 devices_.emplace(name, std::make_unique<IioDeviceImpl>(this, device));
48 return devices_[name].get();
49}
50
Enrico Granata51cdb942019-06-18 16:40:17 -070051} // namespace libmems