blob: e3d56a855b6128f0883caa50d6ddf8c3c2949bb1 [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
Harvey Yang6698c862019-09-16 17:24:38 +080010#include "libmems/common_types.h"
Enrico Granata51cdb942019-06-18 16:40:17 -070011#include "libmems/iio_channel_impl.h"
12#include "libmems/iio_context_impl.h"
13#include "libmems/iio_device_impl.h"
Enrico Granata60a818d2019-05-09 09:56:09 -070014
Enrico Granata51cdb942019-06-18 16:40:17 -070015namespace libmems {
Enrico Granata60a818d2019-05-09 09:56:09 -070016
17IioContextImpl::IioContextImpl() {
18 Reload();
19}
20
21void IioContextImpl::Reload() {
22 // This context will only be destroyed when the entire IioContextImpl goes
23 // out of scope. In practice, there will only be at most two contexts
24 // in existence (i.e. the initial one and the one we create if we need
25 // to initialize the IIO sysfs trigger). This is done in the interest of
26 // not having to invalidate existing iio_device pointers, as their lifetime
27 // is statically bound to the context that created them (and contexts are
28 // themselves static objects that do not update as devices are added
29 // and/or removed at runtime).
30 context_.push_back({iio_create_local_context(), iio_context_destroy});
31 CHECK(GetCurrentContext());
32}
33
34iio_context* IioContextImpl::GetCurrentContext() const {
35 if (context_.empty())
36 return nullptr;
37 return context_.back().get();
38}
39
Harvey Yang6698c862019-09-16 17:24:38 +080040bool IioContextImpl::SetTimeout(uint32_t timeout) {
41 int error = iio_context_set_timeout(GetCurrentContext(), timeout);
42 if (error) {
43 char errMsg[kErrorBufferSize];
44 iio_strerror(-error, errMsg, sizeof(errMsg));
45 LOG(ERROR) << "Unable to set timeout " << timeout << ": " << errMsg;
46
47 return false;
48 }
49
50 return true;
51}
52
Enrico Granata60a818d2019-05-09 09:56:09 -070053IioDevice* IioContextImpl::GetDevice(const std::string& name) {
54 auto k = devices_.find(name);
55 if (k != devices_.end())
56 return k->second.get();
57 iio_device* device =
58 iio_context_find_device(GetCurrentContext(), name.c_str());
59 if (device == nullptr)
60 return nullptr;
61 devices_.emplace(name, std::make_unique<IioDeviceImpl>(this, device));
62 return devices_[name].get();
63}
64
Enrico Granata51cdb942019-06-18 16:40:17 -070065} // namespace libmems