sensor: re-sample pressure data and perform lazy insertions to reduce DB overhead
[platform/core/context/context-provider.git] / src / sensor / sleep / SleepMonitor.cpp
1 /*
2  * Copyright (c) 2016 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 <Types.h>
18 #include "../TypesInternal.h"
19 #include "../TimeUtil.h"
20 #include "SleepMonitor.h"
21
22 #define IDX_SLEEP_STATE 0
23 #define IDX_REMAINING   6
24
25 using namespace ctx;
26
27 SleepMonitor::SleepMonitor(SleepLogger *logger) :
28         __logger(logger),
29         __lazyStopOn(false)
30 {
31         setSensor(HUMAN_SLEEP_MONITOR_SENSOR);
32         setPowerSave(false);
33 }
34
35 SleepMonitor::~SleepMonitor()
36 {
37 }
38
39 bool SleepMonitor::start()
40 {
41         _D("START");
42         __lazyStopOn = false;
43         return listen();
44 }
45
46 void SleepMonitor::stop()
47 {
48         _D("STOP");
49         unlisten();
50 }
51
52 void SleepMonitor::lazyStop()
53 {
54         if (!isRunning())
55                 return;
56
57         __lazyStopOn = true;
58 }
59
60 void SleepMonitor::onEvent(sensor_data_t *eventData)
61 {
62         _D("%d at %llu", (int)eventData->values[IDX_SLEEP_STATE], eventData->timestamp);
63
64         uint64_t timestamp = TimeUtil::getTime(eventData->timestamp);
65         __logger->record(timestamp - SEC_TO_MS(SECONDS_PER_MINUTE), timestamp,
66                         static_cast<int>(eventData->values[IDX_SLEEP_STATE]));
67
68         if (static_cast<int>(eventData->values[IDX_REMAINING]) > 0)
69                 return;
70
71         __logger->flushCache();
72
73         if (__lazyStopOn)
74                 stop();
75 }