sensord: enable samsung pedometer sensor for fused location
[platform/core/system/sensord.git] / src / sensor / pedometer / average_filter.cpp
1 /*
2  *  Copyright (c) 2016-2017 Samsung Electronics Co., Ltd.
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 #include "average_filter.h"
18
19 #include <stdlib.h>
20
21 static double mean(double *array, int size)
22 {
23         double avrg = 0;
24
25         for (int i = 0; i < size; ++i)
26                 avrg = avrg + array[i];
27
28         return avrg / size;
29 }
30
31 average_filter::average_filter(int sz)
32 : m_size(sz)
33 , m_index(0)
34 , m_ready(false)
35 {
36         m_array = (double *)calloc(sz, sizeof(double));
37 }
38
39 average_filter::~average_filter()
40 {
41         if (m_array == NULL)
42                 return;
43
44         free(m_array);
45         m_array = NULL;
46         m_size = 0;
47 }
48
49 double average_filter::filter(double value)
50 {
51         m_array[m_index++] = value;
52
53         if (m_index >= m_size) {
54                 m_ready = true;
55                 m_index = 0;
56         }
57         return mean(m_array, (m_ready ? m_size : m_index));
58 }
59
60 void average_filter::reset(void)
61 {
62         m_index = 0;
63         m_ready = false;
64 }