SensorNotifier.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright (C) 2024 The LineageOS Project
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #define LOG_TAG "SensorNotifier"
  7. #include "SensorNotifier.h"
  8. #include <android-base/logging.h>
  9. using android::hardware::sensors::V1_0::SensorFlagBits;
  10. using android::hardware::sensors::V1_0::SensorInfo;
  11. SensorNotifier::SensorNotifier(sp<ISensorManager> manager) : mManager(manager) {}
  12. SensorNotifier::~SensorNotifier() {
  13. if (mQueue != nullptr) {
  14. /*
  15. * Free the event queue.
  16. * kernel calls decStrong() on server side implementation of IEventQueue,
  17. * hence resources (including the callback) are freed as well.
  18. */
  19. mQueue = nullptr;
  20. }
  21. }
  22. Result SensorNotifier::initializeSensorQueue(std::string typeAsString, bool wakeup,
  23. sp<IEventQueueCallback> callback) {
  24. Result res;
  25. std::vector<SensorInfo> sensorList;
  26. mManager->getSensorList([&sensorList, &res](const auto& l, auto r) {
  27. sensorList = l;
  28. res = r;
  29. });
  30. if (res != Result::OK) {
  31. LOG(ERROR) << "failed to get sensors list";
  32. return res;
  33. }
  34. auto it = std::find_if(sensorList.begin(), sensorList.end(),
  35. [this, &typeAsString, &wakeup](const SensorInfo& sensor) {
  36. return (sensor.typeAsString == typeAsString) &&
  37. ((sensor.flags & SensorFlagBits::WAKE_UP) == wakeup);
  38. });
  39. if (it != sensorList.end()) {
  40. mSensorHandle = it->sensorHandle;
  41. } else {
  42. LOG(ERROR) << "failed to get " << typeAsString << " sensor with wake-up: " << wakeup;
  43. return Result::NOT_EXIST;
  44. }
  45. mManager->createEventQueue(callback, [this, &res](const auto& q, auto r) {
  46. this->mQueue = q;
  47. res = r;
  48. });
  49. if (res != Result::OK) {
  50. LOG(ERROR) << "failed to create event queue";
  51. return res;
  52. }
  53. return Result::OK;
  54. }
  55. void SensorNotifier::activate() {
  56. if (mActive) {
  57. return;
  58. }
  59. mActive = true;
  60. mThread = std::thread(&SensorNotifier::notify, this);
  61. }
  62. void SensorNotifier::deactivate() {
  63. if (!mActive) {
  64. return;
  65. }
  66. mActive = false;
  67. if (mThread.joinable()) {
  68. mThread.join();
  69. }
  70. if (mQueue != nullptr) {
  71. mQueue->disableSensor(mSensorHandle);
  72. }
  73. }