capacitor-community / bluetooth-le

Capacitor plugin for Bluetooth Low Energy
MIT License
284 stars 86 forks source link

Can you Please help me Adding Bluetooth Connectivity in my ionic react project. I'm facing the error while scanning the BLE devices. #596

Closed Shruti2906 closed 1 year ago

Shruti2906 commented 1 year ago

Here is my code : // BluetoothService.tsx :

import { BleClient, BleDevice, ScanResult, numberToUUID } from '@capacitor-community/bluetooth-le'; const HEART_RATE_SERVICE = numberToUUID(0x180d);

class BluetoothService { async startScanning(handleDiscovery: (device: ScanResult) => void) { try { await BleClient.initialize(); console.log('bleClient initialized'); await BleClient.requestLEScan({ services: [HEART_RATE_SERVICE],}, (result) => { console.log('startscanning: ',result); handleDiscovery(result); });

} catch (error) {
  console.error('Error scanning for devices:', error);
  throw error;
}

}

async stopScanning() { try { await BleClient.stopLEScan(); } catch (error) { console.error('Error stopping scan:', error); throw error; } }

async connectToDevice(deviceId: string) { try { await BleClient.connect(deviceId); } catch (error) { console.error('Error connecting to device:', error); throw error; } }

async disconnectDevice(deviceId: string) { try { await BleClient.disconnect(deviceId ); } catch (error) { console.error('Error disconnecting from device:', error); throw error; } } } export default new BluetoothService();

// BluetoothScanningPage.tsx :

import React, { useEffect, useState } from 'react'; import { IonPage, IonContent, IonList, IonItem, IonLabel, IonButton, IonAlert } from '@ionic/react'; import BluetoothService from '../../services/BluetoothService'; import { BleDevice, ScanResult } from '@capacitor-community/bluetooth-le'; import { useHistory } from 'react-router-dom';

const BluetoothScan: React.FC = () => { const history = useHistory(); const [devices, setDevices] = useState<ScanResult[]>([]); const [showConnectAlert, setShowConnectAlert] = useState(false);

useEffect(() => { const handleDeviceDiscovery = (result: ScanResult) => { console.log(result); setDevices((prevDevices) => [...prevDevices, result]); };

BluetoothService.startScanning(handleDeviceDiscovery);

return () => {
  BluetoothService.stopScanning();
};

}, []);

const handleConnectToDevice = async (device: ScanResult) => { try { await BluetoothService.connectToDevice("device.id"); setShowConnectAlert(true); } catch (error) { console.error('Error connecting to device:', error); } };

return (

scanList

{devices.map((device) => ( {device.localName || 'Unnamed'} handleConnectToDevice(device)}>Connect ))}
{ setShowConnectAlert(false); history.push('/home'); }} header="Device Connected" message="The device has been successfully connected." buttons={['OK']} />

); };

export default BluetoothScan;

in brave browser the error in console is : Error scanning for devices: Error: No Bluetooth radio available. at BluetoothLeWeb.unavailable (web-plugin.js:68:16) at BluetoothLeWeb.initialize (web.ts:44:18) at async bleClient.ts:323:7 at async BleClientClass.initialize (bleClient.ts:322:5) at async BluetoothService.startScanning

in edge browser error is : BluetoothService.tsx?t=1699868982228:13 Error scanning for devices: TypeError: navigator.bluetooth.requestLEScan is not a function at BluetoothLeWeb.requestLEScan

mutasimissa commented 1 year ago

The code you provided is not readable, please provide a github gist or a sandbox repository to see and test. Also you can see here a simple (and old ) implementation of the plugin in react https://github.com/sourcya/ble-tester

Shruti2906 commented 1 year ago

@mutasimissa https://gist.github.com/Shruti2906/33f647fc421b9c1def88594a76871381

This is project github repo : https://github.com/Shruti2906/SmartMedicineBoxBLEConnectivity

Please feel free to make changes in this repo