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 
17 #include "Sensor.h"
18 #include <hardware/sensors.h>
19 #include <log/log.h>
20 #include <utils/SystemClock.h>
21 #include <cmath>
22 
23 namespace android {
24 namespace hardware {
25 namespace sensors {
26 namespace V2_0 {
27 namespace subhal {
28 namespace implementation {
29 
30 using ::android::hardware::sensors::V1_0::MetaDataEventType;
31 using ::android::hardware::sensors::V1_0::SensorFlagBits;
32 using ::android::hardware::sensors::V1_0::SensorStatus;
33 
SensorBase(int32_t sensorHandle,ISensorsEventCallback * callback,SensorType type)34 SensorBase::SensorBase(int32_t sensorHandle, ISensorsEventCallback* callback, SensorType type)
35     : mIsEnabled(false), mSamplingPeriodNs(0), mCallback(callback), mMode(OperationMode::NORMAL) {
36     mSensorInfo.type = type;
37     mSensorInfo.sensorHandle = sensorHandle;
38     mSensorInfo.vendor = "Google";
39     mSensorInfo.version = 1;
40     mSensorInfo.fifoReservedEventCount = 0;
41     mSensorInfo.fifoMaxEventCount = 0;
42     mSensorInfo.requiredPermission = "";
43     mSensorInfo.flags = 0;
44     switch (type) {
45         case SensorType::ACCELEROMETER:
46             mSensorInfo.typeAsString = SENSOR_STRING_TYPE_ACCELEROMETER;
47             break;
48         case SensorType::GYROSCOPE:
49             mSensorInfo.typeAsString = SENSOR_STRING_TYPE_GYROSCOPE;
50             break;
51         default:
52             ALOGE("unsupported sensor type %d", type);
53             break;
54     }
55     // TODO(jbhayana) : Make the threading policy configurable
56     mRunThread = std::thread(std::bind(&SensorBase::run, this));
57 }
58 
~SensorBase()59 SensorBase::~SensorBase() {
60     // Ensure that lock is unlocked before calling mRunThread.join() or a
61     // deadlock will occur.
62     {
63         std::unique_lock<std::mutex> lock(mRunMutex);
64         mStopThread = true;
65         mIsEnabled = false;
66         mWaitCV.notify_all();
67     }
68     mRunThread.join();
69 }
70 
~HWSensorBase()71 HWSensorBase::~HWSensorBase() {
72     close(mpollfd_iio.fd);
73 }
74 
getSensorInfo() const75 const SensorInfo& SensorBase::getSensorInfo() const {
76     return mSensorInfo;
77 }
78 
batch(int32_t samplingPeriodNs)79 void HWSensorBase::batch(int32_t samplingPeriodNs) {
80     samplingPeriodNs =
81             std::clamp(samplingPeriodNs, mSensorInfo.minDelay * 1000, mSensorInfo.maxDelay * 1000);
82     if (mSamplingPeriodNs != samplingPeriodNs) {
83         unsigned int sampling_frequency = ns_to_frequency(samplingPeriodNs);
84         int i = 0;
85         mSamplingPeriodNs = samplingPeriodNs;
86         std::vector<double>::iterator low =
87                 std::lower_bound(miio_data.sampling_freq_avl.begin(),
88                                  miio_data.sampling_freq_avl.end(), sampling_frequency);
89         i = low - miio_data.sampling_freq_avl.begin();
90         set_sampling_frequency(miio_data.sysfspath, miio_data.sampling_freq_avl[i]);
91         // Wake up the 'run' thread to check if a new event should be generated now
92         mWaitCV.notify_all();
93     }
94 }
95 
activate(bool enable)96 void HWSensorBase::activate(bool enable) {
97     std::unique_lock<std::mutex> lock(mRunMutex);
98     if (mIsEnabled != enable) {
99         mIsEnabled = enable;
100         enable_sensor(miio_data.sysfspath, enable);
101         mWaitCV.notify_all();
102     }
103 }
104 
flush()105 Result SensorBase::flush() {
106     // Only generate a flush complete event if the sensor is enabled and if the sensor is not a
107     // one-shot sensor.
108     if (!mIsEnabled || (mSensorInfo.flags & static_cast<uint32_t>(SensorFlagBits::ONE_SHOT_MODE))) {
109         return Result::BAD_VALUE;
110     }
111 
112     // Note: If a sensor supports batching, write all of the currently batched events for the sensor
113     // to the Event FMQ prior to writing the flush complete event.
114     Event ev;
115     ev.sensorHandle = mSensorInfo.sensorHandle;
116     ev.sensorType = SensorType::META_DATA;
117     ev.u.meta.what = MetaDataEventType::META_DATA_FLUSH_COMPLETE;
118     std::vector<Event> evs{ev};
119     mCallback->postEvents(evs, isWakeUpSensor());
120     return Result::OK;
121 }
122 
processScanData(uint8_t * data,Event * evt)123 void HWSensorBase::processScanData(uint8_t* data, Event* evt) {
124     float channelData[NUM_OF_CHANNEL_SUPPORTED - 1];
125     int64_t ts;
126     unsigned int chanIdx;
127     evt->sensorHandle = mSensorInfo.sensorHandle;
128     evt->sensorType = mSensorInfo.type;
129     for (auto i = 0u; i < miio_data.channelInfo.size(); i++) {
130         chanIdx = miio_data.channelInfo[i].index;
131         if (miio_data.channelInfo[i].sign) {
132             int64_t val = *reinterpret_cast<int64_t*>(
133                     data + chanIdx * miio_data.channelInfo[i].storage_bytes);
134             if (chanIdx == (miio_data.channelInfo.size() - 1)) {
135                 ts = val;
136             } else {
137                 channelData[chanIdx] = (static_cast<float>(val) * miio_data.resolution);
138             }
139         } else {
140             uint64_t val = *reinterpret_cast<uint64_t*>(
141                     data + chanIdx * miio_data.channelInfo[i].storage_bytes);
142             channelData[chanIdx] = (static_cast<float>(val) * miio_data.resolution);
143         }
144     }
145     evt->u.vec3.x = channelData[0];
146     evt->u.vec3.y = channelData[1];
147     evt->u.vec3.z = channelData[2];
148     evt->timestamp = ts;
149     evt->u.vec3.status = SensorStatus::ACCURACY_HIGH;
150 }
151 
run()152 void HWSensorBase::run() {
153     int err;
154     int read_size;
155     std::vector<Event> events;
156     Event event;
157 
158     while (!mStopThread) {
159         if (!mIsEnabled || mMode == OperationMode::DATA_INJECTION) {
160             std::unique_lock<std::mutex> runLock(mRunMutex);
161             mWaitCV.wait(runLock, [&] {
162                 return ((mIsEnabled && mMode == OperationMode::NORMAL) || mStopThread);
163             });
164         } else {
165             err = poll(&mpollfd_iio, 1, mSamplingPeriodNs * 1000);
166             if (err <= 0) {
167                 ALOGE("Sensor %s poll returned %d", miio_data.name.c_str(), err);
168                 continue;
169             }
170             if (mpollfd_iio.revents & POLLIN) {
171                 read_size = read(mpollfd_iio.fd, &msensor_raw_data[0], mscan_size);
172                 if (read_size <= 0) {
173                     ALOGE("%s: Failed to read data from iio char device.", miio_data.name.c_str());
174                     continue;
175                 }
176                 events.clear();
177                 processScanData(&msensor_raw_data[0], &event);
178                 events.push_back(event);
179                 mCallback->postEvents(events, isWakeUpSensor());
180             }
181         }
182     }
183 }
184 
isWakeUpSensor()185 bool SensorBase::isWakeUpSensor() {
186     return mSensorInfo.flags & static_cast<uint32_t>(SensorFlagBits::WAKE_UP);
187 }
188 
setOperationMode(OperationMode mode)189 void SensorBase::setOperationMode(OperationMode mode) {
190     std::unique_lock<std::mutex> lock(mRunMutex);
191     if (mMode != mode) {
192         mMode = mode;
193         mWaitCV.notify_all();
194     }
195 }
196 
supportsDataInjection() const197 bool SensorBase::supportsDataInjection() const {
198     return mSensorInfo.flags & static_cast<uint32_t>(SensorFlagBits::DATA_INJECTION);
199 }
200 
injectEvent(const Event & event)201 Result SensorBase::injectEvent(const Event& event) {
202     Result result = Result::OK;
203     if (event.sensorType == SensorType::ADDITIONAL_INFO) {
204         // When in OperationMode::NORMAL, SensorType::ADDITIONAL_INFO is used to push operation
205         // environment data into the device.
206     } else if (!supportsDataInjection()) {
207         result = Result::INVALID_OPERATION;
208     } else if (mMode == OperationMode::DATA_INJECTION) {
209         mCallback->postEvents(std::vector<Event>{event}, isWakeUpSensor());
210     } else {
211         result = Result::BAD_VALUE;
212     }
213     return result;
214 }
215 
calculateScanSize()216 ssize_t HWSensorBase::calculateScanSize() {
217     ssize_t numBytes = 0;
218     for (auto i = 0u; i < miio_data.channelInfo.size(); i++) {
219         numBytes += miio_data.channelInfo[i].storage_bytes;
220     }
221     return numBytes;
222 }
223 
HWSensorBase(int32_t sensorHandle,ISensorsEventCallback * callback,SensorType type,const struct iio_device_data & data)224 HWSensorBase::HWSensorBase(int32_t sensorHandle, ISensorsEventCallback* callback, SensorType type,
225                            const struct iio_device_data& data)
226     : SensorBase(sensorHandle, callback, type) {
227     std::string buffer_path;
228     mSensorInfo.flags |= SensorFlagBits::CONTINUOUS_MODE;
229     mSensorInfo.name = data.name;
230     mSensorInfo.resolution = data.resolution;
231     mSensorInfo.maxRange = data.max_range * data.resolution;
232     mSensorInfo.power =
233             (data.power_microwatts / 1000.f) / SENSOR_VOLTAGE_DEFAULT;  // converting uW to mA
234     miio_data = data;
235     unsigned int max_sampling_frequency = 0;
236     unsigned int min_sampling_frequency = UINT_MAX;
237     for (auto i = 0u; i < data.sampling_freq_avl.size(); i++) {
238         if (max_sampling_frequency < data.sampling_freq_avl[i])
239             max_sampling_frequency = data.sampling_freq_avl[i];
240         if (min_sampling_frequency > data.sampling_freq_avl[i])
241             min_sampling_frequency = data.sampling_freq_avl[i];
242     }
243     mSensorInfo.minDelay = frequency_to_us(max_sampling_frequency);
244     mSensorInfo.maxDelay = frequency_to_us(min_sampling_frequency);
245     mscan_size = calculateScanSize();
246     buffer_path = "/dev/iio:device";
247     buffer_path.append(std::to_string(miio_data.iio_dev_num));
248     mpollfd_iio.fd = open(buffer_path.c_str(), O_RDONLY | O_NONBLOCK);
249     if (mpollfd_iio.fd < 0) {
250         ALOGE("%s: Failed to open iio char device (%s).", data.name.c_str(), buffer_path.c_str());
251         return;
252     }
253     mpollfd_iio.events = POLLIN;
254     msensor_raw_data.resize(mscan_size);
255 }
256 
Accelerometer(int32_t sensorHandle,ISensorsEventCallback * callback,const struct iio_device_data & data)257 Accelerometer::Accelerometer(int32_t sensorHandle, ISensorsEventCallback* callback,
258                              const struct iio_device_data& data)
259     : HWSensorBase(sensorHandle, callback, SensorType::ACCELEROMETER, data) {
260 }
261 
Gyroscope(int32_t sensorHandle,ISensorsEventCallback * callback,const struct iio_device_data & data)262 Gyroscope::Gyroscope(int32_t sensorHandle, ISensorsEventCallback* callback,
263                      const struct iio_device_data& data)
264     : HWSensorBase(sensorHandle, callback, SensorType::GYROSCOPE, data) {
265 }
266 
267 }  // namespace implementation
268 }  // namespace subhal
269 }  // namespace V2_0
270 }  // namespace sensors
271 }  // namespace hardware
272 }  // namespace android
273