summaryrefslogtreecommitdiff
path: root/firmware/os/drivers/tilt_detection/tilt_detection.c
blob: 2e90bd9e94b5efcde5aaa88491ae66305746693a (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
/*
 * Copyright (C) 2016 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.
 */

#include <stdlib.h>
#include <string.h>
#include <timer.h>
#include <heap.h>
#include <plat/rtc.h>
#include <plat/syscfg.h>
#include <hostIntf.h>
#include <nanohubPacket.h>

#include <seos.h>

#include <nanohub_math.h>
#include <sensors.h>
#include <limits.h>

#define TILT_APP_VERSION 1

#define EVT_SENSOR_ANY_MOTION sensorGetMyEventType(SENS_TYPE_ANY_MOTION)
#define EVT_SENSOR_NO_MOTION sensorGetMyEventType(SENS_TYPE_NO_MOTION)
#define EVT_SENSOR_ACCEL sensorGetMyEventType(SENS_TYPE_ACCEL)

#define ACCEL_MIN_RATE    SENSOR_HZ(50)
#define ACCEL_MAX_LATENCY 250000000ull   // 250 ms

#define BATCH_TIME      2000000000ull // 2.0 seconds
#define ANGLE_THRESH    (0.819 * 9.81 * 9.81) // ~cos(35) * (1G in m/s^2)^2

struct TiltAlgoState {
    uint64_t this_batch_init_ts;
    uint32_t this_batch_num_samples;
    float this_batch_sample_sum[3];
    float this_batch_g[3];
    float last_ref_g_vector[3];
    bool last_ref_g_vector_valid;
    bool anamoly_this_batch;
    bool tilt_detected;
};

static struct TiltDetectionTask {
    struct TiltAlgoState algoState;
    uint32_t taskId;
    uint32_t handle;
    uint32_t anyMotionHandle;
    uint32_t noMotionHandle;
    uint32_t accelHandle;
    enum {
        STATE_DISABLED,
        STATE_AWAITING_ANY_MOTION,
        STATE_AWAITING_TILT,
    } taskState;
} mTask;

// *****************************************************************************

static void algoInit()
{
    // nothing here
}

static bool algoUpdate(struct TripleAxisDataEvent *ev)
{
    float dotProduct = 0.0f;
    uint64_t dt;
    bool latch_g_vector = false;
    bool tilt_detected = false;
    struct TiltAlgoState *state = &mTask.algoState;
    uint64_t sample_ts = ev->referenceTime;
    uint32_t numSamples = ev->samples[0].firstSample.numSamples;
    uint32_t i;
    struct TripleAxisDataPoint *sample;
    float invN;

    for (i = 0; i < numSamples; i++) {
        sample = &ev->samples[i];
        if (i > 0)
            sample_ts += sample->deltaTime;

        if (state->this_batch_init_ts == 0) {
            state->this_batch_init_ts = sample_ts;
        }

        state->this_batch_sample_sum[0] += sample->x;
        state->this_batch_sample_sum[1] += sample->y;
        state->this_batch_sample_sum[2] += sample->z;

        state->this_batch_num_samples++;

        dt = (sample_ts - state->this_batch_init_ts);

        if (dt > BATCH_TIME) {
            invN = 1.0f / state->this_batch_num_samples;
            state->this_batch_g[0] = state->this_batch_sample_sum[0] * invN;
            state->this_batch_g[1] = state->this_batch_sample_sum[1] * invN;
            state->this_batch_g[2] = state->this_batch_sample_sum[2] * invN;

            if (state->last_ref_g_vector_valid) {
                dotProduct = state->this_batch_g[0] * state->last_ref_g_vector[0] +
                    state->this_batch_g[1] * state->last_ref_g_vector[1] +
                    state->this_batch_g[2] * state->last_ref_g_vector[2];

                if (dotProduct < ANGLE_THRESH) {
                    tilt_detected = true;
                    latch_g_vector = true;
                }
            } else { // reference g vector not valid, first time computing
                latch_g_vector = true;
                state->last_ref_g_vector_valid = true;
            }

            // latch the first batch or when dotProduct < ANGLE_THRESH
            if (latch_g_vector) {
                state->last_ref_g_vector[0] = state->this_batch_g[0];
                state->last_ref_g_vector[1] = state->this_batch_g[1];
                state->last_ref_g_vector[2] = state->this_batch_g[2];
            }

            // Seed the next batch
            state->this_batch_init_ts = 0;
            state->this_batch_num_samples = 0;
            state->this_batch_sample_sum[0] = 0;
            state->this_batch_sample_sum[1] = 0;
            state->this_batch_sample_sum[2] = 0;
        }
    }

    return tilt_detected;
}

static void configAnyMotion(bool on) {
    if (on) {
        sensorRequest(mTask.taskId, mTask.anyMotionHandle, SENSOR_RATE_ONCHANGE, 0);
        osEventSubscribe(mTask.taskId, EVT_SENSOR_ANY_MOTION);
    } else {
        sensorRelease(mTask.taskId, mTask.anyMotionHandle);
        osEventUnsubscribe(mTask.taskId, EVT_SENSOR_ANY_MOTION);
    }
}

static void configNoMotion(bool on) {
    if (on) {
        sensorRequest(mTask.taskId, mTask.noMotionHandle, SENSOR_RATE_ONCHANGE, 0);
        osEventSubscribe(mTask.taskId, EVT_SENSOR_NO_MOTION);
    } else {
        sensorRelease(mTask.taskId, mTask.noMotionHandle);
        osEventUnsubscribe(mTask.taskId, EVT_SENSOR_NO_MOTION);
    }
}

static void configAccel(bool on) {
    if (on) {
        sensorRequest(mTask.taskId, mTask.accelHandle, ACCEL_MIN_RATE,
                      ACCEL_MAX_LATENCY);
        osEventSubscribe(mTask.taskId, EVT_SENSOR_ACCEL);
    } else {
        sensorRelease(mTask.taskId, mTask.accelHandle);
        osEventUnsubscribe(mTask.taskId, EVT_SENSOR_ACCEL);
    }

}

// *****************************************************************************

static const struct SensorInfo mSi =
{
    .sensorName = "Tilt Detection",
    .sensorType = SENS_TYPE_TILT,
    .numAxis = NUM_AXIS_EMBEDDED,
    .interrupt = NANOHUB_INT_WAKEUP,
    .minSamples = 20
};

static bool tiltDetectionPower(bool on, void *cookie)
{
    if (on) {
        configAnyMotion(true);
        mTask.taskState = STATE_AWAITING_ANY_MOTION;
    } else {
        configAnyMotion(false);
        configNoMotion(false);
        configAccel(false);
        mTask.taskState = STATE_DISABLED;
    }

    sensorSignalInternalEvt(mTask.handle, SENSOR_INTERNAL_EVT_POWER_STATE_CHG,
                            on, 0);
    return true;
}

static bool tiltDetectionSetRate(uint32_t rate, uint64_t latency, void *cookie)
{
    sensorSignalInternalEvt(mTask.handle, SENSOR_INTERNAL_EVT_RATE_CHG, rate,
                            latency);
    return true;
}

static bool tiltDetectionFirmwareUpload(void *cookie)
{
    sensorSignalInternalEvt(mTask.handle, SENSOR_INTERNAL_EVT_FW_STATE_CHG,
            1, 0);
    return true;
}

static bool tiltDetectionFlush(void *cookie)
{
    return osEnqueueEvt(sensorGetMyEventType(SENS_TYPE_TILT),
                        SENSOR_DATA_EVENT_FLUSH, NULL);
}

static void tiltDetectionHandleEvent(uint32_t evtType, const void* evtData)
{
    if (evtData == SENSOR_DATA_EVENT_FLUSH)
        return;

    switch (evtType) {
    case EVT_APP_START:
        osEventUnsubscribe(mTask.taskId, EVT_APP_START);
        sensorFind(SENS_TYPE_ANY_MOTION, 0, &mTask.anyMotionHandle);
        sensorFind(SENS_TYPE_NO_MOTION, 0, &mTask.noMotionHandle);
        sensorFind(SENS_TYPE_ACCEL, 0, &mTask.accelHandle);
        break;

    case EVT_SENSOR_ANY_MOTION:
        if (mTask.taskState == STATE_AWAITING_ANY_MOTION) {
            configAnyMotion(false);
            configNoMotion(true);
            configAccel(true);

            mTask.taskState = STATE_AWAITING_TILT;
        }
        break;

    case EVT_SENSOR_NO_MOTION:
        if (mTask.taskState == STATE_AWAITING_TILT) {
            configNoMotion(false);
            configAccel(false);
            configAnyMotion(true);

            mTask.taskState = STATE_AWAITING_ANY_MOTION;
        }
        break;

    case EVT_SENSOR_ACCEL:
        if (mTask.taskState == STATE_AWAITING_TILT) {
            if (algoUpdate((struct TripleAxisDataEvent *)evtData)) {
                union EmbeddedDataPoint sample;
                sample.idata = 1;
                osEnqueueEvt(sensorGetMyEventType(SENS_TYPE_TILT), sample.vptr, NULL);
            }
        }
        break;
    }
}

static const struct SensorOps mSops =
{
    .sensorPower = tiltDetectionPower,
    .sensorFirmwareUpload = tiltDetectionFirmwareUpload,
    .sensorSetRate = tiltDetectionSetRate,
    .sensorFlush = tiltDetectionFlush,
};

static bool tiltDetectionStart(uint32_t taskId)
{
    mTask.taskId = taskId;
    mTask.handle = sensorRegister(&mSi, &mSops, NULL, true);
    algoInit();
    osEventSubscribe(taskId, EVT_APP_START);
    return true;
}

static void tiltDetectionEnd()
{
}

INTERNAL_APP_INIT(
        APP_ID_MAKE(NANOHUB_VENDOR_GOOGLE, 8),
        TILT_APP_VERSION,
        tiltDetectionStart,
        tiltDetectionEnd,
        tiltDetectionHandleEvent);