summaryrefslogtreecommitdiff
path: root/sensorhal/hubconnection.h
blob: 4dbd64e00b33c98bf12141df9fe688ea5a55c103 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef HUB_CONNECTION_H_

#define HUB_CONNECTION_H_

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <poll.h>

#include <utils/Errors.h>
#include <utils/Mutex.h>
#include <utils/Thread.h>

#include <list>

#include "activityeventhandler.h"
#include "directchannel.h"
#include "eventnums.h"
#include "halIntf.h"
#include "hubdefs.h"
#include "ring.h"

#ifdef USE_SENSORSERVICE_TO_GET_FIFO
#include <thread>
#endif
#include <unordered_map>

#define WAKELOCK_NAME "sensorHal"

#define ACCEL_BIAS_TAG     "accel"
#define ACCEL_SW_BIAS_TAG  "accel_sw"
#define GYRO_BIAS_TAG      "gyro"
#define GYRO_OTC_DATA_TAG  "gyro_otc"
#define GYRO_SW_BIAS_TAG   "gyro_sw"
#define MAG_BIAS_TAG       "mag"

#define MAX_ALTERNATES     2

namespace android {

struct HubConnection : public Thread {
    static HubConnection *getInstance();

    status_t initCheck() const;

    enum ProximitySensorType {
        PROXIMITY_UNKNOWN,
        PROXIMITY_ROHM,
        PROXIMITY_AMS,
    };

    // Blocks until it can return a status
    status_t getAliveCheck();

    virtual bool threadLoop();

    void queueActivate(int handle, bool enable);
    void queueSetDelay(int handle, nsecs_t delayNs);
    void queueBatch(int handle, nsecs_t sampling_period_ns,
            nsecs_t max_report_latency_ns);
    void queueFlush(int handle);
    void queueData(int handle, void *data, size_t length);

    void setOperationParameter(const additional_info_event_t &info);

    bool isWakeEvent(int32_t sensor);
    void releaseWakeLockIfAppropriate();
    ssize_t getWakeEventCount();
    ssize_t decrementWakeEventCount();

    //TODO: factor out event ring buffer functionality into a separate class
    ssize_t read(sensors_event_t *ev, size_t size);
    ssize_t write(const sensors_event_t *ev, size_t n);

    void setActivityCallback(ActivityEventHandler *eventHandler);

    void saveSensorSettings() const;

    void setRawScale(float scaleAccel, float scaleMag) {
        mScaleAccel = scaleAccel;
        mScaleMag = scaleMag;
    }

    void setLeftyMode(bool enable);

protected:
    HubConnection();
    virtual ~HubConnection();

    virtual void onFirstRef();

private:
    typedef uint32_t rate_q10_t;  // q10 means lower 10 bits are for fractions

    bool mWakelockHeld;
    int32_t mWakeEventCount;

    void protectIfWakeEvent(int32_t sensor);

    static inline uint64_t period_ns_to_frequency_q10(nsecs_t period_ns) {
        return 1024000000000ULL / period_ns;
    }

    static inline nsecs_t frequency_q10_to_period_ns(uint64_t frequency_q10) {
        if (frequency_q10)
            return 1024000000000LL / frequency_q10;
        else
            return (nsecs_t)0;
    }

    static inline uint64_t frequency_to_frequency_q10(float frequency) {
        return period_ns_to_frequency_q10(static_cast<nsecs_t>(1e9f/frequency));
    }

    enum
    {
        CONFIG_CMD_DISABLE      = 0,
        CONFIG_CMD_ENABLE       = 1,
        CONFIG_CMD_FLUSH        = 2,
        CONFIG_CMD_CFG_DATA     = 3,
        CONFIG_CMD_CALIBRATE    = 4,
    };

    struct ConfigCmd
    {
        uint32_t evtType;
        uint64_t latency;
        rate_q10_t rate;
        uint8_t sensorType;
        uint8_t cmd;
        uint16_t flags;
        uint8_t data[];
    } __attribute__((packed));

    struct MsgCmd
    {
        uint32_t evtType;
        struct HostHubRawPacket msg;
    } __attribute__((packed));

    struct LeftyState
    {
        bool accel; // Process wrist-aware accel samples as lefty mode
        bool gyro; // Process wrist-aware gyro samples as lefty mode
        bool hub; // Sensor hub is currently operating in lefty mode
    };

    struct Flush
    {
        int handle;
        uint8_t count;

        // Used to synchronize the transition in and out of
        // lefty mode between nanohub and the AP.
        bool internal;
    };

    struct SensorState {
        uint64_t latency;
        uint64_t lastTimestamp;
        uint64_t desiredTSample;
        rate_q10_t rate;
        uint8_t sensorType;
        uint8_t primary;
        uint8_t alt[MAX_ALTERNATES];
        bool enable;
    };

    struct FirstSample
    {
        uint8_t numSamples;
        uint8_t numFlushes;
        uint8_t highAccuracy : 1;
        uint8_t biasPresent : 1;
        uint8_t biasSample : 6;
        uint8_t pad;
    };

    struct RawThreeAxisSample
    {
        uint32_t deltaTime;
        int16_t ix, iy, iz;
    } __attribute__((packed));

    struct ThreeAxisSample
    {
        uint32_t deltaTime;
        float x, y, z;
    } __attribute__((packed));

    struct OneAxisSample
    {
        uint32_t deltaTime;
        union
        {
            float fdata;
            uint32_t idata;
        };
    } __attribute__((packed));

