1 /*
2  * Copyright (c) 2021-2023 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 CLIENT_H
17 #define CLIENT_H
18 
19 #include "nocopyable.h"
20 
21 #include "circle_stream_buffer.h"
22 #include "i_client.h"
23 
24 namespace OHOS {
25 namespace Msdp {
26 namespace DeviceStatus {
27 class Client final : public StreamClient, public IClient, public std::enable_shared_from_this<IClient> {
28 public:
29     Client() = default;
30     DISALLOW_COPY_AND_MOVE(Client);
31     ~Client() override;
32 
33     int32_t Socket() override;
34     void SetEventHandler(EventHandlerPtr eventHandler) override;
35     void MarkIsEventHandlerChanged(EventHandlerPtr eventHandler) override;
36     bool Start() override;
37     void RegisterConnectedFunction(ConnectCallback function) override;
38     void RegisterDisconnectedFunction(ConnectCallback fun) override;
39     void Stop() override;
40     bool GetCurrentConnectedStatus() const override;
41     bool SendMessage(const NetPacket& pkt) const override;
42     void OnRecvMsg(const char *buf, size_t size) override;
43     int32_t Reconnect() override;
44     void OnDisconnect() override;
45     IClientPtr GetSharedPtr() override;
CheckValidFd()46     inline bool CheckValidFd() const override
47     {
48         return GetFd() > 0;
49     }
IsEventHandlerChanged()50     bool IsEventHandlerChanged() const override
51     {
52         return isEventHandlerChanged_;
53     }
54 
55 private:
56     bool StartEventRunner();
57     void OnReconnect();
58     bool AddFdListener(int32_t fd);
59     bool DelFdListener(int32_t fd);
60     void OnPacket(NetPacket &pkt);
61     const std::string &GetErrorStr(ErrCode code) const;
62     void OnConnected() override;
63     void OnDisconnected() override;
64     void OnMsgHandler(const StreamClient &client, NetPacket &pkt);
65 
66 private:
67     ConnectCallback funConnected_ { nullptr };
68     ConnectCallback funDisconnected_ { nullptr };
69     CircleStreamBuffer circBuf_;
70     std::mutex mtx_;
71     EventHandlerPtr eventHandler_ { nullptr };
72     bool isEventHandlerChanged_ { false };
73     bool isListening_ { false };
74 };
75 } // namespace DeviceStatus
76 } // namespace Msdp
77 } // namespace OHOS
78 #endif // CLIENT_H
79