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 "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(
46             int64_t timestampNs,
47             unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>>& firedAlarms);
48 
49 protected:
50     // For test only. Returns the alarm timestamp in seconds. Otherwise returns 0.
getAlarmTimestampSec()51     inline int32_t getAlarmTimestampSec() const {
52         return mInternalAlarm == nullptr ? 0 : mInternalAlarm->timestampSec;
53     }
54 
55     int64_t findNextAlarmSec(int64_t currentTimeMillis);
56 
57     // statsd_config.proto Alarm message that defines this tracker.
58     const Alarm mAlarmConfig;
59 
60     // A reference to the Alarm's config key.
61     const ConfigKey mConfigKey;
62 
63     // The subscriptions that depend on this alarm.
64     std::vector<Subscription> mSubscriptions;
65 
66     // Alarm monitor.
67     sp<AlarmMonitor> mAlarmMonitor;
68 
69     // The current expected alarm time in seconds.
70     int64_t mAlarmSec;
71 
72     // The current alarm.
73     sp<const InternalAlarm> mInternalAlarm;
74 
75     FRIEND_TEST(AlarmTrackerTest, TestTriggerTimestamp);
76     FRIEND_TEST(AlarmE2eTest, TestMultipleAlarms);
77     FRIEND_TEST(ConfigUpdateTest, TestUpdateAlarms);
78 };
79 
80 }  // namespace statsd
81 }  // namespace os
82 }  // namespace android
83