    // The following structure should match struct HostIntfDataBuffer found in
    // firmware/inc/hostIntf.h
    struct nAxisEvent
    {
        uint32_t evtType;
        union
        {
            struct
            {
                uint64_t referenceTime;
                union
                {
                    struct FirstSample firstSample;
                    struct OneAxisSample oneSamples[];
                    struct RawThreeAxisSample rawThreeSamples[];
                    struct ThreeAxisSample threeSamples[];
                };
            };
            uint8_t buffer[];
        };
    } __attribute__((packed));

    static Mutex sInstanceLock;
    static HubConnection *sInstance;

    // This lock is used for synchronization between the write thread (from
    // sensorservice) and the read thread polling from the nanohub driver.
    Mutex mLock;

    RingBuffer mRing;

    ActivityEventHandler *mActivityEventHandler;

    float mMagBias[3];
    uint8_t mMagAccuracy;
    uint8_t mMagAccuracyRestore;

    float mGyroBias[3], mAccelBias[3];
    GyroOtcData mGyroOtcData;

    float mScaleAccel, mScaleMag;

    LeftyState mLefty;

    SensorState mSensorState[NUM_COMMS_SENSORS_PLUS_1];
    std::list<struct Flush> mFlushesPending[NUM_COMMS_SENSORS_PLUS_1];

    uint64_t mStepCounterOffset;
    uint64_t mLastStepCount;

    int mFd;
    int mInotifyPollIndex;
    struct pollfd mPollFds[4];
    int mNumPollFds;

    sensors_event_t *initEv(sensors_event_t *ev, uint64_t timestamp, uint32_t type, uint32_t sensor);
    uint8_t magAccuracyUpdate(sensors_vec_t *sv);
    void processSample(uint64_t timestamp, uint32_t type, uint32_t sensor, struct OneAxisSample *sample, bool highAccuracy);
    void processSample(uint64_t timestamp, uint32_t type, uint32_t sensor, struct RawThreeAxisSample *sample, bool highAccuracy);
    void processSample(uint64_t timestamp, uint32_t type, uint32_t sensor, struct ThreeAxisSample *sample, bool highAccuracy);
    void postOsLog(uint8_t *buf, ssize_t len);
    void processAppData(uint8_t *buf, ssize_t len);
    ssize_t processBuf(uint8_t *buf, size_t len);

    inline bool isValidHandle(int handle) {
        return handle >= 0
            && handle < NUM_COMMS_SENSORS_PLUS_1
            && mSensorState[handle].sensorType;
    }

    ssize_t sendCmd(const void *buf, size_t count);
    void initConfigCmd(struct ConfigCmd *cmd, int handle);

    void queueFlushInternal(int handle, bool internal);

    void queueDataInternal(int handle, void *data, size_t length);

    void discardInotifyEvent();
    void waitOnNanohubLock();

    void initNanohubLock();

    void restoreSensorState();
    void sendCalibrationOffsets();

#ifdef USE_SENSORSERVICE_TO_GET_FIFO
    // Enable SCHED_FIFO priority for main thread
    std::thread mEnableSchedFifoThread;
#endif
    static void enableSchedFifoMode(sp<HubConnection> hub);

#ifdef LID_STATE_REPORTING_ENABLED
    int mUinputFd;

    status_t initializeUinputNode();
    void sendFolioEvent(int32_t data);
#endif  // LID_STATE_REPORTING_ENABLED

#ifdef USB_MAG_BIAS_REPORTING_ENABLED
    int mMagBiasPollIndex;
    float mUsbMagBias;

    void queueUsbMagBias();
#endif  // USB_MAG_BIAS_REPORTING_ENABLED

#ifdef DOUBLE_TOUCH_ENABLED
    int mDoubleTouchPollIndex;
#endif  // DOUBLE_TOUCH_ENABLED

    // Direct report functions
public:
    int addDirectChannel(const struct sensors_direct_mem_t *mem);
    int removeDirectChannel(int channel_handle);
    int configDirectReport(int sensor_handle, int channel_handle, int rate_level);
    bool isDirectReportSupported() const;
private:
    void sendDirectReportEvent(const sensors_event_t *nev, size_t n);
    void mergeDirectReportRequest(struct ConfigCmd *cmd, int handle);
    bool isSampleIntervalSatisfied(int handle, uint64_t timestamp);
    void updateSampleRate(int handle, int reason);
#ifdef DIRECT_REPORT_ENABLED
    int stopAllDirectReportOnChannel(
            int channel_handle, std::vector<int32_t> *unstoppedSensors);
    uint64_t rateLevelToDeviceSamplingPeriodNs(int handle, int rateLevel) const;
    inline static bool intervalLargeEnough(uint64_t actual, uint64_t desired) {
        return (actual + (actual >> 4)) >= desired; // >= 94.11% of desired
    }

    struct DirectChannelTimingInfo{
        uint64_t lastTimestamp;
        int rateLevel;
    };
    Mutex mDirectChannelLock;
    //sensor_handle=>(channel_handle => DirectChannelTimingInfo)
    std::unordered_map<int32_t,
            std::unordered_map<int32_t, DirectChannelTimingInfo> > mSensorToChannel;
    //channel_handle=>ptr of Channel obj
    std::unordered_map<int32_t, std::unique_ptr<DirectChannelBase>> mDirectChannel;
    int32_t mDirectChannelHandle;
#endif

    DISALLOW_EVIL_CONSTRUCTORS(HubConnection);
};

}  // namespace android

#endif  // HUB_CONNECTION_H_