1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #ifndef SCENE_TIMER_OH_IMPL_H
16 #define SCENE_TIMER_OH_IMPL_H
17 
18 #include "ISceneTimerInfrastructure.h"
19 #include <map>
20 #include <mutex>
21 #include <condition_variable>
22 
23 namespace OHOS {
24 namespace HiviewDFX {
25 /* this design is difficult to UT, that's a problem */
26 class SceneTimerOhImpl : public ISceneTimerInfrastructure {
27 public:
28     const static unsigned int checkInterval = 500; // this means accuracy
29 
30     SceneTimerOhImpl();
31     void RegUser(int userId, ICb* cb) override;
32     void UnRegUser(int userId) override;
33     void Start(int user, int id, long interval) override;
34     void Stop(int user, int id) override;
35 
36 private:
37     const static int maxUserId = 16;
38     const static int maxRecordPerUser = 128;
39 
40     std::map<int, long long> records;
41     std::mutex mut;
42     std::condition_variable cv;
43     std::map<int, ICb*> callbacks; // userId as key, potentially multi-thread problem, but for now, lock is not needed
44 
45     void Loop();
46     void FillRecordAndNotify(int key, long long expireTs);
47     void ValidateDuplication(int key);
48     void ValidateExistence(int key);
49     long long GetCurTimeStamp();
50     void CheckRecordsAndTrigger();
51     static int BuildRecordKey(int user, int id);
52     long long CalcExpireTimeStamp(long delay);
53     void TriggerCallbak(int recordKey);
54     static int ExtractUserFromRecordKey(int key);
55     static int ExtractIdFromRecordKey(int key);
56     void RemoveRecordAndNotify(int key);
57 };
58 } // HiviewDFX
59 } // OHOS
60 #endif
61