This repository was archived by the owner on Jan 3, 2020. It is now read-only.
forked from jhonber/react-native-bluetooth-serial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
46 lines (41 loc) · 1.42 KB
/
index.js
File metadata and controls
46 lines (41 loc) · 1.42 KB
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
const ReactNative = require('react-native')
const { Buffer } = require('buffer')
const { NativeModules, DeviceEventEmitter } = ReactNative
const BluetoothSerial = NativeModules.BluetoothSerial
/**
* Listen for available events
* @param {String} eventName Name of event one of connectionSuccess, connectionLost, data, rawData
* @param {Function} handler Event handler
*/
BluetoothSerial.on = (eventName, handler) => {
DeviceEventEmitter.addListener(eventName, handler)
}
/**
* Stop listening for event
* @param {String} eventName Name of event one of connectionSuccess, connectionLost, data, rawData
* @param {Function} handler Event handler
*/
BluetoothSerial.removeListener = (eventName, handler) => {
DeviceEventEmitter.removeListener(eventName, handler)
}
/**
* Write data to device, you can pass string or buffer,
* We must convert to base64 in RN there is no way to pass buffer directly
* @param {Buffer|String} data
* @return {Promise<Boolean>}
*/
BluetoothSerial.write = (data) => {
if (typeof data === 'string') {
data = new Buffer(data)
}
return BluetoothSerial.writeToDevice(data.toString('base64'))
}
/**
* Read all the data currently in the buffer.
* We must convert to base64 in RN there is no way to pass buffer directly
* @return {Promise<Buffer>}
*/
BluetoothSerial.read = async () => {
return Buffer.from(await BluetoothSerial.readFromDevice(), 'base64');
}
module.exports = BluetoothSerial