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 #pragma once
18 #include <android-base/unique_fd.h>
19 #include <V2_1/SubHal.h>
20 #include <atomic>
21 #include <functional>
22 #include <condition_variable>
23 #include <cstdint>
24 #include <random>
25 #include <queue>
26 #include <thread>
27 #include <vector>
28 
29 #include "multihal_sensors_transport.h"
30 
31 namespace goldfish {
32 namespace ahs = ::android::hardware::sensors;
33 namespace ahs21 = ahs::V2_1;
34 namespace ahs10 = ahs::V1_0;
35 
36 using ahs21::implementation::IHalProxyCallback;
37 using ahs21::SensorInfo;
38 using ahs21::Event;
39 using ahs10::AdditionalInfo;
40 using ahs10::OperationMode;
41 using ahs10::RateLevel;
42 using ahs10::Result;
43 using ahs10::SharedMemInfo;
44 
45 using ::android::base::unique_fd;
46 using ::android::hardware::hidl_handle;
47 using ::android::hardware::hidl_string;
48 using ::android::hardware::hidl_vec;
49 using ::android::hardware::Return;
50 using ::android::sp;
51 
52 struct MultihalSensors : public ahs21::implementation::ISensorsSubHal {
53     using SensorsTransportFactory = std::function<std::unique_ptr<SensorsTransport>()>;
54 
55     MultihalSensors(SensorsTransportFactory);
56     ~MultihalSensors();
57 
58     Return<void> debug(const hidl_handle& fd, const hidl_vec<hidl_string>& args) override;
59     Return<void> getSensorsList_2_1(getSensorsList_2_1_cb _hidl_cb) override;
60     Return<Result> setOperationMode(OperationMode mode) override;
61     Return<Result> activate(int32_t sensorHandle, bool enabled) override;
62     Return<Result> batch(int32_t sensorHandle,
63                            int64_t samplingPeriodNs,
64                            int64_t maxReportLatencyNs) override;
65     Return<Result> flush(int32_t sensorHandle) override;
66     Return<Result> injectSensorData_2_1(const Event& event) override;
67 
68 
69     Return<void> registerDirectChannel(const SharedMemInfo& mem,
70                                        registerDirectChannel_cb _hidl_cb) override;
71     Return<Result> unregisterDirectChannel(int32_t channelHandle) override;
72     Return<void> configDirectReport(int32_t sensorHandle,
73                                     int32_t channelHandle,
74                                     RateLevel rate,
75                                     configDirectReport_cb _hidl_cb) override;
76 
77     const std::string getName() override;
78     Return<Result> initialize(const sp<IHalProxyCallback>& halProxyCallback) override;
79 
80 private:
81     struct QemuSensorsProtocolState {
82         int64_t timeBiasNs = -500000000;
83         int32_t sensorsUpdateIntervalMs = 200;
84 
85         static constexpr float kSensorNoValue = -1e+30;
86 
87         // on change sensors (host does not support them)
88         float lastAmbientTemperatureValue = kSensorNoValue;
89         float lastProximityValue = kSensorNoValue;
90         float lastLightValue = kSensorNoValue;
91         float lastRelativeHumidityValue = kSensorNoValue;
92         float lastHingeAngle0Value = kSensorNoValue;
93         float lastHingeAngle1Value = kSensorNoValue;
94         float lastHingeAngle2Value = kSensorNoValue;
95         float lastHeartRateValue = kSensorNoValue;
96         float lastWristTiltMeasurement = -1;
97     };
98 
99     bool isSensorHandleValid(int sensorHandle) const;
isSensorActiveMultihalSensors100     bool isSensorActive(int sensorHandle) const {
101         return m_activeSensorsMask & (1u << sensorHandle);  // m_mtx required
102     }
103     Event activationOnChangeSensorEvent(int32_t sensorHandle, const SensorInfo& sensor) const;
104     static bool setSensorsReportingImpl(SensorsTransport& st, int sensorHandle, bool enabled);
105     static bool setAllSensorsReporting(SensorsTransport& st,
106                                        uint32_t availableSensorsMask, bool enabled);
107     static bool setSensorsGuestTime(SensorsTransport& st, int64_t value);
108     static bool setSensorsUpdateIntervalMs(SensorsTransport& st, uint32_t value);
109     void parseQemuSensorEventLocked(QemuSensorsProtocolState* state);
110     void postSensorEventLocked(const Event& event);
111     void doPostSensorEventLocked(const SensorInfo& sensor, const Event& event);
112     void setAdditionalInfoFrames();
113     void sendAdditionalInfoReport(int sensorHandle);
114 
115     bool qemuSensorListenerThreadImpl(int transportFd);
116     void qemuSensorListenerThread();
117     void batchThread();
118 
119     double randomError(float lo, float hi);
120 
121     static constexpr char kCMD_QUIT = 'q';
122     static constexpr char kCMD_RESTART = 'r';
123     bool qemuSensorThreadSendCommand(char cmd) const;
124 
125     const SensorsTransportFactory m_sensorsTransportFactory;
126     SensorsTransport*   m_sensorsTransport;
127 
128     uint32_t            m_availableSensorsMask = 0;
129     // a pair of connected sockets to talk to the worker thread
130     unique_fd           m_callersFd;        // a caller writes here
131     unique_fd           m_sensorThreadFd;   // the worker thread listens from here
132     std::thread         m_sensorThread;
133 
134     // changed by API
135     uint32_t                m_activeSensorsMask = 0;
136     OperationMode           m_opMode = OperationMode::NORMAL;
137     sp<IHalProxyCallback>   m_halProxyCallback;
138 
139     std::vector<AdditionalInfo> mAdditionalInfoFrames;
140 
141     // batching
142     struct BatchEventRef {
143         int64_t  timestamp = -1;
144         int      sensorHandle = -1;
145         int      generation = 0;
146 
147         bool operator<(const BatchEventRef &rhs) const {
148             // not a typo, we want m_batchQueue.top() to be the smallest timestamp
149             return timestamp > rhs.timestamp;
150         }
151     };
152 
153     struct BatchInfo {
154         Event       event;
155         int64_t     samplingPeriodNs = 0;
156         int         generation = 0;
157     };
158 
159     QemuSensorsProtocolState                m_protocolState;
160     std::priority_queue<BatchEventRef>      m_batchQueue;
161     std::vector<BatchInfo>                  m_batchInfo;
162     std::condition_variable                 m_batchUpdated;
163     std::thread                             m_batchThread;
164     std::atomic<bool>                       m_batchRunning = true;
165 
166     mutable std::mutex                      m_mtx;
167 
168     std::random_device rd;
169     std::mt19937 gen = std::mt19937(rd());
170 };
171 
172 }  // namespace goldfish
173