1 /*
2  * Copyright (C) 2018 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 
19 #include <gtest/gtest_prod.h>
20 
21 #include "AlarmMonitor.h"
22 #include "config/ConfigKey.h"
23 #include "frameworks/base/cmds/statsd/src/statsd_config.pb.h"  // Alarm
24 
25 #include <stdlib.h>
26 #include <utils/RefBase.h>
27 
28 namespace android {
29 namespace os {
30 namespace statsd {
31 
32 class AlarmTracker : public virtual RefBase {
33 public:
34     AlarmTracker(const int64_t startMillis,
35                  const int64_t currentMillis,
36                  const Alarm& alarm, const ConfigKey& configKey,
37                  const sp<AlarmMonitor>& subscriberAlarmMonitor);
38 
39     virtual ~AlarmTracker();
40 
41     void onAlarmFired();
42 
43     void addSubscription(const Subscription& subscription);
44 
45     void informAlarmsFired(const int64_t& timestampNs,
46             unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>>& firedAlarms);
47 
48 protected:
49     // For test only. Returns the alarm timestamp in seconds. Otherwise returns 0.
getAlarmTimestampSec()50     inline int32_t getAlarmTimestampSec() const {
51         return mInternalAlarm == nullptr ? 0 : mInternalAlarm->timestampSec;
52     }
53 
54     int64_t findNextAlarmSec(int64_t currentTimeMillis);
55 
56     // statsd_config.proto Alarm message that defines this tracker.
57     const Alarm mAlarmConfig;
58 
59     // A reference to the Alarm's config key.
60     const ConfigKey mConfigKey;
61 
62     // The subscriptions that depend on this alarm.
63     std::vector<Subscription> mSubscriptions;
64 
65     // Alarm monitor.
66     sp<AlarmMonitor> mAlarmMonitor;
67 
68     // The current expected alarm time in seconds.
69     int64_t mAlarmSec;
70 
71     // The current alarm.
72     sp<const InternalAlarm> mInternalAlarm;
73 
74     FRIEND_TEST(AlarmTrackerTest, TestTriggerTimestamp);
75     FRIEND_TEST(AlarmE2eTest, TestMultipleAlarms);
76 };
77 
78 }  // namespace statsd
79 }  // namespace os
80 }  // namespace android
81