• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 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 #define LOG_TAG "GoogleIIOSensorSubHal"
17 
18 #include "Sensor.h"
19 #include <hardware/sensors.h>
20 #include <log/log.h>
21 #include <utils/SystemClock.h>
22 #include <cmath>
23 
24 namespace android {
25 namespace hardware {
26 namespace sensors {
27 namespace V2_0 {
28 namespace subhal {
29 namespace implementation {
30 
31 using ::android::hardware::sensors::V1_0::AdditionalInfoType;
32 using ::android::hardware::sensors::V1_0::MetaDataEventType;
33 using ::android::hardware::sensors::V1_0::SensorFlagBits;
34 using ::android::hardware::sensors::V1_0::SensorStatus;
35 using ::sensor::hal::configuration::V1_0::Location;
36 using ::sensor::hal::configuration::V1_0::Orientation;
37 
SensorBase(int32_t sensorHandle,ISensorsEventCallback * callback,SensorType type)38 SensorBase::SensorBase(int32_t sensorHandle, ISensorsEventCallback* callback, SensorType type)
39     : mIsEnabled(false),
40       mSamplingPeriodNs(0),
41       mCallback(callback),
42       mMode(OperationMode::NORMAL),
43       mSensorThread(this) {
44     mSensorInfo.type = type;
45     mSensorInfo.sensorHandle = sensorHandle;
46     mSensorInfo.vendor = "Google";
47     mSensorInfo.version = 1;
48     mSensorInfo.fifoReservedEventCount = 0;
49     mSensorInfo.fifoMaxEventCount = 0;
50     mSensorInfo.requiredPermission = "";
51     mSensorInfo.flags = 0;
52 
53     switch (type) {
54         case SensorType::ACCELEROMETER:
55             mSensorInfo.typeAsString = SENSOR_STRING_TYPE_ACCELEROMETER;
56             break;
57         case SensorType::GYROSCOPE:
58             mSensorInfo.typeAsString = SENSOR_STRING_TYPE_GYROSCOPE;
59             break;
60         default:
61             ALOGE("unsupported sensor type %d", type);
62             break;
63     }
64 
65     mSensorThread.start();
66 }
67 
~SensorBase()68 SensorBase::~SensorBase() {
69     mIsEnabled = false;
70 }
71 
isEnabled() const72 bool SensorBase::isEnabled() const {
73     return mIsEnabled;
74 }
75 
getOperationMode() const76 OperationMode SensorBase::getOperationMode() const {
77     return mMode;
78 }
79 
~HWSensorBase()80 HWSensorBase::~HWSensorBase() {
81     close(mPollFdIio.fd);
82 }
83 
getSensorInfo() const84 const SensorInfo& SensorBase::getSensorInfo() const {
85     return mSensorInfo;
86 }
87 
batch(int32_t samplingPeriodNs)88 void HWSensorBase::batch(int32_t samplingPeriodNs) {
89     samplingPeriodNs =
90             std::clamp(samplingPeriodNs, mSensorInfo.minDelay * 1000, mSensorInfo.maxDelay * 1000);
91     if (mSamplingPeriodNs != samplingPeriodNs) {
92         unsigned int sampling_frequency = ns_to_frequency(samplingPeriodNs);
93         int i = 0;
94         mSamplingPeriodNs = samplingPeriodNs;
95         std::vector<double>::iterator low =
96                 std::lower_bound(mIioData.sampling_freq_avl.begin(),
97                                  mIioData.sampling_freq_avl.end(), sampling_frequency);
98         i = low - mIioData.sampling_freq_avl.begin();
99         set_sampling_frequency(mIioData.sysfspath, mIioData.sampling_freq_avl[i]);
100         // Wake up the 'run' thread to check if a new event should be generated now
101         mSensorThread.notifyAll();
102     }
103 }
104 
sendAdditionalInfoReport()105 void HWSensorBase::sendAdditionalInfoReport() {
106     std::vector<Event> events;
107 
108     for (const auto& frame : mAdditionalInfoFrames) {
109         events.emplace_back(Event{
110                 .sensorHandle = mSensorInfo.sensorHandle,
111                 .sensorType = SensorType::ADDITIONAL_INFO,
112                 .timestamp = android::elapsedRealtimeNano(),
113                 .u.additional = frame,
114         });
115     }
116 
117     if (!events.empty()) mCallback->postEvents(events, isWakeUpSensor());
118 }
119 
activate(bool enable)120 void HWSensorBase::activate(bool enable) {
121     std::unique_lock<std::mutex> lock(mSensorThread.lock());
122     if (mIsEnabled != enable) {
123         mIsEnabled = enable;
124         enable_sensor(mIioData.sysfspath, enable);
125         if (enable) sendAdditionalInfoReport();
126         mSensorThread.notifyAll();
127     }
128 }
129 
flush()130 Result SensorBase::flush() {
131     // Only generate a flush complete event if the sensor is enabled and if the sensor is not a
132     // one-shot sensor.
133     if (!mIsEnabled || (mSensorInfo.flags & static_cast<uint32_t>(SensorFlagBits::ONE_SHOT_MODE))) {
134         return Result::BAD_VALUE;
135     }
136 
137     // Note: If a sensor supports batching, write all of the currently batched events for the sensor
138     // to the Event FMQ prior to writing the flush complete event.
139     Event ev;
140     ev.sensorHandle = mSensorInfo.sensorHandle;
141     ev.sensorType = SensorType::META_DATA;
142     ev.u.meta.what = MetaDataEventType::META_DATA_FLUSH_COMPLETE;
143     std::vector<Event> evs{ev};
144     mCallback->postEvents(evs, isWakeUpSensor());
145     return Result::OK;
146 }
147 
flush()148 Result HWSensorBase::flush() {
149     Result result = Result::OK;
150     result = SensorBase::flush();
151     if (result == Result::OK) sendAdditionalInfoReport();
152     return result;
153 }
154 
155 template <size_t N>
getChannelData(const std::array<float,N> & channelData,int64_t map,bool negate)156 static float getChannelData(const std::array<float, N>& channelData, int64_t map, bool negate) {
157     return negate ? -channelData[map] : channelData[map];
158 }
159 
processScanData(uint8_t * data,Event * evt)160 void HWSensorBase::processScanData(uint8_t* data, Event* evt) {
161     std::array<float, NUM_OF_DATA_CHANNELS> channelData;
162     unsigned int chanIdx;
163     evt->sensorHandle = mSensorInfo.sensorHandle;
164     evt->sensorType = mSensorInfo.type;
165     for (auto i = 0u; i < mIioData.channelInfo.size(); i++) {
166         chanIdx = mIioData.channelInfo[i].index;
167 
168         const int64_t val =
169                 *reinterpret_cast<int64_t*>(data + chanIdx * mIioData.channelInfo[i].storage_bytes);
170         // If the channel index is the last, it is timestamp
171         // else it is sensor data
172         if (chanIdx == mIioData.channelInfo.size() - 1) {
173             evt->timestamp = val;
174         } else {
175             channelData[chanIdx] = static_cast<float>(val) * mIioData.scale;
176         }
177     }
178 
179     evt->u.vec3.x = getChannelData(channelData, mXMap, mXNegate);
180     evt->u.vec3.y = getChannelData(channelData, mYMap, mYNegate);
181     evt->u.vec3.z = getChannelData(channelData, mZMap, mZNegate);
182     evt->u.vec3.status = SensorStatus::ACCURACY_HIGH;
183 }
184 
pollForEvents()185 void HWSensorBase::pollForEvents() {
186     int err = poll(&mPollFdIio, 1, mSamplingPeriodNs * 1000);
187     if (err <= 0) {
188         ALOGE("Sensor %s poll returned %d", mIioData.name.c_str(), err);
189         return;
190     }
191 
192     if (mPollFdIio.revents & POLLIN) {
193         int read_size = read(mPollFdIio.fd, &mSensorRawData[0], mScanSize);
194         if (read_size <= 0) {
195             ALOGE("%s: Failed to read data from iio char device.", mIioData.name.c_str());
196             return;
197         }
198 
199         Event evt;
200         processScanData(&mSensorRawData[0], &evt);
201         mCallback->postEvents({evt}, isWakeUpSensor());
202     }
203 }
204 
idleLoop()205 void HWSensorBase::idleLoop() {
206     mSensorThread.wait([this] {
207         return ((mIsEnabled && mMode == OperationMode::NORMAL) || mSensorThread.isStopped());
208     });
209 }
210 
pollSensor()211 void HWSensorBase::pollSensor() {
212     if (!mIsEnabled || mMode == OperationMode::DATA_INJECTION) {
213         idleLoop();
214     } else {
215         pollForEvents();
216     }
217 }
218 
isWakeUpSensor()219 bool SensorBase::isWakeUpSensor() {
220     return mSensorInfo.flags & static_cast<uint32_t>(SensorFlagBits::WAKE_UP);
221 }
222 
setOperationMode(OperationMode mode)223 void SensorBase::setOperationMode(OperationMode mode) {
224     std::unique_lock<std::mutex> lock(mSensorThread.lock());
225     if (mMode != mode) {
226         mMode = mode;
227         mSensorThread.notifyAll();
228     }
229 }
230 
supportsDataInjection() const231 bool SensorBase::supportsDataInjection() const {
232     return mSensorInfo.flags & static_cast<uint32_t>(SensorFlagBits::DATA_INJECTION);
233 }
234 
injectEvent(const Event & event)235 Result SensorBase::injectEvent(const Event& event) {
236     Result result = Result::OK;
237     if (event.sensorType == SensorType::ADDITIONAL_INFO) {
238         // When in OperationMode::NORMAL, SensorType::ADDITIONAL_INFO is used to push operation
239         // environment data into the device.
240     } else if (!supportsDataInjection()) {
241         result = Result::INVALID_OPERATION;
242     } else if (mMode == OperationMode::DATA_INJECTION) {
243         mCallback->postEvents(std::vector<Event>{event}, isWakeUpSensor());
244     } else {
245         result = Result::BAD_VALUE;
246     }
247     return result;
248 }
249 
calculateScanSize()250 ssize_t HWSensorBase::calculateScanSize() {
251     ssize_t numBytes = 0;
252     for (auto i = 0u; i < mIioData.channelInfo.size(); i++) {
253         numBytes += mIioData.channelInfo[i].storage_bytes;
254     }
255     return numBytes;
256 }
257 
checkAxis(int64_t map)258 static status_t checkAxis(int64_t map) {
259     if (map < 0 || map >= NUM_OF_DATA_CHANNELS)
260         return BAD_VALUE;
261     else
262         return OK;
263 }
264 
getOrientation(std::optional<std::vector<Configuration>> config)265 static std::optional<std::vector<Orientation>> getOrientation(
266         std::optional<std::vector<Configuration>> config) {
267     if (!config) return std::nullopt;
268     if (config->empty()) return std::nullopt;
269     Configuration& sensorCfg = (*config)[0];
270     return sensorCfg.getOrientation();
271 }
272 
getLocation(std::optional<std::vector<Configuration>> config)273 static std::optional<std::vector<Location>> getLocation(
274         std::optional<std::vector<Configuration>> config) {
275     if (!config) return std::nullopt;
276     if (config->empty()) return std::nullopt;
277     Configuration& sensorCfg = (*config)[0];
278     return sensorCfg.getLocation();
279 }
280 
checkOrientation(std::optional<std::vector<Configuration>> config)281 static status_t checkOrientation(std::optional<std::vector<Configuration>> config) {
282     status_t ret = OK;
283     std::optional<std::vector<Orientation>> sensorOrientationList = getOrientation(config);
284     if (!sensorOrientationList) return OK;
285     if (sensorOrientationList->empty()) return OK;
286     Orientation& sensorOrientation = (*sensorOrientationList)[0];
287     if (!sensorOrientation.getFirstX() || !sensorOrientation.getFirstY() ||
288         !sensorOrientation.getFirstZ())
289         return BAD_VALUE;
290 
291     int64_t xMap = sensorOrientation.getFirstX()->getMap();
292     ret = checkAxis(xMap);
293     if (ret != OK) return ret;
294     int64_t yMap = sensorOrientation.getFirstY()->getMap();
295     ret = checkAxis(yMap);
296     if (ret != OK) return ret;
297     int64_t zMap = sensorOrientation.getFirstZ()->getMap();
298     ret = checkAxis(zMap);
299     if (ret != OK) return ret;
300     if (xMap == yMap || yMap == zMap || zMap == xMap) return BAD_VALUE;
301     return ret;
302 }
303 
setAxisDefaultValues()304 void HWSensorBase::setAxisDefaultValues() {
305     mXMap = 0;
306     mYMap = 1;
307     mZMap = 2;
308     mXNegate = mYNegate = mZNegate = false;
309 }
setOrientation(std::optional<std::vector<Configuration>> config)310 void HWSensorBase::setOrientation(std::optional<std::vector<Configuration>> config) {
311     std::optional<std::vector<Orientation>> sensorOrientationList = getOrientation(config);
312 
313     if (sensorOrientationList && !sensorOrientationList->empty()) {
314         Orientation& sensorOrientation = (*sensorOrientationList)[0];
315 
316         if (sensorOrientation.getRotate()) {
317             mXMap = sensorOrientation.getFirstX()->getMap();
318             mXNegate = sensorOrientation.getFirstX()->getNegate();
319             mYMap = sensorOrientation.getFirstY()->getMap();
320             mYNegate = sensorOrientation.getFirstY()->getNegate();
321             mZMap = sensorOrientation.getFirstZ()->getMap();
322             mZNegate = sensorOrientation.getFirstZ()->getNegate();
323         } else {
324             setAxisDefaultValues();
325         }
326     } else {
327         setAxisDefaultValues();
328     }
329 }
330 
checkIIOData(const struct iio_device_data & iio_data)331 static status_t checkIIOData(const struct iio_device_data& iio_data) {
332     status_t ret = OK;
333     for (auto i = 0u; i < iio_data.channelInfo.size(); i++) {
334         if (iio_data.channelInfo[i].index > NUM_OF_DATA_CHANNELS) return BAD_VALUE;
335     }
336     return ret;
337 }
338 
setSensorPlacementData(AdditionalInfo * sensorPlacement,int index,float value)339 static status_t setSensorPlacementData(AdditionalInfo* sensorPlacement, int index, float value) {
340     if (!sensorPlacement) return BAD_VALUE;
341 
342     int arraySize =
343             sizeof(sensorPlacement->u.data_float) / sizeof(sensorPlacement->u.data_float[0]);
344     if (index < 0 || index >= arraySize) return BAD_VALUE;
345 
346     sensorPlacement->u.data_float[index] = value;
347     return OK;
348 }
349 
getSensorPlacement(AdditionalInfo * sensorPlacement,const std::optional<std::vector<Configuration>> & config)350 status_t HWSensorBase::getSensorPlacement(AdditionalInfo* sensorPlacement,
351                                           const std::optional<std::vector<Configuration>>& config) {
352     if (!sensorPlacement) return BAD_VALUE;
353 
354     auto sensorLocationList = getLocation(config);
355     if (!sensorLocationList) return BAD_VALUE;
356     if (sensorLocationList->empty()) return BAD_VALUE;
357 
358     auto sensorOrientationList = getOrientation(config);
359     if (!sensorOrientationList) return BAD_VALUE;
360     if (sensorOrientationList->empty()) return BAD_VALUE;
361 
362     sensorPlacement->type = AdditionalInfoType::AINFO_SENSOR_PLACEMENT;
363     sensorPlacement->serial = 0;
364     memset(&sensorPlacement->u.data_float, 0, sizeof(sensorPlacement->u.data_float));
365 
366     Location& sensorLocation = (*sensorLocationList)[0];
367     // SensorPlacementData is given as a 3x4 matrix consisting of a 3x3 rotation matrix (R)
368     // concatenated with a 3x1 location vector (t) in row major order. Example: This raw buffer:
369     // {x1,y1,z1,l1,x2,y2,z2,l2,x3,y3,z3,l3} corresponds to the following 3x4 matrix:
370     //  x1 y1 z1 l1
371     //  x2 y2 z2 l2
372     //  x3 y3 z3 l3
373     // LOCATION_X_IDX,LOCATION_Y_IDX,LOCATION_Z_IDX corresponds to the indexes of the location
374     // vector (l1,l2,l3) in the raw buffer.
375     status_t ret = setSensorPlacementData(sensorPlacement, HWSensorBase::LOCATION_X_IDX,
376                                           sensorLocation.getX());
377     if (ret != OK) return ret;
378     ret = setSensorPlacementData(sensorPlacement, HWSensorBase::LOCATION_Y_IDX,
379                                  sensorLocation.getY());
380     if (ret != OK) return ret;
381     ret = setSensorPlacementData(sensorPlacement, HWSensorBase::LOCATION_Z_IDX,
382                                  sensorLocation.getZ());
383     if (ret != OK) return ret;
384 
385     Orientation& sensorOrientation = (*sensorOrientationList)[0];
386     if (sensorOrientation.getRotate()) {
387         // If the HAL is already rotating the sensor orientation to align with the Android
388         // Coordinate system, then the sensor rotation matrix will be an identity matrix
389         // ROTATION_X_IDX, ROTATION_Y_IDX, ROTATION_Z_IDX corresponds to indexes of the
390         // (x1,y1,z1) in the raw buffer.
391         ret = setSensorPlacementData(sensorPlacement, HWSensorBase::ROTATION_X_IDX + 0, 1);
392         if (ret != OK) return ret;
393         ret = setSensorPlacementData(sensorPlacement, HWSensorBase::ROTATION_Y_IDX + 4, 1);
394         if (ret != OK) return ret;
395         ret = setSensorPlacementData(sensorPlacement, HWSensorBase::ROTATION_Z_IDX + 8, 1);
396         if (ret != OK) return ret;
397     } else {
398         ret = setSensorPlacementData(
399                 sensorPlacement,
400                 HWSensorBase::ROTATION_X_IDX + 4 * sensorOrientation.getFirstX()->getMap(),
401                 sensorOrientation.getFirstX()->getNegate() ? -1 : 1);
402         if (ret != OK) return ret;
403         ret = setSensorPlacementData(
404                 sensorPlacement,
405                 HWSensorBase::ROTATION_Y_IDX + 4 * sensorOrientation.getFirstY()->getMap(),
406                 sensorOrientation.getFirstY()->getNegate() ? -1 : 1);
407         if (ret != OK) return ret;
408         ret = setSensorPlacementData(
409                 sensorPlacement,
410                 HWSensorBase::ROTATION_Z_IDX + 4 * sensorOrientation.getFirstZ()->getMap(),
411                 sensorOrientation.getFirstZ()->getNegate() ? -1 : 1);
412         if (ret != OK) return ret;
413     }
414     return OK;
415 }
416 
setAdditionalInfoFrames(const std::optional<std::vector<Configuration>> & config)417 status_t HWSensorBase::setAdditionalInfoFrames(
418         const std::optional<std::vector<Configuration>>& config) {
419     AdditionalInfo additionalInfoSensorPlacement;
420     status_t ret = getSensorPlacement(&additionalInfoSensorPlacement, config);
421     if (ret != OK) return ret;
422 
423     const AdditionalInfo additionalInfoBegin = {
424             .type = AdditionalInfoType::AINFO_BEGIN,
425             .serial = 0,
426     };
427     const AdditionalInfo additionalInfoEnd = {
428             .type = AdditionalInfoType::AINFO_END,
429             .serial = 0,
430     };
431 
432     mAdditionalInfoFrames.insert(
433             mAdditionalInfoFrames.end(),
434             {additionalInfoBegin, additionalInfoSensorPlacement, additionalInfoEnd});
435     return OK;
436 }
437 
buildSensor(int32_t sensorHandle,ISensorsEventCallback * callback,const struct iio_device_data & iio_data,const std::optional<std::vector<Configuration>> & config)438 HWSensorBase* HWSensorBase::buildSensor(int32_t sensorHandle, ISensorsEventCallback* callback,
439                                         const struct iio_device_data& iio_data,
440                                         const std::optional<std::vector<Configuration>>& config) {
441     if (checkOrientation(config) != OK) {
442         ALOGE("Orientation of the sensor %s in the configuration file is invalid",
443               iio_data.name.c_str());
444         return nullptr;
445     }
446     if (checkIIOData(iio_data) != OK) {
447         ALOGE("IIO channel index of the sensor %s  is invalid", iio_data.name.c_str());
448         return nullptr;
449     }
450     return new HWSensorBase(sensorHandle, callback, iio_data, config);
451 }
452 
HWSensorBase(int32_t sensorHandle,ISensorsEventCallback * callback,const struct iio_device_data & data,const std::optional<std::vector<Configuration>> & config)453 HWSensorBase::HWSensorBase(int32_t sensorHandle, ISensorsEventCallback* callback,
454                            const struct iio_device_data& data,
455                            const std::optional<std::vector<Configuration>>& config)
456     : SensorBase(sensorHandle, callback, data.type) {
457     std::string buffer_path;
458     mSensorInfo.flags |= SensorFlagBits::CONTINUOUS_MODE;
459     mSensorInfo.name = data.name;
460     mSensorInfo.resolution = data.resolution * data.scale;
461     mSensorInfo.maxRange = data.max_range * data.scale;
462     mSensorInfo.power = 0;
463     mIioData = data;
464     setOrientation(config);
465     status_t ret = setAdditionalInfoFrames(config);
466     if (ret == OK) mSensorInfo.flags |= SensorFlagBits::ADDITIONAL_INFO;
467     unsigned int max_sampling_frequency = 0;
468     unsigned int min_sampling_frequency = UINT_MAX;
469     for (auto i = 0u; i < data.sampling_freq_avl.size(); i++) {
470         if (max_sampling_frequency < data.sampling_freq_avl[i])
471             max_sampling_frequency = data.sampling_freq_avl[i];
472         if (min_sampling_frequency > data.sampling_freq_avl[i])
473             min_sampling_frequency = data.sampling_freq_avl[i];
474     }
475     mSensorInfo.minDelay = frequency_to_us(max_sampling_frequency);
476     mSensorInfo.maxDelay = frequency_to_us(min_sampling_frequency);
477     mScanSize = calculateScanSize();
478     buffer_path = "/dev/iio:device";
479     buffer_path.append(std::to_string(mIioData.iio_dev_num));
480     mPollFdIio.fd = open(buffer_path.c_str(), O_RDONLY | O_NONBLOCK);
481     if (mPollFdIio.fd < 0) {
482         ALOGE("%s: Failed to open iio char device (%s).", data.name.c_str(), buffer_path.c_str());
483         return;
484     }
485     mPollFdIio.events = POLLIN;
486     mSensorRawData.resize(mScanSize);
487 }
488 
489 }  // namespace implementation
490 }  // namespace subhal
491 }  // namespace V2_0
492 }  // namespace sensors
493 }  // namespace hardware
494 }  // namespace android
495