Home | History | Annotate | Download | only in nanotool
      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 
     17 #ifndef CONTEXTHUB_H_
     18 #define CONTEXTHUB_H_
     19 
     20 #include "nanomessage.h"
     21 #include "noncopyable.h"
     22 
     23 #include <bitset>
     24 #include <functional>
     25 #include <vector>
     26 
     27 namespace android {
     28 
     29 class AppToHostEvent;
     30 class SensorEvent;
     31 
     32 // Array length helper macro
     33 #define ARRAY_LEN(arr) (sizeof(arr) / sizeof(arr[0]))
     34 
     35 enum class SensorType {
     36     Invalid_ = 0,
     37 
     38     // The order of this enum must correspond to sensor types in nanohub's
     39     // sensType.h
     40     Accel,
     41     AnyMotion,
     42     NoMotion,
     43     SignificantMotion,
     44     Flat,
     45     Gyro,
     46     GyroUncal,
     47     Magnetometer,
     48     MagnetometerUncal,
     49     Barometer,
     50     Temperature,
     51     AmbientLightSensor,
     52     Proximity,
     53     Orientation,
     54     HeartRateECG,
     55     HeartRatePPG,
     56     Gravity,
     57     LinearAccel,
     58     RotationVector,
     59     GeomagneticRotationVector,
     60     GameRotationVector,
     61     StepCount,
     62     StepDetect,
     63     Gesture,
     64     Tilt,
     65     DoubleTwist,
     66     DoubleTap,
     67     WindowOrientation,
     68     Hall,
     69     Activity,
     70     Vsync,
     71     CompressedAccel,
     72     WristTilt = 39,
     73 
     74     Max_
     75 };
     76 
     77 // Overloaded values of rate used in sensor enable request (see sensors.h)
     78 enum class SensorSpecialRate : uint32_t {
     79     None     = 0,
     80     OnDemand = 0xFFFFFF00,
     81     OnChange = 0xFFFFFF01,
     82     OneShot  = 0xFFFFFF02,
     83 };
     84 
     85 struct SensorSpec {
     86     SensorType sensor_type = SensorType::Invalid_;
     87 
     88     // When enabling a sensor, rate can be specified in Hz or as one of the
     89     // special values
     90     SensorSpecialRate special_rate = SensorSpecialRate::None;
     91     float rate_hz = -1;
     92     uint64_t latency_ns = 0;
     93 
     94     // Reference value (ground truth) used for calibration
     95     bool have_cal_ref = false;
     96     float cal_ref;
     97 };
     98 
     99 /*
    100  * An interface for communicating with a ContextHub.
    101  */
    102 class ContextHub : public NonCopyable {
    103   public:
    104     virtual ~ContextHub() {};
    105 
    106     static std::string SensorTypeToAbbrevName(SensorType sensor_type);
    107     static SensorType SensorAbbrevNameToType(const char *abbrev_name);
    108     static SensorType SensorAbbrevNameToType(const std::string& abbrev_name);
    109     static std::string ListAllSensorAbbrevNames();
    110 
    111     /*
    112      * Performs initialization to allow commands to be sent to the context hub.
    113      * Must be called before any other functions that send commands. Returns
    114      * true on success, false on failure.
    115      */
    116     virtual bool Initialize() = 0;
    117 
    118     /*
    119      * Configures the ContextHub to allow logs to be printed to stdout.
    120      */
    121     virtual void SetLoggingEnabled(bool logging_enabled) = 0;
    122 
    123     /*
    124      * Loads a new firmware image to the ContextHub. The firmware image is
    125      * specified by filename. Returns false if an error occurs.
    126      */
    127     bool Flash(const std::string& filename);
    128 
    129     /*
    130      * Performs the sensor calibration routine and writes the resulting data to
    131      * a file.
    132      */
    133     bool CalibrateSensors(const std::vector<SensorSpec>& sensors);
    134 
    135     /*
    136      * Performs the sensor self-test routine.
    137      */
    138     bool TestSensors(const std::vector<SensorSpec>& sensors);
    139 
    140     /*
    141      * Sends a sensor enable request to the context hub.
    142      */
    143     bool EnableSensor(const SensorSpec& sensor);
    144     bool EnableSensors(const std::vector<SensorSpec>& sensors);
    145 
    146     /*
    147      * Sends a disable sensor request to context hub. Note that this always
    148      * results in sending a request, i.e. this does not check whether the sensor
    149      * is currently enabled or not.
    150      */
    151     bool DisableSensor(SensorType sensor_type);
    152     bool DisableSensors(const std::vector<SensorSpec>& sensors);
    153 
    154     /*
    155      * Sends a disable sensor request for every sensor type we know about.
    156      */
    157     bool DisableAllSensors();
    158 
    159     /*
    160      * Calls DisableSensor() on all active sensors (i.e. those which have been
    161      * enabled but not yet disabled). This should be called from the destructor
    162      * of derived classes before tearing down communications to ensure we don't
    163      * leave sensors enabled after exiting.
    164      */
    165     bool DisableActiveSensors();
    166 
    167     /*
    168      * Sends all data stored in the calibration file to the context hub.
    169      */
    170     virtual bool LoadCalibration();
    171 
    172     /*
    173      * Prints up to <limit> incoming events. If limit is 0, then continues
    174      * indefinitely.
    175      */
    176     void PrintAllEvents(unsigned int limit);
    177 
    178     /*
    179      * Requests bridge version information
    180      */
    181     bool PrintBridgeVersion();
    182 
    183     /*
    184      * Prints up to <sample_limit> incoming sensor samples corresponding to the
    185      * given SensorType, ignoring other events. If sample_limit is 0, then
    186      * continues indefinitely.
    187      */
    188     void PrintSensorEvents(SensorType sensor_type, int sample_limit);
    189     void PrintSensorEvents(const std::vector<SensorSpec>& sensors,
    190         int sample_limit);
    191 
    192   protected:
    193     enum class TransportResult {
    194         Success,
    195         GeneralFailure,
    196         Timeout,
    197         ParseFailure,
    198         Canceled,
    199         // Add more specific error reasons as needed
    200     };
    201 
    202     // Performs the calibration routine, but does not call SaveCalibration()
    203     bool CalibrateSingleSensor(const SensorSpec& sensor);
    204 
    205     // Performs the self-test routine
    206     bool TestSingleSensor(const SensorSpec& sensor);
    207 
    208     /*
    209      * Iterates over sensors, invoking the given callback on each element.
    210      * Returns true if all callbacks returned true. Exits early on failure.
    211      */
    212     bool ForEachSensor(const std::vector<SensorSpec>& sensors,
    213         std::function<bool(const SensorSpec&)> callback);
    214 
    215     /*
    216      * Parses a calibration result event and invokes the appropriate
    217      * SetCalibration function with the calibration data.
    218      */
    219     bool HandleCalibrationResult(const SensorSpec& sensor,
    220         const AppToHostEvent &event);
    221 
    222     /*
    223      * Parses a self-test result event
    224      */
    225     bool HandleTestResult(const SensorSpec& sensor,
    226         const AppToHostEvent &event);
    227 
    228     /*
    229      * Same as ReadSensorEvents, but filters on AppToHostEvent instead of
    230      * SensorEvent.
    231      */
    232     TransportResult ReadAppEvents(std::function<bool(const AppToHostEvent&)> callback,
    233         int timeout_ms = 0);
    234 
    235     /*
    236      * Calls ReadEvent in a loop, handling errors and ignoring events that
    237      * didn't originate from a sensor. Valid SensorEvents are passed to the
    238      * callback for further processing. The callback should return a boolean
    239      * indicating whether to continue (true) or exit the read loop (false).
    240      */
    241     void ReadSensorEvents(std::function<bool(const SensorEvent&)> callback);
    242 
    243     /*
    244      * Sends the given calibration data down to the hub
    245      */
    246     bool SendCalibrationData(SensorType sensor_type,
    247         const std::vector<uint8_t>& cal_data);
    248 
    249     /*
    250      * Read an event from the sensor hub. Block until a event is successfully
    251      * read, no event traffic is generated for the timeout period, or an error
    252      * occurs, such as a CRC check failure.
    253      */
    254     virtual TransportResult ReadEvent(std::vector<uint8_t>& response,
    255         int timeout_ms) = 0;
    256     virtual TransportResult WriteEvent(const std::vector<uint8_t>& request) = 0;
    257 
    258     // Implements the firmware loading functionality for the sensor hub. Returns
    259     // false if an error occurs while writing the firmware to the device.
    260     virtual bool FlashSensorHub(const std::vector<uint8_t>& bytes) = 0;
    261 
    262     // Convenience functions that build on top of the more generic byte-level
    263     // interface
    264     TransportResult ReadEvent(std::unique_ptr<ReadEventResponse>* response,
    265         int timeout_ms = 0);
    266     TransportResult WriteEvent(const WriteEventRequest& request);
    267 
    268     // Override these if saving calibration data to persistent storage is
    269     // supported on the platform
    270     virtual bool SetCalibration(SensorType sensor_type, int32_t data);
    271     virtual bool SetCalibration(SensorType sensor_type, float data);
    272     virtual bool SetCalibration(SensorType sensor_type, int32_t x,
    273         int32_t y, int32_t z);
    274     virtual bool SetCalibration(SensorType sensor_type, int32_t x,
    275         int32_t y, int32_t z, int32_t w);
    276     virtual bool SaveCalibration();
    277 
    278 private:
    279     std::bitset<static_cast<int>(SensorType::Max_)> sensor_is_active_;
    280 };
    281 
    282 }  // namespace android
    283 
    284 #endif  // CONTEXTHUB_H_
    285