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 #ifndef NAPI_BLUETOOTH_UTILS_H
16 #define NAPI_BLUETOOTH_UTILS_H
17
18 #include "bluetooth_gatt_client.h"
19 #include "bluetooth_gatt_descriptor.h"
20 #include "bluetooth_gatt_server.h"
21 #include "bluetooth_gatt_service.h"
22 #include "bluetooth_log.h"
23 #include "bluetooth_opp.h"
24 #include "bluetooth_remote_device.h"
25 #include "napi/native_api.h"
26 #include "napi/native_node_api.h"
27
28 #include <atomic>
29 #include <condition_variable>
30 #include <mutex>
31 #include <cstdint>
32 #include <string>
33 #include <vector>
34
35 #include "uv.h"
36
37 #include "bluetooth_socket.h"
38
39 namespace OHOS {
40 namespace Bluetooth {
41 constexpr size_t CALLBACK_SIZE = 1;
42 constexpr size_t ARGS_SIZE_ZERO = 0;
43 constexpr size_t ARGS_SIZE_ONE = 1;
44 constexpr size_t ARGS_SIZE_TWO = 2;
45 constexpr size_t ARGS_SIZE_THREE = 3;
46 constexpr size_t ARGS_SIZE_FOUR = 4;
47 constexpr int32_t DEFAULT_INT32 = 0;
48 constexpr int32_t PARAM0 = 0;
49 constexpr int32_t PARAM1 = 1;
50 constexpr int32_t PARAM2 = 2;
51 constexpr int32_t CODE_SUCCESS = 0;
52 constexpr int32_t CODE_FAILED = -1;
53 constexpr int ASYNC_IDLE = 0;
54 constexpr int ASYNC_START = 1;
55 constexpr int ASYNC_DONE = 2;
56 constexpr int32_t THREAD_WAIT_TIMEOUT = 5;
57 constexpr int32_t BLUETOOTH_DEVICE_FIND_TYPE = 1;
58 constexpr int32_t STATE_CHANGE_TYPE = 2;
59 constexpr int32_t PIN_REQUEST_TYPE = 3;
60 constexpr int32_t BOND_STATE_CHANGE_TYPE = 4;
61 constexpr int32_t BLE_DEVICE_FIND_TYPE = 5;
62
63 constexpr uint32_t INVALID_REF_COUNT = 0xFF;
64
65 struct ServerResponse {
66 std::string deviceId = "";
67 int transId = 0;
68 int status = 0;
69 int offset = 0;
70 uint8_t *value = nullptr;
71 int length = 0;
SetValueServerResponse72 void SetValue(uint8_t *values, size_t len)
73 {
74 HILOGI("GattCharacteristic::SetValue starts");
75 if (value != nullptr) {
76 value = nullptr;
77 }
78
79 length = static_cast<int>(len);
80 value = values;
81 }
82 };
83
84 struct SppOption {
85 std::string uuid_ = "";
86 bool secure_ = false;
87 BtSocketType type_;
88 };
89
90 const char * const REGISTER_STATE_CHANGE_TYPE = "stateChange";
91
92 const char * const INVALID_DEVICE_ID = "00:00:00:00:00:00";
93
94 bool ParseString(napi_env env, std::string ¶m, napi_value args);
95 bool ParseInt32(napi_env env, int32_t ¶m, napi_value args);
96 bool ParseBool(napi_env env, bool ¶m, napi_value args);
97 bool ParseArrayBuffer(napi_env env, uint8_t **data, size_t &size, napi_value args);
98 napi_value GetCallbackErrorValue(napi_env env, int errCode);
99
100 napi_status ConvertStringVectorToJS(napi_env env, napi_value result, std::vector<std::string> &stringVector);
101 void ConvertStateChangeParamToJS(napi_env env, napi_value result, const std::string &device, int state, int cause);
102 void ConvertScoStateChangeParamToJS(napi_env env, napi_value result, const std::string &device, int state);
103 void ConvertUuidsVectorToJS(napi_env env, napi_value result, const std::vector<std::string> &uuids);
104 napi_status ConvertOppTransferInformationToJS(napi_env env,
105 napi_value result, const BluetoothOppTransferInformation& transferInformation);
106
107 std::shared_ptr<SppOption> GetSppOptionFromJS(napi_env env, napi_value object);
108
109 void SetNamedPropertyByInteger(napi_env env, napi_value dstObj, int32_t objName, const char *propName);
110 void SetNamedPropertyByString(napi_env env, napi_value dstObj, const std::string &strValue, const char *propName);
111 napi_value NapiGetNull(napi_env env);
112 napi_value NapiGetBooleanFalse(napi_env env);
113 napi_value NapiGetBooleanTrue(napi_env env);
114 napi_value NapiGetBooleanRet(napi_env env, bool ret);
115 napi_value NapiGetUndefinedRet(napi_env env);
116 napi_value NapiGetInt32Ret(napi_env env, int32_t res);
117
118 int GetProfileConnectionState(int state);
119 int GetScoConnectionState(int state);
120 uint32_t GetProfileId(int profile);
121
122 struct AsyncCallbackInfo {
123 napi_env env_;
124 napi_async_work asyncWork_;
125 napi_deferred deferred_;
126 napi_ref callback_ = 0;
127 int errorCode_ = 0;
128 };
129
130 struct BluetoothCallbackInfo {
131 napi_env env_;
132 napi_ref callback_ = 0;
133 int state_;
134 std::string deviceId_;
135 int info_;
136 };
137
138 struct PairConfirmedCallBackInfo {
139 int number;
140 int pinType;
141 std::string deviceAddr;
142
PairConfirmedCallBackInfoPairConfirmedCallBackInfo143 PairConfirmedCallBackInfo(int number, int pinType, std::string deviceAddr)
144 {
145 this->number = number;
146 this->pinType = pinType;
147 this->deviceAddr = deviceAddr;
148 }
149 };
150
151 struct TransforInformationCallbackInfo : public BluetoothCallbackInfo {
152 std::shared_ptr<BluetoothOppTransferInformation> information_;
153 };
154
155 namespace {
156 using sysBLEMap = std::map<std::string, std::array<std::shared_ptr<BluetoothCallbackInfo>, ARGS_SIZE_THREE>>;
157 sysBLEMap g_sysBLEObserver;
158 std::mutex g_sysBLEObserverMutex;
159 std::map<std::string, std::shared_ptr<BluetoothCallbackInfo>> g_Observer;
160 std::mutex g_observerMutex;
161 } // namespace
162 std::map<std::string, std::shared_ptr<BluetoothCallbackInfo>> GetObserver();
163 const sysBLEMap &GetSysBLEObserver();
164
165 void RegisterSysBLEObserver(const std::shared_ptr<BluetoothCallbackInfo> &, int32_t, const std::string &);
166 void UnregisterSysBLEObserver(const std::string &);
167 std::shared_ptr<BluetoothCallbackInfo> GetCallbackInfoByType(const std::string &type);
168
169 struct ScanFilter {
170 std::string deviceId; // The name of a BLE peripheral device
171 std::string name; // The name of a BLE peripheral device
172 UUID serviceUuid; // The service UUID of a BLE peripheral device
173 UUID serviceUuidMask;
174 UUID serviceSolicitationUuid;
175 UUID serviceSolicitationUuidMask;
176
177 std::vector<uint8_t> serviceData;
178 std::vector<uint8_t> serviceDataMask;
179
180 uint16_t manufacturerId = 0;
181 std::vector<uint8_t> manufactureData;
182 std::vector<uint8_t> manufactureDataMask;
183 };
184
185 enum class MatchMode {
186 MATCH_MODE_AGGRESSIVE = 1, // aggressive mode
187 MATCH_MODE_STICKY = 2 // sticky mode
188 };
189
190 enum class ScanDuty {
191 SCAN_MODE_LOW_POWER = 0, // low power mode */
192 SCAN_MODE_BALANCED = 1, // balanced power mode
193 SCAN_MODE_LOW_LATENCY = 2 // Scan using highest duty cycle
194 };
195
196 enum class PhyType {
197 PHY_LE_1M = 1, // phy 1M
198 PHY_LE_2M = 2, // phy 2M
199 PHY_LE_CODED = 3, // phy coded
200 PHY_LE_ALL_SUPPORTED = 255 // phy coded
201 };
202
203 enum class AdvertisingState {
204 STARTED = 1, // advertiser started
205 ENABLED = 2, // advertiser temporarily enabled
206 DISABLED = 3, // advertiser temporarily disabled
207 STOPPED = 4 // advertiser stopped
208 };
209
210 // Report mode used during scan.
211 enum class ScanReportMode {
212 NORMAL = 1
213 };
214
215 enum class ScanReportType {
216 ON_FOUND = 1, // the found of advertisement packet
217 ON_LOST = 2 // the lost of advertisement packet
218 };
219
220 struct ScanOptions {
221 int32_t interval = 0; // Time of delay for reporting the scan result
222 ScanDuty dutyMode = ScanDuty::SCAN_MODE_LOW_POWER; // Bluetooth LE scan mode
223 MatchMode matchMode = MatchMode::MATCH_MODE_AGGRESSIVE; // Match mode for Bluetooth LE scan filters hardware match
224 PhyType phyType = PhyType::PHY_LE_1M; // Phy for Bluetooth LE scan
225 ScanReportMode reportMode = ScanReportMode::NORMAL; // Scan report mode
226 };
227
228 struct ScanResult {
229 std::string deviceId; // Address of the scanned device
230 int32_t rssi; // RSSI of the remote device
231 std::vector<uint8_t> data; // The raw data of broadcast packet
232 };
233
234 struct ScanReport {
235 ScanReportType reportType;
236 std::vector<ScanResult> scanResult;
237 };
238
239 struct NapiAdvManufactureData {
240 uint16_t id = 0;
241 std::string value {};
242 };
243
244 struct NapiAdvServiceData {
245 std::string uuid {};
246 std::vector<uint8_t> value {};
247 };
248
249 struct NapiNotifyCharacteristic {
250 UUID serviceUuid;
251 UUID characterUuid;
252 std::vector<uint8_t> characterValue {};
253 bool confirm;
254 };
255
256 struct NapiGattsServerResponse {
257 std::string deviceId {};
258 int transId;
259 int status;
260 int offset;
261 std::vector<uint8_t> value;
262 };
263
264 enum ProfileConnectionState {
265 STATE_DISCONNECTED = 0, // the current profile is disconnected
266 STATE_CONNECTING = 1, // the current profile is being connected
267 STATE_CONNECTED = 2, // the current profile is connected
268 STATE_DISCONNECTING = 3 // the current profile is being disconnected
269 };
270
271 enum ScoState {
272 SCO_DISCONNECTED,
273 SCO_CONNECTING,
274 SCO_DISCONNECTING,
275 SCO_CONNECTED
276 };
277
278 enum ConnectionStrategy {
279 CONNECTION_UNKNOWN = 0,
280 CONNECTION_ALLOWED = 1,
281 CONNECTION_FORBIDDEN = 2,
282 };
283
284 enum MajorClass {
285 MAJOR_MISC = 0x0000,
286 MAJOR_COMPUTER = 0x0100,
287 MAJOR_PHONE = 0x0200,
288 MAJOR_NETWORKING = 0x0300,
289 MAJOR_AUDIO_VIDEO = 0x0400,
290 MAJOR_PERIPHERAL = 0x0500,
291 MAJOR_IMAGING = 0x0600,
292 MAJOR_WEARABLE = 0x0700,
293 MAJOR_TOY = 0x0800,
294 MAJOR_HEALTH = 0x0900,
295 MAJOR_UNCATEGORIZED = 0x1F00
296 };
297
298 enum MajorMinorClass {
299 // The Minor Device Class field
300 // Computer Major Class
301 COMPUTER_UNCATEGORIZED = 0x0100,
302 COMPUTER_DESKTOP = 0x0104,
303 COMPUTER_SERVER = 0x0108,
304 COMPUTER_LAPTOP = 0x010C,
305 COMPUTER_HANDHELD_PC_PDA = 0x0110,
306 COMPUTER_PALM_SIZE_PC_PDA = 0x0114,
307 COMPUTER_WEARABLE = 0x0118,
308 COMPUTER_TABLET = 0x011C,
309
310 // Phone Major Class
311 PHONE_UNCATEGORIZED = 0x0200,
312 PHONE_CELLULAR = 0x0204,
313 PHONE_CORDLESS = 0x0208,
314 PHONE_SMART = 0x020C,
315 PHONE_MODEM_OR_GATEWAY = 0x0210,
316 PHONE_ISDN = 0x0214,
317
318 // LAN/Network Access Point Major Class
319 NETWORK_FULLY_AVAILABLE = 0x0300,
320 NETWORK_1_TO_17_UTILIZED = 0x0320,
321 NETWORK_17_TO_33_UTILIZED = 0x0340,
322 NETWORK_33_TO_50_UTILIZED = 0x0360,
323 NETWORK_60_TO_67_UTILIZED = 0x0380,
324 NETWORK_67_TO_83_UTILIZED = 0x03A0,
325 NETWORK_83_TO_99_UTILIZED = 0x03C0,
326 NETWORK_NO_SERVICE = 0x03E0,
327
328 // Audio/Video Major Class
329 AUDIO_VIDEO_UNCATEGORIZED = 0x0400,
330 AUDIO_VIDEO_WEARABLE_HEADSET = 0x0404,
331 AUDIO_VIDEO_HANDSFREE = 0x0408,
332 AUDIO_VIDEO_MICROPHONE = 0x0410,
333 AUDIO_VIDEO_LOUDSPEAKER = 0x0414,
334 AUDIO_VIDEO_HEADPHONES = 0x0418,
335 AUDIO_VIDEO_PORTABLE_AUDIO = 0x041C,
336 AUDIO_VIDEO_CAR_AUDIO = 0x0420,
337 AUDIO_VIDEO_SET_TOP_BOX = 0x0424,
338 AUDIO_VIDEO_HIFI_AUDIO = 0x0428,
339 AUDIO_VIDEO_VCR = 0x042C,
340 AUDIO_VIDEO_VIDEO_CAMERA = 0x0430,
341 AUDIO_VIDEO_CAMCORDER = 0x0434,
342 AUDIO_VIDEO_VIDEO_MONITOR = 0x0438,
343 AUDIO_VIDEO_VIDEO_DISPLAY_AND_LOUDSPEAKER = 0x043C,
344 AUDIO_VIDEO_VIDEO_CONFERENCING = 0x0440,
345 AUDIO_VIDEO_VIDEO_GAMING_TOY = 0x0448,
346
347 // Peripheral Major Class
348 PERIPHERAL_NON_KEYBOARD_NON_POINTING = 0x0500,
349 PERIPHERAL_KEYBOARD = 0x0540,
350 PERIPHERAL_POINTING_DEVICE = 0x0580,
351 PERIPHERAL_KEYBOARD_POINTING = 0x05C0,
352 PERIPHERAL_UNCATEGORIZED = 0x0500,
353 PERIPHERAL_JOYSTICK = 0x0504,
354 PERIPHERAL_GAMEPAD = 0x0508,
355 PERIPHERAL_REMOTE_CONTROL = 0x05C0,
356 PERIPHERAL_SENSING_DEVICE = 0x0510,
357 PERIPHERAL_DIGITIZER_TABLET = 0x0514,
358 PERIPHERAL_CARD_READER = 0x0518,
359 PERIPHERAL_DIGITAL_PEN = 0x051C,
360 PERIPHERAL_SCANNER_RFID = 0x0520,
361 PERIPHERAL_GESTURAL_INPUT = 0x0522,
362
363 // Imaging Major Class
364 IMAGING_UNCATEGORIZED = 0x0600,
365 IMAGING_DISPLAY = 0x0610,
366 IMAGING_CAMERA = 0x0620,
367 IMAGING_SCANNER = 0x0640,
368 IMAGING_PRINTER = 0x0680,
369
370 // Wearable Major Class
371 WEARABLE_UNCATEGORIZED = 0x0700,
372 WEARABLE_WRIST_WATCH = 0x0704,
373 WEARABLE_PAGER = 0x0708,
374 WEARABLE_JACKET = 0x070C,
375 WEARABLE_HELMET = 0x0710,
376 WEARABLE_GLASSES = 0x0714,
377
378 // Minor Device Class field - Toy Major Class
379 TOY_UNCATEGORIZED = 0x0800,
380 TOY_ROBOT = 0x0804,
381 TOY_VEHICLE = 0x0808,
382 TOY_DOLL_ACTION_FIGURE = 0x080C,
383 TOY_CONTROLLER = 0x0810,
384 TOY_GAME = 0x0814,
385
386 // Minor Device Class field - Health
387 HEALTH_UNCATEGORIZED = 0x0900,
388 HEALTH_BLOOD_PRESSURE = 0x0904,
389 HEALTH_THERMOMETER = 0x0908,
390 HEALTH_WEIGHING = 0x090C,
391 HEALTH_GLUCOSE = 0x0910,
392 HEALTH_PULSE_OXIMETER = 0x0914,
393 HEALTH_PULSE_RATE = 0x0918,
394 HEALTH_DATA_DISPLAY = 0x091C,
395 HEALTH_STEP_COUNTER = 0x0920,
396 HEALTH_BODY_COMPOSITION_ANALYZER = 0x0924,
397 HEALTH_PEAK_FLOW_MOITOR = 0x0928, // HEALTH_PEAK_FLOW_MOITOR is compatible with api8.
398 HEALTH_PEAK_FLOW_MONITOR = 0x0928,
399 HEALTH_MEDICATION_MONITOR = 0x092C,
400 HEALTH_KNEE_PROSTHESIS = 0x0930,
401 HEALTH_ANKLE_PROSTHESIS = 0x0934,
402 HEALTH_GENERIC_HEALTH_MANAGER = 0x0938,
403 HEALTH_PERSONAL_MOBILITY_DEVICE = 0x093C,
404 };
405
406 enum SppType {
407 /** RFCOMM */
408 SPP_RFCOMM = 0
409 };
410
411 enum PlayingState {
412 STATE_NOT_PLAYING = 0,
413 STATE_PLAYING = 1
414 };
415
416 enum ProfileId {
417 PROFILE_A2DP_SINK = 0,
418 PROFILE_A2DP_SOURCE = 1,
419 PROFILE_AVRCP_CT = 2,
420 PROFILE_AVRCP_TG = 3,
421 PROFILE_HANDS_FREE_AUDIO_GATEWAY = 4,
422 PROFILE_HANDS_FREE_UNIT = 5,
423 PROFILE_HID_HOST = 6,
424 PROFILE_PAN_NETWORK = 7,
425 PROFILE_PBAP_CLIENT = 8,
426 PROFILE_PBAP_SERVER = 9,
427 PROFILE_OPP = 10
428 };
429
430 enum AccessAuthorization {
431 UNKNOWN = 0,
432 ALLOWED = 1,
433 REJECTED = 2,
434 };
435
436 template<typename T1, typename T2, typename T3>
437 struct AfterWorkCallbackData {
438 T1* object;
439 T2 function;
440 napi_env env;
441 napi_ref callback;
442 T3 data;
443 };
444
445 template<typename T>
AfterWorkCallback(uv_work_t * work,int status)446 void AfterWorkCallback(uv_work_t *work, int status)
447 {
448 if (work == nullptr) {
449 return;
450 }
451 T data = static_cast<T>(work->data);
452 if (data == nullptr) {
453 return;
454 }
455 (data->object->*(data->function))(work, data->data);
456 if (work->data != nullptr) {
457 delete data;
458 work->data = nullptr;
459 }
460 delete work;
461 work = nullptr;
462 }
463
464 #define NAPI_BT_CALL_RETURN(func) \
465 do { \
466 napi_status ret = (func); \
467 if (ret != napi_ok) { \
468 HILOGE("napi call function failed. ret:%{public}d", ret); \
469 return ret; \
470 } \
471 } while (0)
472
473 #define NAPI_BT_RETURN_IF(condition, msg, ret) \
474 do { \
475 if ((condition)) { \
476 HILOGE(msg); \
477 return (ret); \
478 } \
479 } while (0)
480
481 int DoInJsMainThread(napi_env env, std::function<void(void)> func);
482
483 bool IsValidAddress(std::string bdaddr);
484 bool IsValidTransport(int transport);
485 bool IsValidConnectStrategy(int strategy);
486 napi_status NapiIsBoolean(napi_env env, napi_value value);
487 napi_status NapiIsNumber(napi_env env, napi_value value);
488 napi_status NapiIsString(napi_env env, napi_value value);
489 napi_status NapiIsFunction(napi_env env, napi_value value);
490 napi_status NapiIsArray(napi_env env, napi_value value);
491 napi_status NapiIsArrayBuffer(napi_env env, napi_value value);
492 napi_status NapiIsObject(napi_env env, napi_value value);
493 napi_status ParseNumberParams(napi_env env, napi_value object, const char *name, bool &outExist, napi_value &outParam);
494 napi_status ParseInt32Params(napi_env env, napi_value object, const char *name, bool &outExist, int32_t &outParam);
495 napi_status ParseUint32Params(napi_env env, napi_value object, const char *name, bool &outExist, uint32_t &outParam);
496 napi_status ParseBooleanParams(napi_env env, napi_value object, const char *name, bool &outExist, bool &outParam);
497 napi_status ParseStringParams(napi_env env, napi_value object, const char *name, bool &outExist,
498 std::string &outParam);
499 napi_status ParseArrayBufferParams(napi_env env, napi_value object, const char *name, bool &outExist,
500 std::vector<uint8_t> &outParam);
501 napi_status ParseUuidParams(napi_env env, napi_value object, const char *name, bool &outExist, UUID &outUuid);
502
503 bool CheckDeivceIdParam(napi_env env, napi_callback_info info, std::string &addr);
504 bool CheckProfileIdParam(napi_env env, napi_callback_info info, int &profileId);
505 bool CheckProfileIdParamEx(napi_env env, napi_callback_info info, int &profileId, size_t &argc);
506 bool CheckSetDevicePairingConfirmationParam(napi_env env, napi_callback_info info, std::string &addr, bool &accept);
507 bool CheckLocalNameParam(napi_env env, napi_callback_info info, std::string &name);
508 bool CheckSetBluetoothScanModeParam(napi_env env, napi_callback_info info, int32_t &mode, int32_t &duration);
509 napi_status CheckEmptyParam(napi_env env, napi_callback_info info);
510 napi_status NapiCheckObjectPropertiesName(napi_env env, napi_value object, const std::vector<std::string> &names);
511 napi_status CheckSetConnectStrategyParam(napi_env env, napi_callback_info info, std::string &addr, int32_t &strategy);
512 napi_status CheckDeviceAddressParam(napi_env env, napi_callback_info info, std::string &addr);
513 napi_status CheckAccessAuthorizationParam(napi_env env, napi_callback_info info, std::string &addr,
514 int32_t &accessAuthorization);
515 napi_status NapiGetOnOffCallbackName(napi_env env, napi_callback_info info, std::string &name);
516 } // namespace Bluetooth
517 } // namespace OHOS
518 #endif // NAPI_BLUETOOTH_UTILS_H
519