Transfer information through the react-native-ble-plx module

To initiate a project involving connected devices, I must establish a Bluetooth connection among the different devices.

The objective is to develop an application using React Native and then transmit data from this application to my Raspberry Pi. The Raspberry Pi is equipped with an HC-08 module responsible for managing Bluetooth communication.

Currently, I am looking into utilizing the react-native-ble-plx library to facilitate data transmission via Bluetooth. While I have successfully established a connection between my Android device and the module, I am struggling to comprehend the process of sending data...

Here is the code snippet I am working with:

constructor() {
        super()
        this.manager = new BleManager()
    }
    componentWillMount() {
        console.log("mounted")
        const subscription = this.manager.onStateChange((state) => {
            if (state === 'PoweredOn') {
                this.scanAndConnect();
                subscription.remove();
            }
        }, true);
    }

    scanAndConnect() {
        this.manager.startDeviceScan(null, null, (error, device) => {
            if (error) {
                // Handle error (scanning will be stopped automatically)
                return
            }

            console.log(device.name)

            if (device.name === 'SH-HC-08') {
                this.manager.stopDeviceScan();
                console.log(`Found ${device.name}`)
                this.setState({
                    device: device
                })
                device.connect()
                    .then((device) => {
                        console.log(device)
                        return device.discoverAllServicesAndCharacteristics()
                    })
                    .then((device) => {
                        console.log(device)
                    })
                    .then((result) => {
                        console.log(result)
                        console.log("connected")
                    })
                    .catch((error) => {
                        console.log(error)
                    });
            }
        });
    }

    send() {
        this.manager.writeCharacteristicWithResponseForDevice("58:7A:62:4F:EF:6D",
            this.device.serviceUUIDs[0],
            this.manager.characteristicsForDevice(this.device.id),
            "ok")
            .catch((error) => {
                console.log('error in writing data');
                console.log(error);
            })
    }

I am seeking assistance in creating a send method that can efficiently transmit data as needed. If anyone could provide guidance or offer an example, I would greatly appreciate it.

Many thanks in advance.

Answer №1

I successfully incorporated the following in my code:

