1 /*
2  * Copyright (c) 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 LNN_STATE_MACHINE_H
17 #define LNN_STATE_MACHINE_H
18 
19 #include <stdint.h>
20 
21 #include "common_list.h"
22 #include "message_handler.h"
23 
24 #ifdef __cplusplus
25 extern "C" {
26 #endif
27 
28 #define FSM_FLAG_RUNNING 0x1
29 
30 #define FSM_CTRL_MSG_START 0
31 #define FSM_CTRL_MSG_DATA 1
32 #define FSM_CTRL_MSG_STOP 2
33 #define FSM_CTRL_MSG_DEINIT 3
34 
35 struct tagFsmStateMachine;
36 
37 typedef void (*StateEnterFunc)(struct tagFsmStateMachine *fsm);
38 typedef void (*StateExitFunc)(struct tagFsmStateMachine *fsm);
39 typedef bool (*StateProcessFunc)(struct tagFsmStateMachine *fsm, int32_t msgType, void *para);
40 
41 typedef struct {
42     ListNode list;
43     StateEnterFunc enter;
44     StateProcessFunc process;
45     StateExitFunc exit;
46 } FsmState;
47 
48 typedef void (*FsmDeinitCallback)(struct tagFsmStateMachine *fsm);
49 
50 typedef struct tagFsmStateMachine {
51     FsmState *curState;
52     uint32_t flag;
53 
54     ListNode stateList;
55     SoftBusLooper *looper;
56     SoftBusHandler handler;
57 
58     FsmDeinitCallback deinitCallback;
59 } FsmStateMachine;
60 
61 typedef struct {
62     FsmStateMachine *fsm;
63     void *obj;
64 } FsmCtrlMsgObj;
65 
66 int32_t LnnFsmInit(FsmStateMachine *fsm, SoftBusLooper *looper, char *name, FsmDeinitCallback cb);
67 int32_t LnnFsmDeinit(FsmStateMachine *fsm);
68 
69 int32_t LnnFsmAddState(FsmStateMachine *fsm, FsmState *state);
70 
71 int32_t LnnFsmStart(FsmStateMachine *fsm, FsmState *initialState);
72 int32_t LnnFsmStop(FsmStateMachine *fsm);
73 
74 int32_t LnnFsmPostMessage(FsmStateMachine *fsm, uint32_t msgType, void *data);
75 int32_t LnnFsmPostMessageDelay(FsmStateMachine *fsm, uint32_t msgType, void *data, uint64_t delayMillis);
76 
77 int32_t LnnFsmRemoveMessageByType(FsmStateMachine *fsm, int32_t what);
78 
79 /* msgType value should not be 0 */
80 int32_t LnnFsmRemoveMessage(FsmStateMachine *fsm, int32_t msgType);
81 int32_t LnnFsmRemoveMessageSpecific(FsmStateMachine *fsm,
82     int32_t (*customFunc)(const SoftBusMessage*, void*), void *args);
83 
84 int32_t LnnFsmTransactState(FsmStateMachine *fsm, FsmState *state);
85 
86 #ifdef __cplusplus
87 }
88 #endif
89 
90 #endif
91