• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 /**
17  * @addtogroup Bluetooth
18  * @{
19  *
20  * @brief Defines map mce service object.
21  *
22  */
23 
24 /**
25  * @file map_mce_service.cpp
26  *
27  * @brief map mce source file .
28  *
29  */
30 
31 #include "map_mce_service.h"
32 #include "adapter_config.h"
33 #include "class_creator.h"
34 #include "log.h"
35 #include "log_util.h"
36 #include "map_mce_types.h"
37 #include "map_mce_instance_stm.h"
38 #include "map_mce_mns_server.h"
39 #include "profile_config.h"
40 #include "profile_service_manager.h"
41 #include "sdp.h"
42 
43 namespace OHOS {
44 namespace bluetooth {
45 // c language function declare
MceAnalyseSupportedFeatrueAttribute(int & supportedFeatrue,const SdpService & servicePointer)46 int MceAnalyseSupportedFeatrueAttribute(int &supportedFeatrue, const SdpService &servicePointer)
47 {
48     bool findInstanceFeature = false;
49     int ret = BT_SUCCESS;
50     SdpAttribute *tempAttribute = servicePointer.attribute;
51     for (int attSeqCount = 0; attSeqCount < servicePointer.attributeNumber; attSeqCount++, tempAttribute++) {
52         if (tempAttribute->attributeId == MAP_MCE_SUPPORTED_FEATURES_ATTRIBUTE_ID) {
53             supportedFeatrue = *(uint32_t *)tempAttribute->attributeValue;
54             findInstanceFeature = true;
55             break;
56         }
57     }
58     // check param value
59     if (!findInstanceFeature) {
60         // param error
61         ret = RET_BAD_PARAM;
62         LOG_ERROR("%{public}s param error:feature=%{public}d", __PRETTY_FUNCTION__, findInstanceFeature);
63     }
64     return ret;
65 }
66 
MapMceGetSupportFeatureSdpSearchCb(const BtAddr * addr,const SdpService * serviceAry,uint16_t serviceNum,void * context)67 void MapMceGetSupportFeatureSdpSearchCb(
68     const BtAddr *addr, const SdpService *serviceAry, uint16_t serviceNum, void *context)
69 {
70     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
71 
72     int supportedFeatrue = 0;
73     int supportedFeatrueAll = 0;
74     int finishId = MSG_MCESERVICE_GET_SURPORT_FEATURES_FINISH;
75     int failedId = MSG_MCESERVICE_GET_SURPORT_FEATURES_FAILED;
76     const SdpService *tempServicePointer = serviceAry;
77     IProfileManager *serviceMgr = IProfileManager::GetInstance();
78     if ((serviceMgr == nullptr) || (addr == nullptr) || (serviceNum == 0)) {
79         LOG_ERROR("%{public}s no service mgr, serviceNum= %{public}d", __PRETTY_FUNCTION__, int(serviceNum));
80         return;
81     }
82     auto mnsService = static_cast<MapMceService *>(serviceMgr->GetProfileService(PROFILE_NAME_MAP_MCE));
83     if (mnsService == nullptr) {
84         LOG_ERROR("%{public}s mnsService is nullptr", __PRETTY_FUNCTION__);
85         return;
86     }
87     BtAddr *argPrt = new (std::nothrow)BtAddr;
88     if (argPrt == nullptr) {
89         LOG_ERROR("%{public}s argPrt is nullptr", __PRETTY_FUNCTION__);
90         return;
91     }
92     utility::Message msg(failedId);
93     *argPrt = *addr;
94     msg.arg2_ = (void *)argPrt;
95     for (int serviceCount = 0; serviceCount < serviceNum; serviceCount++, tempServicePointer++) {
96         // check param array
97         if (tempServicePointer->attributeNumber == 0) {
98             mnsService->PostMessage(msg);
99             LOG_ERROR("%{public}s param error:attributeNumber is null", __PRETTY_FUNCTION__);
100             return;
101         }
102         int ret = MceAnalyseSupportedFeatrueAttribute(supportedFeatrue, *tempServicePointer);
103         // check sdp param value
104         if (ret != BT_SUCCESS) {
105             mnsService->PostMessage(msg);
106             LOG_ERROR("%{public}s mot found supportedFeatrue", __PRETTY_FUNCTION__);
107             return;
108         }
109         supportedFeatrueAll |= supportedFeatrue;  // make param
110     }
111     msg.what_ = finishId;
112     msg.arg1_ = supportedFeatrueAll;
113     mnsService->PostMessage(msg);
114     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
115 }
116 
MapMceService()117 MapMceService::MapMceService() : utility::Context(PROFILE_NAME_MAP_MCE, "1.4.2")
118 {
119     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
120     serviceState_ = MAP_MCE_STATE_SHUTDOWN;
121     serviceDispatcher_ = GetDispatcher();
122     if (serviceDispatcher_ == nullptr) {
123         LOG_INFO("%{public}s dispatch error", __PRETTY_FUNCTION__);
124     }
125     mnsServer_ = nullptr;
126     serviceBtDeviceInstMgrMap_.clear();
127     notificationRegistration_ = false;
128     insDefaultConfig_.l2capMtu = MCE_INSTANCE_CLIENT_OBEX_MTU;
129     insDefaultConfig_.rfcommMtu = MCE_INSTANCE_CLIENT_OBEX_MTU;
130     insDefaultConfig_.isSupportSrm = true;
131     insDefaultConfig_.deviceId = 0;
132     insDefaultConfig_.singleInstMode = false;
133     insDefaultConfig_.singleInstanceId = 0;
134     insDefaultConfig_.maxOfDevice = MCE_MAX_OF_CONNECTED_DEVICES;
135     insDefaultConfig_.maxOfGetUnread = MAP_MAX_LIST_COUNT_FOR_GET_UNREAD_MESSAGE;
136 
137     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
138 }
139 
~MapMceService()140 MapMceService::~MapMceService()
141 {
142     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
143     // release all client stm memory
144     RemoveAllDevice();
145     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
146 }
147 
GetContext()148 utility::Context *MapMceService::GetContext()
149 {
150     return this;
151 }
152 
RegisterObserver(IProfileMapMceObserver & observer)153 void MapMceService::RegisterObserver(IProfileMapMceObserver &observer)
154 {
155     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
156     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
157 
158     serviceRpcCallbackMgr_.RegisterObserver(observer);
159     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
160 }
161 
DeregisterObserver(IProfileMapMceObserver & observer)162 void MapMceService::DeregisterObserver(IProfileMapMceObserver &observer)
163 {
164     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
165     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
166 
167     serviceRpcCallbackMgr_.DeregisterObserver(observer);
168     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
169 }
170 
IsConnected(const RawAddress & device)171 bool MapMceService::IsConnected(const RawAddress &device)
172 {
173     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
174     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
175 
176     bool ret = false;
177     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
178     if (serviceState_ != MAP_MCE_STATE_STARTUP) {
179         LOG_ERROR("%{public}s error:RET_BAD_STATUS", __PRETTY_FUNCTION__);
180         return false;
181     }
182     // find the device
183     std::string tempDev = device.GetAddress();
184     auto it = serviceBtDeviceInstMgrMap_.find(tempDev);
185     if (it != serviceBtDeviceInstMgrMap_.end()) {
186         if (it->second->GetCurrentDeviceState() == MAP_MCE_DEV_STATE_CONNECTED) {
187             ret = true;
188         }
189     }
190     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
191     return ret;
192 }
193 
GetDevicesByStates(const std::vector<int> & statusList)194 std::vector<RawAddress> MapMceService::GetDevicesByStates(const std::vector<int> &statusList)
195 {
196     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
197     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
198 
199     std::vector<RawAddress> deviceList;
200     if (serviceState_ != MAP_MCE_STATE_STARTUP) {
201         LOG_ERROR("%{public}s error:RET_BAD_STATUS", __PRETTY_FUNCTION__);
202         return deviceList;
203     }
204     // find the device
205     std::unique_ptr<RawAddress> rawAddressPtr = nullptr;
206     for (auto it = serviceBtDeviceInstMgrMap_.begin(); it != serviceBtDeviceInstMgrMap_.end(); it++) {
207         for (auto itState = statusList.begin(); itState != statusList.end(); itState++) {
208             if (it->second->GetCurrentDeviceState() == *itState) {
209                 rawAddressPtr = std::make_unique<RawAddress>(it->second->GetBtDevice());
210                 deviceList.push_back(*rawAddressPtr);
211                 break;
212             }
213         }
214     }
215     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
216     return deviceList;
217 }
218 
SetConnectionStrategy(const RawAddress & device,int strategy)219 int MapMceService::SetConnectionStrategy(const RawAddress &device, int strategy)
220 {
221     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
222     IProfileConfig *config = ProfileConfig::GetInstance();
223     if ((serviceState_ != MAP_MCE_STATE_STARTUP) || (config == nullptr)) {
224         LOG_ERROR(
225             "%{public}s state error: service state=%{public}d or IProfileConfig is NULL",
226             __PRETTY_FUNCTION__, int(serviceState_));
227         return RET_BAD_STATUS;
228     }
229     // param error
230     if ((BTStrategyType(strategy) != BTStrategyType::CONNECTION_ALLOWED) &&
231         (BTStrategyType(strategy) != BTStrategyType::CONNECTION_FORBIDDEN)) {
232         LOG_ERROR("%{public}s strategy type unknown", __PRETTY_FUNCTION__);
233         return RET_BAD_PARAM;
234     }
235     // save the value
236     int value;
237     if (BTStrategyType(strategy) == BTStrategyType::CONNECTION_ALLOWED) {
238         value = 1;
239     } else {
240         value = 0;
241     }
242     bool ret = config->SetValue(
243         device.GetAddress(), SECTION_CONNECTION_POLICIES, PROPERTY_MAP_CLIENT_CONNECTION_POLICY, value);
244     // set success
245     if (ret) {
246         // check dispatcher
247         utility::Dispatcher *dispatcher = GetDispatcher();
248         if (dispatcher != nullptr) {
249             if (value == 1) {
250                 // service function execute
251                 dispatcher->PostTask(std::bind(&MapMceService::ConnectInternal, this, device, false, 0));
252             } else {
253                 // service function execute
254                 dispatcher->PostTask(std::bind(&MapMceService::DisconnectInternal, this, device));
255             }
256         } else {
257             LOG_ERROR("%{public}s dispatcher error", __PRETTY_FUNCTION__);
258         }
259         LOG_INFO("%{public}s success end", __PRETTY_FUNCTION__);
260         return BT_SUCCESS;
261     } else {
262         LOG_ERROR("%{public}s error end", __PRETTY_FUNCTION__);
263         return RET_BAD_STATUS;
264     }
265 }
266 
GetConnectionStrategy(const RawAddress & device) const267 int MapMceService::GetConnectionStrategy(const RawAddress &device) const
268 {
269     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
270     if (serviceState_ != MAP_MCE_STATE_STARTUP) {
271         LOG_ERROR("%{public}s error: startup error", __PRETTY_FUNCTION__);
272         return int(BTStrategyType::CONNECTION_FORBIDDEN);
273     }
274     IProfileConfig *config = ProfileConfig::GetInstance();
275     int value = 0;
276     const std::string dev = device.GetAddress();
277     if (!config->GetValue(dev, SECTION_CONNECTION_POLICIES, PROPERTY_MAP_CLIENT_CONNECTION_POLICY, value)) {
278         HILOGI("%{public}s %{public}s not found",
279             GetEncryptAddr(dev).c_str(), PROPERTY_MAP_CLIENT_CONNECTION_POLICY.c_str());
280         return int(BTStrategyType::CONNECTION_UNKNOWN);
281     }
282     if (value) {
283         return int(BTStrategyType::CONNECTION_ALLOWED);
284     } else {
285         return int(BTStrategyType::CONNECTION_FORBIDDEN);
286     }
287 }
288 
GetUnreadMessages(const RawAddress & device,MapMessageType type,uint8_t max)289 int MapMceService::GetUnreadMessages(const RawAddress &device, MapMessageType type, uint8_t max)
290 {
291     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
292     IProfileGetMessagesListingParameters para;
293     para.folder = u"inbox";
294     para.MaxListCount = max;  // max of items
295     para.ListStartOffset = 0;
296     para.SubjectLength = MCE_MAX_LENGTH_10;  // 1-255
297     para.ParameterMask = MAP_GETMESSAGELIST_PARAMETER_MASK_SUBJECT | MAP_GETMESSAGELIST_PARAMETER_MASK_TYPE |
298                          MAP_GETMESSAGELIST_PARAMETER_MASK_RECEPTION_STATUS | MAP_GETMESSAGELIST_PARAMETER_MASK_READ |
299                          MAP_GETMESSAGELIST_PARAMETER_MASK_SENT;
300     para.FilterMessageType = MAP_FILTER_MESSAGE_MASK_NO_FILTERING;  // get alltype
301     para.FilterPeriodBegin = "";
302     para.FilterPeriodEnd = "";
303     para.FilterReadStatus = MAP_FILTER_READ_STATUS_MASK_UNREAD;
304     para.FilterRecipient = "";
305     para.FilterOriginator = "";
306     para.FilterPriority = MAP_FILTER_PRIORITY_MASK_NO_FILTERING;
307     para.ConversationID = "";
308     para.FilterMessageHandle = "";
309 
310     MapMceRequestConfig cfg;
311     cfg.maxOfGetUnread = insDefaultConfig_.maxOfGetUnread;
312 
313     utility::Message outMsg(MSG_MCEDEVICE_REQ_SEND_REQUEST);
314     std::unique_ptr<MapMceInstanceRequest> reqPtr = std::make_unique<MapMceRequestGetUreadMessages>(type, para);
315     reqPtr->SetRequestConfig(cfg);
316     int ret = SendRequestToConnectedDevice(device, outMsg, reqPtr);
317     if (ret != BT_SUCCESS) {
318         reqPtr = nullptr;
319     }
320     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
321     return ret;
322 }
323 
GetSupportedFeatures(const RawAddress & device)324 int MapMceService::GetSupportedFeatures(const RawAddress &device)
325 {
326     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
327     int ret = BT_SUCCESS;
328     if (serviceState_ != MAP_MCE_STATE_STARTUP) {
329         LOG_ERROR("%{public}s error: startup error", __PRETTY_FUNCTION__);
330         return RET_BAD_STATUS;
331     }
332     // check dispatcher
333     utility::Dispatcher *dispatcher = GetDispatcher();
334     if (dispatcher == nullptr) {
335         LOG_INFO("%{public}s dispatcher error", __PRETTY_FUNCTION__);
336         return RET_NO_SUPPORT;
337     }
338     dispatcher->PostTask(std::bind(&MapMceService::CheckSdpForGetSupportedFeatures, this, device));
339     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
340     return ret;
341 }
342 
SendMessage(const RawAddress & device,const IProfileSendMessageParameters & msg)343 int MapMceService::SendMessage(const RawAddress &device, const IProfileSendMessageParameters &msg)
344 {
345     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
346     // if version_property is 1.1, need check the device's version
347     if ((msg.Charset == MapCharsetType::INVALID) || (msg.bmessage_.folder_property == u"")) {
348         LOG_ERROR("%{public}s Charset or Folder null", __PRETTY_FUNCTION__);
349         return RET_BAD_PARAM;
350     }
351     if (msg.MessageHandle != "") {
352         if ((msg.Attachment == MapAttachmentType::INVALID) || (msg.ModifyText == MapModifyTextType::INVALID)) {
353             LOG_ERROR("%{public}s have MessageHandle ,but no Attachment or ModifyText", __PRETTY_FUNCTION__);
354             return RET_BAD_PARAM;
355         }
356     }
357     if (msg.bmessage_.envelope_.maxLevelOfEnvelope_ == 0 ||
358         msg.bmessage_.envelope_.maxLevelOfEnvelope_ > MCE_RECIPIENT_LEVEL3) {
359         LOG_ERROR("%{public}s envelope_ level error = %{public}d",
360             __PRETTY_FUNCTION__, msg.bmessage_.envelope_.maxLevelOfEnvelope_);
361         return RET_BAD_PARAM;
362     }
363     utility::Message outMsg(MSG_MCEDEVICE_REQ_SEND_REQUEST);
364     std::unique_ptr<MapMceInstanceRequest> reqPtr = std::make_unique<MapMceRequestPushMessage>(msg);
365     int ret = SendRequestToConnectedDevice(device, outMsg, reqPtr);
366     if (ret != BT_SUCCESS) {
367         reqPtr = nullptr;
368     }
369     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
370     return ret;
371 }
372 
SetNotificationFilter(const RawAddress & device,const int mask)373 int MapMceService::SetNotificationFilter(const RawAddress &device, const int mask)
374 {
375     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
376     if (!notificationRegistration_) {
377         LOG_ERROR("%{public}s error: MNS server FALSE", __PRETTY_FUNCTION__);
378         return RET_BAD_STATUS;
379     }
380     utility::Message msg(MSG_MCEDEVICE_REQ_SEND_REQUEST);
381     std::unique_ptr<MapMceInstanceRequest> reqPtr = std::make_unique<MapMceRequestSetNotificationFilter>(mask);
382     int ret = SendRequestToConnectedDevice(device, msg, reqPtr);
383     if (ret != BT_SUCCESS) {
384         reqPtr = nullptr;
385     }
386     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
387     return ret;
388 }
389 
SetNotificationRegistration(const RawAddress & device,const bool on)390 int MapMceService::SetNotificationRegistration(const RawAddress &device, const bool on)
391 {
392     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
393     if (!notificationRegistration_) {
394         LOG_ERROR("%{public}s error: MNS server FALSE", __PRETTY_FUNCTION__);
395         return RET_BAD_STATUS;
396     }
397     utility::Message msg(MSG_MCEDEVICE_REQ_SEND_REQUEST);
398     std::unique_ptr<MapMceInstanceRequest> reqPtr = std::make_unique<MapMceRequestSetNotificationRegistration>(on);
399     int ret = SendRequestToConnectedDevice(device, msg, reqPtr);
400     if (ret != BT_SUCCESS) {
401         reqPtr = nullptr;
402     }
403     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
404     return ret;
405 }
406 
GetMessagesListing(const RawAddress & device,const IProfileGetMessagesListingParameters & para)407 int MapMceService::GetMessagesListing(const RawAddress &device, const IProfileGetMessagesListingParameters &para)
408 {
409     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
410     utility::Message msg(MSG_MCEDEVICE_REQ_SEND_REQUEST);
411     std::unique_ptr<MapMceInstanceRequest> reqPtr = std::make_unique<MapMceRequestGetMessagesListing>(para);
412     int ret = SendRequestToConnectedDevice(device, msg, reqPtr);
413     if (ret != BT_SUCCESS) {
414         reqPtr = nullptr;
415     }
416     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
417     return ret;
418 }
419 
GetMessage(const RawAddress & device,MapMessageType type,const std::u16string & msgHandle,const IProfileGetMessageParameters & para)420 int MapMceService::GetMessage(const RawAddress &device, MapMessageType type, const std::u16string &msgHandle,
421     const IProfileGetMessageParameters &para)
422 {
423     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
424     utility::Message msg(MSG_MCEDEVICE_REQ_SEND_REQUEST);
425     std::unique_ptr<MapMceInstanceRequest> reqPtr = std::make_unique<MapMceRequestGetMessage>(msgHandle, para);
426     reqPtr->SetSupportMessageType(MapMessageTypeToIprofileMask(type));
427     int ret = SendRequestToConnectedDevice(device, msg, reqPtr);
428     if (ret != BT_SUCCESS) {
429         reqPtr = nullptr;
430     }
431     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
432     return ret;
433 }
434 
GetMessageWithReqCfg(const RawAddress & device,MapMessageType type,const std::u16string & msgHandle,const IProfileGetMessageParameters & para,const MapMceRequestConfig & cfg)435 int MapMceService::GetMessageWithReqCfg(const RawAddress &device, MapMessageType type, const std::u16string &msgHandle,
436     const IProfileGetMessageParameters &para, const MapMceRequestConfig &cfg)
437 {
438     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
439     utility::Message msg(MSG_MCEDEVICE_REQ_SEND_REQUEST);
440     std::unique_ptr<MapMceInstanceRequest> reqPtr = std::make_unique<MapMceRequestGetMessage>(msgHandle, para);
441     reqPtr->SetSupportMessageType(MapMessageTypeToIprofileMask(type));
442     reqPtr->SetRequestConfig(cfg);
443     int ret = SendRequestToConnectedDevice(device, msg, reqPtr);
444     if (ret != BT_SUCCESS) {
445         reqPtr = nullptr;
446     }
447     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
448     return ret;
449 }
450 
UpdateInbox(const RawAddress & device,MapMessageType type)451 int MapMceService::UpdateInbox(const RawAddress &device, MapMessageType type)
452 {
453     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
454     utility::Message msg(MSG_MCEDEVICE_REQ_SEND_REQUEST);
455     std::unique_ptr<MapMceInstanceRequest> reqPtr = std::make_unique<MapMceRequestUpdateInbox>();
456     reqPtr->SetSupportMessageType(MapMessageTypeToIprofileMask(type));
457     int ret = SendRequestToConnectedDevice(device, msg, reqPtr);
458     if (ret != BT_SUCCESS) {
459         reqPtr = nullptr;
460     }
461     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
462     return ret;
463 }
464 
GetConversationListing(const RawAddress & device,const IProfileGetConversationListingParameters & para)465 int MapMceService::GetConversationListing(
466     const RawAddress &device, const IProfileGetConversationListingParameters &para)
467 {
468     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
469     utility::Message msg(MSG_MCEDEVICE_REQ_SEND_REQUEST);
470     std::unique_ptr<MapMceInstanceRequest> reqPtr = std::make_unique<MapMceRequestGetConversationListing>(para);
471     reqPtr->SetSupportMessageType(MAP_MCE_SUPPORTED_MESSAGE_TYPE_IM);
472     int ret = SendRequestToConnectedDevice(device, msg, reqPtr);
473     if (ret != BT_SUCCESS) {
474         reqPtr = nullptr;
475     }
476     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
477     return ret;
478 }
479 
SetMessageStatus(const RawAddress & device,MapMessageType type,const IProfileSetMessageStatus & msgStatus)480 int MapMceService::SetMessageStatus(
481     const RawAddress &device, MapMessageType type, const IProfileSetMessageStatus &msgStatus)
482 {
483     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
484     utility::Message msg(MSG_MCEDEVICE_REQ_SEND_REQUEST);
485     std::unique_ptr<MapMceInstanceRequest> reqPtr = std::make_unique<MapMceRequestSetMessageStatus>(
486         msgStatus.msgHandle, msgStatus.statusIndicator, msgStatus.statusValue, msgStatus.extendedData);
487     reqPtr->SetSupportMessageType(MapMessageTypeToIprofileMask(type));
488     int ret = SendRequestToConnectedDevice(device, msg, reqPtr);
489     if (ret != BT_SUCCESS) {
490         reqPtr = nullptr;
491     }
492     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
493     return ret;
494 }
495 
SetOwnerStatus(const RawAddress & device,const IProfileSetOwnerStatusParameters & para)496 int MapMceService::SetOwnerStatus(const RawAddress &device, const IProfileSetOwnerStatusParameters &para)
497 {
498     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
499     utility::Message msg(MSG_MCEDEVICE_REQ_SEND_REQUEST);
500     std::unique_ptr<MapMceInstanceRequest> reqPtr = std::make_unique<MapMceRequestSetOwnerStatus>(para);
501     reqPtr->SetSupportMessageType(MAP_MCE_SUPPORTED_MESSAGE_TYPE_IM);
502     int ret = SendRequestToConnectedDevice(device, msg, reqPtr);
503     if (ret != BT_SUCCESS) {
504         reqPtr = nullptr;
505     }
506     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
507     return ret;
508 }
509 
GetOwnerStatus(const RawAddress & device,const std::string & conversationId)510 int MapMceService::GetOwnerStatus(const RawAddress &device, const std::string &conversationId)
511 {
512     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
513     utility::Message msg(MSG_MCEDEVICE_REQ_SEND_REQUEST);
514     std::unique_ptr<MapMceInstanceRequest> reqPtr = std::make_unique<MapMceRequestGetOwnerStatus>(conversationId);
515     reqPtr->SetSupportMessageType(MAP_MCE_SUPPORTED_MESSAGE_TYPE_IM);
516     int ret = SendRequestToConnectedDevice(device, msg, reqPtr);
517     if (ret != BT_SUCCESS) {
518         reqPtr = nullptr;
519     }
520     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
521     return ret;
522 }
523 
Connect(const RawAddress & device)524 int MapMceService::Connect(const RawAddress &device)  // override
525 {
526     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
527     // check service status
528     if (serviceState_ != MAP_MCE_STATE_STARTUP) {
529         LOG_ERROR("%{public}s connect startup error", __PRETTY_FUNCTION__);
530         return RET_BAD_STATUS;
531     }
532     // check dispatcher
533     utility::Dispatcher *dispatcher = GetDispatcher();
534     if (dispatcher == nullptr) {
535         LOG_ERROR("%{public}s Connect dispatcher error", __PRETTY_FUNCTION__);
536         return RET_BAD_STATUS;
537     }
538 
539     RawAddress rawDevice(device.GetAddress());
540     BTStrategyType strate = BTStrategyType(GetConnectionStrategy(rawDevice));
541     if (strate == BTStrategyType::CONNECTION_FORBIDDEN) {
542         return RET_BAD_STATUS;
543     }
544 
545     // check device connected status
546     int checkResult = CheckDeviceConnectStatus(rawDevice);
547     if (checkResult != BT_SUCCESS) {
548         LOG_INFO("%{public}s device status error", __PRETTY_FUNCTION__);
549         return RET_BAD_STATUS;
550     }
551     // service function execute
552     dispatcher->PostTask(std::bind(&MapMceService::ConnectInternal, this, rawDevice, false, 0));
553     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
554     return BT_SUCCESS;
555 }
556 
ConnectInstance(const RawAddress & device,int instanceId)557 int MapMceService::ConnectInstance(const RawAddress &device, int instanceId)
558 {
559     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
560     // check service status
561     if (serviceState_ != MAP_MCE_STATE_STARTUP) {
562         LOG_ERROR("%{public}s ConnectInstance startup error", __PRETTY_FUNCTION__);
563         return RET_BAD_STATUS;
564     }
565     // check dispatcher
566     utility::Dispatcher *dispatcher = GetDispatcher();
567     if (dispatcher == nullptr) {
568         LOG_INFO("%{public}s ConnectInstance dispatcher error", __PRETTY_FUNCTION__);
569         return RET_BAD_STATUS;
570     }
571     RawAddress rawDevice(device.GetAddress());
572     BTStrategyType strate = BTStrategyType(GetConnectionStrategy(rawDevice));
573     if (strate == BTStrategyType::CONNECTION_FORBIDDEN) {
574         return RET_BAD_STATUS;
575     }
576     // check device connected status
577     int checkResult = CheckDeviceConnectStatus(rawDevice);
578     if (checkResult != BT_SUCCESS) {
579         LOG_INFO("%{public}s device status error", __PRETTY_FUNCTION__);
580         return RET_BAD_STATUS;
581     }
582     // service function execute
583     dispatcher->PostTask(std::bind(&MapMceService::ConnectInternal, this, rawDevice, true, instanceId));
584     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
585     return BT_SUCCESS;
586 }
587 
Disconnect(const RawAddress & device)588 int MapMceService::Disconnect(const RawAddress &device)  // override
589 {
590     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
591     // check service status
592     if (serviceState_ != MAP_MCE_STATE_STARTUP) {
593         LOG_ERROR("%{public}s Disconnect error", __PRETTY_FUNCTION__);
594         return RET_BAD_STATUS;
595     }
596     // check dispatcher
597     utility::Dispatcher *dispatcher = GetDispatcher();
598     if (dispatcher == nullptr) {
599         LOG_INFO("%{public}s Disconnect dispatcher error", __PRETTY_FUNCTION__);
600         return RET_BAD_STATUS;
601     }
602     // check device connected status
603     RawAddress rawDevice(device.GetAddress());
604     int checkResult = CheckDeviceDisconnectStatus(rawDevice);
605     if (checkResult != BT_SUCCESS) {
606         LOG_INFO("%{public}s device status error", __PRETTY_FUNCTION__);
607         return RET_BAD_STATUS;
608     }
609     // service function execute
610     dispatcher->PostTask(std::bind(&MapMceService::DisconnectInternal, this, rawDevice));
611     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
612     return BT_SUCCESS;
613 }
614 
CountSendingRequest(const RawAddress & device,MceRequestType requestType)615 int MapMceService::CountSendingRequest(const RawAddress &device, MceRequestType requestType)
616 {
617     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
618     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
619 
620     int retSum = 0;
621     // find the device
622     std::string tempDev = device.GetAddress();
623     auto it = serviceBtDeviceInstMgrMap_.find(tempDev);
624     // if device in the map
625     if (it != serviceBtDeviceInstMgrMap_.end()) {
626         retSum = it->second->CountSendingRequest(requestType);
627     }
628     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
629     return retSum;
630 }
631 
CheckDeviceConnectStatus(const RawAddress & device)632 int MapMceService::CheckDeviceConnectStatus(const RawAddress &device)
633 {
634     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
635     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
636 
637     int ret = BT_SUCCESS;
638     // find the device
639     std::string tempDev = device.GetAddress();
640     auto it = serviceBtDeviceInstMgrMap_.find(tempDev);
641     // if device in the map
642     if (it != serviceBtDeviceInstMgrMap_.end()) {
643         if (it->second->GetCurrentDeviceState() != MAP_MCE_DEV_STATE_DISCONNECTED) {
644             ret = RET_BAD_STATUS;
645         }
646         LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
647         return ret;
648     }
649     if (serviceBtDeviceInstMgrMap_.size() >= insDefaultConfig_.maxOfDevice) {
650         ret = RET_NO_SUPPORT;
651         for (auto it2 = serviceBtDeviceInstMgrMap_.begin(); it2 != serviceBtDeviceInstMgrMap_.end(); ++it2) {
652             // if it have disconnect devcie in the list
653             if (it2->second->GetCurrentDeviceState() == MAP_MCE_DEV_STATE_DISCONNECTED) {
654                 ret = BT_SUCCESS;
655             }
656         }
657     }
658     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
659     return ret;
660 }
661 
CheckDeviceDisconnectStatus(const RawAddress & device)662 int MapMceService::CheckDeviceDisconnectStatus(const RawAddress &device)
663 {
664     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
665     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
666 
667     int ret = BT_SUCCESS;
668     // find the device
669     std::string tempDev = device.GetAddress();
670     auto it = serviceBtDeviceInstMgrMap_.find(tempDev);
671     // if device in the map
672     if (it != serviceBtDeviceInstMgrMap_.end()) {
673         if (it->second->GetCurrentDeviceState() != MAP_MCE_DEV_STATE_CONNECTED) {
674             ret = RET_BAD_STATUS;
675         }
676     } else {
677         // device is not in the list
678         ret = RET_NO_SUPPORT;
679     }
680 
681     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
682     return ret;
683 }
684 
SendRequestToConnectedDevice(const RawAddress & device,utility::Message msg,std::unique_ptr<MapMceInstanceRequest> & req)685 int MapMceService::SendRequestToConnectedDevice(
686     const RawAddress &device, utility::Message msg, std::unique_ptr<MapMceInstanceRequest> &req)
687 {
688     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
689     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
690 
691     int ret = RET_BAD_STATUS;
692     if (serviceState_ != MAP_MCE_STATE_STARTUP) {
693         LOG_ERROR("%{public}s error:RET_BAD_STATUS", __PRETTY_FUNCTION__);
694         return ret;
695     }
696     // ready
697     std::string tempDev = device.GetAddress();
698     // find bt device
699     auto it = serviceBtDeviceInstMgrMap_.find(tempDev);
700     // find ok
701     if (it != serviceBtDeviceInstMgrMap_.end()) {
702         // check max send request
703         int retSum = it->second->CountSendingRequest(MCE_REQUEST_TYPE_ALL);
704         if (retSum < MCE_MAX_OF_SENDING_REQUEST) {
705             // api only valid in connected state, if not valid return error at now
706             if (it->second->GetCurrentDeviceState() == MAP_MCE_DEV_STATE_CONNECTED) {
707                 // send command to the state machine
708                 ret = it->second->PostMessageWithRequest(msg, req);
709             } else {
710                 LOG_ERROR("%{public}s device not connected", __PRETTY_FUNCTION__);
711             }
712         } else {
713             LOG_ERROR("%{public}s error, MCE_MAX_OF_SENDING_REQUEST", __PRETTY_FUNCTION__);
714         }
715     } else {
716         LOG_ERROR("%{public}s not fount the device", __PRETTY_FUNCTION__);
717     }
718     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
719     return ret;
720 }
721 
ConnectInternal(const RawAddress & device,bool sInsMode,int sInsId)722 int MapMceService::ConnectInternal(const RawAddress &device, bool sInsMode, int sInsId)
723 {
724     HILOGI("address=%{public}s", GET_ENCRYPT_ADDR(device));
725     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
726 
727     insDefaultConfig_.singleInstMode = sInsMode;
728     insDefaultConfig_.singleInstanceId = sInsId;
729     LOG_INFO("%{public}s singleInstMode=%{public}d,singleInstanceId=%{public}d ",
730         __PRETTY_FUNCTION__, sInsMode, sInsId);
731 
732     int ret = BT_SUCCESS;
733     if (serviceState_ != MAP_MCE_STATE_STARTUP) {
734         LOG_ERROR("%{public}s error return", __PRETTY_FUNCTION__);
735         return RET_BAD_STATUS;
736     }
737     // find the device
738     std::string tempDev = device.GetAddress();
739     auto it = serviceBtDeviceInstMgrMap_.find(tempDev);
740     if (it == serviceBtDeviceInstMgrMap_.end()) {
741         // device did not in the map
742         // remove the no useful device and instance if the map is max
743         RemoveNoUseDeviceAndInstance();
744         // insert the instance and create the client stm
745         if (serviceBtDeviceInstMgrMap_.size() < insDefaultConfig_.maxOfDevice) {
746             insDefaultConfig_.deviceId++;
747             auto deviceCtl1 = std::make_unique<MapMceDeviceCtrl>(
748                 tempDev, *this, notificationRegistration_, insDefaultConfig_, serviceRpcCallbackMgr_);
749             utility::Message outMsg1(MSG_MCEDEVICE_REQ_DEVICE_CONNECT);
750             deviceCtl1->ProcessMessage(outMsg1);
751             serviceBtDeviceInstMgrMap_.insert(
752                 std::pair<const std::string, std::unique_ptr<MapMceDeviceCtrl>>(tempDev, std::move(deviceCtl1)));
753             // start device connect
754         } else {
755             // error , device max
756             ret = RET_NO_SUPPORT;
757             LOG_ERROR("%{public}s error:connect max", __PRETTY_FUNCTION__);
758         }
759     } else {
760         // device is in the map , refresh config and connect again
761         it->second->SetDeviceCtlConfig(insDefaultConfig_);
762         utility::Message outMsg2(MSG_MCEDEVICE_REQ_DEVICE_CONNECT);
763         it->second->ProcessMessage(outMsg2);
764     }
765     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
766     return ret;
767 }
768 
DisconnectInternal(const RawAddress & device)769 int MapMceService::DisconnectInternal(const RawAddress &device)
770 {
771     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
772     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
773 
774     int ret = BT_SUCCESS;
775     if (serviceState_ != MAP_MCE_STATE_STARTUP) {
776         LOG_ERROR("%{public}s DisconnectInternal startup error", __PRETTY_FUNCTION__);
777         return RET_BAD_STATUS;
778     }
779     // find the device
780     std::string tempDev = device.GetAddress();
781     auto it = serviceBtDeviceInstMgrMap_.find(tempDev);
782     // device is in the map
783     if (it != serviceBtDeviceInstMgrMap_.end()) {
784         // request disconnect
785         utility::Message outMsg(MSG_MCEDEVICE_REQ_DEVICE_DISCONNECT);
786         it->second->PostMessage(outMsg);
787     }
788     // find device in the device map
789     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
790     return ret;
791 }
792 
793 // find and remove the disconnect bluetooth device
RemoveNoUseDeviceAndInstance()794 void MapMceService::RemoveNoUseDeviceAndInstance()
795 {
796     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
797     // check map length
798     if (serviceBtDeviceInstMgrMap_.size() < insDefaultConfig_.maxOfDevice) {
799         return;
800     }
801     // check iterator in map
802     for (auto it = serviceBtDeviceInstMgrMap_.begin(); it != serviceBtDeviceInstMgrMap_.end(); ++it) {
803         if (it->second->GetCurrentDeviceState() == MAP_MCE_DEV_STATE_DISCONNECTED) {
804             serviceBtDeviceInstMgrMap_.erase(it);
805             break;
806         }
807     }
808     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
809 }
810 
RemoveAllDevice()811 void MapMceService::RemoveAllDevice()
812 {
813     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
814     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
815 
816     serviceBtDeviceInstMgrMap_.clear();
817     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
818     return;
819 }
820 
MapMessageTypeToIprofileMask(MapMessageType type)821 int MapMceService::MapMessageTypeToIprofileMask(MapMessageType type)
822 {
823     uint8_t serviceMask;
824     switch (type) {
825         case MapMessageType::SMS_GSM:
826             serviceMask = MAP_MCE_SUPPORTED_MESSAGE_TYPE_SMS_GSM;
827             break;
828         case MapMessageType::SMS_CDMA:
829             serviceMask = MAP_MCE_SUPPORTED_MESSAGE_TYPE_SMS_CDMA;
830             break;
831         case MapMessageType::MMS:
832             serviceMask = MAP_MCE_SUPPORTED_MESSAGE_TYPE_MMS;
833             break;
834         case MapMessageType::EMAIL:
835             serviceMask = MAP_MCE_SUPPORTED_MESSAGE_TYPE_EMAIL;
836             break;
837         case MapMessageType::IM:
838             serviceMask = MAP_MCE_SUPPORTED_MESSAGE_TYPE_IM;
839             break;
840         default:
841             serviceMask = MAP_MCE_SUPPORTED_MESSAGE_TYPE_ALL;
842             break;
843     }
844     return int(serviceMask);
845 }
846 
GetConnectDevices()847 std::list<RawAddress> MapMceService::GetConnectDevices()
848 {
849     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
850     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
851 
852     std::list<RawAddress> devList;
853     // check iterator in client device map
854     for (auto it = serviceBtDeviceInstMgrMap_.begin(); it != serviceBtDeviceInstMgrMap_.end(); ++it) {
855         if (it->second != nullptr) {
856             if (it->second->GetCurrentDeviceState() == MAP_MCE_DEV_STATE_CONNECTED) {
857                 RawAddress rawAddress(it->second->GetBtDevice());
858                 devList.push_back(rawAddress);
859             }
860         }
861     }
862     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
863     return devList;
864 }
865 
GetConnectState()866 int MapMceService::GetConnectState()
867 {
868     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
869     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
870 
871     MapMceDeviceStateType state;
872     int profileState = 0;
873     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
874     for (auto it = serviceBtDeviceInstMgrMap_.begin(); it != serviceBtDeviceInstMgrMap_.end(); it++) {
875         if (it->second != nullptr) {
876             state = it->second->GetCurrentDeviceState();
877             profileState |= it->second->DeviceStateConvertToProfileState(state);
878         }
879     }
880     // not device connect
881     if (profileState == 0) {
882         profileState = PROFILE_STATE_DISCONNECTED;
883     }
884     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
885     return profileState;
886 }
887 
GetDeviceConnectState(const RawAddress & device)888 int MapMceService::GetDeviceConnectState(const RawAddress &device)
889 {
890     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
891     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
892 
893     MapMceDeviceStateType ret = MAP_MCE_DEV_STATE_DISCONNECTED;
894     auto it = serviceBtDeviceInstMgrMap_.find(device.GetAddress());
895     if (it != serviceBtDeviceInstMgrMap_.end()) {
896         if (it->second != nullptr) {
897             ret = it->second->GetCurrentDeviceState();
898         }
899     }
900     LOG_INFO("%{public}s end,status=%{public}d", __PRETTY_FUNCTION__, ret);
901     return ret;  // return state
902 }
903 
GetFolderListing(const RawAddress & device,uint16_t maxOfListCount,uint16_t startOffset)904 int MapMceService::GetFolderListing(const RawAddress &device, uint16_t maxOfListCount, uint16_t startOffset)
905 {
906     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
907     int ret;
908     utility::Message outMsg(MSG_MCEDEVICE_REQ_SEND_REQUEST);
909     std::unique_ptr<MapMceInstanceRequest> reqPtr =
910         std::make_unique<MapMceRequestGetFolderListing>(maxOfListCount, startOffset);
911     ret = SendRequestToConnectedDevice(device, outMsg, reqPtr);
912     if (ret != BT_SUCCESS) {
913         reqPtr = nullptr;
914     }
915     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
916     return ret;
917 }
918 
SetPath(const RawAddress & device,const uint8_t flags,const std::u16string & folder,std::vector<std::u16string> & folderList)919 int MapMceService::SetPath(const RawAddress &device, const uint8_t flags,
920     const std::u16string &folder, std::vector<std::u16string> &folderList)
921 {
922     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
923     int ret;
924     utility::Message outMsg(MSG_MCEDEVICE_REQ_SEND_REQUEST);
925     std::unique_ptr<MapMceInstanceRequest> reqPtr =
926         std::make_unique<MapMceRequestSetPath>(flags, folder, folderList);
927     ret = SendRequestToConnectedDevice(device, outMsg, reqPtr);
928     if (ret != BT_SUCCESS) {
929         reqPtr = nullptr;
930     }
931     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
932     return ret;
933 }
934 
GetMasInstanceInfo(const RawAddress & device)935 IProfileMasInstanceInfoList MapMceService::GetMasInstanceInfo(const RawAddress &device)
936 {
937     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
938     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
939 
940     IProfileMasInstanceInfoList masInfoList;
941     masInfoList.isValid = false;
942     std::vector<IProfileMasInstanceInfo> instanceinfoList;
943     auto it = serviceBtDeviceInstMgrMap_.find(device.GetAddress());
944     if (it != serviceBtDeviceInstMgrMap_.end()) {
945         if (it->second != nullptr) {
946             instanceinfoList = it->second->GetMasInstanceInfo(device);
947             if (int(instanceinfoList.size()) == it->second->GetDeviceInstanseStmMapSize()) {
948                 masInfoList.isValid = true;
949                 masInfoList.masInfoList = instanceinfoList;
950             }
951         }
952     }
953     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
954     return masInfoList;
955 }
956 
Enable()957 void MapMceService::Enable()
958 {
959     LOG_INFO("%{public}s execute", __PRETTY_FUNCTION__);
960     utility::Dispatcher *dispatcher = GetDispatcher();
961     if (dispatcher != nullptr) {
962         dispatcher->PostTask(std::bind(&MapMceService::StartUpInternal, this));
963     } else {
964         LOG_ERROR("%{public}s dispatcher error", __PRETTY_FUNCTION__);
965     }
966 }
967 
StartUpInternal()968 int MapMceService::StartUpInternal()
969 {
970     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
971     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
972 
973     serviceState_ = MAP_MCE_STATE_STARTUP;
974     // send response to adapt manager
975     utility::Context *context = GetContext();
976     if (context != nullptr) {
977         context->OnEnable(PROFILE_NAME_MAP_MCE, true);
978     }
979     // get config parameter
980     GetConfigFromXml();
981     // mns startup
982     mnsServer_ = std::make_unique<MapMceMnsServer>(*this, insDefaultConfig_);
983     // start up mns server
984     int ret = mnsServer_->StartUp();
985     if (ret == BT_SUCCESS) {
986         notificationRegistration_ = true;
987     } else {
988         notificationRegistration_ = false;
989         LOG_ERROR("%{public}s mns start error", __PRETTY_FUNCTION__);
990     }
991 #ifndef MCE_DISABLE_L2CAP
992     ObexMpClient::RegisterL2capLPsm(MAP_MCE_GOEP_L2CAP_PSM_VALUE);
993 #endif
994     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
995     return BT_SUCCESS;
996 }
997 
GetMaxConnectNum()998 int MapMceService::GetMaxConnectNum()
999 {
1000     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
1001     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
1002 
1003     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
1004     return serviceBtDeviceInstMgrMap_.size();
1005 }
1006 
Disable()1007 void MapMceService::Disable()
1008 {
1009     LOG_INFO("%{public}s execute", __PRETTY_FUNCTION__);
1010     utility::Dispatcher *dispatcher = GetDispatcher();
1011     if (dispatcher != nullptr) {
1012         dispatcher->PostTask(std::bind(&MapMceService::ShutDownInternal, this));
1013     } else {
1014         LOG_ERROR("%{public}s dispatcher error", __PRETTY_FUNCTION__);
1015     }
1016 }
1017 
ShutDownInternal()1018 int MapMceService::ShutDownInternal()
1019 {
1020     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
1021     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
1022 
1023     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
1024     return ShutDownInternalCommon();
1025 }
1026 
ShutDownInternalCommon()1027 int MapMceService::ShutDownInternalCommon()
1028 {
1029     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
1030     MapMceServiceStateType targetState = MAP_MCE_STATE_SHUTDOWN;
1031     serviceState_ = MAP_MCE_STATE_SHUTDOWNING;
1032     // check iterator in client device map
1033     for (auto it = serviceBtDeviceInstMgrMap_.begin(); it != serviceBtDeviceInstMgrMap_.end(); ++it) {
1034         if (it->second->GetCurrentDeviceState() != MAP_MCE_DEV_STATE_DISCONNECTED) {
1035             // request disconnect
1036             utility::Message outMsg(MSG_MCEDEVICE_REQ_DEVICE_DISCONNECT);
1037             it->second->PostMessage(outMsg);
1038             targetState = MAP_MCE_STATE_SHUTDOWNING;
1039         }
1040     }
1041     // all client have shutdown
1042     if (targetState == MAP_MCE_STATE_SHUTDOWN) {
1043         serviceState_ = MAP_MCE_STATE_SHUTDOWN;
1044 #ifndef MCE_DISABLE_L2CAP
1045         ObexMpClient::DeregisterL2capLPsm(MAP_MCE_GOEP_L2CAP_PSM_VALUE);
1046 #endif
1047         // release mns server
1048         if (mnsServer_ != nullptr) {
1049             mnsServer_->ShutDown();
1050         }
1051         // send response to adapt manager right now
1052         utility::Context *context = GetContext();
1053         if (context != nullptr) {
1054             LOG_INFO("%{public}s context->OnDisable execute", __PRETTY_FUNCTION__);
1055             context->OnDisable(PROFILE_NAME_MAP_MCE, true);
1056         }
1057     } else {  // if some client is working
1058         // need wait all client shutdown response callback
1059         serviceState_ = MAP_MCE_STATE_SHUTDOWNING;
1060         // send response to adapt manager when callback all come
1061     }
1062     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
1063     return BT_SUCCESS;
1064 }
1065 
PostMessage(utility::Message msg)1066 void MapMceService::PostMessage(utility::Message msg)
1067 {
1068     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
1069     utility::Dispatcher *dispatcher = GetDispatcher();
1070     if (dispatcher == nullptr) {
1071         LOG_INFO("%{public}s dispatcher error", __PRETTY_FUNCTION__);
1072         return;
1073     }
1074     dispatcher->PostTask(std::bind(&MapMceService::ProcessMessage, this, msg));
1075     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
1076 }
1077 
GetServiceStates()1078 MapMceServiceStateType MapMceService::GetServiceStates()
1079 {
1080     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
1081     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
1082 
1083     LOG_INFO("%{public}s end,state=%{public}d", __PRETTY_FUNCTION__, int(serviceState_));
1084     return MapMceServiceStateType(int(serviceState_));
1085 }
1086 
MnsPostMessage(const utility::Message & msg,std::string btAddr)1087 void MapMceService::MnsPostMessage(const utility::Message &msg, std::string btAddr)
1088 {
1089     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
1090     utility::Dispatcher *dispatcher = GetDispatcher();
1091     if (dispatcher == nullptr) {
1092         LOG_INFO("%{public}s dispatcher error", __PRETTY_FUNCTION__);
1093         return;
1094     }
1095     dispatcher->PostTask(std::bind(&MapMceService::MnsProcessMessage, this, msg, btAddr));
1096     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
1097 }
1098 
MnsPostMessageWithHeader(const utility::Message & msg,std::string btAddr,const ObexHeader & req)1099 void MapMceService::MnsPostMessageWithHeader(const utility::Message &msg, std::string btAddr, const ObexHeader &req)
1100 {
1101     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
1102     utility::Dispatcher *dispatcher = GetDispatcher();
1103     if (dispatcher == nullptr) {
1104         LOG_INFO("%{public}s dispatcher error", __PRETTY_FUNCTION__);
1105         return;
1106     }
1107     dispatcher->PostTask(std::bind(&MapMceService::MnsProcessMessageWithHeader, this, msg, btAddr, req));
1108     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
1109 }
1110 
MnsProcessMessage(utility::Message msg,std::string btAddr)1111 void MapMceService::MnsProcessMessage(utility::Message msg, std::string btAddr)
1112 {
1113     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
1114     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
1115 
1116     auto it = serviceBtDeviceInstMgrMap_.find(btAddr);
1117     if (it != serviceBtDeviceInstMgrMap_.end()) {
1118         it->second->ProcessMessage(msg);
1119     } else {
1120         HILOGE("address error = %{public}s", GetEncryptAddr(btAddr).c_str());
1121     }
1122     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
1123 }
1124 
MnsProcessMessageWithHeader(utility::Message msg,std::string btAddr,ObexHeader req)1125 void MapMceService::MnsProcessMessageWithHeader(utility::Message msg, std::string btAddr, ObexHeader req)
1126 {
1127     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
1128     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
1129 
1130     auto it = serviceBtDeviceInstMgrMap_.find(btAddr);
1131     if (it != serviceBtDeviceInstMgrMap_.end()) {
1132         it->second->ProcessMnsObexObserverMessage(req, msg);
1133     } else {
1134         HILOGE("address error = %{public}s", GetEncryptAddr(btAddr).c_str());
1135     }
1136     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
1137 }
1138 
ProcessMessage(const utility::Message & msg)1139 void MapMceService::ProcessMessage(const utility::Message &msg)
1140 {
1141     LOG_INFO("%{public}s enter,input msg=0x%x", __PRETTY_FUNCTION__, msg.what_);
1142     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
1143 
1144     switch (msg.what_) {
1145         case MSG_MCEDEVICE_SDP_GET_INSTANCE_FINISH:
1146         case MSG_MCEDEVICE_SDP_GET_INSTANCE_FAILED:
1147             SdpDispatchToDeviceInstMgr(msg);
1148             break;
1149         case MSG_MCESERVICE_GET_SURPORT_FEATURES_FINISH:
1150         case MSG_MCESERVICE_GET_SURPORT_FEATURES_FAILED:
1151             ProcessGetSupportedFeaturesRespones(msg);
1152             break;
1153         case MSG_MCESERVICE_DEVICE_CONNECTED:
1154             break;
1155         case MSG_MCESERVICE_DEVICE_DISCONNECTED:
1156             break;
1157         default:
1158             break;
1159     }
1160     if (serviceState_ == MAP_MCE_STATE_STARTUP) {
1161         // empty
1162     } else if (serviceState_ == MAP_MCE_STATE_SHUTDOWNING) {
1163         switch (msg.what_) {
1164             case MSG_MCESERVICE_DEVICE_DISCONNECTED:
1165                 // shutdown again;
1166                 ShutDownInternalCommon();
1167                 break;
1168             default:
1169                 break;
1170         }
1171     } else {
1172     }
1173     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
1174 }
1175 
SdpDispatchToDeviceInstMgr(const utility::Message & msg)1176 void MapMceService::SdpDispatchToDeviceInstMgr(const utility::Message &msg)
1177 {
1178     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
1179     auto argPrt = static_cast<MapSdpMsgArgPrt *>(msg.arg2_);
1180     if (argPrt == nullptr) {
1181         LOG_INFO("%{public}s error return", __PRETTY_FUNCTION__);
1182         return;
1183     }
1184     // check iterator in map
1185     for (auto it = serviceBtDeviceInstMgrMap_.begin(); it != serviceBtDeviceInstMgrMap_.end(); ++it) {
1186         BtAddr btAddress = it->second->GetBtAddress();
1187         if (memcmp(&(argPrt->address), &btAddress, sizeof(BtAddr)) == 0) {  // same bt address
1188             // send to the bt device
1189             it->second->ProcessMessage(msg);
1190             break;
1191         }
1192     }
1193     delete argPrt;
1194     argPrt = nullptr;
1195     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
1196 }
1197 
1198 // call by post task
CheckSdpForGetSupportedFeatures(const RawAddress & device)1199 int MapMceService::CheckSdpForGetSupportedFeatures(const RawAddress &device)
1200 {
1201     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
1202     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
1203     int index = 0;
1204     int retServiceVal;
1205     int retStackVal;
1206     IProfileMapAction retAction;
1207     MapExecuteStatus resCode;
1208     SdpAttributeIdList attributeIdList = {SDP_TYPE_LIST, .attributeIdList = {0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}};
1209     BtUuid btUuid = {0, {.uuid128 = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}};
1210     SdpUuid sdpUuid = {0, nullptr};
1211 
1212     // get the bluetooth address
1213     BtAddr btAddr = {{0, 0, 0, 0, 0, 0}, 0};
1214     btAddr.type = BT_PUBLIC_DEVICE_ADDRESS;
1215     RawAddress rawAddr(device.GetAddress());
1216     rawAddr.ConvertToUint8(btAddr.addr, sizeof(btAddr.addr));
1217 
1218     // config search attribute
1219     attributeIdList.attributeIdList.attributeId[index++] = MAP_MCE_SUPPORTED_FEATURES_ATTRIBUTE_ID;
1220     attributeIdList.attributeIdList.attributeIdNumber = index;
1221     attributeIdList.type = SDP_TYPE_LIST;
1222     // set uuid
1223     btUuid.type = BT_UUID_16;
1224     btUuid.uuid16 = MAP_MCE_SERVICE_CLASS_UUID;
1225 
1226     sdpUuid.uuid = &btUuid;
1227     sdpUuid.uuidNum = 1;
1228     // search sdp
1229     retStackVal =
1230         SDP_ServiceSearchAttribute(&btAddr, &sdpUuid, attributeIdList, nullptr, MapMceGetSupportFeatureSdpSearchCb);
1231     if (retStackVal != BT_SUCCESS) {
1232         LOG_ERROR("%{public}s error:SDP_ServiceSearchAttribute", __PRETTY_FUNCTION__);
1233         retServiceVal = RET_NO_SUPPORT;
1234         // action complete fail
1235         resCode = MapExecuteStatus::NOT_SUPPORT;
1236         retAction.action_ = MapActionType::GET_SUPPORTED_FEATURES;
1237         serviceRpcCallbackMgr_.ExcuteObserverOnMapActionCompleted(device.GetAddress(), retAction, resCode);
1238     } else {
1239         retServiceVal = BT_SUCCESS;
1240     }
1241     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
1242     return retServiceVal;
1243 }
1244 
1245 // internal
ProcessGetSupportedFeaturesRespones(utility::Message const & msg)1246 void MapMceService::ProcessGetSupportedFeaturesRespones(utility::Message const &msg)
1247 {
1248     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
1249     uint32_t devSupportedFeatrue = 0;
1250     IProfileMapAction retAction;
1251     BtAddr *argPrt = (BtAddr *)msg.arg2_;
1252     if (argPrt == nullptr) {
1253         LOG_ERROR("%{public}s argPrt null", __PRETTY_FUNCTION__);
1254         return;
1255     }
1256     MapExecuteStatus resCode;
1257     if (msg.what_ == MSG_MCESERVICE_GET_SURPORT_FEATURES_FINISH) {
1258         devSupportedFeatrue = msg.arg1_;
1259         // call observer
1260         resCode = MapExecuteStatus::SUCCEED;
1261     } else {
1262         resCode = MapExecuteStatus::NOT_SUPPORT;
1263     }
1264     retAction.supportedFeatures_ = devSupportedFeatrue;
1265     retAction.action_ = MapActionType::GET_SUPPORTED_FEATURES;
1266     RawAddress btDevice = RawAddress::ConvertToString(argPrt->addr);
1267     serviceRpcCallbackMgr_.ExcuteObserverOnMapActionCompleted(btDevice.GetAddress(), retAction, resCode);
1268     // delete memory
1269     delete argPrt;
1270     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
1271 }
1272 
SetDefaultConfig(const MasInstanceConfig & configSave)1273 void MapMceService::SetDefaultConfig(const MasInstanceConfig &configSave)
1274 {
1275     LOG_INFO("%{public}s enter", __PRETTY_FUNCTION__);
1276     std::lock_guard<std::recursive_mutex> lock(mceDeviceMapMutex_);
1277 
1278     int saveId = insDefaultConfig_.deviceId;
1279     insDefaultConfig_ = configSave;
1280     insDefaultConfig_.deviceId = saveId;
1281     LOG_INFO("%{public}s end", __PRETTY_FUNCTION__);
1282 }
1283 
GetConfigFromXml()1284 void MapMceService::GetConfigFromXml()
1285 {
1286     LOG_DEBUG("%{public}s enter", __PRETTY_FUNCTION__);
1287     int value = 0;
1288     bool boolValue = 0;
1289     IAdapterConfig *config = AdapterConfig::GetInstance();
1290 
1291     if (!config->GetValue(SECTION_MAP_MCE_SERVICE, "MaxConnectedDevices", value)) {
1292         LOG_ERROR("%{public}s error:MaxConnectedDevices not found", __PRETTY_FUNCTION__);
1293     } else {
1294         insDefaultConfig_.maxOfDevice = value;
1295     }
1296     if (!config->GetValue(SECTION_MAP_MCE_SERVICE, PROPERTY_L2CAP_MTU, value)) {
1297         LOG_ERROR("%{public}s error:l2capMtu not found", __PRETTY_FUNCTION__);
1298     } else {
1299         insDefaultConfig_.l2capMtu = value;
1300     }
1301     if (!config->GetValue(SECTION_MAP_MCE_SERVICE, PROPERTY_RFCOMM_MTU, value)) {
1302         LOG_ERROR("%{public}s error:rfcomm Mtu not found", __PRETTY_FUNCTION__);
1303     } else {
1304         insDefaultConfig_.rfcommMtu = value;
1305     }
1306     if (!config->GetValue(SECTION_MAP_MCE_SERVICE, PROPERTY_MAP_MAX_OF_GET_UREAD, value)) {
1307         LOG_ERROR("%{public}s error:MaxOfGetUreadMessage not found", __PRETTY_FUNCTION__);
1308     } else {
1309         insDefaultConfig_.maxOfGetUnread = value;
1310     }
1311     if (!config->GetValue(SECTION_MAP_MCE_SERVICE, PROPERTY_SRM_ENABLE, boolValue)) {
1312         LOG_ERROR("%{public}s error:SrmEnable not found", __PRETTY_FUNCTION__);
1313     } else {
1314         insDefaultConfig_.isSupportSrm = boolValue;
1315     }
1316     HILOGI("maxOfDevice = %{public}d, l2capMtu = %{public}d, rfcommMtu = %{public}d, UreadNumber = %{public}d, "
1317         "EnableSrm_ = %{public}d", insDefaultConfig_.maxOfDevice, insDefaultConfig_.l2capMtu,
1318         insDefaultConfig_.rfcommMtu, insDefaultConfig_.maxOfGetUnread, insDefaultConfig_.isSupportSrm);
1319 }
1320 
1321 REGISTER_CLASS_CREATOR(MapMceService);
1322 }  // namespace bluetooth
1323 }  // namespace OHOS
1324