sensor_request_manager.cc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. /*
  2. * Copyright (C) 2016 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "chre/core/sensor_request_manager.h"
  17. #include "chre_api/chre/version.h"
  18. #include "chre/core/event_loop_manager.h"
  19. #include "chre/platform/fatal_error.h"
  20. #include "chre/platform/shared/platform_sensor_util.h"
  21. #include "chre/util/nested_data_ptr.h"
  22. #include "chre/util/system/debug_dump.h"
  23. #define LOG_INVALID_SENSOR(x) \
  24. LOGE("Invalid sensor type %" PRIu8 ": line %d", \
  25. static_cast<uint8_t>(x), __LINE__)
  26. namespace chre {
  27. namespace {
  28. bool isSensorRequestValid(const Sensor& sensor,
  29. const SensorRequest& sensorRequest) {
  30. bool isRequestContinuous = sensorModeIsContinuous(
  31. sensorRequest.getMode());
  32. bool isRequestOneShot = sensorModeIsOneShot(sensorRequest.getMode());
  33. uint64_t requestedInterval = sensorRequest.getInterval().toRawNanoseconds();
  34. SensorType sensorType = sensor.getSensorType();
  35. bool success = true;
  36. if (requestedInterval < sensor.getMinInterval()) {
  37. success = false;
  38. LOGE("Requested interval %" PRIu64 " < sensor's minInterval %" PRIu64,
  39. requestedInterval, sensor.getMinInterval());
  40. } else if (isRequestContinuous) {
  41. if (sensorTypeIsOneShot(sensorType)) {
  42. success = false;
  43. LOGE("Invalid continuous request for a one-shot sensor.");
  44. }
  45. } else if (isRequestOneShot) {
  46. if (!sensorTypeIsOneShot(sensorType)) {
  47. success = false;
  48. LOGE("Invalid one-shot request for a continuous sensor.");
  49. }
  50. }
  51. return success;
  52. }
  53. } // namespace
  54. SensorRequestManager::SensorRequestManager() {
  55. mSensorRequests.resize(mSensorRequests.capacity());
  56. }
  57. SensorRequestManager::~SensorRequestManager() {
  58. for (size_t i = 0; i < mSensorRequests.size(); i++) {
  59. // Disable sensors that have been enabled previously.
  60. if (mSensorRequests[i].isSensorSupported()) {
  61. mSensorRequests[i].removeAll();
  62. }
  63. }
  64. PlatformSensor::deinit();
  65. }
  66. void SensorRequestManager::init() {
  67. // The Platform sensor must be initialized prior to interacting with any
  68. // sensors.
  69. PlatformSensor::init();
  70. DynamicVector<Sensor> sensors;
  71. sensors.reserve(8); // Avoid some initial reallocation churn
  72. if (!PlatformSensor::getSensors(&sensors)) {
  73. LOGE("Failed to query the platform for sensors");
  74. } else if (sensors.empty()) {
  75. LOGW("Platform returned zero sensors");
  76. } else {
  77. for (size_t i = 0; i < sensors.size(); i++) {
  78. SensorType sensorType = sensors[i].getSensorType();
  79. size_t sensorIndex = getSensorTypeArrayIndex(sensorType);
  80. if (!isValidSensorType(sensorType)) {
  81. LOG_INVALID_SENSOR(sensorType);
  82. } else if (sensors[i].getMinInterval() == 0) {
  83. LOGE("Invalid sensor minInterval: %s", getSensorTypeName(sensorType));
  84. } else {
  85. mSensorRequests[sensorIndex].setSensor(std::move(sensors[i]));
  86. LOGD("Found sensor: %s", getSensorTypeName(sensorType));
  87. }
  88. }
  89. }
  90. }
  91. bool SensorRequestManager::getSensorHandle(SensorType sensorType,
  92. uint32_t *sensorHandle) const {
  93. CHRE_ASSERT(sensorHandle);
  94. bool sensorHandleIsValid = false;
  95. if (!isValidSensorType(sensorType)) {
  96. LOG_INVALID_SENSOR(sensorType);
  97. } else {
  98. size_t sensorIndex = getSensorTypeArrayIndex(sensorType);
  99. sensorHandleIsValid = mSensorRequests[sensorIndex].isSensorSupported();
  100. if (sensorHandleIsValid) {
  101. *sensorHandle = getSensorHandleFromSensorType(sensorType);
  102. }
  103. }
  104. return sensorHandleIsValid;
  105. }
  106. bool SensorRequestManager::setSensorRequest(Nanoapp *nanoapp,
  107. uint32_t sensorHandle, const SensorRequest& sensorRequest) {
  108. CHRE_ASSERT(nanoapp);
  109. // Validate the input to ensure that a valid handle has been provided.
  110. SensorType sensorType = getSensorTypeFromSensorHandle(sensorHandle);
  111. if (!isValidSensorType(sensorType)) {
  112. LOG_INVALID_SENSOR(sensorType);
  113. return false;
  114. }
  115. // Ensure that the runtime is aware of this sensor type.
  116. size_t sensorIndex = getSensorTypeArrayIndex(sensorType);
  117. SensorRequests& requests = mSensorRequests[sensorIndex];
  118. if (!requests.isSensorSupported()) {
  119. LOGW("Attempting to configure non-existent sensor");
  120. return false;
  121. }
  122. const Sensor& sensor = requests.getSensor();
  123. if (!isSensorRequestValid(sensor, sensorRequest)) {
  124. return false;
  125. }
  126. size_t requestIndex;
  127. uint16_t eventType = getSampleEventTypeForSensorType(sensorType);
  128. bool nanoappHasRequest = (requests.find(nanoapp->getInstanceId(),
  129. &requestIndex) != nullptr);
  130. bool success;
  131. bool requestChanged;
  132. if (sensorRequest.getMode() == SensorMode::Off) {
  133. if (nanoappHasRequest) {
  134. // The request changes the mode to off and there was an existing request.
  135. // The existing request is removed from the multiplexer. The nanoapp is
  136. // unregistered from events of this type if this request was successful.
  137. success = requests.remove(requestIndex, &requestChanged);
  138. if (success) {
  139. cancelFlushRequests(sensorType, nanoapp->getInstanceId());
  140. nanoapp->unregisterForBroadcastEvent(eventType);
  141. uint16_t biasEventType;
  142. if (getSensorBiasEventType(sensorType, &biasEventType)) {
  143. // Per API requirements, turn off bias reporting when unsubscribing
  144. // from the sensor.
  145. nanoapp->unregisterForBroadcastEvent(biasEventType);
  146. }
  147. }
  148. } else {
  149. // The sensor is being configured to Off, but is already Off (there is no
  150. // existing request). We assign to success to be true and no other
  151. // operation is required.
  152. requestChanged = false;
  153. success = true;
  154. }
  155. } else if (!nanoappHasRequest) {
  156. // The request changes the mode to the enabled state and there was no
  157. // existing request. The request is newly created and added to the
  158. // multiplexer. The nanoapp is registered for events if this request was
  159. // successful.
  160. success = requests.add(sensorRequest, &requestChanged);
  161. if (success) {
  162. nanoapp->registerForBroadcastEvent(eventType);
  163. // Per API requirements, turn on bias reporting for calibrated sensors
  164. // by default when subscribed.
  165. uint16_t biasEventType;
  166. if (getSensorBiasEventType(sensorType, &biasEventType)
  167. && sensorTypeIsCalibrated(sensorType)) {
  168. nanoapp->registerForBroadcastEvent(biasEventType);
  169. }
  170. // Deliver last valid event to new clients of on-change sensors
  171. if (sensorTypeIsOnChange(sensor.getSensorType()) &&
  172. sensor.getLastEvent() != nullptr) {
  173. EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
  174. getSampleEventTypeForSensorType(sensorType), sensor.getLastEvent(),
  175. nullptr, nanoapp->getInstanceId());
  176. }
  177. }
  178. } else {
  179. // The request changes the mode to the enabled state and there was an
  180. // existing request. The existing request is updated.
  181. success = requests.update(requestIndex, sensorRequest, &requestChanged);
  182. }
  183. if (requestChanged) {
  184. // TODO: Send an event to nanoapps to indicate the rate change.
  185. }
  186. return success;
  187. }
  188. bool SensorRequestManager::getSensorInfo(uint32_t sensorHandle,
  189. const Nanoapp& nanoapp,
  190. struct chreSensorInfo *info) const {
  191. CHRE_ASSERT(info);
  192. bool success = false;
  193. // Validate the input to ensure that a valid handle has been provided.
  194. SensorType sensorType = getSensorTypeFromSensorHandle(sensorHandle);
  195. if (!isValidSensorType(sensorType)) {
  196. LOG_INVALID_SENSOR(sensorType);
  197. } else {
  198. size_t sensorIndex = getSensorTypeArrayIndex(sensorType);
  199. if (!mSensorRequests[sensorIndex].isSensorSupported()) {
  200. LOGW("Attempting to get sensor info for unsupported sensor handle %"
  201. PRIu32, sensorHandle);
  202. } else {
  203. // Platform-independent properties.
  204. info->sensorType = getUnsignedIntFromSensorType(sensorType);
  205. info->isOnChange = sensorTypeIsOnChange(sensorType);
  206. info->isOneShot = sensorTypeIsOneShot(sensorType);
  207. info->reportsBiasEvents = sensorTypeReportsBias(sensorType);
  208. info->unusedFlags = 0;
  209. // Platform-specific properties.
  210. const Sensor& sensor = mSensorRequests[sensorIndex].getSensor();
  211. info->sensorName = sensor.getSensorName();
  212. // minInterval was added in CHRE API v1.1 - do not attempt to populate for
  213. // nanoapps targeting v1.0 as their struct will not be large enough
  214. if (nanoapp.getTargetApiVersion() >= CHRE_API_VERSION_1_1) {
  215. info->minInterval = sensor.getMinInterval();
  216. }
  217. success = true;
  218. }
  219. }
  220. return success;
  221. }
  222. bool SensorRequestManager::removeAllRequests(SensorType sensorType) {
  223. bool success = false;
  224. if (!isValidSensorType(sensorType)) {
  225. LOG_INVALID_SENSOR(sensorType);
  226. } else {
  227. size_t sensorIndex = getSensorTypeArrayIndex(sensorType);
  228. SensorRequests& requests = mSensorRequests[sensorIndex];
  229. uint16_t eventType = getSampleEventTypeForSensorType(sensorType);
  230. for (const SensorRequest& request : requests.getRequests()) {
  231. Nanoapp *nanoapp = EventLoopManagerSingleton::get()->getEventLoop()
  232. .findNanoappByInstanceId(request.getInstanceId());
  233. if (nanoapp != nullptr) {
  234. nanoapp->unregisterForBroadcastEvent(eventType);
  235. }
  236. }
  237. cancelFlushRequests(sensorType);
  238. success = requests.removeAll();
  239. }
  240. return success;
  241. }
  242. Sensor *SensorRequestManager::getSensor(SensorType sensorType) {
  243. Sensor *sensorPtr = nullptr;
  244. if (!isValidSensorType(sensorType)) {
  245. LOG_INVALID_SENSOR(sensorType);
  246. } else {
  247. size_t sensorIndex = getSensorTypeArrayIndex(sensorType);
  248. if (mSensorRequests[sensorIndex].isSensorSupported()) {
  249. sensorPtr = &mSensorRequests[sensorIndex].getSensor();
  250. }
  251. }
  252. return sensorPtr;
  253. }
  254. bool SensorRequestManager::getSensorSamplingStatus(
  255. uint32_t sensorHandle, struct chreSensorSamplingStatus *status) const {
  256. CHRE_ASSERT(status);
  257. bool success = false;
  258. SensorType sensorType = getSensorTypeFromSensorHandle(sensorHandle);
  259. if (!isValidSensorType(sensorType)) {
  260. LOG_INVALID_SENSOR(sensorType);
  261. } else {
  262. size_t sensorIndex = getSensorTypeArrayIndex(sensorType);
  263. if (mSensorRequests[sensorIndex].isSensorSupported()) {
  264. success = mSensorRequests[sensorIndex].getSamplingStatus(status);
  265. }
  266. }
  267. return success;
  268. }
  269. const DynamicVector<SensorRequest>& SensorRequestManager::getRequests(
  270. SensorType sensorType) const {
  271. size_t sensorIndex = 0;
  272. if (!isValidSensorType(sensorType)) {
  273. LOG_INVALID_SENSOR(sensorType);
  274. } else {
  275. sensorIndex = getSensorTypeArrayIndex(sensorType);
  276. }
  277. return mSensorRequests[sensorIndex].getRequests();
  278. }
  279. bool SensorRequestManager::configureBiasEvents(
  280. Nanoapp *nanoapp, uint32_t sensorHandle, bool enable) {
  281. bool success = false;
  282. uint16_t eventType;
  283. SensorType sensorType = getSensorTypeFromSensorHandle(sensorHandle);
  284. if (getSensorBiasEventType(sensorType, &eventType)) {
  285. if (enable) {
  286. nanoapp->registerForBroadcastEvent(eventType);
  287. } else {
  288. nanoapp->unregisterForBroadcastEvent(eventType);
  289. }
  290. success = true;
  291. }
  292. return success;
  293. }
  294. bool SensorRequestManager::getThreeAxisBias(
  295. uint32_t sensorHandle, struct chreSensorThreeAxisData *bias) const {
  296. CHRE_ASSERT(bias != nullptr);
  297. bool success = false;
  298. if (bias != nullptr) {
  299. SensorType sensorType = getSensorTypeFromSensorHandle(sensorHandle);
  300. if (!isValidSensorType(sensorType)) {
  301. LOG_INVALID_SENSOR(sensorType);
  302. } else {
  303. size_t sensorIndex = getSensorTypeArrayIndex(sensorType);
  304. if (mSensorRequests[sensorIndex].isSensorSupported()) {
  305. success = mSensorRequests[sensorIndex].getThreeAxisBias(bias);
  306. }
  307. }
  308. }
  309. return success;
  310. }
  311. bool SensorRequestManager::flushAsync(
  312. Nanoapp *nanoapp, uint32_t sensorHandle, const void *cookie) {
  313. bool success = false;
  314. uint32_t nanoappInstanceId = nanoapp->getInstanceId();
  315. SensorType sensorType = getSensorTypeFromSensorHandle(sensorHandle);
  316. // NOTE: One-shot sensors do not support flush per API
  317. if (!isValidSensorType(sensorType) || sensorTypeIsOneShot(sensorType)) {
  318. LOGE("Cannot flush for sensor type %" PRIu32,
  319. static_cast<uint32_t>(sensorType));
  320. } else if (mFlushRequestQueue.full()) {
  321. LOG_OOM();
  322. } else {
  323. mFlushRequestQueue.emplace_back(sensorType, nanoappInstanceId, cookie);
  324. size_t sensorIndex = getSensorTypeArrayIndex(sensorType);
  325. success = (mSensorRequests[sensorIndex].makeFlushRequest(
  326. mFlushRequestQueue.back()) == CHRE_ERROR_NONE);
  327. if (!success) {
  328. mFlushRequestQueue.pop_back();
  329. }
  330. }
  331. return success;
  332. }
  333. void SensorRequestManager::handleFlushCompleteEvent(
  334. uint8_t errorCode, SensorType sensorType) {
  335. size_t sensorIndex = getSensorTypeArrayIndex(sensorType);
  336. if (isValidSensorType(sensorType)
  337. && mSensorRequests[sensorIndex].isFlushRequestPending()) {
  338. // Cancel flush request timer before posting to the event queue to ensure
  339. // a timeout event isn't processed by CHRE now that the complete event
  340. // has been received.
  341. mSensorRequests[sensorIndex].cancelPendingFlushRequestTimer();
  342. struct CallbackState {
  343. uint8_t errorCode;
  344. SensorType sensorType;
  345. };
  346. NestedDataPtr<CallbackState> state = {};
  347. state.data.errorCode = errorCode;
  348. state.data.sensorType = sensorType;
  349. auto callback = [](uint16_t /* eventType */, void *eventData) {
  350. NestedDataPtr<CallbackState> nestedState;
  351. nestedState.dataPtr = eventData;
  352. EventLoopManagerSingleton::get()->getSensorRequestManager()
  353. .handleFlushCompleteEventSync(nestedState.data.errorCode,
  354. nestedState.data.sensorType);
  355. };
  356. EventLoopManagerSingleton::get()->deferCallback(
  357. SystemCallbackType::SensorFlushComplete, state.dataPtr, callback);
  358. }
  359. }
  360. void SensorRequestManager::handleSensorEvent(SensorType sensorType,
  361. void *event) {
  362. uint16_t eventType = getSampleEventTypeForSensorType(sensorType);
  363. // Only allow dropping continuous sensor events since losing one-shot or
  364. // on-change events could result in nanoapps stuck in a bad state.
  365. if (sensorTypeIsContinuous(sensorType)) {
  366. EventLoopManagerSingleton::get()->getEventLoop().postLowPriorityEventOrFree(
  367. eventType, event, sensorDataEventFree);
  368. } else {
  369. EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
  370. eventType, event, sensorDataEventFree);
  371. }
  372. }
  373. void SensorRequestManager::logStateToBuffer(char *buffer, size_t *bufferPos,
  374. size_t bufferSize) const {
  375. debugDumpPrint(buffer, bufferPos, bufferSize, "\nSensors:\n");
  376. for (uint8_t i = 0; i < static_cast<uint8_t>(SensorType::SENSOR_TYPE_COUNT);
  377. i++) {
  378. SensorType sensor = static_cast<SensorType>(i);
  379. if (isValidSensorType(sensor)) {
  380. for (const auto& request : getRequests(sensor)) {
  381. debugDumpPrint(buffer, bufferPos, bufferSize, " %s: mode=%d"
  382. " interval(ns)=%" PRIu64 " latency(ns)=%"
  383. PRIu64 " nanoappId=%" PRIu32 "\n",
  384. getSensorTypeName(sensor), request.getMode(),
  385. request.getInterval().toRawNanoseconds(),
  386. request.getLatency().toRawNanoseconds(),
  387. request.getInstanceId());
  388. }
  389. }
  390. }
  391. }
  392. void SensorRequestManager::postFlushCompleteEvent(
  393. uint32_t sensorHandle, uint8_t errorCode, const FlushRequest& request) {
  394. auto *event = memoryAlloc<chreSensorFlushCompleteEvent>();
  395. if (event == nullptr) {
  396. LOG_OOM();
  397. } else {
  398. event->sensorHandle = sensorHandle;
  399. event->errorCode = errorCode;
  400. event->cookie = request.cookie;
  401. memset(event->reserved, 0, sizeof(event->reserved));
  402. EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
  403. CHRE_EVENT_SENSOR_FLUSH_COMPLETE, event, freeEventDataCallback,
  404. request.nanoappInstanceId);
  405. }
  406. }
  407. void SensorRequestManager::completeFlushRequestAtIndex(
  408. size_t index, uint8_t errorCode) {
  409. if (index < mFlushRequestQueue.size()) {
  410. const FlushRequest& request = mFlushRequestQueue[index];
  411. SensorType sensorType = request.sensorType;
  412. if (request.isActive) {
  413. SensorRequests& requests = getSensorRequests(sensorType);
  414. requests.clearPendingFlushRequest();
  415. }
  416. uint32_t sensorHandle;
  417. if (getSensorHandle(sensorType, &sensorHandle)) {
  418. postFlushCompleteEvent(sensorHandle, errorCode, request);
  419. }
  420. mFlushRequestQueue.erase(index);
  421. }
  422. }
  423. void SensorRequestManager::dispatchNextFlushRequest(SensorType sensorType) {
  424. SensorRequests& requests = getSensorRequests(sensorType);
  425. for (size_t i = 0; i < mFlushRequestQueue.size(); i++) {
  426. FlushRequest& request = mFlushRequestQueue[i];
  427. if (request.sensorType == sensorType) {
  428. uint8_t newRequestErrorCode = requests.makeFlushRequest(request);
  429. if (newRequestErrorCode == CHRE_ERROR_NONE) {
  430. break;
  431. } else {
  432. completeFlushRequestAtIndex(i, newRequestErrorCode);
  433. i--;
  434. }
  435. }
  436. }
  437. }
  438. void SensorRequestManager::handleFlushCompleteEventSync(
  439. uint8_t errorCode, SensorType sensorType) {
  440. for (size_t i = 0; i < mFlushRequestQueue.size(); i++) {
  441. if (mFlushRequestQueue[i].sensorType == sensorType) {
  442. completeFlushRequestAtIndex(i, errorCode);
  443. dispatchNextFlushRequest(sensorType);
  444. break;
  445. }
  446. }
  447. }
  448. void SensorRequestManager::cancelFlushRequests(
  449. SensorType sensorType, uint32_t nanoappInstanceId) {
  450. bool removeAll = (nanoappInstanceId == kSystemInstanceId);
  451. for (size_t i = 0; i < mFlushRequestQueue.size(); i++) {
  452. const FlushRequest& request = mFlushRequestQueue[i];
  453. if (request.sensorType == sensorType &&
  454. (request.nanoappInstanceId == nanoappInstanceId || removeAll)) {
  455. completeFlushRequestAtIndex(
  456. i, CHRE_ERROR_FUNCTION_DISABLED /* errorCode */);
  457. i--;
  458. }
  459. }
  460. SensorRequests& requests = getSensorRequests(sensorType);
  461. if (!requests.isFlushRequestPending()) {
  462. dispatchNextFlushRequest(sensorType);
  463. }
  464. }
  465. const SensorRequest *SensorRequestManager::SensorRequests::find(
  466. uint32_t instanceId, size_t *index) const {
  467. CHRE_ASSERT(index);
  468. const auto& requests = mMultiplexer.getRequests();
  469. for (size_t i = 0; i < requests.size(); i++) {
  470. const SensorRequest& sensorRequest = requests[i];
  471. if (sensorRequest.getInstanceId() == instanceId) {
  472. *index = i;
  473. return &sensorRequest;
  474. }
  475. }
  476. return nullptr;
  477. }
  478. bool SensorRequestManager::SensorRequests::add(const SensorRequest& request,
  479. bool *requestChanged) {
  480. CHRE_ASSERT(requestChanged != nullptr);
  481. CHRE_ASSERT(isSensorSupported());
  482. size_t addIndex;
  483. bool success = true;
  484. if (!mMultiplexer.addRequest(request, &addIndex, requestChanged)) {
  485. *requestChanged = false;
  486. success = false;
  487. LOG_OOM();
  488. } else if (*requestChanged) {
  489. success = mSensor->setRequest(mMultiplexer.getCurrentMaximalRequest());
  490. if (!success) {
  491. // Remove the newly added request since the platform failed to handle it.
  492. // The sensor is expected to maintain the existing request so there is no
  493. // need to reset the platform to the last maximal request.
  494. mMultiplexer.removeRequest(addIndex, requestChanged);
  495. // This is a roll-back operation so the maximal change in the multiplexer
  496. // must not have changed. The request changed state is forced to false.
  497. *requestChanged = false;
  498. }
  499. }
  500. return success;
  501. }
  502. bool SensorRequestManager::SensorRequests::remove(size_t removeIndex,
  503. bool *requestChanged) {
  504. CHRE_ASSERT(requestChanged != nullptr);
  505. CHRE_ASSERT(isSensorSupported());
  506. bool success = true;
  507. mMultiplexer.removeRequest(removeIndex, requestChanged);
  508. if (*requestChanged) {
  509. success = mSensor->setRequest(mMultiplexer.getCurrentMaximalRequest());
  510. if (!success) {
  511. LOGE("SensorRequestManager failed to remove a request");
  512. // If the platform fails to handle this request in a debug build there is
  513. // likely an error in the platform. This is not strictly a programming
  514. // error but it does make sense to use assert semantics when a platform
  515. // fails to handle a request that it had been sent previously.
  516. CHRE_ASSERT(false);
  517. // The request to the platform to set a request when removing has failed
  518. // so the request has not changed.
  519. *requestChanged = false;
  520. }
  521. }
  522. return success;
  523. }
  524. bool SensorRequestManager::SensorRequests::update(size_t updateIndex,
  525. const SensorRequest& request,
  526. bool *requestChanged) {
  527. CHRE_ASSERT(requestChanged != nullptr);
  528. CHRE_ASSERT(isSensorSupported());
  529. bool success = true;
  530. SensorRequest previousRequest = mMultiplexer.getRequests()[updateIndex];
  531. mMultiplexer.updateRequest(updateIndex, request, requestChanged);
  532. if (*requestChanged) {
  533. success = mSensor->setRequest(mMultiplexer.getCurrentMaximalRequest());
  534. if (!success) {
  535. // Roll back the request since sending it to the sensor failed. The
  536. // request will roll back to the previous maximal. The sensor is
  537. // expected to maintain the existing request if a request fails so there
  538. // is no need to reset the platform to the last maximal request.
  539. mMultiplexer.updateRequest(updateIndex, previousRequest, requestChanged);
  540. // This is a roll-back operation so the maximal change in the multiplexer
  541. // must not have changed. The request changed state is forced to false.
  542. *requestChanged = false;
  543. }
  544. }
  545. return success;
  546. }
  547. bool SensorRequestManager::SensorRequests::removeAll() {
  548. CHRE_ASSERT(isSensorSupported());
  549. bool requestChanged;
  550. mMultiplexer.removeAllRequests(&requestChanged);
  551. bool success = true;
  552. if (requestChanged) {
  553. SensorRequest maximalRequest = mMultiplexer.getCurrentMaximalRequest();
  554. success = mSensor->setRequest(maximalRequest);
  555. if (!success) {
  556. LOGE("SensorRequestManager failed to remove all request");
  557. // If the platform fails to handle this request in a debug build there is
  558. // likely an error in the platform. This is not strictly a programming
  559. // error but it does make sense to use assert semantics when a platform
  560. // fails to handle a request that it had been sent previously.
  561. CHRE_ASSERT(false);
  562. }
  563. }
  564. return success;
  565. }
  566. uint8_t SensorRequestManager::SensorRequests::makeFlushRequest(
  567. FlushRequest& request) {
  568. uint8_t errorCode = CHRE_ERROR;
  569. if (!isSensorSupported()) {
  570. LOGE("Cannot flush on unsupported sensor");
  571. } else if (mMultiplexer.getRequests().size() == 0) {
  572. LOGE("Cannot flush on disabled sensor");
  573. } else if (!isFlushRequestPending()) {
  574. Nanoseconds now = SystemTime::getMonotonicTime();
  575. Nanoseconds deadline = request.deadlineTimestamp;
  576. if (now >= deadline) {
  577. LOGE("Flush sensor %" PRIu32 " failed for nanoapp ID %" PRIu32
  578. ": deadline exceeded", static_cast<uint32_t>(request.sensorType),
  579. request.nanoappInstanceId);
  580. errorCode = CHRE_ERROR_TIMEOUT;
  581. } else if (doMakeFlushRequest()) {
  582. errorCode = CHRE_ERROR_NONE;
  583. Nanoseconds delay = deadline - now;
  584. request.isActive = true;
  585. NestedDataPtr<SensorType> nestedType = {};
  586. nestedType.data = request.sensorType;
  587. auto callback = [](uint16_t /* eventType */, void * eventData) {
  588. LOGE("Flush request timed out.");
  589. NestedDataPtr<SensorType> nestedType;
  590. nestedType.dataPtr = eventData;
  591. // Send a complete event, thus closing out this flush request. If the
  592. // request that has just timed out receives a response later, this may
  593. // inadvertently close out a new request before it has actually
  594. // completed.
  595. // TODO: Attach an ID to all flush requests / responses so stale
  596. // responses can be properly dropped.
  597. EventLoopManagerSingleton::get()->getSensorRequestManager()
  598. .handleFlushCompleteEventSync(CHRE_ERROR_TIMEOUT,
  599. nestedType.data);
  600. };
  601. mFlushRequestTimerHandle =
  602. EventLoopManagerSingleton::get()->setDelayedCallback(
  603. SystemCallbackType::SensorFlushTimeout, nestedType.dataPtr,
  604. callback, delay);
  605. }
  606. } else {
  607. // Flush request will be made once the pending request is completed.
  608. // Return true so that the nanoapp can wait for a result through the
  609. // CHRE_EVENT_SENSOR_FLUSH_COMPLETE event.
  610. errorCode = CHRE_ERROR_NONE;
  611. }
  612. return errorCode;
  613. }
  614. void SensorRequestManager::SensorRequests::clearPendingFlushRequest() {
  615. cancelPendingFlushRequestTimer();
  616. mFlushRequestPending = false;
  617. }
  618. void SensorRequestManager::SensorRequests::cancelPendingFlushRequestTimer() {
  619. if (mFlushRequestTimerHandle != CHRE_TIMER_INVALID) {
  620. EventLoopManagerSingleton::get()->cancelDelayedCallback(
  621. mFlushRequestTimerHandle);
  622. mFlushRequestTimerHandle = CHRE_TIMER_INVALID;
  623. }
  624. }
  625. bool SensorRequestManager::SensorRequests::doMakeFlushRequest() {
  626. // Set to true before making the request since it's a synchronous request
  627. // and we may get the complete event before it returns.
  628. mFlushRequestPending = true;
  629. mFlushRequestPending = mSensor->flushAsync();
  630. return mFlushRequestPending;
  631. }
  632. } // namespace chre