• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <condition_variable>
17 #include <memory>
18 #include <set>
19 #include "bluetooth_gatt_server.h"
20 #include "bluetooth_host.h"
21 #include "bluetooth_log.h"
22 #include "bluetooth_host_proxy.h"
23 #include "bluetooth_gatt_server_proxy.h"
24 #include "bluetooth_gatt_server_callback_stub.h"
25 #include "gatt_data.h"
26 #include "iservice_registry.h"
27 #include "raw_address.h"
28 #include "system_ability_definition.h"
29 
30 namespace OHOS {
31 namespace Bluetooth {
32 const int EIGHT_BITS = 8;
33 std::string GattServerServiceName = "bluetooth-gatt-server-server";
34 
35 constexpr uint8_t REQUEST_TYPE_CHARACTERISTICS_READ = 0x00;
36 constexpr uint8_t REQUEST_TYPE_CHARACTERISTICS_WRITE = 0x01;
37 constexpr uint8_t REQUEST_TYPE_DESCRIPTOR_READ = 0x02;
38 constexpr uint8_t REQUEST_TYPE_DESCRIPTOR_WRITE = 0x03;
39 
40 struct RequestInformation {
41     uint8_t type_;
42     bluetooth::GattDevice device_;
43     union {
44         GattCharacteristic *characteristic_;
45         GattDescriptor *descriptor_;
46     } context_;
47 
RequestInformationOHOS::Bluetooth::RequestInformation48     RequestInformation(uint8_t type, const bluetooth::GattDevice &device, GattCharacteristic *characteristic)
49         : type_(type), device_(device), context_ {
50             .characteristic_ = characteristic
51         }
52     {}
53 
RequestInformationOHOS::Bluetooth::RequestInformation54     RequestInformation(uint8_t type, const bluetooth::GattDevice &device, GattDescriptor *decriptor)
55         : type_(type), device_(device), context_ {
56             .descriptor_ = decriptor
57         }
58     {}
59 
RequestInformationOHOS::Bluetooth::RequestInformation60     RequestInformation(uint8_t type, const bluetooth::GattDevice &device) : type_(type), device_(device)
61     {}
62 
operator ==OHOS::Bluetooth::RequestInformation63     bool operator==(const RequestInformation &rhs) const
64     {
65         return (device_ == rhs.device_ && type_ == rhs.type_);
66     };
67 
operator <OHOS::Bluetooth::RequestInformation68     bool operator<(const RequestInformation &rhs) const
69     {
70         return (device_ < rhs.device_ && type_ == rhs.type_);
71     };
72 };
73 
74 struct GattServer::impl {
75     class BluetoothGattServerCallbackStubImpl;
76     bool isRegisterSucceeded_;
77     std::mutex serviceListMutex_;
78     std::mutex requestListMutex_;
79     std::list<GattService> gattServices_;
80     sptr<BluetoothGattServerCallbackStubImpl> serviceCallback_;
81     std::optional<std::reference_wrapper<GattCharacteristic>> FindCharacteristic(uint16_t handle);
82     std::optional<std::reference_wrapper<GattDescriptor>> FindDescriptor(uint16_t handle);
83     std::set<RequestInformation> requests_;
84     std::list<bluetooth::GattDevice> devices_;
85     GattServerCallback &callback_;
86     int BuildRequestId(uint8_t type, uint8_t transport);
87     int RespondCharacteristicRead(
88         const bluetooth::GattDevice &device, uint16_t handle, const uint8_t *value, size_t length, int ret);
89     int RespondCharacteristicWrite(const bluetooth::GattDevice &device, uint16_t handle, int ret);
90     int RespondDescriptorRead(
91         const bluetooth::GattDevice &device, uint16_t handle, const uint8_t *value, size_t length, int ret);
92     int RespondDescriptorWrite(const bluetooth::GattDevice &device, uint16_t handle, int ret);
93     int applicationId_;
94     std::mutex deviceListMutex_;
95     GattService *GetIncludeService(uint16_t handle);
96     bluetooth::GattDevice *FindConnectedDevice(const BluetoothRemoteDevice &device);
97     GattService BuildService(const BluetoothGattService &svc);
98     void BuildIncludeService(GattService &svc, const std::vector<bluetooth::Service> &iSvcs);
99     impl(GattServerCallback &callback, GattServer &server);
100     class BluetoothGattServerDeathRecipient;
101     sptr<BluetoothGattServerDeathRecipient> deathRecipient_;
102     sptr<IBluetoothGattServer> proxy_;
103 };
104 
105 class GattServer::impl::BluetoothGattServerDeathRecipient final : public IRemoteObject::DeathRecipient {
106 public:
BluetoothGattServerDeathRecipient(GattServer::impl & gattserver)107     BluetoothGattServerDeathRecipient(GattServer::impl &gattserver) : gattserver_(gattserver){};
108     ~BluetoothGattServerDeathRecipient() final = default;
109     BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BluetoothGattServerDeathRecipient);
110 
OnRemoteDied(const wptr<IRemoteObject> & remote)111     void OnRemoteDied(const wptr<IRemoteObject> &remote) final
112     {
113         HILOGI("GattServer::impl::BluetoothGattServerDeathRecipient::OnRemoteDied starts");
114         gattserver_.proxy_->AsObject()->RemoveDeathRecipient(gattserver_.deathRecipient_);
115         gattserver_.proxy_ = nullptr;
116     }
117 
118 private:
119     GattServer::impl &gattserver_;
120 };
121 
122 class GattServer::impl::BluetoothGattServerCallbackStubImpl : public BluetoothGattServerCallbackStub {
123 public:
OnCharacteristicReadRequest(const BluetoothGattDevice & device,const BluetoothGattCharacteristic & characteristic)124     void OnCharacteristicReadRequest(
125         const BluetoothGattDevice &device, const BluetoothGattCharacteristic &characteristic) override
126     {
127         HILOGI("%{public}s:%{public}s:%{public}d entry", __FILE__, __FUNCTION__, __LINE__);
128         std::lock_guard<std::mutex> lock(server_.pimpl->serviceListMutex_);
129         auto gattcharacter = server_.pimpl->FindCharacteristic(characteristic.handle_);
130         if (gattcharacter.has_value()) {
131             {
132                 std::lock_guard<std::mutex> lck(server_.pimpl->requestListMutex_);
133                 server_.pimpl->requests_.emplace(
134                     RequestInformation(REQUEST_TYPE_CHARACTERISTICS_READ, device, &gattcharacter.value().get()));
135             }
136             server_.pimpl->callback_.OnCharacteristicReadRequest(
137                 BluetoothRemoteDevice(device.addr_.GetAddress(),
138                     (device.transport_ == GATT_TRANSPORT_TYPE_LE) ? BT_TRANSPORT_BLE : BT_TRANSPORT_BREDR),
139                 gattcharacter.value().get(),
140                 server_.pimpl->BuildRequestId(REQUEST_TYPE_CHARACTERISTICS_READ, device.transport_));
141             return;
142         } else {
143             HILOGE("Can not Find Characteristic! Handle");
144         }
145         return;
146     }
147 
OnCharacteristicWriteRequest(const BluetoothGattDevice & device,const BluetoothGattCharacteristic & characteristic,bool needRespones)148     void OnCharacteristicWriteRequest(const BluetoothGattDevice &device,
149         const BluetoothGattCharacteristic &characteristic, bool needRespones) override
150     {
151         HILOGI("%{public}s:%{public}s:%{public}d entry", __FILE__, __FUNCTION__, __LINE__);
152         std::lock_guard<std::mutex> lock(server_.pimpl->serviceListMutex_);
153         auto gattcharacter = server_.pimpl->FindCharacteristic(characteristic.handle_);
154         if (gattcharacter.has_value()) {
155             gattcharacter.value().get().SetValue(characteristic.value_.get(), characteristic.length_);
156             gattcharacter.value().get().SetWriteType(
157                 needRespones ? GattCharacteristic::WriteType::DEFAULT : GattCharacteristic::WriteType::NO_RESPONSE);
158 
159             {
160                 std::lock_guard<std::mutex> lck(server_.pimpl->requestListMutex_);
161                 server_.pimpl->requests_.emplace(
162                     RequestInformation(REQUEST_TYPE_CHARACTERISTICS_WRITE, device, &gattcharacter.value().get()));
163             }
164 
165             server_.pimpl->callback_.OnCharacteristicWriteRequest(
166                 BluetoothRemoteDevice(device.addr_.GetAddress(),
167                     (device.transport_ == GATT_TRANSPORT_TYPE_LE) ? BT_TRANSPORT_BLE : BT_TRANSPORT_BREDR),
168                 gattcharacter.value().get(),
169                 server_.pimpl->BuildRequestId(REQUEST_TYPE_CHARACTERISTICS_WRITE, device.transport_));
170             return;
171         } else {
172             HILOGE("Can not Find Characteristic!");
173         }
174 
175         return;
176     }
177 
OnDescriptorReadRequest(const BluetoothGattDevice & device,const BluetoothGattDescriptor & descriptor)178     void OnDescriptorReadRequest(const BluetoothGattDevice &device, const BluetoothGattDescriptor &descriptor) override
179     {
180         HILOGI("%{public}s:%{public}s:%{public}d entry", __FILE__, __FUNCTION__, __LINE__);
181         std::lock_guard<std::mutex> lock(server_.pimpl->serviceListMutex_);
182         auto gattdesc = server_.pimpl->FindDescriptor(descriptor.handle_);
183         if (gattdesc.has_value()) {
184             {
185                 std::lock_guard<std::mutex> lck(server_.pimpl->requestListMutex_);
186                 server_.pimpl->requests_.emplace(
187                     RequestInformation(REQUEST_TYPE_DESCRIPTOR_READ, device, &gattdesc.value().get()));
188             }
189             server_.pimpl->callback_.OnDescriptorReadRequest(
190                 BluetoothRemoteDevice(device.addr_.GetAddress(),
191                     (device.transport_ == GATT_TRANSPORT_TYPE_LE) ? BT_TRANSPORT_BLE : BT_TRANSPORT_BREDR),
192                 gattdesc.value().get(),
193                 server_.pimpl->BuildRequestId(REQUEST_TYPE_DESCRIPTOR_READ, device.transport_));
194             return;
195         } else {
196             HILOGE("Can not Find Descriptor!");
197         }
198 
199         return;
200     }
201 
OnDescriptorWriteRequest(const BluetoothGattDevice & device,const BluetoothGattDescriptor & descriptor)202     void OnDescriptorWriteRequest(const BluetoothGattDevice &device, const BluetoothGattDescriptor &descriptor) override
203     {
204         HILOGI("%{public}s:%{public}s:%{public}d entry", __FILE__, __FUNCTION__, __LINE__);
205         std::lock_guard<std::mutex> lock(server_.pimpl->serviceListMutex_);
206         auto gattdesc = server_.pimpl->FindDescriptor(descriptor.handle_);
207         if (gattdesc.has_value()) {
208             gattdesc.value().get().SetValue(descriptor.value_.get(), descriptor.length_);
209 
210             {
211                 std::lock_guard<std::mutex> lck(server_.pimpl->requestListMutex_);
212                 server_.pimpl->requests_.emplace(
213                     RequestInformation(REQUEST_TYPE_DESCRIPTOR_WRITE, device, &gattdesc.value().get()));
214             }
215             server_.pimpl->callback_.OnDescriptorWriteRequest(
216                 BluetoothRemoteDevice(device.addr_.GetAddress(),
217                     (device.transport_ == GATT_TRANSPORT_TYPE_LE) ? BT_TRANSPORT_BLE : BT_TRANSPORT_BREDR),
218                 gattdesc.value().get(),
219                 server_.pimpl->BuildRequestId(REQUEST_TYPE_DESCRIPTOR_WRITE, device.transport_));
220             return;
221         } else {
222             HILOGE("Can not Find Descriptor!");
223         }
224         return;
225     }
226 
OnNotifyConfirm(const BluetoothGattDevice & device,const BluetoothGattCharacteristic & characteristic,int result)227     void OnNotifyConfirm(
228         const BluetoothGattDevice &device, const BluetoothGattCharacteristic &characteristic, int result) override
229     {
230         HILOGI("%{public}s:%{public}s:%{public}d entry", __FILE__, __FUNCTION__, __LINE__);
231         server_.pimpl->callback_.OnNotificationCharacteristicChanged(
232             BluetoothRemoteDevice(device.addr_.GetAddress(),
233                 (device.transport_ == GATT_TRANSPORT_TYPE_LE) ? BT_TRANSPORT_BLE : BT_TRANSPORT_BREDR),
234             result);
235         return;
236     }
237 
OnConnectionStateChanged(const BluetoothGattDevice & device,int32_t ret,int32_t state)238     void OnConnectionStateChanged(const BluetoothGattDevice &device, int32_t ret, int32_t state) override
239     {
240         HILOGI("%{public}s:%{public}s:%{public}d entry", __FILE__, __FUNCTION__, __LINE__);
241         if (state == static_cast<int>(BTConnectState::CONNECTED)) {
242             std::lock_guard<std::mutex> lck(server_.pimpl->deviceListMutex_);
243             server_.pimpl->devices_.push_back((bluetooth::GattDevice)device);
244         } else if (state == static_cast<int>(BTConnectState::DISCONNECTED)) {
245             std::lock_guard<std::mutex> lck(server_.pimpl->deviceListMutex_);
246             for (auto it = server_.pimpl->devices_.begin(); it != server_.pimpl->devices_.end(); it++) {
247                 if (*it == (bluetooth::GattDevice)device) {
248                     server_.pimpl->devices_.erase(it);
249                     break;
250                 }
251             }
252         }
253         HILOGI("%{public}s:%{public}s:%{public}d OnConnectionStateUpdate called", __FILE__, __FUNCTION__, __LINE__);
254         server_.pimpl->callback_.OnConnectionStateUpdate(
255             BluetoothRemoteDevice(device.addr_.GetAddress(),
256                 (device.transport_ == GATT_TRANSPORT_TYPE_LE) ? BT_TRANSPORT_BLE : BT_TRANSPORT_BREDR),
257             state);
258 
259         return;
260     }
261 
OnMtuChanged(const BluetoothGattDevice & device,int32_t mtu)262     void OnMtuChanged(const BluetoothGattDevice &device, int32_t mtu) override
263     {
264         HILOGI("%{public}s:%{public}s:%{public}d entry", __FILE__, __FUNCTION__, __LINE__);
265         server_.pimpl->callback_.OnMtuUpdate(
266             BluetoothRemoteDevice(device.addr_.GetAddress(),
267                 (device.transport_ == GATT_TRANSPORT_TYPE_LE) ? BT_TRANSPORT_BLE : BT_TRANSPORT_BREDR),
268             mtu);
269         return;
270     }
271 
OnAddService(int32_t ret,const BluetoothGattService & service)272     void OnAddService(int32_t ret, const BluetoothGattService &service) override
273     {
274         HILOGI("%{public}s:%{public}s:%{public}d entry", __FILE__, __FUNCTION__, __LINE__);
275         GattService *ptr = nullptr;
276         if (GattStatus::GATT_SUCCESS == ret) {
277             GattService gattSvc = server_.pimpl->BuildService(service);
278             server_.pimpl->BuildIncludeService(gattSvc, service.includeServices_);
279             {
280                 std::lock_guard<std::mutex> lck(server_.pimpl->serviceListMutex_);
281                 auto it = server_.pimpl->gattServices_.emplace(server_.pimpl->gattServices_.end(), std::move(gattSvc));
282                 ptr = &(*it);
283             }
284         }
285         HILOGI("%{public}s:%{public}s:%{public}d OnServiceAdded called", __FILE__, __FUNCTION__, __LINE__);
286         server_.pimpl->callback_.OnServiceAdded(ptr, ret);
287         return;
288     }
289 
OnConnectionParameterChanged(const BluetoothGattDevice & device,int32_t interval,int32_t latency,int32_t timeout,int32_t status)290     void OnConnectionParameterChanged(
291         const BluetoothGattDevice &device, int32_t interval, int32_t latency, int32_t timeout, int32_t status) override
292     {
293         HILOGI("%{public}s:%{public}s:%{public}d entry", __FILE__, __FUNCTION__, __LINE__);
294         server_.pimpl->callback_.OnConnectionParameterChanged(
295             BluetoothRemoteDevice(device.addr_.GetAddress(),
296                 (device.transport_ == GATT_TRANSPORT_TYPE_LE) ? BT_TRANSPORT_BLE : BT_TRANSPORT_BREDR),
297             interval,
298             latency,
299             timeout,
300             status);
301 
302         return;
303     }
304 
BluetoothGattServerCallbackStubImpl(GattServer & server)305     BluetoothGattServerCallbackStubImpl(GattServer &server) : server_(server)
306     {
307         HILOGD("GattServer::impl::BluetoothGattServerCallbackStubImpl start.");
308     }
~BluetoothGattServerCallbackStubImpl()309     ~BluetoothGattServerCallbackStubImpl()
310     {
311         HILOGD("GattServer::impl::~BluetoothGattServerCallbackStubImpl start.");
312     }
313 
314 private:
315     GattServer &server_;
316 };
317 
BuildService(const BluetoothGattService & service)318 GattService GattServer::impl::BuildService(const BluetoothGattService &service)
319 {
320     GattService gattService(UUID::ConvertFrom128Bits(service.uuid_.ConvertTo128Bits()),
321         service.handle_,
322         service.endHandle_,
323         service.isPrimary_ ? GattServiceType::PRIMARY : GattServiceType::SECONDARY);
324 
325     for (auto &character : service.characteristics_) {
326         GattCharacteristic gattcharacter(UUID::ConvertFrom128Bits(character.uuid_.ConvertTo128Bits()),
327             character.handle_,
328             character.permissions_,
329             character.properties_);
330 
331         gattcharacter.SetValue(character.value_.get(), character.length_);
332 
333         for (auto &desc : character.descriptors_) {
334             GattDescriptor gattDesc(
335                 UUID::ConvertFrom128Bits(desc.uuid_.ConvertTo128Bits()), desc.handle_, desc.permissions_);
336 
337             gattDesc.SetValue(desc.value_.get(), desc.length_);
338             gattcharacter.AddDescriptor(std::move(gattDesc));
339         }
340 
341         gattService.AddCharacteristic(std::move(gattcharacter));
342     }
343 
344     return gattService;
345 }
346 
BuildIncludeService(GattService & svc,const std::vector<bluetooth::Service> & iSvcs)347 void GattServer::impl::BuildIncludeService(GattService &svc, const std::vector<bluetooth::Service> &iSvcs)
348 {
349     for (auto &iSvc : iSvcs) {
350         GattService *pSvc = GetIncludeService(iSvc.startHandle_);
351         if (!pSvc) {
352             HILOGE("GattServer::impl::BuildIncludeService: Can not find include service entity in service ");
353             continue;
354         }
355         svc.AddService(std::ref(*pSvc));
356     }
357 }
358 
GetIncludeService(uint16_t handle)359 GattService *GattServer::impl::GetIncludeService(uint16_t handle)
360 {
361     for (auto &svc : gattServices_) {
362         if (svc.GetHandle() == handle) {
363             return &svc;
364         }
365     }
366 
367     return nullptr;
368 }
369 
impl(GattServerCallback & callback,GattServer & server)370 GattServer::impl::impl(GattServerCallback &callback, GattServer &server)
371     : serviceCallback_(new BluetoothGattServerCallbackStubImpl(server)), callback_(callback), applicationId_(0)
372 {
373     HILOGI("GattServer::impl::impl starts");
374     sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
375     sptr<IRemoteObject> hostRemote = samgr->GetSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID);
376 
377     if (!hostRemote) {
378         HILOGI("GattServer::impl:impl() failed: no hostRemote");
379         return;
380     }
381     sptr<IBluetoothHost> hostProxy = iface_cast<IBluetoothHost>(hostRemote);
382     sptr<IRemoteObject> remote = hostProxy->GetProfile(PROFILE_GATT_SERVER);
383 
384     if (!remote) {
385         HILOGE("GattServer::impl:impl() failed: no remote");
386         return;
387     }
388     HILOGI("GattServer::impl:impl() remote obtained");
389 
390     proxy_ = iface_cast<IBluetoothGattServer>(remote);
391 
392     deathRecipient_ = new BluetoothGattServerDeathRecipient(*this);
393     proxy_->AsObject()->AddDeathRecipient(deathRecipient_);
394 };
395 
GattServer(GattServerCallback & callback)396 GattServer::GattServer(GattServerCallback &callback) : pimpl(new GattServer::impl(callback, *this))
397 {
398     HILOGI("GattServer::GattServer starts");
399     int result = GattStatus::REQUEST_NOT_SUPPORT;
400     if (!pimpl->proxy_) {
401         HILOGE("GattServer::GattServer: proxy_ is nullptr");
402         return;
403     }
404     result = pimpl->proxy_->RegisterApplication(pimpl->serviceCallback_);
405     if (result > 0) {
406         pimpl->applicationId_ = result;
407         pimpl->isRegisterSucceeded_ = true;
408     } else {
409         HILOGE("Can not Register to gatt server service! result = %{public}d", result);
410     }
411 }
412 
FindCharacteristic(uint16_t handle)413 std::optional<std::reference_wrapper<GattCharacteristic>> GattServer::impl::FindCharacteristic(uint16_t handle)
414 {
415     for (auto &svc : gattServices_) {
416         for (auto &character : svc.GetCharacteristics()) {
417             if (character.GetHandle() == handle) {
418                 return character;
419             }
420         }
421     }
422     return std::nullopt;
423 }
FindConnectedDevice(const BluetoothRemoteDevice & device)424 bluetooth::GattDevice *GattServer::impl::FindConnectedDevice(const BluetoothRemoteDevice &device)
425 {
426     std::lock_guard<std::mutex> lock(deviceListMutex_);
427     for (auto &gattDevice : devices_) {
428         if (device.GetDeviceAddr().compare(gattDevice.addr_.GetAddress()) == 0 &&
429             (device.GetTransportType() ==
430             (gattDevice.transport_ == GATT_TRANSPORT_TYPE_LE) ? BT_TRANSPORT_BLE : BT_TRANSPORT_BREDR)) {
431             return &gattDevice;
432         }
433     }
434     return nullptr;
435 }
FindDescriptor(uint16_t handle)436 std::optional<std::reference_wrapper<GattDescriptor>> GattServer::impl::FindDescriptor(uint16_t handle)
437 {
438     for (auto &svc : gattServices_) {
439         for (auto &character : svc.GetCharacteristics()) {
440             for (auto &desc : character.GetDescriptors()) {
441                 if (desc.GetHandle() == handle) {
442                     return desc;
443                 }
444             }
445         }
446     }
447     return std::nullopt;
448 }
449 
BuildRequestId(uint8_t type,uint8_t transport)450 int GattServer::impl::BuildRequestId(uint8_t type, uint8_t transport)
451 {
452     int requestId = 0;
453 
454     requestId = type << EIGHT_BITS;
455     requestId |= transport;
456 
457     return requestId;
458 }
459 
RespondCharacteristicRead(const bluetooth::GattDevice & device,uint16_t handle,const uint8_t * value,size_t length,int ret)460 int GattServer::impl::RespondCharacteristicRead(
461     const bluetooth::GattDevice &device, uint16_t handle, const uint8_t *value, size_t length, int ret)
462 {
463     if (!proxy_) {
464         HILOGE("GattServer::impl::RespondCharacteristicRead: proxy_ is nullptr");
465         return GattStatus::REQUEST_NOT_SUPPORT;
466     }
467     if (GattStatus::GATT_SUCCESS == ret) {
468         BluetoothGattCharacteristic character(bluetooth::Characteristic(handle, value, length));
469 
470         return proxy_->RespondCharacteristicRead(device, &character, ret);
471     }
472     BluetoothGattCharacteristic character;
473     character.handle_ = handle;
474     return proxy_->RespondCharacteristicRead(device, &character, ret);
475 }
476 
RespondCharacteristicWrite(const bluetooth::GattDevice & device,uint16_t handle,int ret)477 int GattServer::impl::RespondCharacteristicWrite(const bluetooth::GattDevice &device, uint16_t handle, int ret)
478 {
479     if (!proxy_) {
480         HILOGE("GattServer::impl::RespondCharacteristicWrite: proxy_ is nullptr");
481         return GattStatus::REQUEST_NOT_SUPPORT;
482     }
483     return proxy_->RespondCharacteristicWrite(
484         device, (BluetoothGattCharacteristic)bluetooth::Characteristic(handle), ret);
485 }
486 
RespondDescriptorRead(const bluetooth::GattDevice & device,uint16_t handle,const uint8_t * value,size_t length,int ret)487 int GattServer::impl::RespondDescriptorRead(
488     const bluetooth::GattDevice &device, uint16_t handle, const uint8_t *value, size_t length, int ret)
489 {
490     if (!proxy_) {
491         HILOGE("GattServer::impl::RespondDescriptorRead: proxy_ is nullptr");
492         return GattStatus::REQUEST_NOT_SUPPORT;
493     }
494     if (GattStatus::GATT_SUCCESS == ret) {
495         BluetoothGattDescriptor desc(bluetooth::Descriptor(handle, value, length));
496         return proxy_->RespondDescriptorRead(device, &desc, ret);
497     }
498     BluetoothGattDescriptor desc;
499     desc.handle_ = handle;
500     return proxy_->RespondDescriptorRead(device, &desc, ret);
501 }
502 
RespondDescriptorWrite(const bluetooth::GattDevice & device,uint16_t handle,int ret)503 int GattServer::impl::RespondDescriptorWrite(const bluetooth::GattDevice &device, uint16_t handle, int ret)
504 {
505     if (!proxy_) {
506         HILOGE("GattServer::impl::RespondDescriptorWrite: proxy_ is nullptr");
507         return GattStatus::REQUEST_NOT_SUPPORT;
508     }
509     return proxy_->RespondDescriptorWrite(device, (BluetoothGattDescriptor)bluetooth::Descriptor(handle), ret);
510 }
511 
AddService(GattService & service)512 int GattServer::AddService(GattService &service)
513 {
514     HILOGI("start.");
515     if (!pimpl->proxy_) {
516         HILOGE("GattServer::AddService: proxy_ is nullptr");
517         return GattStatus::REQUEST_NOT_SUPPORT;
518     }
519     if (!pimpl->isRegisterSucceeded_) {
520         return GattStatus::REQUEST_NOT_SUPPORT;
521     }
522 
523     BluetoothGattService svc;
524     svc.isPrimary_ = service.IsPrimary();
525     svc.uuid_ = bluetooth::Uuid::ConvertFrom128Bits(service.GetUuid().ConvertTo128Bits());
526 
527     for (auto &isvc : service.GetIncludedServices()) {
528         svc.includeServices_.push_back(bluetooth::Service(isvc.get().GetHandle()));
529     }
530 
531     for (auto &character : service.GetCharacteristics()) {
532         size_t length = 0;
533         uint8_t *value = character.GetValue(&length).get();
534         bluetooth::Characteristic c(bluetooth::Uuid::ConvertFrom128Bits(character.GetUuid().ConvertTo128Bits()),
535             character.GetHandle(),
536             character.GetProperties(),
537             character.GetPermissions(),
538             value,
539             length);
540 
541         for (auto &desc : character.GetDescriptors()) {
542             value = desc.GetValue(&length).get();
543             bluetooth::Descriptor d(bluetooth::Uuid::ConvertFrom128Bits(desc.GetUuid().ConvertTo128Bits()),
544                 desc.GetHandle(),
545                 desc.GetPermissions(),
546                 value,
547                 length);
548 
549             c.descriptors_.push_back(std::move(d));
550         }
551 
552         svc.characteristics_.push_back(std::move(c));
553     }
554     int appId = pimpl->applicationId_;
555     int result = pimpl->proxy_->AddService(appId, &svc);
556     HILOGI("appId = %{public}d, result = %{public}d.", appId, result);
557     return result;
558 }
559 
ClearServices()560 void GattServer::ClearServices()
561 {
562     HILOGI("start.");
563     if (!pimpl->proxy_) {
564         HILOGE("GattServer::ClearServices: proxy_ is nullptr");
565         return;
566     }
567     if (!pimpl->isRegisterSucceeded_) {
568         return;
569     }
570     int appId = pimpl->applicationId_;
571     pimpl->proxy_->ClearServices(int(appId));
572     pimpl->gattServices_.clear();
573 }
CancelConnection(const BluetoothRemoteDevice & device)574 void GattServer::CancelConnection(const BluetoothRemoteDevice &device)
575 {
576     HILOGI("start.");
577     if (!pimpl->proxy_) {
578         HILOGE("GattServer::CancelConnection: proxy_ is nullptr");
579         return;
580     }
581     if (!device.IsValidBluetoothRemoteDevice() || !pimpl->isRegisterSucceeded_) {
582         return;
583     }
584 
585     auto gattDevice = pimpl->FindConnectedDevice(device);
586     if (gattDevice == nullptr) {
587         HILOGI("GattServer::CancelConnection: gattDevice is nullptr");
588         return;
589     }
590 
591     pimpl->proxy_->CancelConnection(*gattDevice);
592 }
GetService(const UUID & uuid,bool isPrimary)593 std::optional<std::reference_wrapper<GattService>> GattServer::GetService(const UUID &uuid, bool isPrimary)
594 {
595     HILOGI("start.");
596     std::unique_lock<std::mutex> lock(pimpl->serviceListMutex_);
597 
598     for (auto &svc : pimpl->gattServices_) {
599         if (svc.GetUuid().Equals(uuid) && svc.IsPrimary() == isPrimary) {
600             return svc;
601         }
602     }
603 
604     return std::nullopt;
605 }
606 
GetServices()607 std::list<GattService> &GattServer::GetServices()
608 {
609     HILOGI("start.");
610     std::unique_lock<std::mutex> lock(pimpl->serviceListMutex_);
611     return pimpl->gattServices_;
612 }
NotifyCharacteristicChanged(const BluetoothRemoteDevice & device,const GattCharacteristic & characteristic,bool confirm)613 int GattServer::NotifyCharacteristicChanged(
614     const BluetoothRemoteDevice &device, const GattCharacteristic &characteristic, bool confirm)
615 {
616     HILOGI("start.");
617     if (!pimpl->proxy_) {
618         HILOGE("GattServer::NotifyCharacteristicChanged: proxy_ is nullptr");
619         return GattStatus::REQUEST_NOT_SUPPORT;
620     }
621     if (!device.IsValidBluetoothRemoteDevice() || !pimpl->isRegisterSucceeded_) {
622         return GattStatus::INVALID_REMOTE_DEVICE;
623     }
624 
625     if (pimpl->FindConnectedDevice(device) == nullptr) {
626         return GattStatus::REQUEST_NOT_SUPPORT;
627     }
628 
629     if (!pimpl->proxy_ || !pimpl->isRegisterSucceeded_) {
630         return GattStatus::REQUEST_NOT_SUPPORT;
631     }
632 
633     size_t length = 0;
634     auto &characterValue = characteristic.GetValue(&length);
635 
636     BluetoothGattCharacteristic character(
637         bluetooth::Characteristic(characteristic.GetHandle(), characterValue.get(), length));
638     std::string address = device.GetDeviceAddr();
639     int result = pimpl->proxy_->NotifyClient(
640         bluetooth::GattDevice(bluetooth::RawAddress(address), 0), &character, confirm);
641     HILOGI("result = %{public}d.", result);
642     return result;
643 }
644 
RemoveGattService(const GattService & service)645 int GattServer::RemoveGattService(const GattService &service)
646 {
647     HILOGI("start.");
648     if (!pimpl->proxy_) {
649         HILOGE("GattServer::RemoveGattService: proxy_ is nullptr");
650         return GattStatus::REQUEST_NOT_SUPPORT;
651     }
652     if (!pimpl->isRegisterSucceeded_) {
653         return GattStatus::REQUEST_NOT_SUPPORT;
654     }
655 
656     int result = GattStatus::INVALID_PARAMETER;
657     for (auto sIt = pimpl->gattServices_.begin(); sIt != pimpl->gattServices_.end(); sIt++) {
658         if (sIt->GetHandle() == service.GetHandle()) {
659             pimpl->proxy_->RemoveService(
660                 pimpl->applicationId_, (BluetoothGattService)bluetooth::Service(service.GetHandle()));
661             pimpl->gattServices_.erase(sIt);
662             result = GattStatus::GATT_SUCCESS;
663             break;
664         }
665     }
666     HILOGI("result = %{public}d.", result);
667     return result;
668 }
SendResponse(const BluetoothRemoteDevice & device,int requestId,int status,int offset,const uint8_t * value,int length)669 int GattServer::SendResponse(
670     const BluetoothRemoteDevice &device, int requestId, int status, int offset, const uint8_t *value, int length)
671 {
672     HILOGI("start.");
673     if (!pimpl->proxy_) {
674         HILOGE("GattServer::SendResponse proxy_ is nullptr");
675         return GattStatus::REQUEST_NOT_SUPPORT;
676     }
677     if (!device.IsValidBluetoothRemoteDevice() || !pimpl->isRegisterSucceeded_) {
678         return GattStatus::INVALID_REMOTE_DEVICE;
679     }
680 
681     if (pimpl->FindConnectedDevice(device) == nullptr) {
682         return GattStatus::REQUEST_NOT_SUPPORT;
683     }
684 
685     int result = GattStatus::INVALID_PARAMETER;
686     uint8_t requestType = requestId >> EIGHT_BITS;
687     uint8_t transport = requestId & 0xFF;
688     if (transport != GATT_TRANSPORT_TYPE_CLASSIC && transport != GATT_TRANSPORT_TYPE_LE) {
689         return result;
690     }
691     bluetooth::GattDevice gattdevice(bluetooth::RawAddress(device.GetDeviceAddr()), transport);
692 
693     std::lock_guard<std::mutex> lock(pimpl->requestListMutex_);
694     auto request = pimpl->requests_.find(RequestInformation(requestType, gattdevice));
695     if (request != pimpl->requests_.end()) {
696         switch (requestType) {
697             case REQUEST_TYPE_CHARACTERISTICS_READ:
698                 result = pimpl->RespondCharacteristicRead(
699                     gattdevice, request->context_.characteristic_->GetHandle(), value, length, status);
700                 break;
701             case REQUEST_TYPE_CHARACTERISTICS_WRITE:
702                 result = pimpl->RespondCharacteristicWrite(
703                     gattdevice, request->context_.characteristic_->GetHandle(), status);
704                 break;
705             case REQUEST_TYPE_DESCRIPTOR_READ:
706                 result = pimpl->RespondDescriptorRead(
707                     gattdevice, request->context_.descriptor_->GetHandle(), value, length, status);
708                 break;
709             case REQUEST_TYPE_DESCRIPTOR_WRITE:
710                 result = pimpl->RespondDescriptorWrite(gattdevice, request->context_.descriptor_->GetHandle(), status);
711                 break;
712             default:
713                 HILOGE("Error request Id!");
714                 break;
715         }
716         if (result == GattStatus::GATT_SUCCESS) {
717             pimpl->requests_.erase(request);
718         }
719     }
720     HILOGI("result = %{public}d.", result);
721     return result;
722 }
723 
~GattServer()724 GattServer::~GattServer()
725 {
726     HILOGI("GattServer::~GattServer start");
727     if (pimpl->isRegisterSucceeded_) {
728         pimpl->proxy_->DeregisterApplication(pimpl->applicationId_);
729     }
730     pimpl->proxy_->AsObject()->RemoveDeathRecipient(pimpl->deathRecipient_);
731     HILOGI("GattServer::~GattServer end");
732 }
733 }  // namespace Bluetooth
734 }  // namespace OHOS