scanAndConnect() {
    this.manager.startDeviceScan(null, null, (error, device) => {
      this.info("Scanning...");
      console.log(device);

      if (error) {
        this.error(error.message);
        return
      }

      if (device.name ==='MyDevice') {
        this.info("Connecting to Tappy");
        this.manager.stopDeviceScan();

        device.connect()
          .then((device) => {
            this.info("Discovering services and characteristics");
            return device.discoverAllServicesAndCharacteristics()
          })
          .then((device) => {
            this.info(device.id);
            device.writeCharacteristicWithResponseForService('12ab', '34cd', 'aGVsbG8gbWlzcyB0YXBweQ==')
              .then((characteristic) => {
                this.info(characteristic.value);
                return 
              })
          })
          .catch((error) => {
            this.error(error.message)
          })
       }
   });

Make sure to replace 12ab with the UUID of your BLE service, 34cd with the UUID of your BLE characteristic, and use base64 encoding for the message you want to send instead of aGVsbG8gbWlzcyB0YXBweQ==.

I hope this information is useful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The optimal method for designing a select menu to ensure it works smoothly on various web browsers

Recently, I encountered an issue with customizing a select menu using CSS and jQuery. After some work, I was able to achieve a result that I am quite pleased with: So far, the styling works perfectly in Mozilla, Opera, Chrome, and IE7+. Below is the curr ...

Monitor and adjust variables simultaneously using AngularJS

My goal is to dynamically calculate and display values based on two other variables in real time. I've successfully managed to track one variable, but not both simultaneously. $scope.color_slider_bar = { value:0, minValue: 0, maxValue: ...

add text nodes with unnecessary quotation marks around my selection list

Looking to incorporate a select list into my website using a button. I must utilize nodes for access within the DOM to retrieve its value later, so innerHTML isn't an option. Experiencing difficulty as createTextNode seems to encase my list in quota ...

Sorting arrays can yield varying results depending on the browser being used

The variations in output between Chrome 70.0, Chrome 69.0, and Firefox 63.0 for the same code are puzzling. var arr = [1,2,43,1233,5546,33,6,11]; arr.sort(() => -1); //[11, 6, 33, 5546, 1233, 43, 2, 1] arr.sort(() => 1); //[1, 2, 43, 1233, 5546, 33, ...

Why does the React Native webview shut down when the app is minimized on Android devices?

Hey there! I've got an app that opens a webview and everything is working perfectly. The only issue I'm facing is when the app goes into the background, it closes the webview and shows the landing screen instead. I'm currently exploring ways ...

Control the line height in DataTables

Is there a way to adjust the line height for a tr using either DataTables settings or CSS? I've attempted different methods, but nothing seems to change the line-height. https://i.sstatic.net/GwFaD.png Table CSS ...

Preventing CORS problems when a web application imports JavaScript modules from different domains

Currently, I am in the process of developing a web application using NodeJS. The application is divided into a back-end responsible for handling database queries with MongoDB, and a front end built on a Node-based web server that utilizes interactjs alongs ...

Get your hands on large files with ease by utilizing jQuery or exploring alternative methods

Within my User Interface, there exists an Advanced Search section where the user can select from 7 different options as depicted in the diagram. Based on these selections, a web service is triggered. This web service returns search results in JSON format, ...

What is the best way to incorporate progressive JPEG images onto a website?

I am currently working on a website called winni.in that is built using Java, Html, and Javascript. I would like to incorporate progressive image rendering upon page load, but I lack the necessary knowledge. I have come across and explored the following re ...

Using ajax to submit a request to the controller

I'm currently developing an ASP.NET Core MVC application and have a registration page set up. My goal is to return View with errors if the model state is false: @model WebApplication2PROP.Entities.UserRegister @* For more information on enabling M ...

Utilize Jquery to extract HTML content from an array of links and implement regular expressions

Currently, I am embarking on the journey of developing a Google Chrome extension despite my limited experience in this field. My aim is to create a tool that can identify individuals who have left reviews on Amazon products. Specifically, I am looking to l ...

What is the best way to loop through an object and show each item in its own row?

My goal is to loop through an object where each item has a type property. The objective is to iterate through the objects and display them in rows based on their type. Currently, it looks like this: https://i.sstatic.net/8iTtG.png I aim to have Frontend, ...

I am currently in the process of creating an application that utilizes two types of users - an admin and a client. However, I am experiencing difficulties with the login functionality for both users. The application is being developed using React Native

I am facing difficulty in showing different screens based on the login users as I cannot seem to login successfully for either user. Here is the code snippet for my login screen: const SignIn = ({ navigation }) => { const [user, setUser] = useState(n ...

Using Vue JS to apply a filter to data fetched from an API

Within my code, I attempted to retrieve users with the role of Admin and only their usernames from the API JSON data. However, I encountered an issue where it did not work as expected. "response": [ { "profil ...

The dynamic combination of jCarousel, jQuery Accordion, and fade in effects

Take a look at this link www.aboud-creative.com/demos/mckinley3. You'll find a jQuery Accordion with jCarousel inside the "Developments" section. I have implemented a standard fadeIn function for the logo, accordion, and a stag on the bottom right to ...

Toggling checkboxes using Angular framework

Within my form, there is a table with checkboxes in each column. The table consists of 3 <tr> elements, and each <tr> uses ng-repeate to call the webservice and display clone data (in JSON format). Upon clicking a checkbox, I create a JavaScrip ...

"Struggling to make the 'overflow: hidden' property work for an absolutely positioned

I'm struggling to conceal an absolutely positioned image within a CSS grid layout. Below is the code snippet: HTML: <div class="relative-parent"> <div v-for="item in 12" class="hiding-parent"> <div c ...

Tips on saving the background image URL value into a variable

How can I save the URL value of a background image in a variable? For example: image: url(images/9XkFhM8tRiuHXZRCKSdm_ny-2.jpg); I store this value as value = images/9XkFhM8tRiuHXZRCKSdm_ny-2.jpg in a variable and then use this variable in an href tag. ...

Tips for adjusting an svg component to suit various screen sizes

I inserted the following SVG component into my HTML file. It fits perfectly on my tablet, but it's too large for my smartphone. How can we automatically adjust the size of the SVG to fit different screens? <svg viewBox="310 -25 380 450" w ...

How can I transform an HTML div into a video file like MP4 using Python and Django?

I'm looking to take a HTML page and target a specific <div> within it in order to convert it into video format. Purpose: I understand that HTML is typically static, but I have a requirement to transform it into a video. I'm seeking method ...