forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBLEManagerImpl.cpp
1428 lines (1190 loc) · 56.6 KB
/
BLEManagerImpl.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* Copyright (c) 2020-2022 Project CHIP Authors
* Copyright (c) 2018 Nest Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* Provides an implementation of the BLEManager singleton object
* for Tizen platforms.
*/
/**
* Note: BLEManager requires ConnectivityManager to be defined beforehand,
* otherwise we will face circular dependency between them. */
#include <platform/ConnectivityManager.h>
/**
* Note: Use public include for BLEManager which includes our local
* platform/<PLATFORM>/BLEManagerImpl.h after defining interface class. */
#include "platform/internal/BLEManager.h"
#include <strings.h>
#include <cstdint>
#include <cstring>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#include <bluetooth.h>
#include <bluetooth_internal.h>
#include <bluetooth_type_internal.h>
#include <glib.h>
#include <ble/Ble.h>
#include <lib/core/CHIPError.h>
#include <lib/core/CHIPSafeCasts.h>
#include <lib/core/ErrorStr.h>
#include <lib/support/BitFlags.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/SetupDiscriminator.h>
#include <lib/support/Span.h>
#include <platform/CHIPDeviceEvent.h>
#include <platform/CHIPDeviceLayer.h>
#include <platform/ConfigurationManager.h>
#include <platform/GLibTypeDeleter.h>
#include <platform/PlatformManager.h>
#include <system/SystemClock.h>
#include <system/SystemLayer.h>
#include <system/SystemPacketBuffer.h>
#include "CHIPDevicePlatformEvent.h"
#include "ChipDeviceScanner.h"
#include "ErrorUtils.h"
#include "SystemInfo.h"
namespace chip {
namespace DeviceLayer {
namespace Internal {
namespace {
constexpr System::Clock::Timeout kNewConnectionScanTimeout = System::Clock::Seconds16(20);
constexpr System::Clock::Timeout kConnectTimeout = System::Clock::Seconds16(20);
constexpr System::Clock::Timeout kFastAdvertiseTimeout =
System::Clock::Milliseconds32(CHIP_DEVICE_CONFIG_BLE_ADVERTISING_INTERVAL_CHANGE_TIME);
}; // namespace
BLEManagerImpl BLEManagerImpl::sInstance;
struct BLEConnection
{
char * peerAddr;
unsigned int mtu;
bool subscribed;
bt_gatt_h gattCharC1Handle;
bt_gatt_h gattCharC2Handle;
bool isChipDevice;
};
static void __BLEConnectionFree(BLEConnection * conn)
{
VerifyOrReturn(conn != nullptr);
g_free(conn->peerAddr);
g_free(conn);
}
void BLEManagerImpl::AdapterStateChangedCb(int result, bt_adapter_state_e adapterState)
{
ChipLogProgress(DeviceLayer, "Adapter State Changed: %s", adapterState == BT_ADAPTER_ENABLED ? "Enabled" : "Disabled");
}
void BLEManagerImpl::GattConnectionStateChangedCb(int result, bool connected, const char * remoteAddress)
{
switch (result)
{
case BT_ERROR_NONE:
case BT_ERROR_ALREADY_DONE:
ChipLogProgress(DeviceLayer, "GATT %s", connected ? "connected" : "disconnected");
HandleConnectionEvent(connected, remoteAddress);
break;
default:
ChipLogError(DeviceLayer, "GATT %s failed: %s", connected ? "connection" : "disconnection", get_error_message(result));
if (connected)
NotifyHandleConnectFailed(TizenToChipError(result));
}
}
CHIP_ERROR BLEManagerImpl::_InitImpl()
{
int ret;
ret = bt_initialize();
VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_initialize() failed: %s", get_error_message(ret)));
ret = bt_adapter_set_state_changed_cb(
+[](int result, bt_adapter_state_e adapterState, void * self) {
return reinterpret_cast<BLEManagerImpl *>(self)->AdapterStateChangedCb(result, adapterState);
},
this);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_adapter_set_state_changed_cb() failed: %s", get_error_message(ret)));
ret = bt_gatt_server_initialize();
VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_initialize() failed: %s", get_error_message(ret)));
ret = bt_gatt_set_connection_state_changed_cb(
+[](int result, bool connected, const char * remoteAddress, void * self) {
return reinterpret_cast<BLEManagerImpl *>(self)->GattConnectionStateChangedCb(result, connected, remoteAddress);
},
this);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_adapter_set_state_changed_cb() failed: %s", get_error_message(ret)));
return CHIP_NO_ERROR;
exit:
return TizenToChipError(ret);
}
static int __GetAttInfo(bt_gatt_h gattHandle, char ** uuid, bt_gatt_type_e * type)
{
int ret = bt_gatt_get_type(gattHandle, type);
VerifyOrReturnError(ret == BT_ERROR_NONE, ret);
return bt_gatt_get_uuid(gattHandle, uuid);
}
static constexpr const char * __ConvertAttTypeToStr(bt_gatt_type_e type)
{
switch (type)
{
case BT_GATT_TYPE_SERVICE:
return "Service";
case BT_GATT_TYPE_CHARACTERISTIC:
return "Characteristic";
case BT_GATT_TYPE_DESCRIPTOR:
return "Descriptor";
default:
return "(unknown)";
}
}
void BLEManagerImpl::HandleAdvertisingTimeout(chip::System::Layer *, void * appState)
{
auto * self = static_cast<BLEManagerImpl *>(appState);
VerifyOrReturn(self->mFlags.Has(Flags::kFastAdvertisingEnabled));
ChipLogDetail(DeviceLayer, "bleAdv Timeout : Start slow advertisement");
self->_SetAdvertisingMode(BLEAdvertisingMode::kSlowAdvertising);
}
BLEManagerImpl::AdvertisingIntervals BLEManagerImpl::GetAdvertisingIntervals() const
{
if (mFlags.Has(Flags::kFastAdvertisingEnabled))
return { CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MIN, CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MAX };
return { CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MIN, CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MAX };
}
void BLEManagerImpl::ReadValueRequestedCb(const char * remoteAddress, int requestId, bt_gatt_server_h server, bt_gatt_h gattHandle,
int offset)
{
int ret, len = 0;
bt_gatt_type_e type;
GAutoPtr<char> uuid;
GAutoPtr<char> value;
VerifyOrReturn(__GetAttInfo(gattHandle, &uuid.GetReceiver(), &type) == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "Failed to fetch GATT Attribute from GATT handle"));
ChipLogProgress(DeviceLayer, "Gatt read requested on %s: uuid=%s", __ConvertAttTypeToStr(type), StringOrNullMarker(uuid.get()));
ret = bt_gatt_get_value(gattHandle, &value.GetReceiver(), &len);
VerifyOrReturn(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_get_value() failed: %s", get_error_message(ret)));
ChipLogByteSpan(DeviceLayer, ByteSpan(Uint8::from_const_char(value.get()), len));
ret = bt_gatt_server_send_response(requestId, BT_GATT_REQUEST_TYPE_READ, offset, 0x00, value.get(), len);
VerifyOrReturn(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_gatt_server_send_response() failed: %s", get_error_message(ret)));
}
void BLEManagerImpl::WriteValueRequestedCb(const char * remoteAddress, int requestId, bt_gatt_server_h server, bt_gatt_h gattHandle,
bool responseNeeded, int offset, const char * value, int len)
{
int ret;
GAutoPtr<char> uuid;
BLEConnection * conn;
bt_gatt_type_e type;
conn = static_cast<BLEConnection *>(g_hash_table_lookup(mConnectionMap, remoteAddress));
VerifyOrReturn(conn != nullptr, ChipLogError(DeviceLayer, "Failed to find connection info"));
VerifyOrReturn(__GetAttInfo(gattHandle, &uuid.GetReceiver(), &type) == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "Failed to fetch GATT Attribute from GATT handle"));
ChipLogProgress(DeviceLayer, "Gatt write requested on %s: uuid=%s len=%d", __ConvertAttTypeToStr(type),
StringOrNullMarker(uuid.get()), len);
ChipLogByteSpan(DeviceLayer, ByteSpan(Uint8::from_const_char(value), len));
ret = bt_gatt_set_value(gattHandle, value, len);
VerifyOrReturn(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_set_value() failed: %s", get_error_message(ret)));
ret = bt_gatt_server_send_response(requestId, BT_GATT_REQUEST_TYPE_WRITE, offset, 0x00, nullptr, 0);
VerifyOrReturn(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_gatt_server_send_response() failed: %s", get_error_message(ret)));
HandleC1CharWriteEvent(conn, Uint8::from_const_char(value), len);
}
void BLEManagerImpl::NotificationStateChangedCb(bool notify, bt_gatt_server_h server, bt_gatt_h charHandle)
{
GAutoPtr<char> uuid;
BLEConnection * conn = nullptr;
bt_gatt_type_e type;
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init(&iter, mConnectionMap);
while (g_hash_table_iter_next(&iter, &key, &value))
{
/* NOTE: Currently Tizen Platform API does not return remote device address, which enables/disables
* notification/indication. Therefore, returning first connection. */
conn = static_cast<BLEConnection *>(value);
break;
}
VerifyOrReturn(conn != nullptr, ChipLogError(DeviceLayer, "Failed to find connection info"));
int ret = __GetAttInfo(charHandle, &uuid.GetReceiver(), &type);
VerifyOrReturn(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "Failed to fetch GATT Attribute from CHAR handle: %s", get_error_message(ret)));
ChipLogProgress(DeviceLayer, "Notification State Changed %d on %s: %s", notify, __ConvertAttTypeToStr(type),
StringOrNullMarker(uuid.get()));
NotifyBLESubscribed(notify ? true : false, conn);
}
void BLEManagerImpl::WriteCompletedCb(int result, bt_gatt_h gattHandle, void * userData)
{
auto conn = static_cast<BLEConnection *>(userData);
VerifyOrReturn(result == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to Send Write request"));
VerifyOrReturn(conn != nullptr, ChipLogError(DeviceLayer, "Connection object is invalid"));
VerifyOrReturn(conn->gattCharC1Handle == gattHandle, ChipLogError(DeviceLayer, "Gatt characteristic handle did not match"));
ChipLogProgress(DeviceLayer, "Write Completed to CHIP peripheral [%s]", conn->peerAddr);
sInstance.NotifyHandleWriteComplete(conn);
}
void BLEManagerImpl::CharacteristicNotificationCb(bt_gatt_h characteristic, char * value, int len, void * userData)
{
auto conn = static_cast<BLEConnection *>(userData);
VerifyOrReturn(value != nullptr);
VerifyOrReturn(conn != nullptr, ChipLogError(DeviceLayer, "Connection object is invalid"));
VerifyOrReturn(conn->gattCharC2Handle == characteristic, ChipLogError(DeviceLayer, "Gatt characteristic handle did not match"));
ChipLogProgress(DeviceLayer, "Notification Received from CHIP peripheral [%s]", conn->peerAddr);
sInstance.HandleRXCharChanged(conn, Uint8::from_const_char(value), len);
}
void BLEManagerImpl::IndicationConfirmationCb(int result, const char * remoteAddress, bt_gatt_server_h server,
bt_gatt_h characteristic, bool completed)
{
BLEConnection * conn = nullptr;
VerifyOrReturn(result == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to Get Indication Confirmation"));
conn = static_cast<BLEConnection *>(g_hash_table_lookup(mConnectionMap, remoteAddress));
VerifyOrReturn(conn != nullptr,
ChipLogError(DeviceLayer, "Could not find connection for [%s]", StringOrNullMarker(remoteAddress)));
VerifyOrReturn(mGattCharC2Handle == characteristic, ChipLogError(DeviceLayer, "Gatt characteristic handle did not match"));
NotifyBLEIndicationConfirmation(conn);
}
void BLEManagerImpl::AdvertisingStateChangedCb(int result, bt_advertiser_h advertiser, bt_adapter_le_advertising_state_e advState)
{
ChipLogProgress(DeviceLayer, "Advertising %s", advState == BT_ADAPTER_LE_ADVERTISING_STARTED ? "Started" : "Stopped");
if (advState == BT_ADAPTER_LE_ADVERTISING_STARTED)
{
mFlags.Set(Flags::kAdvertising);
NotifyBLEPeripheralAdvStartComplete(true, nullptr);
DeviceLayer::SystemLayer().ScheduleLambda([this] {
// Start a timer to make sure that the fast advertising is stopped after specified timeout.
DeviceLayer::SystemLayer().StartTimer(kFastAdvertiseTimeout, HandleAdvertisingTimeout, this);
});
}
else
{
mFlags.Clear(Flags::kAdvertising);
NotifyBLEPeripheralAdvStopComplete(true, nullptr);
DeviceLayer::SystemLayer().ScheduleLambda(
[this] { DeviceLayer::SystemLayer().CancelTimer(HandleAdvertisingTimeout, this); });
}
if (mFlags.Has(Flags::kAdvertisingRefreshNeeded))
{
mFlags.Clear(Flags::kAdvertisingRefreshNeeded);
DeviceLayer::SystemLayer().ScheduleLambda([this] { DriveBLEState(); });
}
mAdvReqInProgress = false;
}
// ====== Private Functions.
void BLEManagerImpl::NotifyBLEPeripheralGATTServerRegisterComplete(bool aIsSuccess, void * apAppstate)
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kPlatformTizenBLEPeripheralGATTServerRegisterComplete;
event.Platform.BLEPeripheralGATTServerRegisterComplete.mIsSuccess = aIsSuccess;
event.Platform.BLEPeripheralGATTServerRegisterComplete.mpAppstate = apAppstate;
PlatformMgr().PostEventOrDie(&event);
}
void BLEManagerImpl::NotifyBLEPeripheralAdvConfiguredComplete(bool aIsSuccess, void * apAppstate)
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kPlatformTizenBLEPeripheralAdvConfiguredComplete;
event.Platform.BLEPeripheralAdvConfiguredComplete.mIsSuccess = aIsSuccess;
event.Platform.BLEPeripheralAdvConfiguredComplete.mpAppstate = apAppstate;
PlatformMgr().PostEventOrDie(&event);
}
void BLEManagerImpl::NotifyBLEPeripheralAdvStartComplete(bool aIsSuccess, void * apAppstate)
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kPlatformTizenBLEPeripheralAdvStartComplete;
event.Platform.BLEPeripheralAdvStartComplete.mIsSuccess = aIsSuccess;
event.Platform.BLEPeripheralAdvStartComplete.mpAppstate = apAppstate;
PlatformMgr().PostEventOrDie(&event);
}
void BLEManagerImpl::NotifyBLEPeripheralAdvStopComplete(bool aIsSuccess, void * apAppstate)
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kPlatformTizenBLEPeripheralAdvStopComplete;
event.Platform.BLEPeripheralAdvStopComplete.mIsSuccess = aIsSuccess;
event.Platform.BLEPeripheralAdvStopComplete.mpAppstate = apAppstate;
PlatformMgr().PostEventOrDie(&event);
}
void BLEManagerImpl::NotifyBLEWriteReceived(System::PacketBufferHandle & buf, BLE_CONNECTION_OBJECT conId)
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kCHIPoBLEWriteReceived;
event.CHIPoBLEWriteReceived.ConId = conId;
event.CHIPoBLEWriteReceived.Data = std::move(buf).UnsafeRelease();
PlatformMgr().PostEventOrDie(&event);
}
void BLEManagerImpl::NotifyBLENotificationReceived(System::PacketBufferHandle & buf, BLE_CONNECTION_OBJECT conId)
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kPlatformTizenBLEIndicationReceived;
event.Platform.BLEIndicationReceived.mConnection = conId;
event.Platform.BLEIndicationReceived.mData = std::move(buf).UnsafeRelease();
PlatformMgr().PostEventOrDie(&event);
}
void BLEManagerImpl::NotifyBLESubscribed(bool indicationsEnabled, BLE_CONNECTION_OBJECT conId)
{
ChipDeviceEvent event;
event.Type = (indicationsEnabled) ? DeviceEventType::kCHIPoBLESubscribe : DeviceEventType::kCHIPoBLEUnsubscribe;
event.CHIPoBLESubscribe.ConId = conId;
PlatformMgr().PostEventOrDie(&event);
}
void BLEManagerImpl::NotifyBLEIndicationConfirmation(BLE_CONNECTION_OBJECT conId)
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kCHIPoBLEIndicateConfirm;
event.CHIPoBLEIndicateConfirm.ConId = conId;
PlatformMgr().PostEventOrDie(&event);
}
void BLEManagerImpl::NotifyBLEConnectionEstablished(BLE_CONNECTION_OBJECT conId, CHIP_ERROR error)
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kCHIPoBLEConnectionEstablished;
PlatformMgr().PostEventOrDie(&event);
}
void BLEManagerImpl::NotifyBLEDisconnection(BLE_CONNECTION_OBJECT conId, CHIP_ERROR error)
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kCHIPoBLEConnectionError;
event.CHIPoBLEConnectionError.ConId = conId;
event.CHIPoBLEConnectionError.Reason = error;
PlatformMgr().PostEventOrDie(&event);
}
void BLEManagerImpl::NotifyHandleConnectFailed(CHIP_ERROR error)
{
ChipLogProgress(DeviceLayer, "Connection failed: %" CHIP_ERROR_FORMAT, error.Format());
if (mIsCentral)
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kPlatformTizenBLECentralConnectFailed;
event.Platform.BLECentralConnectFailed.mError = error;
PlatformMgr().PostEventOrDie(&event);
}
}
void BLEManagerImpl::NotifyHandleNewConnection(BLE_CONNECTION_OBJECT conId)
{
if (mIsCentral)
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kPlatformTizenBLECentralConnected;
event.Platform.BLECentralConnected.mConnection = conId;
PlatformMgr().PostEventOrDie(&event);
}
}
void BLEManagerImpl::NotifyHandleWriteComplete(BLE_CONNECTION_OBJECT conId)
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kPlatformTizenBLEWriteComplete;
event.Platform.BLEWriteComplete.mConnection = conId;
PlatformMgr().PostEventOrDie(&event);
}
void BLEManagerImpl::NotifySubscribeOpComplete(BLE_CONNECTION_OBJECT conId, bool isSubscribed)
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kPlatformTizenBLESubscribeOpComplete;
event.Platform.BLESubscribeOpComplete.mConnection = conId;
event.Platform.BLESubscribeOpComplete.mIsSubscribed = isSubscribed;
PlatformMgr().PostEventOrDie(&event);
}
void BLEManagerImpl::HandleConnectionTimeout(System::Layer *, void * appState)
{
auto * self = static_cast<BLEManagerImpl *>(appState);
self->NotifyHandleConnectFailed(CHIP_ERROR_TIMEOUT);
}
CHIP_ERROR BLEManagerImpl::ConnectChipThing(const char * address)
{
CHIP_ERROR err = CHIP_NO_ERROR;
int ret;
ChipLogProgress(DeviceLayer, "ConnectRequest: Addr [%s]", StringOrNullMarker(address));
ret = bt_gatt_client_create(address, &mGattClient);
VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to create GATT client: %s", get_error_message(ret));
err = TizenToChipError(ret));
ret = bt_gatt_connect(address, false);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "Failed to issue GATT connect request: %s", get_error_message(ret));
err = TizenToChipError(ret));
ChipLogProgress(DeviceLayer, "GATT Connect Issued");
exit:
if (err != CHIP_NO_ERROR)
NotifyHandleConnectFailed(err);
return err;
}
void BLEManagerImpl::OnChipDeviceScanned(void * device, const Ble::ChipBLEDeviceIdentificationInfo & info)
{
auto deviceInfo = reinterpret_cast<bt_adapter_le_device_scan_result_info_s *>(device);
VerifyOrReturn(deviceInfo != nullptr, ChipLogError(DeviceLayer, "Invalid Device Info"));
ChipLogProgress(DeviceLayer, "New device scanned: %s", deviceInfo->remote_address);
if (mBLEScanConfig.mBleScanState == BleScanState::kScanForDiscriminator)
{
if (!mBLEScanConfig.mDiscriminator.MatchesLongDiscriminator(info.GetDeviceDiscriminator()))
{
return;
}
ChipLogProgress(DeviceLayer, "Device discriminator match. Attempting to connect.");
}
else if (mBLEScanConfig.mBleScanState == BleScanState::kScanForAddress)
{
if (strcmp(deviceInfo->remote_address, mBLEScanConfig.mAddress.c_str()) != 0)
{
return;
}
ChipLogProgress(DeviceLayer, "Device address match. Attempting to connect.");
}
else
{
ChipLogError(DeviceLayer, "Unknown discovery type. Ignoring scanned device.");
return;
}
/* Set CHIP Connecting state */
mBLEScanConfig.mBleScanState = BleScanState::kConnecting;
chip::DeviceLayer::PlatformMgr().LockChipStack();
DeviceLayer::SystemLayer().StartTimer(kConnectTimeout, HandleConnectionTimeout, this);
chip::DeviceLayer::PlatformMgr().UnlockChipStack();
mDeviceScanner->StopChipScan();
/* Initiate Connect */
auto params = std::make_pair(this, deviceInfo->remote_address);
PlatformMgrImpl().GLibMatterContextInvokeSync(
+[](typeof(params) * aParams) { return aParams->first->ConnectChipThing(aParams->second); }, ¶ms);
}
void BLEManagerImpl::OnScanComplete()
{
switch (mBLEScanConfig.mBleScanState)
{
case BleScanState::kNotScanning:
ChipLogProgress(Ble, "Scan complete notification without an active scan.");
break;
case BleScanState::kScanForAddress:
case BleScanState::kScanForDiscriminator:
mBLEScanConfig.mBleScanState = BleScanState::kNotScanning;
ChipLogProgress(Ble, "Scan complete. No matching device found.");
break;
case BleScanState::kConnecting:
break;
}
}
void BLEManagerImpl::OnScanError(CHIP_ERROR err)
{
ChipLogDetail(Ble, "BLE scan error: %" CHIP_ERROR_FORMAT, err.Format());
}
CHIP_ERROR BLEManagerImpl::RegisterGATTServer()
{
bt_gatt_server_h server = nullptr;
bt_gatt_h service = nullptr;
bt_gatt_h char1 = nullptr, char2 = nullptr;
bt_gatt_h desc = nullptr;
char desc_value[2] = { 0, 0 };
int ret;
ChipLogProgress(DeviceLayer, "Start GATT Service Registration");
// Create Server
ret = bt_gatt_server_create(&server);
VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_create() failed: %s", get_error_message(ret)));
// Create Service (BTP Service)
ret = bt_gatt_service_create(Ble::CHIP_BLE_SERVICE_LONG_UUID_STR, BT_GATT_SERVICE_TYPE_PRIMARY, &service);
VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_service_create() failed: %s", get_error_message(ret)));
// Create 1st Characteristic (Client TX Buffer)
ret = bt_gatt_characteristic_create(
Ble::CHIP_BLE_CHAR_1_UUID_STR, BT_GATT_PERMISSION_WRITE,
BT_GATT_PROPERTY_WRITE, // Write Request is not coming if we use WITHOUT_RESPONSE property. Let's use WRITE property and
// consider to use WITHOUT_RESPONSE property in the future according to the CHIP Spec 4.16.3.2. BTP
// GATT Service
"CHIPoBLE_C1", strlen("CHIPoBLE_C1"), &char1);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_gatt_characteristic_create() failed: %s", get_error_message(ret)));
ret = bt_gatt_server_set_write_value_requested_cb(
char1,
+[](const char * remoteAddress, int requestId, bt_gatt_server_h gattServer, bt_gatt_h gattHandle, bool responseNeeded,
int offset, const char * value, int len, void * self) {
return reinterpret_cast<BLEManagerImpl *>(self)->WriteValueRequestedCb(remoteAddress, requestId, gattServer, gattHandle,
responseNeeded, offset, value, len);
},
this);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_gatt_server_set_write_value_requested_cb() failed: %s", get_error_message(ret)));
ret = bt_gatt_service_add_characteristic(service, char1);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_gatt_service_add_characteristic() failed: %s", get_error_message(ret)));
// Create 2nd Characteristic (Client RX Buffer)
ret = bt_gatt_characteristic_create(Ble::CHIP_BLE_CHAR_2_UUID_STR, BT_GATT_PERMISSION_READ,
BT_GATT_PROPERTY_READ | BT_GATT_PROPERTY_INDICATE, "CHIPoBLE_C2", strlen("CHIPoBLE_C2"),
&char2);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_gatt_characteristic_create() failed: %s", get_error_message(ret)));
ret = bt_gatt_server_set_read_value_requested_cb(
char2,
+[](const char * remoteAddress, int requestId, bt_gatt_server_h gattServer, bt_gatt_h gattHandle, int offset, void * self) {
return reinterpret_cast<BLEManagerImpl *>(self)->ReadValueRequestedCb(remoteAddress, requestId, gattServer, gattHandle,
offset);
},
this);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_gatt_server_set_read_value_requested_cb() failed: %s", get_error_message(ret)));
ret = bt_gatt_server_set_characteristic_notification_state_change_cb(
char2,
+[](bool notify, bt_gatt_server_h gattServer, bt_gatt_h charHandle, void * self) {
return reinterpret_cast<BLEManagerImpl *>(self)->NotificationStateChangedCb(notify, gattServer, charHandle);
},
this);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_gatt_server_set_characteristic_notification_state_change_cb() failed: %s",
get_error_message(ret)));
// Create CCC Descriptor
ret = bt_gatt_descriptor_create(Ble::CHIP_BLE_DESC_SHORT_UUID_STR, BT_GATT_PERMISSION_READ | BT_GATT_PERMISSION_WRITE,
desc_value, sizeof(desc_value), &desc);
VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_descriptor_create() failed: %s", get_error_message(ret)));
ret = bt_gatt_characteristic_add_descriptor(char2, desc);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_gatt_characteristic_add_descriptor() failed: %s", get_error_message(ret)));
ret = bt_gatt_service_add_characteristic(service, char2);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_gatt_service_add_characteristic() failed: %s", get_error_message(ret)));
// Register Service to Server
ret = bt_gatt_server_register_service(server, service);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_gatt_server_register_service() failed: %s", get_error_message(ret)));
// Start Server
ret = bt_gatt_server_start();
VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_start() failed: %s", get_error_message(ret)));
ChipLogDetail(DeviceLayer, "NotifyBLEPeripheralGATTServerRegisterComplete Success");
BLEManagerImpl::NotifyBLEPeripheralGATTServerRegisterComplete(true, nullptr);
// Save the Local Peripheral char1 & char2 handles
mGattCharC1Handle = char1;
mGattCharC2Handle = char2;
return CHIP_NO_ERROR;
exit:
ChipLogDetail(DeviceLayer, "NotifyBLEPeripheralGATTServerRegisterComplete Failed");
BLEManagerImpl::NotifyBLEPeripheralGATTServerRegisterComplete(false, nullptr);
return TizenToChipError(ret);
}
CHIP_ERROR BLEManagerImpl::StartBLEAdvertising()
{
Ble::ChipBLEDeviceIdentificationInfo deviceIdInfo;
auto intervals = GetAdvertisingIntervals();
PlatformVersion version;
CHIP_ERROR err;
int ret;
if (mAdvReqInProgress)
{
ChipLogProgress(DeviceLayer, "Advertising Request In Progress");
return CHIP_NO_ERROR;
}
ChipLogProgress(DeviceLayer, "Start Advertising");
if (mAdvertiser == nullptr)
{
ret = bt_adapter_le_create_advertiser(&mAdvertiser);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_adapter_le_create_advertiser() failed: %s", get_error_message(ret)));
}
else
{
ret = bt_adapter_le_clear_advertising_data(mAdvertiser, BT_ADAPTER_LE_PACKET_ADVERTISING);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_adapter_le_clear_advertising_data() failed: %s", get_error_message(ret)));
ret = bt_adapter_le_clear_advertising_data(mAdvertiser, BT_ADAPTER_LE_PACKET_SCAN_RESPONSE);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_adapter_le_clear_advertising_data() failed: %s", get_error_message(ret)));
}
ret = bt_adapter_le_set_advertising_interval(mAdvertiser, intervals.first, intervals.second);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_adapter_le_set_advertising_interval() failed: %s", get_error_message(ret)));
err = ConfigurationMgr().GetBLEDeviceIdentificationInfo(deviceIdInfo);
VerifyOrExit(err == CHIP_NO_ERROR,
ChipLogError(DeviceLayer, "GetBLEDeviceIdentificationInfo() failed: %" CHIP_ERROR_FORMAT, err.Format()));
ret = bt_adapter_le_add_advertising_service_data(mAdvertiser, BT_ADAPTER_LE_PACKET_ADVERTISING,
Ble::CHIP_BLE_SERVICE_SHORT_UUID_STR,
reinterpret_cast<const char *>(&deviceIdInfo), sizeof(deviceIdInfo));
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_adapter_le_add_advertising_service_data() failed: %s", get_error_message(ret)));
err = SystemInfo::GetPlatformVersion(version);
VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(DeviceLayer, "GetPlatformVersion() failed: %" CHIP_ERROR_FORMAT, err.Format()));
if (version.mMajor >= 8)
{
ret = bt_adapter_le_set_advertising_flags(
mAdvertiser, BT_ADAPTER_LE_ADVERTISING_FLAGS_GEN_DISC | BT_ADAPTER_LE_ADVERTISING_FLAGS_BREDR_UNSUP);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_adapter_le_set_advertising_flags() failed: %s", get_error_message(ret)));
}
else
{
ChipLogProgress(DeviceLayer, "setting function of advertising flags is available from tizen 7.5 or later");
}
ret = bt_adapter_le_set_advertising_device_name(mAdvertiser, BT_ADAPTER_LE_PACKET_ADVERTISING, true);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_adapter_le_set_advertising_device_name() failed: %s", get_error_message(ret)));
BLEManagerImpl::NotifyBLEPeripheralAdvConfiguredComplete(true, nullptr);
ret = bt_adapter_le_start_advertising_new(
mAdvertiser,
+[](int result, bt_advertiser_h advertiser, bt_adapter_le_advertising_state_e advState, void * self) {
return reinterpret_cast<BLEManagerImpl *>(self)->AdvertisingStateChangedCb(result, advertiser, advState);
},
this);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_adapter_le_start_advertising_new() failed: %s", get_error_message(ret)));
mAdvReqInProgress = true;
return CHIP_NO_ERROR;
exit:
BLEManagerImpl::NotifyBLEPeripheralAdvStartComplete(false, nullptr);
return ret != BT_ERROR_NONE ? TizenToChipError(ret) : err;
}
CHIP_ERROR BLEManagerImpl::StopBLEAdvertising()
{
ChipLogProgress(DeviceLayer, "Stop Advertising");
int ret = bt_adapter_le_stop_advertising(mAdvertiser);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_adapter_le_stop_advertising() failed: %s", get_error_message(ret)));
mAdvReqInProgress = true;
return CHIP_NO_ERROR;
exit:
BLEManagerImpl::NotifyBLEPeripheralAdvStopComplete(false, nullptr);
return TizenToChipError(ret);
}
static bool __GattClientForeachCharCb(int total, int index, bt_gatt_h charHandle, void * data)
{
bt_gatt_type_e type;
GAutoPtr<char> uuid;
auto conn = static_cast<BLEConnection *>(data);
int ret = __GetAttInfo(charHandle, &uuid.GetReceiver(), &type);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "Failed to fetch GATT Attribute from CHAR handle: %s", get_error_message(ret)));
if (strcasecmp(uuid.get(), Ble::CHIP_BLE_CHAR_1_UUID_STR) == 0)
{
ChipLogProgress(DeviceLayer, "CHIP Char C1 TX Found [%s]", StringOrNullMarker(uuid.get()));
conn->gattCharC1Handle = charHandle;
}
else if (strcasecmp(uuid.get(), Ble::CHIP_BLE_CHAR_2_UUID_STR) == 0)
{
ChipLogProgress(DeviceLayer, "CHIP Char C2 RX Found [%s]", StringOrNullMarker(uuid.get()));
conn->gattCharC2Handle = charHandle;
}
exit:
/* Try next Char UUID */
return true;
}
static bool __GattClientForeachServiceCb(int total, int index, bt_gatt_h svcHandle, void * data)
{
bt_gatt_type_e type;
GAutoPtr<char> uuid;
auto conn = static_cast<BLEConnection *>(data);
ChipLogProgress(DeviceLayer, "__GattClientForeachServiceCb");
int ret = __GetAttInfo(svcHandle, &uuid.GetReceiver(), &type);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "Failed to fetch GATT Attribute from SVC handle: %s", get_error_message(ret)));
if (strcasecmp(uuid.get(), chip::Ble::CHIP_BLE_SERVICE_LONG_UUID_STR) == 0)
{
ChipLogProgress(DeviceLayer, "CHIP Service UUID Found [%s]", StringOrNullMarker(uuid.get()));
if (bt_gatt_service_foreach_characteristics(svcHandle, __GattClientForeachCharCb, conn) == BT_ERROR_NONE)
conn->isChipDevice = true;
/* Got CHIP Device, no need to process further service */
return false;
}
exit:
/* Try next Service UUID */
return true;
}
bool BLEManagerImpl::IsDeviceChipPeripheral(BLE_CONNECTION_OBJECT conId)
{
int ret;
if ((ret = bt_gatt_client_foreach_services(mGattClient, __GattClientForeachServiceCb, conId)) != BT_ERROR_NONE)
ChipLogError(DeviceLayer, "Failed to browse GATT services: %s", get_error_message(ret));
return (conId->isChipDevice ? true : false);
}
void BLEManagerImpl::AddConnectionData(const char * remoteAddr)
{
BLEConnection * conn;
ChipLogProgress(DeviceLayer, "AddConnectionData for [%s]", StringOrNullMarker(remoteAddr));
if (!g_hash_table_lookup(mConnectionMap, remoteAddr))
{
ChipLogProgress(DeviceLayer, "Connection not found in map [%s]", StringOrNullMarker(remoteAddr));
conn = static_cast<BLEConnection *>(g_malloc0(sizeof(BLEConnection)));
conn->peerAddr = g_strdup(remoteAddr);
int ret;
if ((ret = bt_gatt_server_get_device_mtu(remoteAddr, &conn->mtu) != BT_ERROR_NONE))
{
ChipLogError(DeviceLayer, "Failed to get MTU for [%s]. ret: %s", StringOrNullMarker(remoteAddr),
get_error_message(ret));
}
if (mIsCentral)
{
/* Local Device is BLE Central Role */
if (IsDeviceChipPeripheral(conn))
{
g_hash_table_insert(mConnectionMap, conn->peerAddr, conn);
ChipLogProgress(DeviceLayer, "New Connection Added for [%s]", StringOrNullMarker(remoteAddr));
NotifyHandleNewConnection(conn);
}
else
{
__BLEConnectionFree(conn);
}
}
else
{
/* Local Device is BLE Peripheral Role, assume remote is CHIP Central */
conn->isChipDevice = true;
/* Save own gatt handles */
conn->gattCharC1Handle = mGattCharC1Handle;
conn->gattCharC2Handle = mGattCharC2Handle;
g_hash_table_insert(mConnectionMap, conn->peerAddr, conn);
ChipLogProgress(DeviceLayer, "New Connection Added for [%s]", StringOrNullMarker(remoteAddr));
}
}
}
void BLEManagerImpl::RemoveConnectionData(const char * remoteAddr)
{
BLEConnection * conn = nullptr;
ChipLogProgress(DeviceLayer, "Connection Remove Request for [%s]", StringOrNullMarker(remoteAddr));
VerifyOrReturn(mConnectionMap != nullptr, ChipLogError(DeviceLayer, "Connection map does not exist"));
conn = static_cast<BLEConnection *>(g_hash_table_lookup(mConnectionMap, remoteAddr));
VerifyOrReturn(conn != nullptr,
ChipLogError(DeviceLayer, "Connection does not exist for [%s]", StringOrNullMarker(remoteAddr)));
g_hash_table_remove(mConnectionMap, remoteAddr);
ChipLogProgress(DeviceLayer, "Connection Removed");
}
void BLEManagerImpl::HandleC1CharWriteEvent(BLE_CONNECTION_OBJECT conId, const uint8_t * value, size_t len)
{
CHIP_ERROR err = CHIP_NO_ERROR;
System::PacketBufferHandle buf;
ChipLogProgress(DeviceLayer, "Write request received for CHIPoBLE Client TX characteristic (data len %u)",
static_cast<unsigned int>(len));
// Copy the data to a packet buffer.
buf = System::PacketBufferHandle::NewWithData(value, len);
VerifyOrExit(!buf.IsNull(), err = CHIP_ERROR_NO_MEMORY);
NotifyBLEWriteReceived(buf, conId);
return;
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "HandleC1CharWriteEvent() failed: %s", ErrorStr(err));
}
}
void BLEManagerImpl::HandleRXCharChanged(BLE_CONNECTION_OBJECT conId, const uint8_t * value, size_t len)
{
CHIP_ERROR err = CHIP_NO_ERROR;
System::PacketBufferHandle buf;
ChipLogProgress(DeviceLayer, "Notification received on CHIPoBLE Client RX characteristic (data len %u)",
static_cast<unsigned int>(len));
// Copy the data to a packet buffer.
buf = System::PacketBufferHandle::NewWithData(value, len);
VerifyOrExit(!buf.IsNull(), err = CHIP_ERROR_NO_MEMORY);
NotifyBLENotificationReceived(buf, conId);
return;
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "HandleRXCharChanged() failed: %s", ErrorStr(err));
}
}
void BLEManagerImpl::HandleConnectionEvent(bool connected, const char * remoteAddress)
{
if (connected)
{
ChipLogProgress(DeviceLayer, "Device Connected [%s]", StringOrNullMarker(remoteAddress));
AddConnectionData(remoteAddress);
}
else
{
ChipLogProgress(DeviceLayer, "Device DisConnected [%s]", StringOrNullMarker(remoteAddress));
RemoveConnectionData(remoteAddress);
}
}
void BLEManagerImpl::DriveBLEState()
{
CHIP_ERROR err = CHIP_NO_ERROR;
ChipLogProgress(DeviceLayer, "Enter DriveBLEState");
if (!mIsCentral && mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !mFlags.Has(Flags::kAppRegistered))
{
err = RegisterGATTServer();
VerifyOrExit(err == CHIP_NO_ERROR,
ChipLogError(DeviceLayer, "Failed to register GATT server: %" CHIP_ERROR_FORMAT, err.Format()));
ChipLogProgress(DeviceLayer, "GATT server registered");
mFlags.Set(Flags::kAppRegistered);
ExitNow();
}
if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && mFlags.Has(Flags::kAdvertisingEnabled))
{
if (!mFlags.Has(Flags::kAdvertising))
{
err = StartBLEAdvertising();
VerifyOrExit(err == CHIP_NO_ERROR,
ChipLogError(DeviceLayer, "Failed to start BLE advertising: %" CHIP_ERROR_FORMAT, err.Format()));
}
else if (mFlags.Has(Flags::kAdvertisingRefreshNeeded))
{
ChipLogProgress(DeviceLayer, "BLE advertising refreshed needed. Stop BLE advertising");
err = StopBLEAdvertising();
VerifyOrExit(err == CHIP_NO_ERROR,
ChipLogError(DeviceLayer, "Failed to stop BLE advertising %" CHIP_ERROR_FORMAT, err.Format()));
}
}
else if (mFlags.Has(Flags::kAdvertising))
{
ChipLogProgress(DeviceLayer, "Stop BLE advertising");
err = StopBLEAdvertising();
VerifyOrExit(err == CHIP_NO_ERROR,
ChipLogError(DeviceLayer, "Failed to stop BLE advertising: %" CHIP_ERROR_FORMAT, err.Format()));
int ret = bt_adapter_le_destroy_advertiser(mAdvertiser);
VerifyOrExit(ret == BT_ERROR_NONE,
ChipLogError(DeviceLayer, "bt_adapter_le_destroy_advertiser() failed: %s", get_error_message(ret));
err = TizenToChipError(ret));
mAdvertiser = nullptr;
}
exit:
if (err != CHIP_NO_ERROR)
{
mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled;
}
}
CHIP_ERROR BLEManagerImpl::_Init()
{
CHIP_ERROR err;
err = BleLayer::Init(this, this, this, &DeviceLayer::SystemLayer());