1 /*
2  * Copyright (C) 2017 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 "HidRawSensor.h"
17 #include "HidSensorDef.h"
18 
19 #include <utils/Errors.h>
20 #include "HidLog.h"
21 
22 #include <HidUtils.h>
23 
24 #include <algorithm>
25 #include <cfloat>
26 #include <codecvt>
27 #include <iomanip>
28 #include <sstream>
29 
30 namespace android {
31 namespace SensorHalExt {
32 
33 namespace {
34 const std::string CUSTOM_TYPE_PREFIX("com.google.hardware.sensor.hid_dynamic.");
35 }
36 
HidRawSensor(SP (HidDevice)device,uint32_t usage,const std::vector<HidParser::ReportPacket> & packets)37 HidRawSensor::HidRawSensor(
38         SP(HidDevice) device, uint32_t usage, const std::vector<HidParser::ReportPacket> &packets)
39         : mReportingStateId(-1), mPowerStateId(-1), mReportIntervalId(-1), mInputReportId(-1),
40         mEnabled(false), mSamplingPeriod(1000LL*1000*1000), mBatchingPeriod(0),
41         mDevice(device), mValid(false) {
42     if (device == nullptr) {
43         return;
44     }
45     memset(&mSensor, 0, sizeof(mSensor));
46 
47     const HidDevice::HidDeviceInfo &info =  device->getDeviceInfo();
48     initFeatureValueFromHidDeviceInfo(&mFeatureInfo, info);
49 
50     if (!populateFeatureValueFromFeatureReport(&mFeatureInfo, packets)) {
51         LOG_E << "populate feature from feature report failed" << LOG_ENDL;
52         return;
53     }
54 
55     if (!findSensorControlUsage(packets)) {
56         LOG_E << "finding sensor control usage failed" << LOG_ENDL;
57         return;
58     }
59 
60     // build translation table
61     bool translationTableValid = false;
62     switch (usage) {
63         using namespace Hid::Sensor::SensorTypeUsage;
64         using namespace Hid::Sensor::ReportUsage;
65         case ACCELEROMETER_3D:
66             // Hid unit default g
67             // Android unit m/s^2
68             // 1g = 9.81 m/s^2
69             mFeatureInfo.typeString = SENSOR_STRING_TYPE_ACCELEROMETER;
70             mFeatureInfo.type = SENSOR_TYPE_ACCELEROMETER;
71             mFeatureInfo.isWakeUp = false;
72 
73             translationTableValid = processTriAxisUsage(packets,
74                                          ACCELERATION_X_AXIS,
75                                          ACCELERATION_Y_AXIS,
76                                          ACCELERATION_Z_AXIS, 9.81);
77             break;
78         case GYROMETER_3D:
79             // Hid unit default degree/s
80             // Android unit rad/s
81             // 1 degree/s = pi/180 rad/s
82             mFeatureInfo.typeString = SENSOR_STRING_TYPE_GYROSCOPE;
83             mFeatureInfo.type = SENSOR_TYPE_GYROSCOPE;
84             mFeatureInfo.isWakeUp = false;
85 
86             translationTableValid = processTriAxisUsage(packets,
87                                          ANGULAR_VELOCITY_X_AXIS,
88                                          ANGULAR_VELOCITY_Y_AXIS,
89                                          ANGULAR_VELOCITY_Z_AXIS, M_PI/180);
90             break;
91         case COMPASS_3D: {
92             // Hid unit default mGauss
93             // Android unit uT
94             // 1uT  = 0.1 nGauss
95             mFeatureInfo.typeString = SENSOR_STRING_TYPE_MAGNETIC_FIELD;
96             mFeatureInfo.type = SENSOR_TYPE_MAGNETIC_FIELD;
97 
98             if (!processTriAxisUsage(packets,
99                                      MAGNETIC_FLUX_X_AXIS,
100                                      MAGNETIC_FLUX_Y_AXIS,
101                                      MAGNETIC_FLUX_Z_AXIS, 0.1)) {
102                 break;
103             }
104             const HidParser::ReportItem *pReportAccuracy = find(packets,
105                                                                   MAGNETOMETER_ACCURACY,
106                                                                   HidParser::REPORT_TYPE_INPUT,
107                                                                   mInputReportId);
108 
109             if (pReportAccuracy == nullptr) {
110                 LOG_E << "Cannot find accuracy field in usage "
111                       << std::hex << usage << std::dec << LOG_ENDL;
112                 break;
113             }
114             if (!pReportAccuracy->isByteAligned()) {
115                 LOG_E << "Accuracy field must align to byte" << LOG_ENDL;
116                 break;
117             }
118             if (pReportAccuracy->minRaw != 0 || pReportAccuracy->maxRaw != 2) {
119                 LOG_E << "Accuracy field value range must be [0, 2]" << LOG_ENDL;
120                 break;
121             }
122             ReportTranslateRecord accuracyRecord = {
123                 .type = TYPE_ACCURACY,
124                 .maxValue = 2,
125                 .minValue = 0,
126                 .byteOffset = pReportAccuracy->bitOffset / 8,
127                 .byteSize = pReportAccuracy->bitSize / 8,
128                 .a = 1,
129                 .b = 1};
130             mTranslateTable.push_back(accuracyRecord);
131             translationTableValid = true;
132             break;
133         }
134         case DEVICE_ORIENTATION:
135             translationTableValid = processQuaternionUsage(packets);
136             break;
137         case CUSTOM: {
138             if (!mFeatureInfo.isAndroidCustom) {
139                 LOG_E << "Invalid android custom sensor" << LOG_ENDL;
140                 break;
141             }
142             const HidParser::ReportPacket *pPacket = nullptr;
143             const uint32_t usages[] = {
144                 CUSTOM_VALUE_1, CUSTOM_VALUE_2, CUSTOM_VALUE_3,
145                 CUSTOM_VALUE_4, CUSTOM_VALUE_5, CUSTOM_VALUE_6
146             };
147             for (const auto &packet : packets) {
148                 if (packet.type == HidParser::REPORT_TYPE_INPUT && std::any_of(
149                         packet.reports.begin(), packet.reports.end(),
150                         [&usages] (const HidParser::ReportItem &d) {
151                                return std::find(std::begin(usages), std::end(usages), d.usage)
152                                        != std::end(usages);
153                         })) {
154                     pPacket = &packet;
155                     break;
156                 }
157             }
158 
159             if (pPacket == nullptr) {
160                 LOG_E << "Cannot find CUSTOM_VALUE_X in custom sensor" << LOG_ENDL;
161                 break;
162             }
163 
164             double range = 0;
165             double resolution = 1;
166 
167             for (const auto &digest : pPacket->reports) {
168                 if (digest.minRaw >= digest.maxRaw) {
169                     LOG_E << "Custome usage " << digest.usage << ", min must < max" << LOG_ENDL;
170                     return;
171                 }
172 
173                 if (!digest.isByteAligned()
174                         || (digest.bitSize != 8 && digest.bitSize != 16 && digest.bitSize != 32)) {
175                     LOG_E << "Custome usage " << std::hex << digest.usage << std::hex
176                           << ", each input must be 8/16/32 bits and must align to byte boundary"
177                           << LOG_ENDL;
178                     return;
179                 }
180 
181                 ReportTranslateRecord record = {
182                     .type = TYPE_FLOAT,
183                     .maxValue = digest.maxRaw,
184                     .minValue = digest.minRaw,
185                     .byteOffset = digest.bitOffset / 8,
186                     .byteSize = digest.bitSize / 8,
187                     .a = digest.a,
188                     .b = digest.b,
189                 };
190                 // keep track of range and resolution
191                 range = std::max(std::max(std::abs((digest.maxRaw + digest.b) * digest.a),
192                                           std::abs((digest.minRaw + digest.b) * digest.a)),
193                                  range);
194                 resolution = std::min(digest.a, resolution);
195 
196                 for (size_t i = 0; i < digest.count; ++i) {
197                     if (mTranslateTable.size() == 16) {
198                         LOG_I << "Custom usage has more than 16 inputs, ignore the rest" << LOG_ENDL;
199                         break;
200                     }
201                     record.index = mTranslateTable.size();
202                     mTranslateTable.push_back(record);
203                     record.byteOffset += digest.bitSize / 8;
204                 }
205                 if (mTranslateTable.size() == 16) {
206                     break;
207                 }
208             }
209             mFeatureInfo.maxRange = range;
210             mFeatureInfo.resolution = resolution;
211             mInputReportId = pPacket->id;
212             translationTableValid = !mTranslateTable.empty();
213             break;
214         }
215         default:
216             LOG_I << "unsupported sensor usage " << usage << LOG_ENDL;
217     }
218 
219     bool sensorValid = validateFeatureValueAndBuildSensor();
220     mValid = translationTableValid && sensorValid;
221     LOG_V << "HidRawSensor init, translationTableValid: " << translationTableValid
222           << ", sensorValid: " << sensorValid << LOG_ENDL;
223 }
224 
processQuaternionUsage(const std::vector<HidParser::ReportPacket> & packets)225 bool HidRawSensor::processQuaternionUsage(const std::vector<HidParser::ReportPacket> &packets) {
226     const HidParser::ReportItem *pReportQuaternion
227             = find(packets,
228                    Hid::Sensor::ReportUsage::ORIENTATION_QUATERNION,
229                    HidParser::REPORT_TYPE_INPUT);
230 
231     if (pReportQuaternion == nullptr) {
232         return false;
233     }
234 
235     const HidParser::ReportItem &quat = *pReportQuaternion;
236     if ((quat.bitSize != 16 && quat.bitSize != 32) || !quat.isByteAligned()) {
237         LOG_E << "Quaternion usage input must be 16 or 32 bits and aligned at byte boundary" << LOG_ENDL;
238         return false;
239     }
240 
241     double min, max;
242     quat.decode(quat.mask(quat.minRaw), &min);
243     quat.decode(quat.mask(quat.maxRaw), &max);
244     if (quat.count != 4 || min > -1 || max < 1) {
245         LOG_E << "Quaternion usage need 4 inputs with range [-1, 1]" << LOG_ENDL;
246         return false;
247     }
248 
249     if (quat.minRaw > quat.maxRaw) {
250         LOG_E << "Quaternion usage min must <= max" << LOG_ENDL;
251         return false;
252     }
253 
254     ReportTranslateRecord record = {
255         .type = TYPE_FLOAT,
256         .maxValue = quat.maxRaw,
257         .minValue = quat.minRaw,
258         .byteOffset = quat.bitOffset / 8,
259         .byteSize = quat.bitSize / 8,
260         .b = quat.b,
261     };
262 
263     // Android X Y Z maps to HID X -Z Y
264     // Android order xyzw, HID order wxyz
265     // X
266     record.index = 0;
267     record.a = quat.a;
268     record.byteOffset = (quat.bitOffset + quat.bitSize) / 8;
269     mTranslateTable.push_back(record);
270     // Y
271     record.index = 1;
272     record.a = -quat.a;
273     record.byteOffset = (quat.bitOffset + 3 * quat.bitSize) / 8;
274     mTranslateTable.push_back(record);
275     // Z
276     record.index = 2;
277     record.a = quat.a;
278     record.byteOffset = (quat.bitOffset + 2 * quat.bitSize) / 8;
279     mTranslateTable.push_back(record);
280     // W
281     record.index = 3;
282     record.a = quat.a;
283     record.byteOffset = quat.bitOffset / 8;
284     mTranslateTable.push_back(record);
285 
286     mFeatureInfo.typeString = SENSOR_STRING_TYPE_ROTATION_VECTOR;
287     mFeatureInfo.type = SENSOR_TYPE_ROTATION_VECTOR;
288     mFeatureInfo.maxRange = 1;
289     mFeatureInfo.resolution = quat.a;
290     mFeatureInfo.reportModeFlag = SENSOR_FLAG_CONTINUOUS_MODE;
291 
292     mInputReportId = quat.id;
293 
294     return true;
295 }
296 
processTriAxisUsage(const std::vector<HidParser::ReportPacket> & packets,uint32_t usageX,uint32_t usageY,uint32_t usageZ,double defaultScaling)297 bool HidRawSensor::processTriAxisUsage(const std::vector<HidParser::ReportPacket> &packets,
298         uint32_t usageX, uint32_t usageY, uint32_t usageZ, double defaultScaling) {
299     const HidParser::ReportItem *pReportX = find(packets, usageX, HidParser::REPORT_TYPE_INPUT);
300     const HidParser::ReportItem *pReportY = find(packets, usageY, HidParser::REPORT_TYPE_INPUT);
301     const HidParser::ReportItem *pReportZ = find(packets, usageZ, HidParser::REPORT_TYPE_INPUT);
302 
303     if (pReportX == nullptr || pReportY == nullptr|| pReportZ == nullptr) {
304         LOG_E << "Three axis sensor does not find all 3 axis" << LOG_ENDL;
305         return false;
306     }
307 
308     const HidParser::ReportItem &reportX = *pReportX;
309     const HidParser::ReportItem &reportY = *pReportY;
310     const HidParser::ReportItem &reportZ = *pReportZ;
311     if (reportX.id != reportY.id || reportY.id != reportZ.id) {
312         LOG_E << "All 3 axis should be in the same report" << LOG_ENDL;
313         return false;
314     }
315     if (reportX.minRaw >= reportX.maxRaw
316             || reportX.minRaw != reportY.minRaw
317             || reportX.maxRaw != reportY.maxRaw
318             || reportY.minRaw != reportZ.minRaw
319             || reportY.maxRaw != reportZ.maxRaw) {
320         LOG_E << "All 3 axis should have same min and max value and min must < max" << LOG_ENDL;
321         return false;
322     }
323     if (reportX.a != reportY.a || reportY.a != reportY.a) {
324         LOG_E << "All 3 axis should have same resolution" << LOG_ENDL;
325         return false;
326     }
327     if (reportX.count != 1 || reportY.count != 1 || reportZ.count != 1
328             || (reportX.bitSize != 16 && reportX.bitSize != 32)
329             || reportX.bitSize != reportY.bitSize || reportY.bitSize != reportZ.bitSize
330             || !reportX.isByteAligned()
331             || !reportY.isByteAligned()
332             || !reportZ.isByteAligned() ) {
333         LOG_E << "All 3 axis should have count == 1, same size == 16 or 32 "
334               "and align at byte boundary" << LOG_ENDL;
335         return false;
336     }
337 
338     if (reportX.unit != 0 || reportY.unit != 0 || reportZ.unit != 0) {
339         LOG_E << "Specified unit for usage is not supported" << LOG_ENDL;
340         return false;
341     }
342 
343     if (reportX.a != reportY.a || reportY.a != reportZ.a
344         || reportX.b != reportY.b || reportY.b != reportZ.b) {
345         LOG_W << "Scaling for 3 axis are different. It is recommended to keep them the same" << LOG_ENDL;
346     }
347 
348     // set features
349     mFeatureInfo.maxRange = std::max(
350         std::abs((reportX.maxRaw + reportX.b) * reportX.a),
351         std::abs((reportX.minRaw + reportX.b) * reportX.a));
352     mFeatureInfo.resolution = reportX.a * defaultScaling;
353     mFeatureInfo.reportModeFlag = SENSOR_FLAG_CONTINUOUS_MODE;
354 
355     ReportTranslateRecord record = {
356         .type = TYPE_FLOAT,
357         .maxValue = reportX.maxRaw,
358         .minValue = reportX.minRaw,
359         .byteSize = reportX.bitSize / 8,
360     };
361 
362     // Reorder and swap axis
363     //
364     // HID class devices are encouraged, where possible, to use a right-handed
365     // coordinate system. If a user is facing a device, report values should increase as
366     // controls are moved from left to right (X), from far to near (Y) and from high to
367     // low (Z).
368     //
369 
370     // Android X axis = Hid X axis
371     record.index = 0;
372     record.a = reportX.a * defaultScaling;
373     record.b = reportX.b;
374     record.byteOffset = reportX.bitOffset / 8;
375     mTranslateTable.push_back(record);
376 
377     // Android Y axis = - Hid Z axis
378     record.index = 1;
379     record.a = -reportZ.a * defaultScaling;
380     record.b = reportZ.b;
381     record.byteOffset = reportZ.bitOffset / 8;
382     mTranslateTable.push_back(record);
383 
384     // Android Z axis = Hid Y axis
385     record.index = 2;
386     record.a = reportY.a * defaultScaling;
387     record.b = reportY.b;
388     record.byteOffset = reportY.bitOffset / 8;
389     mTranslateTable.push_back(record);
390 
391     mInputReportId = reportX.id;
392     return true;
393 }
394 
find(const std::vector<HidParser::ReportPacket> & packets,unsigned int usage,int type,int id)395 const HidParser::ReportItem *HidRawSensor::find(
396         const std::vector<HidParser::ReportPacket> &packets,
397         unsigned int usage, int type, int id) {
398     for (const auto &packet : packets) {
399         if (packet.type != type) {
400             continue;
401         }
402         auto i = std::find_if(
403                 packet.reports.begin(), packet.reports.end(),
404                 [usage, id](const HidParser::ReportItem &p) {
405                     return p.usage == usage
406                             && (id == -1 || p.id == static_cast<unsigned int>(id));
407                 });
408         if (i != packet.reports.end()) {
409             return &(*i);
410         }
411     }
412     return nullptr;
413 };
414 
initFeatureValueFromHidDeviceInfo(FeatureValue * featureValue,const HidDevice::HidDeviceInfo & info)415 void HidRawSensor::initFeatureValueFromHidDeviceInfo(
416         FeatureValue *featureValue, const HidDevice::HidDeviceInfo &info) {
417     featureValue->name = info.name;
418 
419     std::ostringstream ss;
420     ss << info.busType << " "
421        << std::hex << std::setfill('0') << std::setw(4) << info.vendorId
422        << ":" << std::setw(4) << info.productId;
423     featureValue->vendor = ss.str();
424 
425     featureValue->permission = "";
426     featureValue->typeString = "";
427     featureValue->type = -1; // invalid type
428     featureValue->version = 1;
429 
430     featureValue->maxRange = -1.f;
431     featureValue->resolution = FLT_MAX;
432     featureValue->power = 1.f; // default value, does not have a valid source yet
433 
434     featureValue->minDelay = 0;
435     featureValue->maxDelay = 0;
436 
437     featureValue->fifoSize = 0;
438     featureValue->fifoMaxSize = 0;
439 
440     featureValue->reportModeFlag = SENSOR_FLAG_SPECIAL_REPORTING_MODE;
441     featureValue->isWakeUp = false;
442     memset(featureValue->uuid, 0, sizeof(featureValue->uuid));
443     featureValue->isAndroidCustom = false;
444 }
445 
populateFeatureValueFromFeatureReport(FeatureValue * featureValue,const std::vector<HidParser::ReportPacket> & packets)446 bool HidRawSensor::populateFeatureValueFromFeatureReport(
447         FeatureValue *featureValue, const std::vector<HidParser::ReportPacket> &packets) {
448     SP(HidDevice) device = PROMOTE(mDevice);
449     if (device == nullptr) {
450         return false;
451     }
452 
453     std::vector<uint8_t> buffer;
454     for (const auto &packet : packets) {
455         if (packet.type != HidParser::REPORT_TYPE_FEATURE) {
456             continue;
457         }
458 
459         if (!device->getFeature(packet.id, &buffer)) {
460             continue;
461         }
462 
463         std::string str;
464         using namespace Hid::Sensor::PropertyUsage;
465         for (const auto & r : packet.reports) {
466             switch (r.usage) {
467                 case FRIENDLY_NAME:
468                     if (!r.isByteAligned() || r.bitSize != 16 || r.count < 1) {
469                         // invalid friendly name
470                         break;
471                     }
472                     if (decodeString(r, buffer, &str) && !str.empty()) {
473                         featureValue->name = str;
474                     }
475                     break;
476                 case SENSOR_MANUFACTURER:
477                     if (!r.isByteAligned() || r.bitSize != 16 || r.count < 1) {
478                         // invalid manufacturer
479                         break;
480                     }
481                     if (decodeString(r, buffer, &str) && !str.empty()) {
482                         featureValue->vendor = str;
483                     }
484                     break;
485                 case PERSISTENT_UNIQUE_ID:
486                     if (!r.isByteAligned() || r.bitSize != 16 || r.count < 1) {
487                         // invalid unique id string
488                         break;
489                     }
490                     if (decodeString(r, buffer, &str) && !str.empty()) {
491                         featureValue->uniqueId = str;
492                     }
493                     break;
494                 case SENSOR_DESCRIPTION:
495                     if (decodeString(r, buffer, &str)) {
496                         detectSensorFromDescription(str);
497                     }
498                     break;
499                 default:
500                     // do not care about others
501                     break;
502             }
503         }
504     }
505     return true;
506 }
507 
validateFeatureValueAndBuildSensor()508 bool HidRawSensor::validateFeatureValueAndBuildSensor() {
509     if (mFeatureInfo.name.empty() || mFeatureInfo.vendor.empty() || mFeatureInfo.typeString.empty()
510             || mFeatureInfo.type <= 0 || mFeatureInfo.maxRange <= 0
511             || mFeatureInfo.resolution <= 0) {
512         return false;
513     }
514 
515     switch (mFeatureInfo.reportModeFlag) {
516         case SENSOR_FLAG_CONTINUOUS_MODE:
517         case SENSOR_FLAG_ON_CHANGE_MODE:
518             if (mFeatureInfo.minDelay < 0) {
519                 return false;
520             }
521             if (mFeatureInfo.maxDelay != 0 && mFeatureInfo.maxDelay < mFeatureInfo.minDelay) {
522                 return false;
523             }
524             break;
525         case SENSOR_FLAG_ONE_SHOT_MODE:
526             if (mFeatureInfo.minDelay != -1 && mFeatureInfo.maxDelay != 0) {
527                 return false;
528             }
529             break;
530         case SENSOR_FLAG_SPECIAL_REPORTING_MODE:
531             if (mFeatureInfo.minDelay != -1 && mFeatureInfo.maxDelay != 0) {
532                 return false;
533             }
534             break;
535         default:
536             break;
537     }
538 
539     if (mFeatureInfo.fifoMaxSize < mFeatureInfo.fifoSize) {
540         return false;
541     }
542 
543     // initialize uuid field, use name, vendor and uniqueId
544     if (mFeatureInfo.name.size() >= 4
545             && mFeatureInfo.vendor.size() >= 4
546             && mFeatureInfo.typeString.size() >= 4
547             && mFeatureInfo.uniqueId.size() >= 4) {
548         uint32_t tmp[4], h;
549         std::hash<std::string> stringHash;
550         h = stringHash(mFeatureInfo.uniqueId);
551         tmp[0] = stringHash(mFeatureInfo.name) ^ h;
552         tmp[1] = stringHash(mFeatureInfo.vendor) ^ h;
553         tmp[2] = stringHash(mFeatureInfo.typeString) ^ h;
554         tmp[3] = tmp[0] ^ tmp[1] ^ tmp[2];
555         memcpy(mFeatureInfo.uuid, tmp, sizeof(mFeatureInfo.uuid));
556     }
557 
558     mSensor = (sensor_t) {
559         mFeatureInfo.name.c_str(),                 // name
560         mFeatureInfo.vendor.c_str(),               // vendor
561         mFeatureInfo.version,                      // version
562         -1,                                        // handle, dummy number here
563         mFeatureInfo.type,
564         mFeatureInfo.maxRange,                     // maxRange
565         mFeatureInfo.resolution,                   // resolution
566         mFeatureInfo.power,                        // power
567         mFeatureInfo.minDelay,                     // minDelay
568         (uint32_t)mFeatureInfo.fifoSize,           // fifoReservedEventCount
569         (uint32_t)mFeatureInfo.fifoMaxSize,        // fifoMaxEventCount
570         mFeatureInfo.typeString.c_str(),           // type string
571         mFeatureInfo.permission.c_str(),           // requiredPermission
572         (long)mFeatureInfo.maxDelay,               // maxDelay
573         mFeatureInfo.reportModeFlag | (mFeatureInfo.isWakeUp ? 1 : 0),
574         { NULL, NULL }
575     };
576     return true;
577 }
578 
decodeString(const HidParser::ReportItem & report,const std::vector<uint8_t> & buffer,std::string * d)579 bool HidRawSensor::decodeString(
580         const HidParser::ReportItem &report, const std::vector<uint8_t> &buffer, std::string *d) {
581     if (!report.isByteAligned() ||
582         (report.bitSize != 8 && report.bitSize != 16) || report.count < 1) {
583         return false;
584     }
585 
586     size_t charSize = report.bitSize / 8;
587     size_t offset = report.bitOffset / 8;
588     if (offset + report.count * charSize > buffer.size()) {
589         return false;
590     }
591 
592     if (charSize == 1) {
593         *d = std::string(buffer.begin() + offset,
594                          buffer.begin() + offset + report.count);
595     } else {
596         std::vector<uint16_t> data(report.count);
597         auto i = data.begin();
598         auto j = buffer.begin() + offset;
599         for ( ; i != data.end(); ++i, j += sizeof(uint16_t)) {
600             // hid specified little endian
601             *i = *j + (*(j + 1) << 8);
602         }
603         std::wstring wstr(data.begin(), data.end());
604 
605         std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter;
606         *d = converter.to_bytes(wstr);
607     }
608 
609     return true;
610 }
611 
split(const std::string & text,char sep)612 std::vector<std::string> split(const std::string &text, char sep) {
613     std::vector<std::string> tokens;
614     size_t start = 0, end = 0;
615     while ((end = text.find(sep, start)) != std::string::npos) {
616         if (end != start) {
617             tokens.push_back(text.substr(start, end - start));
618         }
619         start = end + 1;
620     }
621     if (end != start) {
622         tokens.push_back(text.substr(start));
623     }
624     return tokens;
625 }
626 
detectSensorFromDescription(const std::string & description)627 void HidRawSensor::detectSensorFromDescription(const std::string &description) {
628     if (detectAndroidHeadTrackerSensor(description) ||
629         detectAndroidCustomSensor(description)) {
630         mFeatureInfo.isAndroidCustom = true;
631     }
632 }
633 
detectAndroidHeadTrackerSensor(const std::string & description)634 bool HidRawSensor::detectAndroidHeadTrackerSensor(
635         const std::string &description) {
636     if (description.find("#AndroidHeadTracker#1.") != 0) {
637         return false;
638     }
639 
640     mFeatureInfo.type = SENSOR_TYPE_DEVICE_PRIVATE_BASE;
641     mFeatureInfo.typeString = CUSTOM_TYPE_PREFIX + "headtracker";
642     mFeatureInfo.reportModeFlag = SENSOR_FLAG_CONTINUOUS_MODE;
643     mFeatureInfo.permission = "";
644     mFeatureInfo.isWakeUp = false;
645 
646     return true;
647 }
648 
detectAndroidCustomSensor(const std::string & description)649 bool HidRawSensor::detectAndroidCustomSensor(const std::string &description) {
650     size_t nullPosition = description.find('\0');
651     if (nullPosition == std::string::npos) {
652         return false;
653     }
654     const std::string prefix("#ANDROID#");
655     if (description.find(prefix, nullPosition + 1) != nullPosition + 1) {
656         return false;
657     }
658 
659     std::string str(description.c_str() + nullPosition + 1 + prefix.size());
660 
661     // Format for predefined sensor types:
662     // #ANDROID#nn,[C|X|T|S],[B|0],[W|N]
663     // Format for vendor type sensor
664     // #ANDROID#xxx.yyy.zzz,[C|X|T|S],[B|0],[W|N]
665     //
666     // C: continuous
667     // X: on-change
668     // T: one-shot
669     // S: special trigger
670     //
671     // B: body permission
672     // 0: no permission required
673     std::vector<std::string> segments;
674     size_t start = 0, end = 0;
675     while ((end = str.find(',', start)) != std::string::npos) {
676         if (end != start) {
677             segments.push_back(str.substr(start, end - start));
678         }
679         start = end + 1;
680     }
681     if (end != start) {
682         segments.push_back(str.substr(start));
683     }
684 
685     if (segments.size() < 4) {
686         LOG_E << "Not enough segments in android custom description" << LOG_ENDL;
687         return false;
688     }
689 
690     // type
691     bool typeParsed = false;
692     if (!segments[0].empty()) {
693         if (::isdigit(segments[0][0])) {
694             int type = ::atoi(segments[0].c_str());
695             // all supported types here
696             switch (type) {
697                 case SENSOR_TYPE_HEART_RATE:
698                     mFeatureInfo.type = SENSOR_TYPE_HEART_RATE;
699                     mFeatureInfo.typeString = SENSOR_STRING_TYPE_HEART_RATE;
700                     typeParsed = true;
701                     break;
702                 case SENSOR_TYPE_AMBIENT_TEMPERATURE:
703                     mFeatureInfo.type = SENSOR_TYPE_AMBIENT_TEMPERATURE;
704                     mFeatureInfo.typeString = SENSOR_STRING_TYPE_AMBIENT_TEMPERATURE;
705                     typeParsed = true;
706                     break;
707                 case SENSOR_TYPE_LIGHT:
708                     mFeatureInfo.type = SENSOR_TYPE_LIGHT;
709                     mFeatureInfo.typeString = SENSOR_STRING_TYPE_LIGHT;
710                     typeParsed = true;
711                     break;
712                 case SENSOR_TYPE_PRESSURE:
713                     mFeatureInfo.type = SENSOR_TYPE_PRESSURE;
714                     mFeatureInfo.typeString = SENSOR_STRING_TYPE_PRESSURE;
715                     typeParsed = true;
716                     break;
717                 default:
718                     LOG_W << "Android type " << type << " has not been supported yet" << LOG_ENDL;
719                     break;
720             }
721         } else {
722             // assume a xxx.yyy.zzz format
723             std::ostringstream s;
724             bool lastIsDot = true;
725             for (auto c : segments[0]) {
726                 if (::isalpha(c)) {
727                     s << static_cast<char>(c);
728                     lastIsDot = false;
729                 } else if (!lastIsDot && c == '.') {
730                     s << static_cast<char>(c);
731                     lastIsDot = true;
732                 } else {
733                     break;
734                 }
735             }
736             if (s.str() == segments[0]) {
737                 mFeatureInfo.type = SENSOR_TYPE_DEVICE_PRIVATE_BASE;
738                 mFeatureInfo.typeString = CUSTOM_TYPE_PREFIX + s.str();
739                 typeParsed = true;
740             }
741         }
742     }
743 
744     // reporting type
745     bool reportingModeParsed = false;
746     if (segments[1].size() == 1) {
747         switch (segments[1][0]) {
748             case 'C':
749                 mFeatureInfo.reportModeFlag = SENSOR_FLAG_CONTINUOUS_MODE;
750                 reportingModeParsed = true;
751                 break;
752             case 'X':
753                 mFeatureInfo.reportModeFlag = SENSOR_FLAG_ON_CHANGE_MODE;
754                 reportingModeParsed = true;
755                 break;
756             case 'T':
757                 mFeatureInfo.reportModeFlag = SENSOR_FLAG_ONE_SHOT_MODE;
758                 reportingModeParsed = true;
759                 break;
760             case 'S':
761                 mFeatureInfo.reportModeFlag = SENSOR_FLAG_SPECIAL_REPORTING_MODE;
762                 reportingModeParsed = true;
763                 break;
764             default:
765                 LOG_E << "Undefined reporting mode designation " << segments[1] << LOG_ENDL;
766         }
767     }
768 
769     // permission parsed
770     bool permissionParsed = false;
771     if (segments[2].size() == 1) {
772         switch (segments[2][0]) {
773             case 'B':
774                 mFeatureInfo.permission = SENSOR_PERMISSION_BODY_SENSORS;
775                 permissionParsed = true;
776                 break;
777             case '0':
778                 mFeatureInfo.permission = "";
779                 permissionParsed = true;
780                 break;
781             default:
782                 LOG_E << "Undefined permission designation " << segments[2] << LOG_ENDL;
783         }
784     }
785 
786     // wake up
787     bool wakeUpParsed = false;
788     if (segments[3].size() == 1) {
789         switch (segments[3][0]) {
790             case 'W':
791                 mFeatureInfo.isWakeUp = true;
792                 wakeUpParsed = true;
793                 break;
794             case 'N':
795                 mFeatureInfo.isWakeUp = false;
796                 wakeUpParsed = true;
797                 break;
798             default:
799                 LOG_E << "Undefined wake up designation " << segments[3] << LOG_ENDL;
800         }
801     }
802 
803     int ret = typeParsed && reportingModeParsed && permissionParsed && wakeUpParsed;
804     if (!ret) {
805         LOG_D << "detectAndroidCustomSensor typeParsed: " << typeParsed
806               << " reportingModeParsed: "  << reportingModeParsed
807               << " permissionParsed: " << permissionParsed
808               << " wakeUpParsed: " << wakeUpParsed << LOG_ENDL;
809     }
810     return ret;
811 }
812 
findSensorControlUsage(const std::vector<HidParser::ReportPacket> & packets)813 bool HidRawSensor::findSensorControlUsage(const std::vector<HidParser::ReportPacket> &packets) {
814     using namespace Hid::Sensor::PowerStateUsage;
815     using namespace Hid::Sensor::PropertyUsage;
816     using namespace Hid::Sensor::ReportingStateUsage;
817 
818     //REPORTING_STATE
819     const HidParser::ReportItem *reportingState
820             = find(packets, REPORTING_STATE, HidParser::REPORT_TYPE_FEATURE);
821 
822     if (reportingState == nullptr) {
823         LOG_W << "Cannot find valid reporting state feature" << LOG_ENDL;
824     } else {
825         mReportingStateId = reportingState->id;
826         mReportingStateBitOffset = reportingState->bitOffset;
827         mReportingStateBitSize = reportingState->bitSize;
828 
829         mReportingStateDisableIndex = -1;
830         mReportingStateEnableIndex = -1;
831         for (unsigned i = 0; i < reportingState->usageVector.size(); ++i) {
832             if (reportingState->usageVector[i] == REPORTING_STATE_NO_EVENTS) {
833                 mReportingStateDisableIndex = i;
834             }
835             if (reportingState->usageVector[i] == REPORTING_STATE_ALL_EVENTS) {
836                 mReportingStateEnableIndex = i;
837             }
838         }
839         if (mReportingStateDisableIndex < 0) {
840             LOG_W << "Cannot find reporting state to disable sensor"
841                   << LOG_ENDL;
842             mReportingStateId = -1;
843         }
844         if (mReportingStateEnableIndex < 0) {
845             LOG_W << "Cannot find reporting state to enable sensor" << LOG_ENDL;
846             mReportingStateId = -1;
847         }
848     }
849 
850     //POWER_STATE
851     const HidParser::ReportItem *powerState
852             = find(packets, POWER_STATE, HidParser::REPORT_TYPE_FEATURE);
853     if (powerState == nullptr) {
854         LOG_W << "Cannot find valid power state feature" << LOG_ENDL;
855     } else {
856         mPowerStateId = powerState->id;
857         mPowerStateBitOffset = powerState->bitOffset;
858         mPowerStateBitSize = powerState->bitSize;
859 
860         mPowerStateOffIndex = -1;
861         mPowerStateOnIndex = -1;
862         for (unsigned i = 0; i < powerState->usageVector.size(); ++i) {
863             if (powerState->usageVector[i] == POWER_STATE_D4_POWER_OFF) {
864                 mPowerStateOffIndex = i;
865             }
866             if (powerState->usageVector[i] == POWER_STATE_D0_FULL_POWER) {
867                 mPowerStateOnIndex = i;
868             }
869         }
870         if (mPowerStateOffIndex < 0) {
871             LOG_W << "Cannot find power state to power off sensor"
872                   << LOG_ENDL;
873             mPowerStateId = -1;
874         }
875         if (mPowerStateOnIndex < 0) {
876             LOG_W << "Cannot find power state to power on sensor" << LOG_ENDL;
877             mPowerStateId = -1;
878         }
879     }
880 
881     //REPORT_INTERVAL
882     const HidParser::ReportItem *reportInterval
883             = find(packets, REPORT_INTERVAL, HidParser::REPORT_TYPE_FEATURE);
884     if (reportInterval == nullptr
885             || reportInterval->minRaw < 0) {
886         LOG_W << "Cannot find valid report interval feature" << LOG_ENDL;
887     } else {
888         mReportIntervalId = reportInterval->id;
889         mReportIntervalBitOffset = reportInterval->bitOffset;
890         mReportIntervalBitSize = reportInterval->bitSize;
891 
892         mFeatureInfo.minDelay = std::max(static_cast<int64_t>(1), reportInterval->minRaw) * 1000;
893         mFeatureInfo.maxDelay = std::min(static_cast<int64_t>(1000000),
894                                     reportInterval->maxRaw) * 1000; // maximum 1000 second
895     }
896     return true;
897     return (mPowerStateId >= 0 || mReportingStateId >= 0) && mReportIntervalId >= 0;
898 }
899 
getSensor() const900 const sensor_t* HidRawSensor::getSensor() const {
901     return &mSensor;
902 }
903 
getUuid(uint8_t * uuid) const904 void HidRawSensor::getUuid(uint8_t* uuid) const {
905     memcpy(uuid, mFeatureInfo.uuid, sizeof(mFeatureInfo.uuid));
906 }
907 
enable(bool enable)908 int HidRawSensor::enable(bool enable) {
909     SP(HidDevice) device = PROMOTE(mDevice);
910 
911     if (device == nullptr) {
912         return NO_INIT;
913     }
914 
915     if (enable == mEnabled) {
916         return NO_ERROR;
917     }
918 
919     std::vector<uint8_t> buffer;
920     bool setPowerOk = true;
921     if (mPowerStateId >= 0) {
922         setPowerOk = false;
923         uint8_t id = static_cast<uint8_t>(mPowerStateId);
924         if (device->getFeature(id, &buffer)
925                 && (8 * buffer.size()) >=
926                    (mPowerStateBitOffset + mPowerStateBitSize)) {
927             uint8_t index = enable ? mPowerStateOnIndex : mPowerStateOffIndex;
928             HidUtil::copyBits(&index, &(buffer[0]), buffer.size(),
929                               0, mPowerStateBitOffset, mPowerStateBitSize);
930             setPowerOk = device->setFeature(id, buffer);
931         } else {
932             LOG_E << "enable: changing POWER STATE failed" << LOG_ENDL;
933         }
934     }
935 
936     bool setReportingOk = true;
937     if (mReportingStateId >= 0) {
938         setReportingOk = false;
939         uint8_t id = static_cast<uint8_t>(mReportingStateId);
940         if (device->getFeature(id, &buffer)
941                 && (8 * buffer.size()) >
942                    (mReportingStateBitOffset + mReportingStateBitSize)) {
943             uint8_t index = enable ? mReportingStateEnableIndex :
944                                      mReportingStateDisableIndex;
945             HidUtil::copyBits(&index, &(buffer[0]), buffer.size(),0,
946                               mReportingStateBitOffset, mReportingStateBitSize);
947             setReportingOk = device->setFeature(id, buffer);
948         } else {
949             LOG_E << "enable: changing REPORTING STATE failed" << LOG_ENDL;
950         }
951     }
952 
953     if (setPowerOk && setReportingOk) {
954         mEnabled = enable;
955         return NO_ERROR;
956     } else {
957         return INVALID_OPERATION;
958     }
959 }
960 
batch(int64_t samplingPeriod,int64_t batchingPeriod)961 int HidRawSensor::batch(int64_t samplingPeriod, int64_t batchingPeriod) {
962     SP(HidDevice) device = PROMOTE(mDevice);
963     if (device == nullptr) {
964         return NO_INIT;
965     }
966 
967     if (samplingPeriod < 0 || batchingPeriod < 0) {
968         return BAD_VALUE;
969     }
970 
971     bool needRefresh = mSamplingPeriod != samplingPeriod || mBatchingPeriod != batchingPeriod;
972     std::vector<uint8_t> buffer;
973 
974     bool ok = true;
975     if (needRefresh && mReportIntervalId >= 0) {
976         ok = false;
977         uint8_t id = static_cast<uint8_t>(mReportIntervalId);
978         if (device->getFeature(id, &buffer)
979                 && (8 * buffer.size()) >=
980                    (mReportIntervalBitOffset + mReportIntervalBitSize)) {
981             int64_t periodMs = samplingPeriod / 1000000; //ns -> ms
982             int64_t maxPeriodMs =
983                 (1LL << std::min(mReportIntervalBitSize, 63U)) - 1;
984             periodMs = std::min(periodMs, maxPeriodMs);
985             HidUtil::copyBits(&periodMs, &(buffer[0]), buffer.size(),
986                               0, mReportIntervalBitOffset,
987                               mReportIntervalBitSize);
988             ok = device->setFeature(id, buffer);
989         }
990     }
991 
992     if (ok) {
993         mSamplingPeriod = samplingPeriod;
994         mBatchingPeriod = batchingPeriod;
995         return NO_ERROR;
996     } else {
997         return INVALID_OPERATION;
998     }
999 }
1000 
handleInput(uint8_t id,const std::vector<uint8_t> & message)1001 void HidRawSensor::handleInput(uint8_t id, const std::vector<uint8_t> &message) {
1002     if (id != mInputReportId || mEnabled == false) {
1003         return;
1004     }
1005     sensors_event_t event = {
1006         .version = sizeof(event),
1007         .sensor = -1,
1008         .type = mSensor.type
1009     };
1010     bool valid = true;
1011     for (const auto &rec : mTranslateTable) {
1012         int64_t v = (message[rec.byteOffset + rec.byteSize - 1] & 0x80) ? -1 : 0;
1013         for (int i = static_cast<int>(rec.byteSize) - 1; i >= 0; --i) {
1014             v = (v << 8) | message[rec.byteOffset + i]; // HID is little endian
1015         }
1016 
1017         switch (rec.type) {
1018             case TYPE_FLOAT:
1019                 if (v > rec.maxValue || v < rec.minValue) {
1020                     valid = false;
1021                 }
1022                 event.data[rec.index] = rec.a * (v + rec.b);
1023                 break;
1024             case TYPE_INT64:
1025                 if (v > rec.maxValue || v < rec.minValue) {
1026                     valid = false;
1027                 }
1028                 event.u64.data[rec.index] = v + rec.b;
1029                 break;
1030             case TYPE_ACCURACY:
1031                 event.magnetic.status = (v & 0xFF) + rec.b;
1032                 break;
1033         }
1034     }
1035     if (!valid) {
1036         LOG_V << "Range error observed in decoding, discard" << LOG_ENDL;
1037     }
1038     event.timestamp = -1;
1039     generateEvent(event);
1040 }
1041 
dump() const1042 std::string HidRawSensor::dump() const {
1043     std::ostringstream ss;
1044     ss << "Feature Values " << LOG_ENDL
1045           << "  name: " << mFeatureInfo.name << LOG_ENDL
1046           << "  vendor: " << mFeatureInfo.vendor << LOG_ENDL
1047           << "  permission: " << mFeatureInfo.permission << LOG_ENDL
1048           << "  typeString: " << mFeatureInfo.typeString << LOG_ENDL
1049           << "  type: " << mFeatureInfo.type << LOG_ENDL
1050           << "  maxRange: " << mFeatureInfo.maxRange << LOG_ENDL
1051           << "  resolution: " << mFeatureInfo.resolution << LOG_ENDL
1052           << "  power: " << mFeatureInfo.power << LOG_ENDL
1053           << "  minDelay: " << mFeatureInfo.minDelay << LOG_ENDL
1054           << "  maxDelay: " << mFeatureInfo.maxDelay << LOG_ENDL
1055           << "  fifoSize: " << mFeatureInfo.fifoSize << LOG_ENDL
1056           << "  fifoMaxSize: " << mFeatureInfo.fifoMaxSize << LOG_ENDL
1057           << "  reportModeFlag: " << mFeatureInfo.reportModeFlag << LOG_ENDL
1058           << "  isWakeUp: " << (mFeatureInfo.isWakeUp ? "true" : "false") << LOG_ENDL
1059           << "  uniqueId: " << mFeatureInfo.uniqueId << LOG_ENDL
1060           << "  uuid: ";
1061 
1062     ss << std::hex << std::setfill('0');
1063     for (auto d : mFeatureInfo.uuid) {
1064           ss << std::setw(2) << static_cast<int>(d) << " ";
1065     }
1066     ss << std::dec << std::setfill(' ') << LOG_ENDL;
1067 
1068     ss << "Input report id: " << mInputReportId << LOG_ENDL;
1069     for (const auto &t : mTranslateTable) {
1070         ss << "  type, index: " << t.type << ", " << t.index
1071               << "; min,max: " << t.minValue << ", " << t.maxValue
1072               << "; byte-offset,size: " << t.byteOffset << ", " << t.byteSize
1073               << "; scaling,bias: " << t.a << ", " << t.b << LOG_ENDL;
1074     }
1075 
1076     ss << "Control features: " << LOG_ENDL;
1077     ss << "  Power state ";
1078     if (mPowerStateId >= 0) {
1079         ss << "found, id: " << mPowerStateId
1080               << " bit offset: " << mPowerStateBitOffset
1081               << " bit size: " << mPowerStateBitSize
1082               << " power off index: " << mPowerStateOffIndex
1083               << " power on index: " << mPowerStateOnIndex
1084               << LOG_ENDL;
1085     } else {
1086         ss << "not found" << LOG_ENDL;
1087     }
1088 
1089     ss << "  Reporting state ";
1090     if (mReportingStateId >= 0) {
1091         ss << "found, id: " << mReportingStateId
1092               << " bit offset: " << mReportingStateBitOffset
1093               << " bit size: " << mReportingStateBitSize
1094               << " disable index: " << mReportingStateDisableIndex
1095               << " enable index: " << mReportingStateEnableIndex
1096               << LOG_ENDL;
1097     } else {
1098         ss << "not found" << LOG_ENDL;
1099     }
1100 
1101     ss << "  Report interval ";
1102     if (mReportIntervalId >= 0) {
1103         ss << "found, id: " << mReportIntervalId
1104               << " bit offset: " << mReportIntervalBitOffset
1105               << " bit size: " << mReportIntervalBitSize << LOG_ENDL;
1106     } else {
1107         ss << "not found" << LOG_ENDL;
1108     }
1109     return ss.str();
1110 }
1111 
1112 } // namespace SensorHalExt
1113 } // namespace android
1114