rusel1989 / react-native-bluetooth-serial

Port of https://github.com/don/BluetoothSerial for react native
475 stars 291 forks source link

Receiving messages from bluetooth device #125

Open ramacha7 opened 3 years ago

ramacha7 commented 3 years ago

I wanted to know how I could receive a message from a Bluetooth device. Currently I am using a Bluetooth module that can be used to communicate between a microcontroller and an App I have created. I wanted to test sending a message from the microcontroller to the app. I was wondering how I could receive the message? I have seen in the RCTBluetoothSerialModule.java file you can read with events like BluetoothSerial.on("read"). I was wondering if there were any examples I could use to figure out how to actually implement reading data from a device

akshay1788 commented 3 years ago

If 'msg' is your state that is going to hold received data, then add these lines in your UNSAFE_componentWillMount() -

BluetoothSerial.withDelimiter('\n').then(() => { Promise.all([ BluetoothSerial.isEnabled(), BluetoothSerial.list(), ]).then(values => { const [isEnabled, devices] = values; this.setState({ devices }); }); BluetoothSerial.on('read', data => { this.setState({msg: data.data}) }); });

Make sure you use correct delimiter while sending data from microcontroller.