1 /*
2  * Copyright (c) 2020-2021 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 
16 #ifndef HI_STATE_MACHINE_H
17 #define HI_STATE_MACHINE_H
18 
19 #include <pthread.h>
20 #include <vector>
21 #include <queue>
22 
23 #include "hi_state.h"
24 #include "hi_state_machine_observer.h"
25 #include "message_looper.h"
26 
27 
28 namespace OHOS {
29 class HiStateMachine : public MessageHandler {
30 public:
31     HiStateMachine();
32 
33     int32_t Init(uint32_t maxQueueSize, uint32_t maxMsgPayloadSize, const std::string smName);
34 
35     int32_t Deinit();
36 
37     virtual ~HiStateMachine();
38 
39     int32_t AddState(HiState &state);
40 
41     int32_t SetInitialState(HiState &state);
42 
43     const HiState *CurrentState();
44 
45     int32_t RegisterObserver(HiStateMachineObserver &observer);
46 
47     int32_t Start(void);
48 
49     int32_t Stop(void);
50 
51     /* handled immediately */
52     int32_t Send(const MsgInfo &msg);
53 
54     /* handled immediately */
55     int32_t Send(int32_t what);
56 
57     /* handled async */
58     int32_t Post(const MsgInfo &msg, uint64_t delayUs);
59 
60     /* handled async */
61     int32_t Post(int32_t what, uint64_t delayUs);
62 
63     int32_t RemoveEvent(const MsgInfo &msg);
64 
65 private:
66     int32_t OnMessageReceived(const MsgInfo &msg) override;
67     bool StateExist(const HiState &state);
68     void Transition(HiState &nextState);
69 
70 private:
71     MessageLooper *m_looper {nullptr};
72     HiState *m_currentState {nullptr};
73     std::vector<HiState *> m_allStates;
74     HiStateMachineObserver *m_observer {nullptr};
75     bool m_running {false};
76 };
77 };
78 #endif
79