1 /*
2 * Copyright (c) 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 #include "state_change_notify.h"
17
18 #include "devicestatus_define.h"
19
20 namespace OHOS {
21 namespace Msdp {
22 namespace DeviceStatus {
23 namespace {
24 constexpr OHOS::HiviewDFX::HiLogLabel LABEL { LOG_CORE, MSDP_DOMAIN_ID, "StateChangeNotify" };
25 } // namespace
26
AddNotifyMsg(std::shared_ptr<MessageInfo> info)27 void StateChangeNotify::AddNotifyMsg(std::shared_ptr<MessageInfo> info)
28 {
29 CALL_DEBUG_ENTER;
30 CHKPV(info);
31 auto it = std::find_if(msgInfos_.begin(), msgInfos_.end(),
32 [info] (auto msgInfo) {
33 return *msgInfo == info;
34 });
35 if (it != msgInfos_.end()) {
36 *it = info;
37 return;
38 }
39 msgInfos_.emplace_back(info);
40 }
41
RemoveNotifyMsg(std::shared_ptr<MessageInfo> info)42 void StateChangeNotify::RemoveNotifyMsg(std::shared_ptr<MessageInfo> info)
43 {
44 CALL_DEBUG_ENTER;
45 if (msgInfos_.empty() || info == nullptr) {
46 FI_HILOGE("Remove listener failed");
47 return;
48 }
49 auto it = std::find_if(msgInfos_.begin(), msgInfos_.end(),
50 [info] (auto msgInfo) {
51 return *msgInfo == info;
52 });
53 if (it != msgInfos_.end()) {
54 msgInfos_.erase(it);
55 }
56 }
57
StateChangedNotify(DragState state)58 int32_t StateChangeNotify::StateChangedNotify(DragState state)
59 {
60 CALL_DEBUG_ENTER;
61 if (msgInfos_.empty()) {
62 FI_HILOGW("No listener, send message failed");
63 return RET_ERR;
64 }
65 for (auto it = msgInfos_.begin(); it != msgInfos_.end(); ++it) {
66 auto info = *it;
67 CHKPC(info);
68 OnStateChangedNotify(info->session, info->msgId, state);
69 }
70 return RET_OK;
71 }
72
OnStateChangedNotify(SessionPtr session,MessageId msgId,DragState state)73 void StateChangeNotify::OnStateChangedNotify(SessionPtr session, MessageId msgId, DragState state)
74 {
75 CALL_DEBUG_ENTER;
76 CHKPV(session);
77 NetPacket pkt(msgId);
78 pkt << static_cast<int32_t>(state);
79 if (pkt.ChkRWError()) {
80 FI_HILOGE("Packet write data failed");
81 return;
82 }
83 if (!session->SendMsg(pkt)) {
84 FI_HILOGE("Sending failed");
85 return;
86 }
87 }
88 } // namespace DeviceStatus
89 } // namespace Msdp
90 } // namespace OHOS
91