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