1 /*
2 * Copyright (C) 2021-2022 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 "gatt_server_service.h"
17 #include <future>
18 #include <set>
19 #include "adapter_config.h"
20 #include "class_creator.h"
21 #include "gatt_based_services_manager.h"
22 #include "gatt_connection.h"
23 #include "gatt_connection_manager.h"
24 #include "gatt_database.h"
25 #include "gatt_defines.h"
26 #include "gatt_server_profile.h"
27 #include "gatt_service_base.h"
28 #include "interface_profile.h"
29 #include "log.h"
30 #include "log_util.h"
31 #include "power_manager.h"
32
33 namespace OHOS {
34 namespace bluetooth {
35 struct ServerApplication {
ServerApplicationOHOS::bluetooth::ServerApplication36 explicit ServerApplication(std::shared_ptr<IGattServerCallback> callback) : services_()
37 {
38 callback_ = callback;
39 }
40
41 std::shared_ptr<IGattServerCallback> callback_;
42 // service handle set of application
43 std::set<uint16_t> services_;
44 };
45
46 using AppIterator = std::map<int, ServerApplication>::iterator;
47
48 struct GattServerService::impl : public GattServiceBase {
49 class GattServerProfileCallbackImplement;
50 class GattConnectionObserverImplement;
51
52 int connectionObserverId_ = 0;
53 GattServerService &self_;
54 std::unique_ptr<GattServerProfileCallbackImplement> profileCallback_ = {nullptr};
55 std::unique_ptr<GattServerProfile> profile_ = {nullptr};
56 std::unique_ptr<GattConnectionObserverImplement> connectionObserver_ = {nullptr};
57 std::unique_ptr<GattBasedServicesManager> basedServicesManager_ = {nullptr};
58 std::mutex remotesMutex_ = {};
59 // connection handle <-> connection entity
60 std::map<uint16_t, GattConnection> remotes_ = {};
61 // application ID <-> application entity
62 std::map<int, ServerApplication> servers_ = {};
63 // attribute handle <-> (application ID, parent service handle)
64 std::map<uint16_t, std::pair<int, uint16_t>> attHandleMap_ = {};
65
66 explicit impl(GattServerService &service);
67 ~impl();
68
69 void RegisterApplication(std::shared_ptr<IGattServerCallback> callback, std::promise<int> &promise);
70 void DeregisterApplication(int appId, std::promise<int> &promise);
71 int RegisterApplicationImpl(std::shared_ptr<IGattServerCallback> callback);
72 int DeregisterApplicationImpl(int appId);
73
74 int AddService(int appId, Service &service, bool IsAsync);
75 int RemoveService(int appId, uint16_t handle);
76 int ClearServices(int appId);
77 void NotifyClient(
78 const GattDevice &device, uint16_t valueHandle, const GattValue &value, size_t length, bool needConfirm);
79 void RespondCharacteristicRead(const GattDevice &device, uint16_t valueHandle, const GattValue &value,
80 size_t length, int ret, bool isUsingUuid);
81 void RespondCharacteristicWrite(const GattDevice &device, uint16_t characteristicHandle, int ret);
82 void RespondDescriptorRead(
83 const GattDevice &device, uint16_t valueHandle, const GattValue &value, size_t length, int ret);
84 void RespondDescriptorWrite(const GattDevice &device, uint16_t descriptorHandle, int ret);
85 void CancelConnection(const GattDevice &device);
86 void SetCharacteristicValue(uint16_t valueHandle, GattValue &value, size_t length);
87 void SetCharacteristicPermission(uint16_t valueHandle, uint8_t properties, uint8_t permission);
88 void OnExchangeMtuEvent(uint16_t connectionHandle, uint16_t rxMtu);
89 void OnReadCharacteristicValueEvent(uint16_t connectionHandle, uint16_t valueHandle, bool isUsingUuid);
90 void OnWriteCharacteristicEvent(
91 uint16_t connectionHandle, uint16_t valueHandle, GattValue &value, size_t length, bool needRespones);
92 void OnDescriptorReadEvent(uint16_t connectionHandle, uint16_t valueHandle);
93 void OnDescriptorWriteEvent(uint16_t connectionHandle, uint16_t valueHandle, GattValue &value, size_t length);
94 void OnIndicationEvent(uint16_t connectionHandle, uint16_t valueHandle, int ret);
95 void OnConnect(const GattDevice &device, uint16_t connectionHandle, int ret);
96 void OnDisconnect(const GattDevice &device, uint16_t connectionHandle, int ret);
97 void OnConnectionChanged(const GattDevice &device, int state);
98 void OnConnectionParameterChanged(const GattDevice &device, int interval, int latency, int timeout, int status);
99 void OnConnetionManagerShutDown();
100
101 std::optional<AppIterator> GetValidApplication(int appId);
102 std::optional<uint16_t> GetValidDeviceConnetionHandle(const GattDevice &device);
103 std::optional<uint16_t> FindDeviceConnetionHandle(const GattDevice &device);
104 bluetooth::Service BuildService(const GattDatabase::Service &src);
105 void AddAttHandleMap(int appId, const Service &service);
106 static bool IsValidAttHandle(uint16_t handle);
107 static uint16_t GetBleServerExchangeMtu();
108 std::optional<AppIterator> GetValidApplicationService(int appId, uint16_t handle);
109 void NotifyServiceChanged(int appId, const Service &service);
110
111 void Enable();
112 void Disable();
113 void CleanApplication();
114 static void GattUpdatePowerStatus(const RawAddress &addr);
115 };
116
GattServerService()117 GattServerService::GattServerService()
118 : utility::Context("GattServerService", "5.0.0"), pimpl(std::make_unique<GattServerService::impl>(*this))
119 {
120 LOG_INFO("ProfileService:%{public}s Create", Name().c_str());
121 }
122
~GattServerService()123 GattServerService::~GattServerService()
124 {
125 LOG_INFO("ProfileService:%{public}s Destroy", Name().c_str());
126 }
127
GetContext()128 utility::Context *GattServerService::GetContext()
129 {
130 return this;
131 }
132
GetConnectDevices()133 std::list<RawAddress> GattServerService::GetConnectDevices()
134 {
135 return std::list<RawAddress>();
136 }
137
GetConnectState()138 int GattServerService::GetConnectState()
139 {
140 return 0;
141 }
142
GetMaxConnectNum()143 int GattServerService::GetMaxConnectNum()
144 {
145 auto maxNum = GattConnectionManager::GetInstance().GetMaximumNumberOfConnections();
146 return maxNum.first + maxNum.second;
147 }
148
Connect(const RawAddress & device)149 int GattServerService::Connect(const RawAddress &device)
150 {
151 return 0;
152 }
153
Disconnect(const RawAddress & device)154 int GattServerService::Disconnect(const RawAddress &device)
155 {
156 return 0;
157 }
158
CancelConnection(const GattDevice & device)159 int GattServerService::CancelConnection(const GattDevice &device)
160 {
161 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
162 if (!pimpl->InRunningState()) {
163 return GattStatus::REQUEST_NOT_SUPPORT;
164 }
165
166 GetDispatcher()->PostTask(std::bind(&impl::CancelConnection, pimpl.get(), device));
167
168 return GattStatus::GATT_SUCCESS;
169 }
170
SetCharacteristicValue(const Characteristic & characteristic)171 int GattServerService::SetCharacteristicValue(const Characteristic &characteristic)
172 {
173 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
174 if (!pimpl->InRunningState()) {
175 return GattStatus::REQUEST_NOT_SUPPORT;
176 }
177
178 auto sharedPtr = pimpl->BuildGattValue(characteristic.value_.get(), characteristic.length_);
179
180 GetDispatcher()->PostTask(std::bind(
181 &impl::SetCharacteristicValue, pimpl.get(), characteristic.valueHandle_, sharedPtr, characteristic.length_));
182
183 return GattStatus::GATT_SUCCESS;
184 }
185
SetCharacteristicPermission(const Characteristic & characteristic,uint8_t properties,uint8_t permission)186 int GattServerService::SetCharacteristicPermission(
187 const Characteristic &characteristic, uint8_t properties, uint8_t permission)
188 {
189 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
190 if (!pimpl->InRunningState()) {
191 return GattStatus::REQUEST_NOT_SUPPORT;
192 }
193
194 GetDispatcher()->PostTask(std::bind(
195 &impl::SetCharacteristicPermission, pimpl.get(), characteristic.valueHandle_, properties, permission));
196
197 return GattStatus::GATT_SUCCESS;
198 }
199
AddService(int appId,Service & service)200 int GattServerService::AddService(int appId, Service &service)
201 {
202 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
203 if (!pimpl->InRunningState()) {
204 LOG_ERROR("%{public}s:%{public}d:%{public}s InRunningState false ", __FILE__, __LINE__, __FUNCTION__);
205 return GattStatus::REQUEST_NOT_SUPPORT;
206 }
207
208 int result = pimpl->profile_->CheckLegalityOfServiceDefinition(service);
209 if (GattStatus::GATT_SUCCESS != result) {
210 LOG_ERROR("%{public}s:%{public}d:%{public}s CheckLegalityOfServiceDefinition failed, result = %{public}d",
211 __FILE__, __LINE__, __FUNCTION__, result);
212 return result;
213 }
214
215 GetDispatcher()->PostTask(std::bind(&impl::AddService, pimpl.get(), appId, service, true));
216
217 return GattStatus::GATT_SUCCESS;
218 }
219
RemoveService(int appId,const Service & service)220 int GattServerService::RemoveService(int appId, const Service &service)
221 {
222 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
223 if (!pimpl->InRunningState()) {
224 LOG_ERROR("%{public}s:%{public}d:%{public}s InRunningState false ", __FILE__, __LINE__, __FUNCTION__);
225 return GattStatus::REQUEST_NOT_SUPPORT;
226 }
227
228 if (!pimpl->IsValidAttHandle(service.handle_)) {
229 return GattStatus::INVALID_PARAMETER;
230 }
231
232 GetDispatcher()->PostTask(std::bind(&impl::RemoveService, pimpl.get(), appId, service.handle_));
233
234 return GattStatus::GATT_SUCCESS;
235 }
236
ClearServices(int appId)237 int GattServerService::ClearServices(int appId)
238 {
239 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
240 if (!pimpl->InRunningState()) {
241 return GattStatus::REQUEST_NOT_SUPPORT;
242 }
243
244 GetDispatcher()->PostTask(std::bind(&impl::ClearServices, pimpl.get(), appId));
245
246 return GattStatus::GATT_SUCCESS;
247 }
248
NotifyClient(const GattDevice & device,Characteristic & characteristic,bool needConfirm)249 int GattServerService::NotifyClient(const GattDevice &device, Characteristic &characteristic, bool needConfirm)
250 {
251 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
252 if (!pimpl->InRunningState()) {
253 return GattStatus::REQUEST_NOT_SUPPORT;
254 }
255
256 if (!pimpl->IsValidAttHandle(characteristic.handle_)) {
257 return GattStatus::INVALID_PARAMETER;
258 }
259
260 if (characteristic.value_ == nullptr || characteristic.length_ <= 0) {
261 return GattStatus::INVALID_PARAMETER;
262 }
263
264 auto sharedPtr = pimpl->MoveToGattValue(characteristic.value_);
265 GetDispatcher()->PostTask(std::bind(&impl::NotifyClient,
266 pimpl.get(),
267 device,
268 characteristic.valueHandle_,
269 sharedPtr,
270 characteristic.length_,
271 needConfirm));
272
273 return GattStatus::GATT_SUCCESS;
274 }
275
RespondCharacteristicRead(const GattDevice & device,Characteristic & characteristic,int ret)276 int GattServerService::RespondCharacteristicRead(const GattDevice &device, Characteristic &characteristic, int ret)
277 {
278 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
279 if (!pimpl->InRunningState()) {
280 return GattStatus::REQUEST_NOT_SUPPORT;
281 }
282
283 if (!pimpl->IsValidAttHandle(characteristic.handle_)) {
284 return GattStatus::INVALID_PARAMETER;
285 }
286
287 if (ret == GattStatus::GATT_SUCCESS && (characteristic.value_ == nullptr || characteristic.length_ <= 0)) {
288 return GattStatus::INVALID_PARAMETER;
289 }
290
291 auto sharedPtr = pimpl->MoveToGattValue(characteristic.value_);
292 GetDispatcher()->PostTask(std::bind(&impl::RespondCharacteristicRead,
293 pimpl.get(),
294 device,
295 characteristic.valueHandle_,
296 sharedPtr,
297 characteristic.length_,
298 ret,
299 false));
300 return GattStatus::GATT_SUCCESS;
301 }
302
RespondCharacteristicReadByUuid(const GattDevice & device,Characteristic & characteristic,int ret)303 int GattServerService::RespondCharacteristicReadByUuid(
304 const GattDevice &device, Characteristic &characteristic, int ret)
305 {
306 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
307 if (!pimpl->InRunningState()) {
308 return GattStatus::REQUEST_NOT_SUPPORT;
309 }
310
311 if (!pimpl->IsValidAttHandle(characteristic.handle_)) {
312 return GattStatus::INVALID_PARAMETER;
313 }
314
315 if (ret == GattStatus::GATT_SUCCESS && (characteristic.value_ == nullptr || characteristic.length_ <= 0)) {
316 return GattStatus::INVALID_PARAMETER;
317 }
318
319 auto sharedPtr = pimpl->MoveToGattValue(characteristic.value_);
320 GetDispatcher()->PostTask(std::bind(&impl::RespondCharacteristicRead,
321 pimpl.get(),
322 device,
323 characteristic.valueHandle_,
324 sharedPtr,
325 characteristic.length_,
326 ret,
327 true));
328 return GattStatus::GATT_SUCCESS;
329 }
330
RespondCharacteristicWrite(const GattDevice & device,const Characteristic & characteristic,int ret)331 int GattServerService::RespondCharacteristicWrite(
332 const GattDevice &device, const Characteristic &characteristic, int ret)
333 {
334 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
335 if (!pimpl->InRunningState()) {
336 return GattStatus::REQUEST_NOT_SUPPORT;
337 }
338
339 GetDispatcher()->PostTask(
340 std::bind(&impl::RespondCharacteristicWrite, pimpl.get(), device, characteristic.valueHandle_, ret));
341
342 return GattStatus::GATT_SUCCESS;
343 }
344
RespondDescriptorRead(const GattDevice & device,Descriptor & descriptor,int ret)345 int GattServerService::RespondDescriptorRead(const GattDevice &device, Descriptor &descriptor, int ret)
346 {
347 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
348 if (!pimpl->InRunningState()) {
349 return GattStatus::REQUEST_NOT_SUPPORT;
350 }
351
352 if (!pimpl->IsValidAttHandle(descriptor.handle_)) {
353 return GattStatus::INVALID_PARAMETER;
354 }
355
356 if (ret == GattStatus::GATT_SUCCESS && (descriptor.value_ == nullptr || descriptor.length_ <= 0)) {
357 return GattStatus::INVALID_PARAMETER;
358 }
359
360 auto sharedPtr = pimpl->MoveToGattValue(descriptor.value_);
361 GetDispatcher()->PostTask(std::bind(
362 &impl::RespondDescriptorRead, pimpl.get(), device, descriptor.handle_, sharedPtr, descriptor.length_, ret));
363
364 return GattStatus::GATT_SUCCESS;
365 }
366
RespondDescriptorWrite(const GattDevice & device,const Descriptor & descriptor,int ret)367 int GattServerService::RespondDescriptorWrite(const GattDevice &device, const Descriptor &descriptor, int ret)
368 {
369 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
370 if (!pimpl->InRunningState()) {
371 return GattStatus::REQUEST_NOT_SUPPORT;
372 }
373
374 if (!pimpl->IsValidAttHandle(descriptor.handle_)) {
375 return GattStatus::INVALID_PARAMETER;
376 }
377
378 GetDispatcher()->PostTask(std::bind(&impl::RespondDescriptorWrite, pimpl.get(), device, descriptor.handle_, ret));
379
380 return GattStatus::GATT_SUCCESS;
381 }
382
RegisterApplication(std::shared_ptr<IGattServerCallback> callback)383 int GattServerService::RegisterApplication(std::shared_ptr<IGattServerCallback> callback)
384 {
385 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
386 if (!pimpl->InRunningState()) {
387 return GattStatus::REQUEST_NOT_SUPPORT;
388 }
389
390 std::promise<int> promise;
391 std::future<int> future = promise.get_future();
392 GetDispatcher()->PostTask(
393 std::bind(&impl::RegisterApplication, pimpl.get(), std::ref(callback), std::ref(promise)));
394
395 return future.get();
396 }
397
DeregisterApplication(int appId)398 int GattServerService::DeregisterApplication(int appId)
399 {
400 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
401 if (!pimpl->InRunningState()) {
402 return GattStatus::REQUEST_NOT_SUPPORT;
403 }
404
405 std::promise<int> promise;
406 std::future<int> future = promise.get_future();
407 GetDispatcher()->PostTask(std::bind(&impl::DeregisterApplication, pimpl.get(), appId, std::ref(promise)));
408
409 return future.get();
410 }
411
RegisterApplicationSync(std::shared_ptr<IGattServerCallback> callback) const412 int GattServerService::RegisterApplicationSync(std::shared_ptr<IGattServerCallback> callback) const
413 {
414 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
415 if (!pimpl->InRunningState()) {
416 return GattStatus::REQUEST_NOT_SUPPORT;
417 }
418
419 return pimpl->RegisterApplicationImpl(callback);
420 }
421
DeregisterApplicationSync(int appId) const422 int GattServerService::DeregisterApplicationSync(int appId) const
423 {
424 LOG_INFO("%{public}s:%{public}d:%{public}s:%{public}d:", __FILE__, __LINE__, __FUNCTION__, appId);
425 if (!pimpl->InRunningState()) {
426 return GattStatus::REQUEST_NOT_SUPPORT;
427 }
428
429 return pimpl->DeregisterApplicationImpl(appId);
430 }
431
AddServiceSync(int appId,Service & service) const432 int GattServerService::AddServiceSync(int appId, Service &service) const
433 {
434 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
435 int result = pimpl->profile_->CheckLegalityOfServiceDefinition(service);
436 if (GattStatus::GATT_SUCCESS != result) {
437 return result;
438 }
439
440 return pimpl->AddService(appId, service, false);
441 }
442
GetDatabaseHash() const443 const std::string GattServerService::GetDatabaseHash() const
444 {
445 return pimpl->profile_->GetDBHash();
446 }
447
448 class GattServerService::impl::GattConnectionObserverImplement : public GattConnectionObserver {
449 public:
OnConnect(const GattDevice & device,uint16_t connectionHandle,int ret)450 void OnConnect(const GattDevice &device, uint16_t connectionHandle, int ret) override
451 {
452 HILOGI("addr: %{public}s ret: %{public}d", GetEncryptAddr(device.addr_.GetAddress()).c_str(), ret);
453 service_.GetDispatcher()->PostTask(
454 std::bind(&impl::OnConnect, service_.pimpl.get(), device, connectionHandle, ret));
455 }
456
OnDisconnect(const GattDevice & device,uint16_t connectionHandle,int ret)457 void OnDisconnect(const GattDevice &device, uint16_t connectionHandle, int ret) override
458 {
459 HILOGI("addr: %{public}s ret: %{public}d", GetEncryptAddr(device.addr_.GetAddress()).c_str(), ret);
460 service_.GetDispatcher()->PostTask(
461 std::bind(&impl::OnDisconnect, service_.pimpl.get(), device, connectionHandle, ret));
462 }
463
OnConnectionChanged(const GattDevice & device,uint16_t connectionHandle,int state)464 void OnConnectionChanged(const GattDevice &device, uint16_t connectionHandle, int state) override
465 {
466 HILOGI("addr: %{public}s ret: %{public}d", GetEncryptAddr(device.addr_.GetAddress()).c_str(), state);
467 service_.GetDispatcher()->PostTask(std::bind(&impl::OnConnectionChanged, service_.pimpl.get(), device, state));
468 }
469
OnConnectionParameterChanged(const GattDevice & device,int interval,int latency,int timeout,int status)470 void OnConnectionParameterChanged(
471 const GattDevice &device, int interval, int latency, int timeout, int status) override
472 {
473 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
474 service_.GetDispatcher()->PostTask(std::bind(
475 &impl::OnConnectionParameterChanged, service_.pimpl.get(), device, interval, latency, timeout, status));
476 }
477
OnShutDown()478 void OnShutDown() override
479 {
480 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
481 service_.GetDispatcher()->PostTask(std::bind(&impl::OnConnetionManagerShutDown, service_.pimpl.get()));
482 }
483
GattConnectionObserverImplement(GattServerService & service)484 explicit GattConnectionObserverImplement(GattServerService &service) : service_(service)
485 {}
~GattConnectionObserverImplement()486 ~GattConnectionObserverImplement()
487 {}
488
489 private:
490 GattServerService &service_;
491 };
492
493 class GattServerService::impl::GattServerProfileCallbackImplement : public GattServerProfileCallback {
494 public:
OnExchangeMtuEvent(uint16_t connectHandle,uint16_t rxMtu)495 void OnExchangeMtuEvent(uint16_t connectHandle, uint16_t rxMtu) override
496 {
497 service_.GetDispatcher()->PostTask(
498 std::bind(&impl::OnExchangeMtuEvent, service_.pimpl.get(), connectHandle, rxMtu));
499 }
500
OnReadCharacteristicValueEvent(uint16_t connectHandle,uint16_t valueHandle)501 void OnReadCharacteristicValueEvent(uint16_t connectHandle, uint16_t valueHandle) override
502 {
503 service_.GetDispatcher()->PostTask(
504 std::bind(&impl::OnReadCharacteristicValueEvent, service_.pimpl.get(), connectHandle, valueHandle, false));
505 }
506
OnReadUsingCharacteristicUuidEvent(uint16_t connectHandle,uint16_t valueHandle)507 void OnReadUsingCharacteristicUuidEvent(uint16_t connectHandle, uint16_t valueHandle) override
508 {
509 service_.GetDispatcher()->PostTask(
510 std::bind(&impl::OnReadCharacteristicValueEvent, service_.pimpl.get(), connectHandle, valueHandle, true));
511 }
512
OnWriteWithoutResponseEvent(uint16_t connectHandle,uint16_t valueHandle,GattValue & value,size_t len)513 void OnWriteWithoutResponseEvent(
514 uint16_t connectHandle, uint16_t valueHandle, GattValue &value, size_t len) override
515 {
516 service_.GetDispatcher()->PostTask(std::bind(
517 &impl::OnWriteCharacteristicEvent, service_.pimpl.get(), connectHandle, valueHandle, value, len, false));
518 }
519
OnWriteCharacteristicValueEvent(uint16_t connectHandle,uint16_t valueHandle,GattValue & value,size_t len)520 void OnWriteCharacteristicValueEvent(
521 uint16_t connectHandle, uint16_t valueHandle, GattValue &value, size_t len) override
522 {
523 service_.GetDispatcher()->PostTask(std::bind(
524 &impl::OnWriteCharacteristicEvent, service_.pimpl.get(), connectHandle, valueHandle, value, len, true));
525 }
526
OnIndicationEvent(uint16_t connectHandle,uint16_t valueHandle,int result)527 void OnIndicationEvent(uint16_t connectHandle, uint16_t valueHandle, int result) override
528 {
529 service_.GetDispatcher()->PostTask(
530 std::bind(&impl::OnIndicationEvent, service_.pimpl.get(), connectHandle, valueHandle, result));
531 }
532
OnReliableWriteEvent(uint16_t connectHandle,uint16_t valueHandle,GattValue & value,size_t len)533 void OnReliableWriteEvent(uint16_t connectHandle, uint16_t valueHandle, GattValue &value, size_t len) override
534 {
535 }
536
OnExecuteWriteEvent(uint16_t connectHandle,uint16_t valueHandle,int state)537 void OnExecuteWriteEvent(uint16_t connectHandle, uint16_t valueHandle, int state) override
538 {
539 }
540
OnDescriptorReadEvent(uint16_t connectHandle,uint16_t valueHandle)541 void OnDescriptorReadEvent(uint16_t connectHandle, uint16_t valueHandle) override
542 {
543 service_.GetDispatcher()->PostTask(
544 std::bind(&impl::OnDescriptorReadEvent, service_.pimpl.get(), connectHandle, valueHandle));
545 };
546
OnDescriptorWriteEvent(uint16_t connectHandle,uint16_t valueHandle,GattValue & value,size_t len)547 void OnDescriptorWriteEvent(uint16_t connectHandle, uint16_t valueHandle, GattValue &value, size_t len) override
548 {
549 service_.GetDispatcher()->PostTask(
550 std::bind(&impl::OnDescriptorWriteEvent, service_.pimpl.get(), connectHandle, valueHandle, value, len));
551 };
552
GattServerProfileCallbackImplement(GattServerService & service)553 GattServerProfileCallbackImplement(GattServerService &service) : service_(service)
554 {}
~GattServerProfileCallbackImplement()555 ~GattServerProfileCallbackImplement()
556 {}
557
558 private:
559 GattServerService &service_;
560 };
561
Enable()562 void GattServerService::impl::Enable()
563 {
564 profile_->Enable();
565
566 CleanApplication();
567
568 Start();
569
570 basedServicesManager_->Enable();
571
572 self_.GetContext()->OnEnable(PROFILE_NAME_GATT_SERVER, true);
573 }
574
Disable()575 void GattServerService::impl::Disable()
576 {
577 basedServicesManager_->Disable();
578
579 Stop();
580
581 profile_->Disable();
582 }
583
CleanApplication()584 void GattServerService::impl::CleanApplication()
585 {
586 servers_.clear();
587 attHandleMap_.clear();
588 }
589
GattUpdatePowerStatus(const RawAddress & addr)590 void GattServerService::impl::GattUpdatePowerStatus(const RawAddress &addr)
591 {
592 IPowerManager::GetInstance().StatusUpdate(RequestStatus::BUSY, PROFILE_NAME_GATT_SERVER, addr);
593 IPowerManager::GetInstance().StatusUpdate(RequestStatus::IDLE, PROFILE_NAME_GATT_SERVER, addr);
594 }
595
Enable()596 void GattServerService::Enable()
597 {
598 if (pimpl->InRunningState()) {
599 LOG_ERROR("ProfileService:%{public}s is already start up!", Name().c_str());
600 return;
601 }
602
603 GetDispatcher()->PostTask(std::bind(&impl::Enable, pimpl.get()));
604 }
605
Disable()606 void GattServerService::Disable()
607 {
608 if (!pimpl->InRunningState()) {
609 LOG_ERROR("ProfileService:%{public}s is already shut down!", Name().c_str());
610 return;
611 }
612
613 GetDispatcher()->PostTask(std::bind(&impl::Disable, pimpl.get()));
614 }
615
impl(GattServerService & service)616 GattServerService::impl::impl(GattServerService &service)
617 : self_(service),
618 profileCallback_(std::make_unique<GattServerProfileCallbackImplement>(service)),
619 profile_(std::make_unique<GattServerProfile>(
620 profileCallback_.get(), service.GetDispatcher(), GetBleServerExchangeMtu())),
621 connectionObserver_(std::make_unique<GattConnectionObserverImplement>(service)),
622 basedServicesManager_(std::make_unique<GattBasedServicesManager>(service, *service.GetDispatcher()))
623 {
624 connectionObserverId_ = GattConnectionManager::GetInstance().RegisterObserver(*connectionObserver_);
625 if (connectionObserverId_ < 0) {
626 LOG_ERROR("%{public}s:%{public}s:%{public}d register to connection manager failed!",
627 __FILE__, __FUNCTION__, __LINE__);
628 }
629 }
630
~impl()631 GattServerService::impl::~impl()
632 {
633 GattConnectionManager::GetInstance().DeregisterObserver(connectionObserverId_);
634 }
635
RegisterApplicationImpl(std::shared_ptr<IGattServerCallback> callback)636 int GattServerService::impl::RegisterApplicationImpl(std::shared_ptr<IGattServerCallback> callback)
637 {
638 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
639 if (servers_.size() >= MAXIMUM_NUMBER_APPLICATION) {
640 return GattStatus::MAX_APPLICATIONS;
641 }
642
643 int result = GattStatus::GATT_FAILURE;
644 int appid = GattServiceBase::GetApplicationId();
645 if (servers_.emplace(appid, std::move(ServerApplication(callback))).second) {
646 result = GattStatus::GATT_SUCCESS;
647 } else {
648 LOG_ERROR("%{public}s:%{public}s:%{public}d register to application failed! same application ID!",
649 __FILE__, __FUNCTION__, __LINE__);
650 }
651
652 return ((result == GattStatus::GATT_SUCCESS) ? appid : result);
653 }
654
DeregisterApplicationImpl(int appId)655 int GattServerService::impl::DeregisterApplicationImpl(int appId)
656 {
657 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
658 auto server = GetValidApplication(appId);
659 if (server.has_value()) {
660 ClearServices(appId);
661 servers_.erase(appId);
662 } else {
663 LOG_ERROR("%{public}s:%{public}d:%{public}s() %{public}s",
664 __FILE__, __LINE__, __FUNCTION__, "Invalid application Id");
665 }
666
667 return GattStatus::GATT_SUCCESS;
668 }
669
RegisterApplication(std::shared_ptr<IGattServerCallback> callback,std::promise<int> & promise)670 void GattServerService::impl::RegisterApplication(
671 std::shared_ptr<IGattServerCallback> callback, std::promise<int> &promise)
672 {
673 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
674 promise.set_value(RegisterApplicationImpl(callback));
675 }
676
DeregisterApplication(int appId,std::promise<int> & promise)677 void GattServerService::impl::DeregisterApplication(int appId, std::promise<int> &promise)
678 {
679 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
680 promise.set_value(DeregisterApplicationImpl(appId));
681 }
682
AddService(int appId,Service & service,bool IsAsync)683 int GattServerService::impl::AddService(int appId, Service &service, bool IsAsync)
684 {
685 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
686 auto server = GetValidApplication(appId);
687 int result = GattStatus::GATT_FAILURE;
688 if (server.has_value()) {
689 result = profile_->AddService(service);
690 if (GattStatus::GATT_SUCCESS == result) {
691 server.value()->second.services_.emplace(service.handle_);
692 AddAttHandleMap(appId, service);
693 NotifyServiceChanged(appId, service);
694 }
695
696 if (IsAsync && server.value()->second.callback_ != nullptr) {
697 LOG_INFO("%{public}s:%{public}d:%{public}s: call OnAddService ", __FILE__, __LINE__, __FUNCTION__);
698 server.value()->second.callback_->OnAddService(result, service);
699 }
700 }
701 return result;
702 }
703
RemoveService(int appId,uint16_t handle)704 int GattServerService::impl::RemoveService(int appId, uint16_t handle)
705 {
706 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
707 auto server = GetValidApplicationService(appId, handle);
708 if (!server.has_value()) {
709 LOG_INFO("%{public}s:%{public}d:%{public}s() %{public}s",
710 __FILE__,
711 __LINE__,
712 __FUNCTION__,
713 "Server Application Delete Service that not belong to it.");
714 return GattStatus::GATT_FAILURE;
715 }
716
717 auto deleteService = profile_->GetService(handle);
718 if (deleteService == nullptr) {
719 return GattStatus::GATT_FAILURE;
720 }
721
722 Service change(deleteService->handle_, deleteService->endHandle_);
723 int result = profile_->RemoveService(handle);
724 if (GattStatus::GATT_SUCCESS != result) {
725 return result;
726 }
727
728 NotifyServiceChanged(appId, change);
729
730 std::list<uint16_t> needDeleteList;
731 for (auto attHandle : attHandleMap_) {
732 if (attHandle.second.second == handle) {
733 needDeleteList.push_back(attHandle.first);
734 }
735 }
736 for (auto attHandle : needDeleteList) {
737 attHandleMap_.erase(attHandle);
738 }
739
740 server.value()->second.services_.erase(handle);
741 return GattStatus::GATT_SUCCESS;
742 }
743
ClearServices(int appId)744 int GattServerService::impl::ClearServices(int appId)
745 {
746 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
747 auto server = GetValidApplication(appId);
748 int result = GattStatus::GATT_SUCCESS;
749 if (server.has_value()) {
750 std::vector<uint16_t> needDelHandle;
751 std::copy(server.value()->second.services_.begin(),
752 server.value()->second.services_.end(),
753 std::back_inserter(needDelHandle));
754
755 for (auto handle : needDelHandle) {
756 result = RemoveService(appId, handle);
757 if (result != GATT_SUCCESS) {
758 break;
759 }
760 }
761 }
762 return result;
763 }
764
NotifyClient(const GattDevice & device,uint16_t valueHandle,const GattValue & value,size_t length,bool needConfirm)765 void GattServerService::impl::NotifyClient(
766 const GattDevice &device, uint16_t valueHandle, const GattValue &value, size_t length, bool needConfirm)
767 {
768 LOG_INFO("%{public}s:%{public}d:%{public}s:Confirm:%{public}d", __FILE__, __LINE__, __FUNCTION__, needConfirm);
769 auto handle = FindDeviceConnetionHandle(device);
770 if (handle.has_value()) {
771 auto connectionHandle = handle.value();
772 if (needConfirm) {
773 profile_->SendIndication(connectionHandle, valueHandle, value, length);
774 } else {
775 profile_->SendNotification(connectionHandle, valueHandle, value, length);
776 }
777
778 if (device.transport_ == GATT_TRANSPORT_TYPE_CLASSIC) {
779 GattUpdatePowerStatus(device.addr_);
780 }
781 }
782 }
783
RespondCharacteristicRead(const GattDevice & device,uint16_t valueHandle,const GattValue & value,size_t length,int ret,bool isUsingUuid)784 void GattServerService::impl::RespondCharacteristicRead(
785 const GattDevice &device, uint16_t valueHandle, const GattValue &value, size_t length, int ret, bool isUsingUuid)
786 {
787 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
788 auto handle = GetValidDeviceConnetionHandle(device);
789 if (handle.has_value()) {
790 auto connectionHandle = handle.value();
791 if (!isUsingUuid) {
792 profile_->SendReadCharacteristicValueResp(connectionHandle, valueHandle, value, length, ret);
793 } else {
794 profile_->SendReadUsingCharacteristicValueResp(connectionHandle, valueHandle, value, length, ret);
795 }
796 }
797 }
798
RespondCharacteristicWrite(const GattDevice & device,uint16_t characteristicHandle,int ret)799 void GattServerService::impl::RespondCharacteristicWrite(
800 const GattDevice &device, uint16_t characteristicHandle, int ret)
801 {
802 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
803 auto handle = GetValidDeviceConnetionHandle(device);
804 if (handle.has_value()) {
805 auto connectionHandle = handle.value();
806 profile_->SendWriteCharacteristicValueResp(connectionHandle, characteristicHandle, ret);
807 }
808 }
809
RespondDescriptorRead(const GattDevice & device,uint16_t valueHandle,const GattValue & value,size_t length,int ret)810 void GattServerService::impl::RespondDescriptorRead(
811 const GattDevice &device, uint16_t valueHandle, const GattValue &value, size_t length, int ret)
812 {
813 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
814 auto handle = GetValidDeviceConnetionHandle(device);
815 if (handle.has_value()) {
816 auto connectionHandle = handle.value();
817 profile_->SendReadDescriptorResp(connectionHandle, valueHandle, value, length, ret);
818 }
819 }
820
RespondDescriptorWrite(const GattDevice & device,uint16_t DescriptorHandle,int ret)821 void GattServerService::impl::RespondDescriptorWrite(const GattDevice &device, uint16_t DescriptorHandle, int ret)
822 {
823 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
824 auto handle = GetValidDeviceConnetionHandle(device);
825 if (handle.has_value()) {
826 auto connectionHandle = handle.value();
827 profile_->SendWriteDescriptorResp(connectionHandle, DescriptorHandle, ret);
828 }
829 }
830
CancelConnection(const GattDevice & device)831 void GattServerService::impl::CancelConnection(const GattDevice &device)
832 {
833 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
834 auto &manager = GattConnectionManager::GetInstance();
835 auto result = manager.Disconnect(device);
836 if (GattStatus::GATT_SUCCESS != result) {
837 if (device.transport_ == GATT_TRANSPORT_TYPE_CLASSIC) {
838 IPowerManager::GetInstance().StatusUpdate(
839 RequestStatus::CONNECT_OFF, PROFILE_NAME_GATT_SERVER, device.addr_);
840 }
841
842 for (auto &server : servers_) {
843 if (server.second.callback_ != nullptr) {
844 server.second.callback_->OnConnectionStateChanged(
845 device, result, ConvertConnectionState(manager.GetDeviceState(device)));
846 }
847 }
848 }
849 }
850
SetCharacteristicValue(uint16_t valueHandle,GattValue & value,size_t length)851 void GattServerService::impl::SetCharacteristicValue(uint16_t valueHandle, GattValue &value, size_t length)
852 {
853 LOG_DEBUG("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
854 GattDatabase::AttributeValue attValue;
855 attValue.value_ = std::move(*value);
856 attValue.length_ = length;
857 profile_->SetAttributeValue(valueHandle, attValue);
858 }
859
SetCharacteristicPermission(uint16_t valueHandle,uint8_t properties,uint8_t permission)860 void GattServerService::impl::SetCharacteristicPermission(uint16_t valueHandle, uint8_t properties, uint8_t permission)
861 {
862 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
863 auto ccc = profile_->GetCharacteristic(valueHandle);
864 if (ccc != nullptr) {
865 ccc->properties_ = properties;
866 auto cccValue = profile_->GetAttributeEntity(valueHandle);
867 if (cccValue.has_value()) {
868 cccValue.value().get().permissions_ = permission;
869 }
870 }
871 }
872
OnExchangeMtuEvent(uint16_t connectionHandle,uint16_t rxMtu)873 void GattServerService::impl::OnExchangeMtuEvent(uint16_t connectionHandle, uint16_t rxMtu)
874 {
875 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
876 auto remote = remotes_.find(connectionHandle);
877 if (remote != remotes_.end()) {
878 if (remote->second.GetDevice().transport_ == GATT_TRANSPORT_TYPE_CLASSIC) {
879 GattUpdatePowerStatus(remote->second.GetDevice().addr_);
880 }
881
882 remote->second.SetMtu(rxMtu);
883 for (auto &server : servers_) {
884 if (server.second.callback_ != nullptr) {
885 server.second.callback_->OnMtuChanged(remote->second.GetDevice(), rxMtu);
886 }
887 }
888 }
889 }
890
OnReadCharacteristicValueEvent(uint16_t connectionHandle,uint16_t valueHandle,bool isUsingUuid)891 void GattServerService::impl::OnReadCharacteristicValueEvent(
892 uint16_t connectionHandle, uint16_t valueHandle, bool isUsingUuid)
893 {
894 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
895 auto appId = attHandleMap_.find(valueHandle);
896 if (appId == attHandleMap_.end()) {
897 LOG_ERROR("%{public}s:%{public}d:%{public}s() %{public}s",
898 __FILE__, __LINE__, __FUNCTION__, "Attribute map error!");
899 return;
900 }
901
902 auto server = servers_.find(appId->second.first);
903 if (server == servers_.end()) {
904 LOG_ERROR("%{public}s:%{public}d:%{public}s() %{public}s",
905 __FILE__, __LINE__, __FUNCTION__, "Server app map error!");
906 return;
907 }
908
909 auto remote = remotes_.find(connectionHandle);
910 if (remote != remotes_.end()) {
911 if (remote->second.GetDevice().transport_ == GATT_TRANSPORT_TYPE_CLASSIC) {
912 GattUpdatePowerStatus(remote->second.GetDevice().addr_);
913 }
914
915 auto ccc = profile_->GetCharacteristic(valueHandle);
916 if (ccc == nullptr) {
917 LOG_ERROR("%{public}s:%{public}d:%{public}s Gatt database Error: Can not find "
918 "Characteristic by value handle.", __FILE__, __LINE__, __FUNCTION__);
919 return;
920 }
921
922 if (server->second.callback_ != nullptr) {
923 if (!isUsingUuid) {
924 server->second.callback_->OnCharacteristicReadRequest(
925 remote->second.GetDevice(), Characteristic(ccc->uuid_, ccc->handle_, ccc->properties_));
926 } else {
927 server->second.callback_->OnCharacteristicReadByUuidRequest(
928 remote->second.GetDevice(), Characteristic(ccc->uuid_, ccc->handle_, ccc->properties_));
929 }
930 }
931 }
932 }
933
OnWriteCharacteristicEvent(uint16_t connectionHandle,uint16_t valueHandle,GattValue & value,size_t length,bool needRespones)934 void GattServerService::impl::OnWriteCharacteristicEvent(
935 uint16_t connectionHandle, uint16_t valueHandle, GattValue &value, size_t length, bool needRespones)
936 {
937 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
938 auto appId = attHandleMap_.find(valueHandle);
939 if (appId == attHandleMap_.end()) {
940 LOG_ERROR("%{public}s:%{public}d:%{public}s() %{public}s",
941 __FILE__, __LINE__, __FUNCTION__, "Attribute map error!");
942 return;
943 }
944
945 auto server = servers_.find(appId->second.first);
946 if (server == servers_.end()) {
947 LOG_ERROR("%{public}s:%{public}d:%{public}s() %{public}s",
948 __FILE__, __LINE__, __FUNCTION__, "Server app map error!");
949 return;
950 }
951
952 auto remote = remotes_.find(connectionHandle);
953 if (remote != remotes_.end()) {
954 if (remote->second.GetDevice().transport_ == GATT_TRANSPORT_TYPE_CLASSIC) {
955 GattUpdatePowerStatus(remote->second.GetDevice().addr_);
956 }
957
958 auto ccc = profile_->GetCharacteristic(valueHandle);
959 if (ccc == nullptr) {
960 LOG_ERROR("%{public}s:%{public}d:%{public}s Gatt database Error: Can not find "
961 "Characteristic by value handle.", __FILE__, __LINE__, __FUNCTION__);
962 return;
963 }
964
965 Characteristic gattCCC(ccc->uuid_, ccc->handle_, ccc->properties_);
966 gattCCC.length_ = length;
967 gattCCC.value_ = std::move(*value);
968 if (server->second.callback_ != nullptr) {
969 server->second.callback_->OnCharacteristicWriteRequest(remote->second.GetDevice(), gattCCC, needRespones);
970 }
971 }
972 }
973
OnDescriptorReadEvent(uint16_t connectionHandle,uint16_t valueHandle)974 void GattServerService::impl::OnDescriptorReadEvent(uint16_t connectionHandle, uint16_t valueHandle)
975 {
976 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
977 auto appId = attHandleMap_.find(valueHandle);
978 if (appId == attHandleMap_.end()) {
979 LOG_ERROR("%{public}s:%{public}d:%{public}s() %{public}s",
980 __FILE__, __LINE__, __FUNCTION__, "Attribute map error!");
981 return;
982 }
983
984 auto server = servers_.find(appId->second.first);
985 if (server == servers_.end()) {
986 LOG_ERROR("%{public}s:%{public}d:%{public}s() %{public}s",
987 __FILE__, __LINE__, __FUNCTION__, "Server app map error!");
988 return;
989 }
990
991 auto remote = remotes_.find(connectionHandle);
992 if (remote != remotes_.end()) {
993 if (remote->second.GetDevice().transport_ == GATT_TRANSPORT_TYPE_CLASSIC) {
994 GattUpdatePowerStatus(remote->second.GetDevice().addr_);
995 }
996
997 auto descriptor = profile_->GetDescriptor(valueHandle);
998 if (descriptor == nullptr) {
999 LOG_ERROR("%{public}s:%{public}d:%{public}s Gatt database Error: Can not find Descriptor by value handle.",
1000 __FILE__,
1001 __LINE__,
1002 __FUNCTION__);
1003 return;
1004 }
1005 if (server->second.callback_ != nullptr) {
1006 server->second.callback_->OnDescriptorReadRequest(
1007 remote->second.GetDevice(), Descriptor(descriptor->handle_, descriptor->uuid_,
1008 descriptor->permissions_));
1009 }
1010 }
1011 }
1012
OnDescriptorWriteEvent(uint16_t connectionHandle,uint16_t valueHandle,GattValue & value,size_t length)1013 void GattServerService::impl::OnDescriptorWriteEvent(
1014 uint16_t connectionHandle, uint16_t valueHandle, GattValue &value, size_t length)
1015 {
1016 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
1017 auto appId = attHandleMap_.find(valueHandle);
1018 if (appId == attHandleMap_.end()) {
1019 LOG_ERROR("%{public}s:%{public}d:%{public}s() %{public}s",
1020 __FILE__, __LINE__, __FUNCTION__, "Attribute map error!");
1021 return;
1022 }
1023
1024 auto server = servers_.find(appId->second.first);
1025 if (server == servers_.end()) {
1026 LOG_ERROR("%{public}s:%{public}d:%{public}s() %{public}s",
1027 __FILE__, __LINE__, __FUNCTION__, "Server app map error!");
1028 return;
1029 }
1030
1031 auto remote = remotes_.find(connectionHandle);
1032 if (remote != remotes_.end()) {
1033 if (remote->second.GetDevice().transport_ == GATT_TRANSPORT_TYPE_CLASSIC) {
1034 GattUpdatePowerStatus(remote->second.GetDevice().addr_);
1035 }
1036
1037 auto descriptor = profile_->GetDescriptor(valueHandle);
1038 Descriptor gattDescriptor(descriptor->handle_, descriptor->uuid_, descriptor->permissions_);
1039 gattDescriptor.length_ = length;
1040 gattDescriptor.value_ = std::move(*value);
1041 if (server->second.callback_ != nullptr) {
1042 server->second.callback_->OnDescriptorWriteRequest(remote->second.GetDevice(), gattDescriptor);
1043 }
1044 }
1045 }
1046
OnIndicationEvent(uint16_t connectionHandle,uint16_t valueHandle,int ret)1047 void GattServerService::impl::OnIndicationEvent(uint16_t connectionHandle, uint16_t valueHandle, int ret)
1048 {
1049 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
1050 auto appId = attHandleMap_.find(valueHandle);
1051 if (appId == attHandleMap_.end()) {
1052 LOG_ERROR("%{public}s:%{public}d:%{public}s() %{public}s",
1053 __FILE__, __LINE__, __FUNCTION__, "Attribute map error!");
1054 return;
1055 }
1056
1057 auto server = servers_.find(appId->second.first);
1058 if (server == servers_.end()) {
1059 LOG_ERROR("%{public}s:%{public}d:%{public}s() %{public}s",
1060 __FILE__, __LINE__, __FUNCTION__, "Server app map error!");
1061 return;
1062 }
1063
1064 auto remote = remotes_.find(connectionHandle);
1065 if (remote != remotes_.end()) {
1066 if (remote->second.GetDevice().transport_ == GATT_TRANSPORT_TYPE_CLASSIC) {
1067 GattUpdatePowerStatus(remote->second.GetDevice().addr_);
1068 }
1069
1070 auto ccc = profile_->GetCharacteristic(valueHandle);
1071 if (ccc == nullptr) {
1072 LOG_ERROR("%{public}s:%{public}d:%{public}s Gatt database Error: Can not "
1073 "find Characteristic by value handle.", __FILE__, __LINE__, __FUNCTION__);
1074 return;
1075 }
1076 if (server->second.callback_ != nullptr) {
1077 server->second.callback_->OnNotifyConfirm(
1078 remote->second.GetDevice(), Characteristic(ccc->uuid_, ccc->handle_, ccc->properties_), ret);
1079 }
1080 }
1081 }
1082
OnConnect(const GattDevice & device,uint16_t connectionHandle,int ret)1083 void GattServerService::impl::OnConnect(const GattDevice &device, uint16_t connectionHandle, int ret)
1084 {
1085 LOG_INFO("%{public}s: server service dev_role: %{public}d, ret: %{public}d", __FUNCTION__, device.role_, ret);
1086 if (GattStatus::GATT_SUCCESS == ret) {
1087 std::lock_guard<std::mutex> lck(remotesMutex_);
1088 remotes_.emplace(connectionHandle, GattConnection(device, 0, connectionHandle));
1089
1090 if (device.transport_ == GATT_TRANSPORT_TYPE_CLASSIC) {
1091 IPowerManager::GetInstance().StatusUpdate(
1092 RequestStatus::CONNECT_ON, PROFILE_NAME_GATT_SERVER, device.addr_);
1093 }
1094 }
1095 if (device.role_ == GATT_ROLE_SLAVE) {
1096 for (auto &server : servers_) {
1097 LOG_DEBUG("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __PRETTY_FUNCTION__);
1098 if (server.second.callback_ != nullptr) {
1099 server.second.callback_->OnConnectionStateChanged(device, ret,
1100 static_cast<int>(BTConnectState::CONNECTED));
1101 }
1102 }
1103 }
1104 }
1105
OnDisconnect(const GattDevice & device,uint16_t connectionHandle,int ret)1106 void GattServerService::impl::OnDisconnect(const GattDevice &device, uint16_t connectionHandle, int ret)
1107 {
1108 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
1109 bool findDevice = false;
1110 auto remote = remotes_.find(connectionHandle);
1111 if (remote != remotes_.end()) {
1112 std::lock_guard<std::mutex> lck(remotesMutex_);
1113 remotes_.erase(connectionHandle);
1114 findDevice = true;
1115 } else {
1116 for (auto it = remotes_.begin(); it != remotes_.end(); it++) {
1117 if (it->second.GetDevice() == device) {
1118 remotes_.erase(it);
1119 findDevice = true;
1120 break;
1121 }
1122 }
1123 }
1124
1125 if (!findDevice) {
1126 return;
1127 }
1128
1129 if (device.transport_ == GATT_TRANSPORT_TYPE_CLASSIC && ret == GattStatus::GATT_SUCCESS) {
1130 IPowerManager::GetInstance().StatusUpdate(
1131 RequestStatus::CONNECT_OFF, PROFILE_NAME_GATT_SERVER, device.addr_);
1132 }
1133
1134 if (device.role_ == GATT_ROLE_SLAVE) {
1135 LOG_INFO("%{public}s: server service dev_role: %{public}d", __FUNCTION__, device.role_);
1136 for (auto &server : servers_) {
1137 LOG_DEBUG("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __PRETTY_FUNCTION__);
1138 if (server.second.callback_ != nullptr) {
1139 server.second.callback_->OnConnectionStateChanged(device, ret,
1140 static_cast<int>(BTConnectState::DISCONNECTED));
1141 }
1142 }
1143 }
1144 }
1145
OnConnectionChanged(const GattDevice & device,int state)1146 void GattServerService::impl::OnConnectionChanged(const GattDevice &device, int state)
1147 {
1148 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
1149 if (device.role_ != GATT_ROLE_SLAVE) {
1150 LOG_ERROR("%{public}s: device role is %{public}d", __FUNCTION__, device.role_);
1151 return;
1152 }
1153 if (state == static_cast<int>(BTConnectState::CONNECTED)) {
1154 return;
1155 }
1156 for (auto &server : servers_) {
1157 if (server.second.callback_ != nullptr) {
1158 server.second.callback_->OnConnectionStateChanged(device, GattStatus::GATT_SUCCESS, state);
1159 }
1160 }
1161 }
1162
OnConnectionParameterChanged(const GattDevice & device,int interval,int latency,int timeout,int status)1163 void GattServerService::impl::OnConnectionParameterChanged(
1164 const GattDevice &device, int interval, int latency, int timeout, int status)
1165 {
1166 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
1167 for (auto &server : servers_) {
1168 if (server.second.callback_ != nullptr) {
1169 server.second.callback_->OnConnectionParameterChanged(device, interval, latency, timeout, status);
1170 }
1171 }
1172 }
1173
OnConnetionManagerShutDown()1174 void GattServerService::impl::OnConnetionManagerShutDown()
1175 {
1176 self_.GetContext()->OnDisable(PROFILE_NAME_GATT_SERVER, true);
1177 }
1178
BuildService(const GattDatabase::Service & src)1179 bluetooth::Service GattServerService::impl::BuildService(const GattDatabase::Service &src)
1180 {
1181 bluetooth::Service dst(src.uuid_, src.handle_, src.handle_, src.endHandle_);
1182 for (auto &inclueService : src.includeServices_) {
1183 dst.includeServices_.push_back(bluetooth::Service(
1184 inclueService.uuid_, inclueService.handle_, inclueService.startHandle_, inclueService.endHandle_));
1185 }
1186
1187 for (auto &ccc : src.characteristics_) {
1188 auto cccValue = profile_->GetAttributeEntity(ccc.second.valueHandle_);
1189
1190 bluetooth::Characteristic gattCCC(ccc.second.uuid_,
1191 ccc.second.handle_,
1192 ccc.second.properties_,
1193 cccValue.value().get().permissions_,
1194 cccValue.value().get().value_.value_.get(),
1195 cccValue.value().get().value_.length_);
1196
1197 for (auto &descriptor : ccc.second.descriptors_) {
1198 auto descriptorValue = profile_->GetAttributeEntity(descriptor.second.handle_);
1199
1200 bluetooth::Descriptor gattDescriptor(descriptorValue.value().get().type_,
1201 descriptor.second.handle_,
1202 descriptorValue.value().get().permissions_,
1203 descriptorValue.value().get().value_.value_.get(),
1204 descriptorValue.value().get().value_.length_);
1205
1206 gattCCC.descriptors_.push_back(std::move(gattDescriptor));
1207 }
1208
1209 dst.characteristics_.push_back(std::move(gattCCC));
1210 }
1211
1212 return dst;
1213 }
1214
AddAttHandleMap(int appId,const bluetooth::Service & service)1215 void GattServerService::impl::AddAttHandleMap(int appId, const bluetooth::Service &service)
1216 {
1217 for (auto &ccc : service.characteristics_) {
1218 attHandleMap_.emplace(ccc.valueHandle_, std::make_pair(appId, service.handle_));
1219 for (auto &descriptor : ccc.descriptors_) {
1220 attHandleMap_.emplace(descriptor.handle_, std::make_pair(appId, service.handle_));
1221 }
1222 }
1223 }
1224
IsValidAttHandle(uint16_t handle)1225 bool GattServerService::impl::IsValidAttHandle(uint16_t handle)
1226 {
1227 return (handle >= MIN_ATTRIBUTE_HANDLE && handle <= MAX_ATTRIBUTE_HANDLE);
1228 }
1229
GetBleServerExchangeMtu()1230 uint16_t GattServerService::impl::GetBleServerExchangeMtu()
1231 {
1232 int result = DEFAULT_BLE_GATT_SERVER_EXCHANGE_MTU;
1233 if (AdapterConfig::GetInstance()->GetValue(SECTION_GATT_SERVICE, PROPERTY_BLE_GATTSERVER_EXCHANGE_MTU, result)) {
1234 return result;
1235 }
1236 return result;
1237 }
1238
GetValidApplication(int appId)1239 std::optional<AppIterator> GattServerService::impl::GetValidApplication(int appId)
1240 {
1241 auto it = servers_.find(appId);
1242 if (it != servers_.end()) {
1243 return it;
1244 }
1245 return std::nullopt;
1246 }
1247
GetValidDeviceConnetionHandle(const GattDevice & device)1248 std::optional<uint16_t> GattServerService::impl::GetValidDeviceConnetionHandle(const GattDevice &device)
1249 {
1250 for (auto &remote : remotes_) {
1251 if (remote.second.GetDevice() == device) {
1252 return remote.first;
1253 }
1254 }
1255 return std::nullopt;
1256 }
1257
FindDeviceConnetionHandle(const GattDevice & device)1258 std::optional<uint16_t> GattServerService::impl::FindDeviceConnetionHandle(const GattDevice &device)
1259 {
1260 for (auto &remote : remotes_) {
1261 if (remote.second.GetDevice().addr_ == device.addr_) {
1262 return remote.first;
1263 }
1264 }
1265 return std::nullopt;
1266 }
1267
GetValidApplicationService(int appId,uint16_t handle)1268 std::optional<AppIterator> GattServerService::impl::GetValidApplicationService(int appId, uint16_t handle)
1269 {
1270 auto server = servers_.find(appId);
1271 if (server != servers_.end()) {
1272 auto service = server->second.services_.find(handle);
1273 if (service != server->second.services_.end()) {
1274 return server;
1275 }
1276 }
1277 return std::nullopt;
1278 }
1279
NotifyServiceChanged(int appId,const Service & service)1280 void GattServerService::impl::NotifyServiceChanged(int appId, const Service &service)
1281 {
1282 LOG_INFO("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
1283 for (auto& server : servers_) {
1284 if (server.first == appId) {
1285 continue;
1286 }
1287 LOG_INFO("%{public}d:%{public}s: call OnServiceChanged", __LINE__, __FUNCTION__);
1288 if (server.second.callback_ != nullptr) {
1289 server.second.callback_->OnServiceChanged(service);
1290 }
1291 }
1292 }
1293
1294 REGISTER_CLASS_CREATOR(GattServerService);
1295 } // namespace bluetooth
1296 } // namespace OHOS
1297