Enrico Granata | 60a818d | 2019-05-09 09:56:09 -0700 | [diff] [blame] | 1 | // 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 Granata | 51cdb94 | 2019-06-18 16:40:17 -0700 | [diff] [blame] | 10 | #include "libmems/iio_channel_impl.h" |
| 11 | #include "libmems/iio_context_impl.h" |
| 12 | #include "libmems/iio_device_impl.h" |
Enrico Granata | 60a818d | 2019-05-09 09:56:09 -0700 | [diff] [blame] | 13 | |
Enrico Granata | 51cdb94 | 2019-06-18 16:40:17 -0700 | [diff] [blame] | 14 | namespace libmems { |
Enrico Granata | 60a818d | 2019-05-09 09:56:09 -0700 | [diff] [blame] | 15 | |
| 16 | IioContextImpl::IioContextImpl() { |
| 17 | Reload(); |
| 18 | } |
| 19 | |
| 20 | void 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 | |
| 33 | iio_context* IioContextImpl::GetCurrentContext() const { |
| 34 | if (context_.empty()) |
| 35 | return nullptr; |
| 36 | return context_.back().get(); |
| 37 | } |
| 38 | |
| 39 | IioDevice* 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 Granata | 51cdb94 | 2019-06-18 16:40:17 -0700 | [diff] [blame] | 51 | } // namespace libmems |